]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_encodeframe.c
Merge "mips msa vp9 convolve8 horiz optimization"
[libvpx] / 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 <limits.h>
12 #include <math.h>
13 #include <stdio.h>
14
15 #include "./vp9_rtcd.h"
16 #include "./vpx_config.h"
17
18 #include "vpx_ports/vpx_timer.h"
19
20 #include "vp9/common/vp9_common.h"
21 #include "vp9/common/vp9_entropy.h"
22 #include "vp9/common/vp9_entropymode.h"
23 #include "vp9/common/vp9_idct.h"
24 #include "vp9/common/vp9_mvref_common.h"
25 #include "vp9/common/vp9_pred_common.h"
26 #include "vp9/common/vp9_quant_common.h"
27 #include "vp9/common/vp9_reconintra.h"
28 #include "vp9/common/vp9_reconinter.h"
29 #include "vp9/common/vp9_seg_common.h"
30 #include "vp9/common/vp9_systemdependent.h"
31 #include "vp9/common/vp9_tile_common.h"
32
33 #include "vp9/encoder/vp9_aq_complexity.h"
34 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
35 #include "vp9/encoder/vp9_aq_variance.h"
36 #include "vp9/encoder/vp9_encodeframe.h"
37 #include "vp9/encoder/vp9_encodemb.h"
38 #include "vp9/encoder/vp9_encodemv.h"
39 #include "vp9/encoder/vp9_ethread.h"
40 #include "vp9/encoder/vp9_extend.h"
41 #include "vp9/encoder/vp9_pickmode.h"
42 #include "vp9/encoder/vp9_rd.h"
43 #include "vp9/encoder/vp9_rdopt.h"
44 #include "vp9/encoder/vp9_segmentation.h"
45 #include "vp9/encoder/vp9_tokenize.h"
46
47 static void encode_superblock(VP9_COMP *cpi, ThreadData * td,
48                               TOKENEXTRA **t, int output_enabled,
49                               int mi_row, int mi_col, BLOCK_SIZE bsize,
50                               PICK_MODE_CONTEXT *ctx);
51
52 // This is used as a reference when computing the source variance for the
53 //  purposes of activity masking.
54 // Eventually this should be replaced by custom no-reference routines,
55 //  which will be faster.
56 static const uint8_t VP9_VAR_OFFS[64] = {
57     128, 128, 128, 128, 128, 128, 128, 128,
58     128, 128, 128, 128, 128, 128, 128, 128,
59     128, 128, 128, 128, 128, 128, 128, 128,
60     128, 128, 128, 128, 128, 128, 128, 128,
61     128, 128, 128, 128, 128, 128, 128, 128,
62     128, 128, 128, 128, 128, 128, 128, 128,
63     128, 128, 128, 128, 128, 128, 128, 128,
64     128, 128, 128, 128, 128, 128, 128, 128
65 };
66
67 #if CONFIG_VP9_HIGHBITDEPTH
68 static const uint16_t VP9_HIGH_VAR_OFFS_8[64] = {
69     128, 128, 128, 128, 128, 128, 128, 128,
70     128, 128, 128, 128, 128, 128, 128, 128,
71     128, 128, 128, 128, 128, 128, 128, 128,
72     128, 128, 128, 128, 128, 128, 128, 128,
73     128, 128, 128, 128, 128, 128, 128, 128,
74     128, 128, 128, 128, 128, 128, 128, 128,
75     128, 128, 128, 128, 128, 128, 128, 128,
76     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, 128*16,
92     128*16, 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, 128*16,
94     128*16, 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, 128*16,
96     128*16, 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, 128*16,
98     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16
99 };
100 #endif  // CONFIG_VP9_HIGHBITDEPTH
101
102 unsigned int vp9_get_sby_perpixel_variance(VP9_COMP *cpi,
103                                            const struct buf_2d *ref,
104                                            BLOCK_SIZE bs) {
105   unsigned int sse;
106   const unsigned int var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
107                                               VP9_VAR_OFFS, 0, &sse);
108   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
109 }
110
111 #if CONFIG_VP9_HIGHBITDEPTH
112 unsigned int vp9_high_get_sby_perpixel_variance(
113     VP9_COMP *cpi, const struct buf_2d *ref, BLOCK_SIZE bs, int bd) {
114   unsigned int var, sse;
115   switch (bd) {
116     case 10:
117       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
118                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10),
119                                0, &sse);
120       break;
121     case 12:
122       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
123                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12),
124                                0, &sse);
125       break;
126     case 8:
127     default:
128       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
129                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8),
130                                0, &sse);
131       break;
132   }
133   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
134 }
135 #endif  // CONFIG_VP9_HIGHBITDEPTH
136
137 static unsigned int get_sby_perpixel_diff_variance(VP9_COMP *cpi,
138                                                    const struct buf_2d *ref,
139                                                    int mi_row, int mi_col,
140                                                    BLOCK_SIZE bs) {
141   unsigned int sse, var;
142   uint8_t *last_y;
143   const YV12_BUFFER_CONFIG *last = get_ref_frame_buffer(cpi, LAST_FRAME);
144
145   assert(last != NULL);
146   last_y =
147       &last->y_buffer[mi_row * MI_SIZE * last->y_stride + mi_col * MI_SIZE];
148   var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride, last_y, last->y_stride, &sse);
149   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
150 }
151
152 static BLOCK_SIZE get_rd_var_based_fixed_partition(VP9_COMP *cpi, MACROBLOCK *x,
153                                                    int mi_row,
154                                                    int mi_col) {
155   unsigned int var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src,
156                                                     mi_row, mi_col,
157                                                     BLOCK_64X64);
158   if (var < 8)
159     return BLOCK_64X64;
160   else if (var < 128)
161     return BLOCK_32X32;
162   else if (var < 2048)
163     return BLOCK_16X16;
164   else
165     return BLOCK_8X8;
166 }
167
168 // Lighter version of set_offsets that only sets the mode info
169 // pointers.
170 static INLINE void set_mode_info_offsets(VP9_COMMON *const cm,
171                                          MACROBLOCKD *const xd,
172                                          int mi_row,
173                                          int mi_col) {
174   const int idx_str = xd->mi_stride * mi_row + mi_col;
175   xd->mi = cm->mi_grid_visible + idx_str;
176   xd->mi[0] = cm->mi + idx_str;
177 }
178
179 static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
180                         MACROBLOCK *const x, int mi_row, int mi_col,
181                         BLOCK_SIZE bsize) {
182   VP9_COMMON *const cm = &cpi->common;
183   MACROBLOCKD *const xd = &x->e_mbd;
184   MB_MODE_INFO *mbmi;
185   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
186   const int mi_height = num_8x8_blocks_high_lookup[bsize];
187   const struct segmentation *const seg = &cm->seg;
188
189   set_skip_context(xd, mi_row, mi_col);
190
191   set_mode_info_offsets(cm, xd, mi_row, mi_col);
192
193   mbmi = &xd->mi[0]->mbmi;
194
195   // Set up destination pointers.
196   vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
197
198   // Set up limit values for MV components.
199   // Mv beyond the range do not produce new/different prediction block.
200   x->mv_row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
201   x->mv_col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
202   x->mv_row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
203   x->mv_col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
204
205   // Set up distance of MB to edge of frame in 1/8th pel units.
206   assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
207   set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width,
208                  cm->mi_rows, cm->mi_cols);
209
210   // Set up source buffers.
211   vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
212
213   // R/D setup.
214   x->rddiv = cpi->rd.RDDIV;
215   x->rdmult = cpi->rd.RDMULT;
216
217   // Setup segment ID.
218   if (seg->enabled) {
219     if (cpi->oxcf.aq_mode != VARIANCE_AQ) {
220       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
221                                                  : cm->last_frame_seg_map;
222       mbmi->segment_id = vp9_get_segment_id(cm, map, bsize, mi_row, mi_col);
223     }
224     vp9_init_plane_quantizers(cpi, x);
225
226     x->encode_breakout = cpi->segment_encode_breakout[mbmi->segment_id];
227   } else {
228     mbmi->segment_id = 0;
229     x->encode_breakout = cpi->encode_breakout;
230   }
231 }
232
233 static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
234                                       int mi_row, int mi_col,
235                                       BLOCK_SIZE bsize) {
236   const int block_width = num_8x8_blocks_wide_lookup[bsize];
237   const int block_height = num_8x8_blocks_high_lookup[bsize];
238   int i, j;
239   for (j = 0; j < block_height; ++j)
240     for (i = 0; i < block_width; ++i) {
241       if (mi_row + j < cm->mi_rows && mi_col + i < cm->mi_cols)
242         xd->mi[j * xd->mi_stride + i] = xd->mi[0];
243     }
244 }
245
246 static void set_block_size(VP9_COMP * const cpi,
247                            MACROBLOCKD *const xd,
248                            int mi_row, int mi_col,
249                            BLOCK_SIZE bsize) {
250   if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
251     set_mode_info_offsets(&cpi->common, xd, mi_row, mi_col);
252     xd->mi[0]->mbmi.sb_type = bsize;
253   }
254 }
255
256 typedef struct {
257   int64_t sum_square_error;
258   int64_t sum_error;
259   int log2_count;
260   int variance;
261 } var;
262
263 typedef struct {
264   var none;
265   var horz[2];
266   var vert[2];
267 } partition_variance;
268
269 typedef struct {
270   partition_variance part_variances;
271   var split[4];
272 } v4x4;
273
274 typedef struct {
275   partition_variance part_variances;
276   v4x4 split[4];
277 } v8x8;
278
279 typedef struct {
280   partition_variance part_variances;
281   v8x8 split[4];
282 } v16x16;
283
284 typedef struct {
285   partition_variance part_variances;
286   v16x16 split[4];
287 } v32x32;
288
289 typedef struct {
290   partition_variance part_variances;
291   v32x32 split[4];
292 } v64x64;
293
294 typedef struct {
295   partition_variance *part_variances;
296   var *split[4];
297 } variance_node;
298
299 typedef enum {
300   V16X16,
301   V32X32,
302   V64X64,
303 } TREE_LEVEL;
304
305 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
306   int i;
307   node->part_variances = NULL;
308   switch (bsize) {
309     case BLOCK_64X64: {
310       v64x64 *vt = (v64x64 *) data;
311       node->part_variances = &vt->part_variances;
312       for (i = 0; i < 4; i++)
313         node->split[i] = &vt->split[i].part_variances.none;
314       break;
315     }
316     case BLOCK_32X32: {
317       v32x32 *vt = (v32x32 *) data;
318       node->part_variances = &vt->part_variances;
319       for (i = 0; i < 4; i++)
320         node->split[i] = &vt->split[i].part_variances.none;
321       break;
322     }
323     case BLOCK_16X16: {
324       v16x16 *vt = (v16x16 *) data;
325       node->part_variances = &vt->part_variances;
326       for (i = 0; i < 4; i++)
327         node->split[i] = &vt->split[i].part_variances.none;
328       break;
329     }
330     case BLOCK_8X8: {
331       v8x8 *vt = (v8x8 *) data;
332       node->part_variances = &vt->part_variances;
333       for (i = 0; i < 4; i++)
334         node->split[i] = &vt->split[i].part_variances.none;
335       break;
336     }
337     case BLOCK_4X4: {
338       v4x4 *vt = (v4x4 *) data;
339       node->part_variances = &vt->part_variances;
340       for (i = 0; i < 4; i++)
341         node->split[i] = &vt->split[i];
342       break;
343     }
344     default: {
345       assert(0);
346       break;
347     }
348   }
349 }
350
351 // Set variance values given sum square error, sum error, count.
352 static void fill_variance(int64_t s2, int64_t s, int c, var *v) {
353   v->sum_square_error = s2;
354   v->sum_error = s;
355   v->log2_count = c;
356 }
357
358 static void get_variance(var *v) {
359   v->variance = (int)(256 * (v->sum_square_error -
360       ((v->sum_error * v->sum_error) >> v->log2_count)) >> v->log2_count);
361 }
362
363 void sum_2_variances(const var *a, const var *b, var *r) {
364   assert(a->log2_count == b->log2_count);
365   fill_variance(a->sum_square_error + b->sum_square_error,
366                 a->sum_error + b->sum_error, a->log2_count + 1, r);
367 }
368
369 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
370   variance_node node;
371   tree_to_node(data, bsize, &node);
372   sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
373   sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
374   sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
375   sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
376   sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
377                   &node.part_variances->none);
378 }
379
380 static int set_vt_partitioning(VP9_COMP *cpi,
381                                MACROBLOCKD *const xd,
382                                void *data,
383                                BLOCK_SIZE bsize,
384                                int mi_row,
385                                int mi_col,
386                                int64_t threshold,
387                                BLOCK_SIZE bsize_min,
388                                int force_split) {
389   VP9_COMMON * const cm = &cpi->common;
390   variance_node vt;
391   const int block_width = num_8x8_blocks_wide_lookup[bsize];
392   const int block_height = num_8x8_blocks_high_lookup[bsize];
393   const int low_res = (cm->width <= 352 && cm->height <= 288);
394
395   assert(block_height == block_width);
396   tree_to_node(data, bsize, &vt);
397
398   if (force_split == 1)
399     return 0;
400
401   // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
402   // variance is below threshold, otherwise split will be selected.
403   // No check for vert/horiz split as too few samples for variance.
404   if (bsize == bsize_min) {
405     // Variance already computed to set the force_split.
406     if (low_res || cm->frame_type == KEY_FRAME)
407       get_variance(&vt.part_variances->none);
408     if (mi_col + block_width / 2 < cm->mi_cols &&
409         mi_row + block_height / 2 < cm->mi_rows &&
410         vt.part_variances->none.variance < threshold) {
411       set_block_size(cpi, xd, mi_row, mi_col, bsize);
412       return 1;
413     }
414     return 0;
415   } else if (bsize > bsize_min) {
416     // Variance already computed to set the force_split.
417     if (low_res || cm->frame_type == KEY_FRAME)
418       get_variance(&vt.part_variances->none);
419     // For key frame: take split for bsize above 32X32 or very high variance.
420     if (cm->frame_type == KEY_FRAME &&
421         (bsize > BLOCK_32X32 ||
422         vt.part_variances->none.variance > (threshold << 4))) {
423       return 0;
424     }
425     // If variance is low, take the bsize (no split).
426     if (mi_col + block_width / 2 < cm->mi_cols &&
427         mi_row + block_height / 2 < cm->mi_rows &&
428         vt.part_variances->none.variance < threshold) {
429       set_block_size(cpi, xd, mi_row, mi_col, bsize);
430       return 1;
431     }
432
433     // Check vertical split.
434     if (mi_row + block_height / 2 < cm->mi_rows) {
435       get_variance(&vt.part_variances->vert[0]);
436       get_variance(&vt.part_variances->vert[1]);
437       if (vt.part_variances->vert[0].variance < threshold &&
438           vt.part_variances->vert[1].variance < threshold) {
439         BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
440         set_block_size(cpi, xd, mi_row, mi_col, subsize);
441         set_block_size(cpi, xd, mi_row, mi_col + block_width / 2, subsize);
442         return 1;
443       }
444     }
445     // Check horizontal split.
446     if (mi_col + block_width / 2 < cm->mi_cols) {
447       get_variance(&vt.part_variances->horz[0]);
448       get_variance(&vt.part_variances->horz[1]);
449       if (vt.part_variances->horz[0].variance < threshold &&
450           vt.part_variances->horz[1].variance < threshold) {
451         BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
452         set_block_size(cpi, xd, mi_row, mi_col, subsize);
453         set_block_size(cpi, xd, mi_row + block_height / 2, mi_col, subsize);
454         return 1;
455       }
456     }
457
458     return 0;
459   }
460   return 0;
461 }
462
463 void vp9_set_vbp_thresholds(VP9_COMP *cpi, int q) {
464   SPEED_FEATURES *const sf = &cpi->sf;
465   if (sf->partition_search_type != VAR_BASED_PARTITION &&
466       sf->partition_search_type != REFERENCE_PARTITION) {
467     return;
468   } else {
469     VP9_COMMON *const cm = &cpi->common;
470     const int is_key_frame = (cm->frame_type == KEY_FRAME);
471     const int threshold_multiplier = is_key_frame ? 20 : 1;
472     const int64_t threshold_base = (int64_t)(threshold_multiplier *
473         cpi->y_dequant[q][1]);
474
475     // TODO(marpan): Allow 4x4 partitions for inter-frames.
476     // use_4x4_partition = (variance4x4downsample[i2 + j] == 1);
477     // If 4x4 partition is not used, then 8x8 partition will be selected
478     // if variance of 16x16 block is very high, so use larger threshold
479     // for 16x16 (threshold_bsize_min) in that case.
480
481     // Array index: 0 - threshold_64x64; 1 - threshold_32x32;
482     // 2 - threshold_16x16; 3 - vbp_threshold_8x8;
483     if (is_key_frame) {
484       cpi->vbp_thresholds[0] = threshold_base;
485       cpi->vbp_thresholds[1] = threshold_base >> 2;
486       cpi->vbp_thresholds[2] = threshold_base >> 2;
487       cpi->vbp_thresholds[3] = threshold_base << 2;
488       cpi->vbp_threshold_sad = 0;
489       cpi->vbp_bsize_min = BLOCK_8X8;
490     } else {
491       cpi->vbp_thresholds[1] = threshold_base;
492       if (cm->width <= 352 && cm->height <= 288) {
493         cpi->vbp_thresholds[0] = threshold_base >> 2;
494         cpi->vbp_thresholds[2] = threshold_base << 3;
495         cpi->vbp_threshold_sad = 100;
496       } else {
497         cpi->vbp_thresholds[0] = threshold_base;
498         cpi->vbp_thresholds[1] = (5 * threshold_base) >> 2;
499         cpi->vbp_thresholds[2] = threshold_base << cpi->oxcf.speed;
500         cpi->vbp_threshold_sad = 1000;
501       }
502       cpi->vbp_bsize_min = BLOCK_16X16;
503     }
504     cpi->vbp_threshold_minmax = 15 + (q >> 3);
505   }
506 }
507
508 // Compute the minmax over the 8x8 subblocks.
509 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
510                               int dp, int x16_idx, int y16_idx,
511 #if CONFIG_VP9_HIGHBITDEPTH
512                               int highbd_flag,
513 #endif
514                               int pixels_wide,
515                               int pixels_high) {
516   int k;
517   int minmax_max = 0;
518   int minmax_min = 255;
519   // Loop over the 4 8x8 subblocks.
520   for (k = 0; k < 4; k++) {
521     int x8_idx = x16_idx + ((k & 1) << 3);
522     int y8_idx = y16_idx + ((k >> 1) << 3);
523     int min = 0;
524     int max = 0;
525     if (x8_idx < pixels_wide && y8_idx < pixels_high) {
526 #if CONFIG_VP9_HIGHBITDEPTH
527       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
528         vp9_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
529                               d + y8_idx * dp + x8_idx, dp,
530                               &min, &max);
531       } else {
532         vp9_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
533                        d + y8_idx * dp + x8_idx, dp,
534                        &min, &max);
535       }
536 #else
537       vp9_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
538                      d + y8_idx * dp + x8_idx, dp,
539                      &min, &max);
540 #endif
541       if ((max - min) > minmax_max)
542         minmax_max = (max - min);
543       if ((max - min) < minmax_min)
544         minmax_min = (max - min);
545     }
546   }
547   return (minmax_max - minmax_min);
548 }
549
550 static void modify_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q) {
551   VP9_COMMON *const cm = &cpi->common;
552   const int64_t threshold_base = (int64_t)(cpi->y_dequant[q][1]);
553
554   // Array index: 0 - threshold_64x64; 1 - threshold_32x32;
555   // 2 - threshold_16x16; 3 - vbp_threshold_8x8;
556   thresholds[1] = threshold_base;
557   if (cm->width <= 352 && cm->height <= 288) {
558     thresholds[0] = threshold_base >> 2;
559     thresholds[2] = threshold_base << 3;
560   } else {
561     thresholds[0] = threshold_base;
562     thresholds[1] = (5 * threshold_base) >> 2;
563     thresholds[2] = threshold_base << cpi->oxcf.speed;
564   }
565 }
566
567 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
568                                  int dp, int x8_idx, int y8_idx, v8x8 *vst,
569 #if CONFIG_VP9_HIGHBITDEPTH
570                                  int highbd_flag,
571 #endif
572                                  int pixels_wide,
573                                  int pixels_high,
574                                  int is_key_frame) {
575   int k;
576   for (k = 0; k < 4; k++) {
577     int x4_idx = x8_idx + ((k & 1) << 2);
578     int y4_idx = y8_idx + ((k >> 1) << 2);
579     unsigned int sse = 0;
580     int sum = 0;
581     if (x4_idx < pixels_wide && y4_idx < pixels_high) {
582       int s_avg;
583       int d_avg = 128;
584 #if CONFIG_VP9_HIGHBITDEPTH
585       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
586         s_avg = vp9_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
587         if (!is_key_frame)
588           d_avg = vp9_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
589       } else {
590         s_avg = vp9_avg_4x4(s + y4_idx * sp + x4_idx, sp);
591         if (!is_key_frame)
592           d_avg = vp9_avg_4x4(d + y4_idx * dp + x4_idx, dp);
593       }
594 #else
595       s_avg = vp9_avg_4x4(s + y4_idx * sp + x4_idx, sp);
596       if (!is_key_frame)
597         d_avg = vp9_avg_4x4(d + y4_idx * dp + x4_idx, dp);
598 #endif
599       sum = s_avg - d_avg;
600       sse = sum * sum;
601     }
602     fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
603   }
604 }
605
606 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
607                                  int dp, int x16_idx, int y16_idx, v16x16 *vst,
608 #if CONFIG_VP9_HIGHBITDEPTH
609                                  int highbd_flag,
610 #endif
611                                  int pixels_wide,
612                                  int pixels_high,
613                                  int is_key_frame) {
614   int k;
615   for (k = 0; k < 4; k++) {
616     int x8_idx = x16_idx + ((k & 1) << 3);
617     int y8_idx = y16_idx + ((k >> 1) << 3);
618     unsigned int sse = 0;
619     int sum = 0;
620     if (x8_idx < pixels_wide && y8_idx < pixels_high) {
621       int s_avg;
622       int d_avg = 128;
623 #if CONFIG_VP9_HIGHBITDEPTH
624       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
625         s_avg = vp9_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
626         if (!is_key_frame)
627           d_avg = vp9_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
628       } else {
629         s_avg = vp9_avg_8x8(s + y8_idx * sp + x8_idx, sp);
630         if (!is_key_frame)
631           d_avg = vp9_avg_8x8(d + y8_idx * dp + x8_idx, dp);
632       }
633 #else
634       s_avg = vp9_avg_8x8(s + y8_idx * sp + x8_idx, sp);
635       if (!is_key_frame)
636         d_avg = vp9_avg_8x8(d + y8_idx * dp + x8_idx, dp);
637 #endif
638       sum = s_avg - d_avg;
639       sse = sum * sum;
640     }
641     fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
642   }
643 }
644
645 // This function chooses partitioning based on the variance between source and
646 // reconstructed last, where variance is computed for down-sampled inputs.
647 static int choose_partitioning(VP9_COMP *cpi,
648                                 const TileInfo *const tile,
649                                 MACROBLOCK *x,
650                                 int mi_row, int mi_col) {
651   VP9_COMMON * const cm = &cpi->common;
652   MACROBLOCKD *xd = &x->e_mbd;
653   int i, j, k, m;
654   v64x64 vt;
655   v16x16 vt2[16];
656   int force_split[21];
657   uint8_t *s;
658   const uint8_t *d;
659   int sp;
660   int dp;
661   int pixels_wide = 64, pixels_high = 64;
662   int64_t thresholds[4] = {cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
663       cpi->vbp_thresholds[2], cpi->vbp_thresholds[3]};
664
665   // Always use 4x4 partition for key frame.
666   const int is_key_frame = (cm->frame_type == KEY_FRAME);
667   const int use_4x4_partition = is_key_frame;
668   const int low_res = (cm->width <= 352 && cm->height <= 288);
669   int variance4x4downsample[16];
670
671   int segment_id = CR_SEGMENT_ID_BASE;
672   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled) {
673     const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map :
674                                                     cm->last_frame_seg_map;
675     segment_id = vp9_get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
676
677     if (cyclic_refresh_segment_id_boosted(segment_id)) {
678       int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
679       modify_vbp_thresholds(cpi, thresholds, q);
680     }
681   }
682
683   set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
684
685   if (xd->mb_to_right_edge < 0)
686     pixels_wide += (xd->mb_to_right_edge >> 3);
687   if (xd->mb_to_bottom_edge < 0)
688     pixels_high += (xd->mb_to_bottom_edge >> 3);
689
690   s = x->plane[0].src.buf;
691   sp = x->plane[0].src.stride;
692
693   if (!is_key_frame) {
694     MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
695     unsigned int uv_sad;
696     const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
697
698     const YV12_BUFFER_CONFIG *yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
699     unsigned int y_sad, y_sad_g;
700     const BLOCK_SIZE bsize = BLOCK_32X32
701         + (mi_col + 4 < cm->mi_cols) * 2 + (mi_row + 4 < cm->mi_rows);
702
703     assert(yv12 != NULL);
704     if (yv12_g && yv12_g != yv12) {
705       vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
706                            &cm->frame_refs[GOLDEN_FRAME - 1].sf);
707       y_sad_g = cpi->fn_ptr[bsize].sdf(x->plane[0].src.buf,
708                                        x->plane[0].src.stride,
709                                        xd->plane[0].pre[0].buf,
710                                        xd->plane[0].pre[0].stride);
711     } else {
712       y_sad_g = UINT_MAX;
713     }
714
715     vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
716                          &cm->frame_refs[LAST_FRAME - 1].sf);
717     mbmi->ref_frame[0] = LAST_FRAME;
718     mbmi->ref_frame[1] = NONE;
719     mbmi->sb_type = BLOCK_64X64;
720     mbmi->mv[0].as_int = 0;
721     mbmi->interp_filter = BILINEAR;
722
723     y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize);
724     if (y_sad_g < y_sad) {
725       vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
726                            &cm->frame_refs[GOLDEN_FRAME - 1].sf);
727       mbmi->ref_frame[0] = GOLDEN_FRAME;
728       mbmi->mv[0].as_int = 0;
729       y_sad = y_sad_g;
730     } else {
731       x->pred_mv[LAST_FRAME] = mbmi->mv[0].as_mv;
732     }
733
734     vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
735
736     for (i = 1; i <= 2; ++i) {
737       struct macroblock_plane  *p = &x->plane[i];
738       struct macroblockd_plane *pd = &xd->plane[i];
739       const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
740
741       if (bs == BLOCK_INVALID)
742         uv_sad = UINT_MAX;
743       else
744         uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride,
745                                      pd->dst.buf, pd->dst.stride);
746
747       x->color_sensitivity[i - 1] = uv_sad > (y_sad >> 2);
748     }
749
750     d = xd->plane[0].dst.buf;
751     dp = xd->plane[0].dst.stride;
752
753     // If the y_sad is very small, take 64x64 as partition and exit.
754     // Don't check on boosted segment for now, as 64x64 is suppressed there.
755     if (segment_id == CR_SEGMENT_ID_BASE &&
756         y_sad < cpi->vbp_threshold_sad) {
757       const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
758       const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
759       if (mi_col + block_width / 2 < cm->mi_cols &&
760           mi_row + block_height / 2 < cm->mi_rows) {
761         set_block_size(cpi, xd, mi_row, mi_col, BLOCK_64X64);
762         return 0;
763       }
764     }
765   } else {
766     d = VP9_VAR_OFFS;
767     dp = 0;
768 #if CONFIG_VP9_HIGHBITDEPTH
769     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
770       switch (xd->bd) {
771         case 10:
772           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10);
773           break;
774         case 12:
775           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12);
776           break;
777         case 8:
778         default:
779           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8);
780           break;
781       }
782     }
783 #endif  // CONFIG_VP9_HIGHBITDEPTH
784   }
785
786   // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
787   // 5-20 for the 16x16 blocks.
788   force_split[0] = 0;
789   // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
790   // for splits.
791   for (i = 0; i < 4; i++) {
792     const int x32_idx = ((i & 1) << 5);
793     const int y32_idx = ((i >> 1) << 5);
794     const int i2 = i << 2;
795     force_split[i + 1] = 0;
796     for (j = 0; j < 4; j++) {
797       const int x16_idx = x32_idx + ((j & 1) << 4);
798       const int y16_idx = y32_idx + ((j >> 1) << 4);
799       const int split_index = 5 + i2 + j;
800       v16x16 *vst = &vt.split[i].split[j];
801       force_split[split_index] = 0;
802       variance4x4downsample[i2 + j] = 0;
803       if (!is_key_frame) {
804         fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
805 #if CONFIG_VP9_HIGHBITDEPTH
806                             xd->cur_buf->flags,
807 #endif
808                             pixels_wide,
809                             pixels_high,
810                             is_key_frame);
811         fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
812         get_variance(&vt.split[i].split[j].part_variances.none);
813         if (vt.split[i].split[j].part_variances.none.variance >
814             thresholds[2]) {
815           // 16X16 variance is above threshold for split, so force split to 8x8
816           // for this 16x16 block (this also forces splits for upper levels).
817           force_split[split_index] = 1;
818           force_split[i + 1] = 1;
819           force_split[0] = 1;
820         } else if (vt.split[i].split[j].part_variances.none.variance >
821                    thresholds[1] &&
822                    !cyclic_refresh_segment_id_boosted(segment_id)) {
823           // We have some nominal amount of 16x16 variance (based on average),
824           // compute the minmax over the 8x8 sub-blocks, and if above threshold,
825           // force split to 8x8 block for this 16x16 block.
826           int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
827 #if CONFIG_VP9_HIGHBITDEPTH
828                                           xd->cur_buf->flags,
829 #endif
830                                           pixels_wide, pixels_high);
831           if (minmax > cpi->vbp_threshold_minmax) {
832             force_split[split_index] = 1;
833             force_split[i + 1] = 1;
834             force_split[0] = 1;
835           }
836         }
837       }
838       if (is_key_frame || (low_res &&
839           vt.split[i].split[j].part_variances.none.variance >
840           (thresholds[1] << 1))) {
841         force_split[split_index] = 0;
842         // Go down to 4x4 down-sampling for variance.
843         variance4x4downsample[i2 + j] = 1;
844         for (k = 0; k < 4; k++) {
845           int x8_idx = x16_idx + ((k & 1) << 3);
846           int y8_idx = y16_idx + ((k >> 1) << 3);
847           v8x8 *vst2 = is_key_frame ? &vst->split[k] :
848               &vt2[i2 + j].split[k];
849           fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
850 #if CONFIG_VP9_HIGHBITDEPTH
851                                xd->cur_buf->flags,
852 #endif
853                                pixels_wide,
854                                pixels_high,
855                                is_key_frame);
856         }
857       }
858     }
859   }
860
861   // Fill the rest of the variance tree by summing split partition values.
862   for (i = 0; i < 4; i++) {
863     const int i2 = i << 2;
864     for (j = 0; j < 4; j++) {
865       if (variance4x4downsample[i2 + j] == 1) {
866         v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] :
867             &vt.split[i].split[j];
868         for (m = 0; m < 4; m++)
869           fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
870         fill_variance_tree(vtemp, BLOCK_16X16);
871       }
872     }
873     fill_variance_tree(&vt.split[i], BLOCK_32X32);
874     // If variance of this 32x32 block is above the threshold, force the block
875     // to split. This also forces a split on the upper (64x64) level.
876     if (!force_split[i + 1]) {
877       get_variance(&vt.split[i].part_variances.none);
878       if (vt.split[i].part_variances.none.variance > thresholds[1]) {
879         force_split[i + 1] = 1;
880         force_split[0] = 1;
881       }
882     }
883   }
884   if (!force_split[0]) {
885     fill_variance_tree(&vt, BLOCK_64X64);
886     get_variance(&vt.part_variances.none);
887   }
888
889   // Now go through the entire structure, splitting every block size until
890   // we get to one that's got a variance lower than our threshold.
891   if ( mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
892       !set_vt_partitioning(cpi, xd, &vt, BLOCK_64X64, mi_row, mi_col,
893                            thresholds[0], BLOCK_16X16, force_split[0])) {
894     for (i = 0; i < 4; ++i) {
895       const int x32_idx = ((i & 1) << 2);
896       const int y32_idx = ((i >> 1) << 2);
897       const int i2 = i << 2;
898       if (!set_vt_partitioning(cpi, xd, &vt.split[i], BLOCK_32X32,
899                                (mi_row + y32_idx), (mi_col + x32_idx),
900                                thresholds[1], BLOCK_16X16,
901                                force_split[i + 1])) {
902         for (j = 0; j < 4; ++j) {
903           const int x16_idx = ((j & 1) << 1);
904           const int y16_idx = ((j >> 1) << 1);
905           // For inter frames: if variance4x4downsample[] == 1 for this 16x16
906           // block, then the variance is based on 4x4 down-sampling, so use vt2
907           // in set_vt_partioning(), otherwise use vt.
908           v16x16 *vtemp = (!is_key_frame &&
909                            variance4x4downsample[i2 + j] == 1) ?
910                            &vt2[i2 + j] : &vt.split[i].split[j];
911           if (!set_vt_partitioning(cpi, xd, vtemp, BLOCK_16X16,
912                                    mi_row + y32_idx + y16_idx,
913                                    mi_col + x32_idx + x16_idx,
914                                    thresholds[2],
915                                    cpi->vbp_bsize_min,
916                                    force_split[5 + i2  + j])) {
917             for (k = 0; k < 4; ++k) {
918               const int x8_idx = (k & 1);
919               const int y8_idx = (k >> 1);
920               if (use_4x4_partition) {
921                 if (!set_vt_partitioning(cpi, xd, &vtemp->split[k],
922                                          BLOCK_8X8,
923                                          mi_row + y32_idx + y16_idx + y8_idx,
924                                          mi_col + x32_idx + x16_idx + x8_idx,
925                                          thresholds[3], BLOCK_8X8, 0)) {
926                   set_block_size(cpi, xd,
927                                  (mi_row + y32_idx + y16_idx + y8_idx),
928                                  (mi_col + x32_idx + x16_idx + x8_idx),
929                                  BLOCK_4X4);
930                 }
931               } else {
932                 set_block_size(cpi, xd,
933                                (mi_row + y32_idx + y16_idx + y8_idx),
934                                (mi_col + x32_idx + x16_idx + x8_idx),
935                                BLOCK_8X8);
936               }
937             }
938           }
939         }
940       }
941     }
942   }
943   return 0;
944 }
945
946 static void update_state(VP9_COMP *cpi, ThreadData *td,
947                          PICK_MODE_CONTEXT *ctx,
948                          int mi_row, int mi_col, BLOCK_SIZE bsize,
949                          int output_enabled) {
950   int i, x_idx, y;
951   VP9_COMMON *const cm = &cpi->common;
952   RD_COUNTS *const rdc = &td->rd_counts;
953   MACROBLOCK *const x = &td->mb;
954   MACROBLOCKD *const xd = &x->e_mbd;
955   struct macroblock_plane *const p = x->plane;
956   struct macroblockd_plane *const pd = xd->plane;
957   MODE_INFO *mi = &ctx->mic;
958   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
959   MODE_INFO *mi_addr = xd->mi[0];
960   const struct segmentation *const seg = &cm->seg;
961   const int bw = num_8x8_blocks_wide_lookup[mi->mbmi.sb_type];
962   const int bh = num_8x8_blocks_high_lookup[mi->mbmi.sb_type];
963   const int x_mis = MIN(bw, cm->mi_cols - mi_col);
964   const int y_mis = MIN(bh, cm->mi_rows - mi_row);
965   MV_REF *const frame_mvs =
966       cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
967   int w, h;
968
969   const int mis = cm->mi_stride;
970   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
971   const int mi_height = num_8x8_blocks_high_lookup[bsize];
972   int max_plane;
973
974   assert(mi->mbmi.sb_type == bsize);
975
976   *mi_addr = *mi;
977
978   // If segmentation in use
979   if (seg->enabled) {
980     // For in frame complexity AQ copy the segment id from the segment map.
981     if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
982       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
983                                                  : cm->last_frame_seg_map;
984       mi_addr->mbmi.segment_id =
985         vp9_get_segment_id(cm, map, bsize, mi_row, mi_col);
986     }
987     // Else for cyclic refresh mode update the segment map, set the segment id
988     // and then update the quantizer.
989     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
990       vp9_cyclic_refresh_update_segment(cpi, &xd->mi[0]->mbmi, mi_row,
991                                         mi_col, bsize, ctx->rate, ctx->dist,
992                                         x->skip);
993     }
994   }
995
996   max_plane = is_inter_block(mbmi) ? MAX_MB_PLANE : 1;
997   for (i = 0; i < max_plane; ++i) {
998     p[i].coeff = ctx->coeff_pbuf[i][1];
999     p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1000     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1001     p[i].eobs = ctx->eobs_pbuf[i][1];
1002   }
1003
1004   for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1005     p[i].coeff = ctx->coeff_pbuf[i][2];
1006     p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1007     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1008     p[i].eobs = ctx->eobs_pbuf[i][2];
1009   }
1010
1011   // Restore the coding context of the MB to that that was in place
1012   // when the mode was picked for it
1013   for (y = 0; y < mi_height; y++)
1014     for (x_idx = 0; x_idx < mi_width; x_idx++)
1015       if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx
1016         && (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1017         xd->mi[x_idx + y * mis] = mi_addr;
1018       }
1019
1020   if (cpi->oxcf.aq_mode)
1021     vp9_init_plane_quantizers(cpi, x);
1022
1023   // FIXME(rbultje) I'm pretty sure this should go to the end of this block
1024   // (i.e. after the output_enabled)
1025   if (bsize < BLOCK_32X32) {
1026     if (bsize < BLOCK_16X16)
1027       ctx->tx_rd_diff[ALLOW_16X16] = ctx->tx_rd_diff[ALLOW_8X8];
1028     ctx->tx_rd_diff[ALLOW_32X32] = ctx->tx_rd_diff[ALLOW_16X16];
1029   }
1030
1031   if (is_inter_block(mbmi) && mbmi->sb_type < BLOCK_8X8) {
1032     mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1033     mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1034   }
1035
1036   x->skip = ctx->skip;
1037   vpx_memcpy(x->zcoeff_blk[mbmi->tx_size], ctx->zcoeff_blk,
1038              sizeof(uint8_t) * ctx->num_4x4_blk);
1039
1040   if (!output_enabled)
1041     return;
1042
1043   if (!vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
1044     for (i = 0; i < TX_MODES; i++)
1045       rdc->tx_select_diff[i] += ctx->tx_rd_diff[i];
1046   }
1047
1048 #if CONFIG_INTERNAL_STATS
1049   if (frame_is_intra_only(cm)) {
1050     static const int kf_mode_index[] = {
1051       THR_DC        /*DC_PRED*/,
1052       THR_V_PRED    /*V_PRED*/,
1053       THR_H_PRED    /*H_PRED*/,
1054       THR_D45_PRED  /*D45_PRED*/,
1055       THR_D135_PRED /*D135_PRED*/,
1056       THR_D117_PRED /*D117_PRED*/,
1057       THR_D153_PRED /*D153_PRED*/,
1058       THR_D207_PRED /*D207_PRED*/,
1059       THR_D63_PRED  /*D63_PRED*/,
1060       THR_TM        /*TM_PRED*/,
1061     };
1062     ++cpi->mode_chosen_counts[kf_mode_index[mbmi->mode]];
1063   } else {
1064     // Note how often each mode chosen as best
1065     ++cpi->mode_chosen_counts[ctx->best_mode_index];
1066   }
1067 #endif
1068   if (!frame_is_intra_only(cm)) {
1069     if (is_inter_block(mbmi)) {
1070       vp9_update_mv_count(td);
1071
1072       if (cm->interp_filter == SWITCHABLE) {
1073         const int ctx = vp9_get_pred_context_switchable_interp(xd);
1074         ++td->counts->switchable_interp[ctx][mbmi->interp_filter];
1075       }
1076     }
1077
1078     rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1079     rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1080     rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1081
1082     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1083       rdc->filter_diff[i] += ctx->best_filter_diff[i];
1084   }
1085
1086   for (h = 0; h < y_mis; ++h) {
1087     MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1088     for (w = 0; w < x_mis; ++w) {
1089       MV_REF *const mv = frame_mv + w;
1090       mv->ref_frame[0] = mi->mbmi.ref_frame[0];
1091       mv->ref_frame[1] = mi->mbmi.ref_frame[1];
1092       mv->mv[0].as_int = mi->mbmi.mv[0].as_int;
1093       mv->mv[1].as_int = mi->mbmi.mv[1].as_int;
1094     }
1095   }
1096 }
1097
1098 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1099                           int mi_row, int mi_col) {
1100   uint8_t *const buffers[3] = {src->y_buffer, src->u_buffer, src->v_buffer };
1101   const int strides[3] = {src->y_stride, src->uv_stride, src->uv_stride };
1102   int i;
1103
1104   // Set current frame pointer.
1105   x->e_mbd.cur_buf = src;
1106
1107   for (i = 0; i < MAX_MB_PLANE; i++)
1108     setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1109                      NULL, x->e_mbd.plane[i].subsampling_x,
1110                      x->e_mbd.plane[i].subsampling_y);
1111 }
1112
1113 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1114                                    RD_COST *rd_cost, BLOCK_SIZE bsize) {
1115   MACROBLOCKD *const xd = &x->e_mbd;
1116   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
1117   INTERP_FILTER filter_ref;
1118
1119   if (xd->up_available)
1120     filter_ref = xd->mi[-xd->mi_stride]->mbmi.interp_filter;
1121   else if (xd->left_available)
1122     filter_ref = xd->mi[-1]->mbmi.interp_filter;
1123   else
1124     filter_ref = EIGHTTAP;
1125
1126   mbmi->sb_type = bsize;
1127   mbmi->mode = ZEROMV;
1128   mbmi->tx_size = MIN(max_txsize_lookup[bsize],
1129                       tx_mode_to_biggest_tx_size[tx_mode]);
1130   mbmi->skip = 1;
1131   mbmi->uv_mode = DC_PRED;
1132   mbmi->ref_frame[0] = LAST_FRAME;
1133   mbmi->ref_frame[1] = NONE;
1134   mbmi->mv[0].as_int = 0;
1135   mbmi->interp_filter = filter_ref;
1136
1137   xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1138   x->skip = 1;
1139
1140   vp9_rd_cost_init(rd_cost);
1141 }
1142
1143 static int set_segment_rdmult(VP9_COMP *const cpi,
1144                                MACROBLOCK *const x,
1145                                int8_t segment_id) {
1146   int segment_qindex;
1147   VP9_COMMON *const cm = &cpi->common;
1148   vp9_init_plane_quantizers(cpi, x);
1149   vp9_clear_system_state();
1150   segment_qindex = vp9_get_qindex(&cm->seg, segment_id,
1151                                   cm->base_qindex);
1152   return vp9_compute_rd_mult(cpi, segment_qindex + cm->y_dc_delta_q);
1153 }
1154
1155 static void rd_pick_sb_modes(VP9_COMP *cpi,
1156                              TileDataEnc *tile_data,
1157                              MACROBLOCK *const x,
1158                              int mi_row, int mi_col, RD_COST *rd_cost,
1159                              BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
1160                              int64_t best_rd) {
1161   VP9_COMMON *const cm = &cpi->common;
1162   TileInfo *const tile_info = &tile_data->tile_info;
1163   MACROBLOCKD *const xd = &x->e_mbd;
1164   MB_MODE_INFO *mbmi;
1165   struct macroblock_plane *const p = x->plane;
1166   struct macroblockd_plane *const pd = xd->plane;
1167   const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1168   int i, orig_rdmult;
1169
1170   vp9_clear_system_state();
1171
1172   // Use the lower precision, but faster, 32x32 fdct for mode selection.
1173   x->use_lp32x32fdct = 1;
1174
1175   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1176   mbmi = &xd->mi[0]->mbmi;
1177   mbmi->sb_type = bsize;
1178
1179   for (i = 0; i < MAX_MB_PLANE; ++i) {
1180     p[i].coeff = ctx->coeff_pbuf[i][0];
1181     p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1182     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1183     p[i].eobs = ctx->eobs_pbuf[i][0];
1184   }
1185   ctx->is_coded = 0;
1186   ctx->skippable = 0;
1187   ctx->pred_pixel_ready = 0;
1188   x->skip_recode = 0;
1189
1190   // Set to zero to make sure we do not use the previous encoded frame stats
1191   mbmi->skip = 0;
1192
1193 #if CONFIG_VP9_HIGHBITDEPTH
1194   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1195     x->source_variance =
1196         vp9_high_get_sby_perpixel_variance(cpi, &x->plane[0].src,
1197                                            bsize, xd->bd);
1198   } else {
1199     x->source_variance =
1200       vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1201   }
1202 #else
1203   x->source_variance =
1204     vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1205 #endif  // CONFIG_VP9_HIGHBITDEPTH
1206
1207   // Save rdmult before it might be changed, so it can be restored later.
1208   orig_rdmult = x->rdmult;
1209
1210   if (aq_mode == VARIANCE_AQ) {
1211     const int energy = bsize <= BLOCK_16X16 ? x->mb_energy
1212                                             : vp9_block_energy(cpi, x, bsize);
1213     if (cm->frame_type == KEY_FRAME ||
1214         cpi->refresh_alt_ref_frame ||
1215         (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
1216       mbmi->segment_id = vp9_vaq_segment_id(energy);
1217     } else {
1218       const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map
1219                                                     : cm->last_frame_seg_map;
1220       mbmi->segment_id = vp9_get_segment_id(cm, map, bsize, mi_row, mi_col);
1221     }
1222     x->rdmult = set_segment_rdmult(cpi, x, mbmi->segment_id);
1223   } else if (aq_mode == COMPLEXITY_AQ) {
1224     x->rdmult = set_segment_rdmult(cpi, x, mbmi->segment_id);
1225   } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1226     const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map
1227                                                   : cm->last_frame_seg_map;
1228     // If segment is boosted, use rdmult for that segment.
1229     if (cyclic_refresh_segment_id_boosted(
1230             vp9_get_segment_id(cm, map, bsize, mi_row, mi_col)))
1231       x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1232   }
1233
1234   // Find best coding mode & reconstruct the MB so it is available
1235   // as a predictor for MBs that follow in the SB
1236   if (frame_is_intra_only(cm)) {
1237     vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
1238   } else {
1239     if (bsize >= BLOCK_8X8) {
1240       if (vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP))
1241         vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
1242                                            ctx, best_rd);
1243       else
1244         vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col,
1245                                   rd_cost, bsize, ctx, best_rd);
1246     } else {
1247       vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col,
1248                                     rd_cost, bsize, ctx, best_rd);
1249     }
1250   }
1251
1252
1253   // Examine the resulting rate and for AQ mode 2 make a segment choice.
1254   if ((rd_cost->rate != INT_MAX) &&
1255       (aq_mode == COMPLEXITY_AQ) && (bsize >= BLOCK_16X16) &&
1256       (cm->frame_type == KEY_FRAME ||
1257        cpi->refresh_alt_ref_frame ||
1258        (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
1259     vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
1260   }
1261
1262   x->rdmult = orig_rdmult;
1263
1264   // TODO(jingning) The rate-distortion optimization flow needs to be
1265   // refactored to provide proper exit/return handle.
1266   if (rd_cost->rate == INT_MAX)
1267     rd_cost->rdcost = INT64_MAX;
1268
1269   ctx->rate = rd_cost->rate;
1270   ctx->dist = rd_cost->dist;
1271 }
1272
1273 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
1274   const MACROBLOCK *x = &td->mb;
1275   const MACROBLOCKD *const xd = &x->e_mbd;
1276   const MODE_INFO *const mi = xd->mi[0];
1277   const MB_MODE_INFO *const mbmi = &mi->mbmi;
1278   const BLOCK_SIZE bsize = mbmi->sb_type;
1279
1280   if (!frame_is_intra_only(cm)) {
1281     FRAME_COUNTS *const counts = td->counts;
1282     const int inter_block = is_inter_block(mbmi);
1283     const int seg_ref_active = vp9_segfeature_active(&cm->seg, mbmi->segment_id,
1284                                                      SEG_LVL_REF_FRAME);
1285     if (!seg_ref_active) {
1286       counts->intra_inter[vp9_get_intra_inter_context(xd)][inter_block]++;
1287       // If the segment reference feature is enabled we have only a single
1288       // reference frame allowed for the segment so exclude it from
1289       // the reference frame counts used to work out probabilities.
1290       if (inter_block) {
1291         const MV_REFERENCE_FRAME ref0 = mbmi->ref_frame[0];
1292         if (cm->reference_mode == REFERENCE_MODE_SELECT)
1293           counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
1294                             [has_second_ref(mbmi)]++;
1295
1296         if (has_second_ref(mbmi)) {
1297           counts->comp_ref[vp9_get_pred_context_comp_ref_p(cm, xd)]
1298                           [ref0 == GOLDEN_FRAME]++;
1299         } else {
1300           counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
1301                             [ref0 != LAST_FRAME]++;
1302           if (ref0 != LAST_FRAME)
1303             counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
1304                               [ref0 != GOLDEN_FRAME]++;
1305         }
1306       }
1307     }
1308     if (inter_block &&
1309         !vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
1310       const int mode_ctx = mbmi->mode_context[mbmi->ref_frame[0]];
1311       if (bsize >= BLOCK_8X8) {
1312         const PREDICTION_MODE mode = mbmi->mode;
1313         ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
1314       } else {
1315         const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
1316         const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
1317         int idx, idy;
1318         for (idy = 0; idy < 2; idy += num_4x4_h) {
1319           for (idx = 0; idx < 2; idx += num_4x4_w) {
1320             const int j = idy * 2 + idx;
1321             const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
1322             ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
1323           }
1324         }
1325       }
1326     }
1327   }
1328 }
1329
1330 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
1331                             ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
1332                             ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
1333                             PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
1334                             BLOCK_SIZE bsize) {
1335   MACROBLOCKD *const xd = &x->e_mbd;
1336   int p;
1337   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1338   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1339   int mi_width = num_8x8_blocks_wide_lookup[bsize];
1340   int mi_height = num_8x8_blocks_high_lookup[bsize];
1341   for (p = 0; p < MAX_MB_PLANE; p++) {
1342     vpx_memcpy(
1343         xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
1344         a + num_4x4_blocks_wide * p,
1345         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
1346         xd->plane[p].subsampling_x);
1347     vpx_memcpy(
1348         xd->left_context[p]
1349             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
1350         l + num_4x4_blocks_high * p,
1351         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
1352         xd->plane[p].subsampling_y);
1353   }
1354   vpx_memcpy(xd->above_seg_context + mi_col, sa,
1355              sizeof(*xd->above_seg_context) * mi_width);
1356   vpx_memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
1357              sizeof(xd->left_seg_context[0]) * mi_height);
1358 }
1359
1360 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
1361                          ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
1362                          ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
1363                          PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
1364                          BLOCK_SIZE bsize) {
1365   const MACROBLOCKD *const xd = &x->e_mbd;
1366   int p;
1367   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1368   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1369   int mi_width = num_8x8_blocks_wide_lookup[bsize];
1370   int mi_height = num_8x8_blocks_high_lookup[bsize];
1371
1372   // buffer the above/left context information of the block in search.
1373   for (p = 0; p < MAX_MB_PLANE; ++p) {
1374     vpx_memcpy(
1375         a + num_4x4_blocks_wide * p,
1376         xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
1377         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
1378         xd->plane[p].subsampling_x);
1379     vpx_memcpy(
1380         l + num_4x4_blocks_high * p,
1381         xd->left_context[p]
1382             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
1383         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
1384         xd->plane[p].subsampling_y);
1385   }
1386   vpx_memcpy(sa, xd->above_seg_context + mi_col,
1387              sizeof(*xd->above_seg_context) * mi_width);
1388   vpx_memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
1389              sizeof(xd->left_seg_context[0]) * mi_height);
1390 }
1391
1392 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile,
1393                      ThreadData *td,
1394                      TOKENEXTRA **tp, int mi_row, int mi_col,
1395                      int output_enabled, BLOCK_SIZE bsize,
1396                      PICK_MODE_CONTEXT *ctx) {
1397   MACROBLOCK *const x = &td->mb;
1398   set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
1399   update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
1400   encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
1401
1402   if (output_enabled) {
1403     update_stats(&cpi->common, td);
1404
1405     (*tp)->token = EOSB_TOKEN;
1406     (*tp)++;
1407   }
1408 }
1409
1410 static void encode_sb(VP9_COMP *cpi, ThreadData *td,
1411                       const TileInfo *const tile,
1412                       TOKENEXTRA **tp, int mi_row, int mi_col,
1413                       int output_enabled, BLOCK_SIZE bsize,
1414                       PC_TREE *pc_tree) {
1415   VP9_COMMON *const cm = &cpi->common;
1416   MACROBLOCK *const x = &td->mb;
1417   MACROBLOCKD *const xd = &x->e_mbd;
1418
1419   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
1420   int ctx;
1421   PARTITION_TYPE partition;
1422   BLOCK_SIZE subsize = bsize;
1423
1424   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1425     return;
1426
1427   if (bsize >= BLOCK_8X8) {
1428     ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
1429     subsize = get_subsize(bsize, pc_tree->partitioning);
1430   } else {
1431     ctx = 0;
1432     subsize = BLOCK_4X4;
1433   }
1434
1435   partition = partition_lookup[bsl][subsize];
1436   if (output_enabled && bsize != BLOCK_4X4)
1437     td->counts->partition[ctx][partition]++;
1438
1439   switch (partition) {
1440     case PARTITION_NONE:
1441       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1442                &pc_tree->none);
1443       break;
1444     case PARTITION_VERT:
1445       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1446                &pc_tree->vertical[0]);
1447       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
1448         encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
1449                  subsize, &pc_tree->vertical[1]);
1450       }
1451       break;
1452     case PARTITION_HORZ:
1453       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1454                &pc_tree->horizontal[0]);
1455       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
1456         encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
1457                  subsize, &pc_tree->horizontal[1]);
1458       }
1459       break;
1460     case PARTITION_SPLIT:
1461       if (bsize == BLOCK_8X8) {
1462         encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1463                  pc_tree->leaf_split[0]);
1464       } else {
1465         encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1466                   pc_tree->split[0]);
1467         encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1468                   subsize, pc_tree->split[1]);
1469         encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1470                   subsize, pc_tree->split[2]);
1471         encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
1472                   subsize, pc_tree->split[3]);
1473       }
1474       break;
1475     default:
1476       assert(0 && "Invalid partition type.");
1477       break;
1478   }
1479
1480   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
1481     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
1482 }
1483
1484 // Check to see if the given partition size is allowed for a specified number
1485 // of 8x8 block rows and columns remaining in the image.
1486 // If not then return the largest allowed partition size
1487 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize,
1488                                       int rows_left, int cols_left,
1489                                       int *bh, int *bw) {
1490   if (rows_left <= 0 || cols_left <= 0) {
1491     return MIN(bsize, BLOCK_8X8);
1492   } else {
1493     for (; bsize > 0; bsize -= 3) {
1494       *bh = num_8x8_blocks_high_lookup[bsize];
1495       *bw = num_8x8_blocks_wide_lookup[bsize];
1496       if ((*bh <= rows_left) && (*bw <= cols_left)) {
1497         break;
1498       }
1499     }
1500   }
1501   return bsize;
1502 }
1503
1504 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis,
1505     int bh_in, int bw_in, int row8x8_remaining, int col8x8_remaining,
1506     BLOCK_SIZE bsize, MODE_INFO **mi_8x8) {
1507   int bh = bh_in;
1508   int r, c;
1509   for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
1510     int bw = bw_in;
1511     for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
1512       const int index = r * mis + c;
1513       mi_8x8[index] = mi + index;
1514       mi_8x8[index]->mbmi.sb_type = find_partition_size(bsize,
1515           row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
1516     }
1517   }
1518 }
1519
1520 // This function attempts to set all mode info entries in a given SB64
1521 // to the same block partition size.
1522 // However, at the bottom and right borders of the image the requested size
1523 // may not be allowed in which case this code attempts to choose the largest
1524 // allowable partition.
1525 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1526                                    MODE_INFO **mi_8x8, int mi_row, int mi_col,
1527                                    BLOCK_SIZE bsize) {
1528   VP9_COMMON *const cm = &cpi->common;
1529   const int mis = cm->mi_stride;
1530   const int row8x8_remaining = tile->mi_row_end - mi_row;
1531   const int col8x8_remaining = tile->mi_col_end - mi_col;
1532   int block_row, block_col;
1533   MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
1534   int bh = num_8x8_blocks_high_lookup[bsize];
1535   int bw = num_8x8_blocks_wide_lookup[bsize];
1536
1537   assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
1538
1539   // Apply the requested partition size to the SB64 if it is all "in image"
1540   if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
1541       (row8x8_remaining >= MI_BLOCK_SIZE)) {
1542     for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
1543       for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
1544         int index = block_row * mis + block_col;
1545         mi_8x8[index] = mi_upper_left + index;
1546         mi_8x8[index]->mbmi.sb_type = bsize;
1547       }
1548     }
1549   } else {
1550     // Else this is a partial SB64.
1551     set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
1552         col8x8_remaining, bsize, mi_8x8);
1553   }
1554 }
1555
1556 const struct {
1557   int row;
1558   int col;
1559 } coord_lookup[16] = {
1560     // 32x32 index = 0
1561     {0, 0}, {0, 2}, {2, 0}, {2, 2},
1562     // 32x32 index = 1
1563     {0, 4}, {0, 6}, {2, 4}, {2, 6},
1564     // 32x32 index = 2
1565     {4, 0}, {4, 2}, {6, 0}, {6, 2},
1566     // 32x32 index = 3
1567     {4, 4}, {4, 6}, {6, 4}, {6, 6},
1568 };
1569
1570 static void set_source_var_based_partition(VP9_COMP *cpi,
1571                                            const TileInfo *const tile,
1572                                            MACROBLOCK *const x,
1573                                            MODE_INFO **mi_8x8,
1574                                            int mi_row, int mi_col) {
1575   VP9_COMMON *const cm = &cpi->common;
1576   const int mis = cm->mi_stride;
1577   const int row8x8_remaining = tile->mi_row_end - mi_row;
1578   const int col8x8_remaining = tile->mi_col_end - mi_col;
1579   MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
1580
1581   vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
1582
1583   assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
1584
1585   // In-image SB64
1586   if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
1587       (row8x8_remaining >= MI_BLOCK_SIZE)) {
1588     int i, j;
1589     int index;
1590     diff d32[4];
1591     const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
1592     int is_larger_better = 0;
1593     int use32x32 = 0;
1594     unsigned int thr = cpi->source_var_thresh;
1595
1596     vpx_memset(d32, 0, 4 * sizeof(diff));
1597
1598     for (i = 0; i < 4; i++) {
1599       diff *d16[4];
1600
1601       for (j = 0; j < 4; j++) {
1602         int b_mi_row = coord_lookup[i * 4 + j].row;
1603         int b_mi_col = coord_lookup[i * 4 + j].col;
1604         int boffset = b_mi_row / 2 * cm->mb_cols +
1605                       b_mi_col / 2;
1606
1607         d16[j] = cpi->source_diff_var + offset + boffset;
1608
1609         index = b_mi_row * mis + b_mi_col;
1610         mi_8x8[index] = mi_upper_left + index;
1611         mi_8x8[index]->mbmi.sb_type = BLOCK_16X16;
1612
1613         // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
1614         // size to further improve quality.
1615       }
1616
1617       is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
1618           (d16[2]->var < thr) && (d16[3]->var < thr);
1619
1620       // Use 32x32 partition
1621       if (is_larger_better) {
1622         use32x32 += 1;
1623
1624         for (j = 0; j < 4; j++) {
1625           d32[i].sse += d16[j]->sse;
1626           d32[i].sum += d16[j]->sum;
1627         }
1628
1629         d32[i].var = d32[i].sse - (((int64_t)d32[i].sum * d32[i].sum) >> 10);
1630
1631         index = coord_lookup[i*4].row * mis + coord_lookup[i*4].col;
1632         mi_8x8[index] = mi_upper_left + index;
1633         mi_8x8[index]->mbmi.sb_type = BLOCK_32X32;
1634       }
1635     }
1636
1637     if (use32x32 == 4) {
1638       thr <<= 1;
1639       is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
1640           (d32[2].var < thr) && (d32[3].var < thr);
1641
1642       // Use 64x64 partition
1643       if (is_larger_better) {
1644         mi_8x8[0] = mi_upper_left;
1645         mi_8x8[0]->mbmi.sb_type = BLOCK_64X64;
1646       }
1647     }
1648   } else {   // partial in-image SB64
1649     int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
1650     int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
1651     set_partial_b64x64_partition(mi_upper_left, mis, bh, bw,
1652         row8x8_remaining, col8x8_remaining, BLOCK_16X16, mi_8x8);
1653   }
1654 }
1655
1656 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
1657                             PICK_MODE_CONTEXT *ctx,
1658                             int mi_row, int mi_col, int bsize) {
1659   VP9_COMMON *const cm = &cpi->common;
1660   MACROBLOCK *const x = &td->mb;
1661   MACROBLOCKD *const xd = &x->e_mbd;
1662   MODE_INFO *const mi = xd->mi[0];
1663   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
1664   const struct segmentation *const seg = &cm->seg;
1665   const int bw = num_8x8_blocks_wide_lookup[mi->mbmi.sb_type];
1666   const int bh = num_8x8_blocks_high_lookup[mi->mbmi.sb_type];
1667   const int x_mis = MIN(bw, cm->mi_cols - mi_col);
1668   const int y_mis = MIN(bh, cm->mi_rows - mi_row);
1669
1670   *(xd->mi[0]) = ctx->mic;
1671
1672   if (seg->enabled && cpi->oxcf.aq_mode) {
1673     // For in frame complexity AQ or variance AQ, copy segment_id from
1674     // segmentation_map.
1675     if (cpi->oxcf.aq_mode == COMPLEXITY_AQ ||
1676         cpi->oxcf.aq_mode == VARIANCE_AQ ) {
1677       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
1678                                                  : cm->last_frame_seg_map;
1679       mbmi->segment_id = vp9_get_segment_id(cm, map, bsize, mi_row, mi_col);
1680     } else {
1681     // Setting segmentation map for cyclic_refresh.
1682       vp9_cyclic_refresh_update_segment(cpi, mbmi, mi_row, mi_col, bsize,
1683                                         ctx->rate, ctx->dist, x->skip);
1684     }
1685     vp9_init_plane_quantizers(cpi, x);
1686   }
1687
1688   if (is_inter_block(mbmi)) {
1689     vp9_update_mv_count(td);
1690     if (cm->interp_filter == SWITCHABLE) {
1691       const int pred_ctx = vp9_get_pred_context_switchable_interp(xd);
1692       ++td->counts->switchable_interp[pred_ctx][mbmi->interp_filter];
1693     }
1694
1695     if (mbmi->sb_type < BLOCK_8X8) {
1696       mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1697       mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1698     }
1699   }
1700
1701   if (cm->use_prev_frame_mvs) {
1702     MV_REF *const frame_mvs =
1703         cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1704     int w, h;
1705
1706     for (h = 0; h < y_mis; ++h) {
1707       MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1708       for (w = 0; w < x_mis; ++w) {
1709         MV_REF *const mv = frame_mv + w;
1710         mv->ref_frame[0] = mi->mbmi.ref_frame[0];
1711         mv->ref_frame[1] = mi->mbmi.ref_frame[1];
1712         mv->mv[0].as_int = mi->mbmi.mv[0].as_int;
1713         mv->mv[1].as_int = mi->mbmi.mv[1].as_int;
1714       }
1715     }
1716   }
1717
1718   x->skip = ctx->skip;
1719   x->skip_txfm[0] = mbmi->segment_id ? 0 : ctx->skip_txfm[0];
1720 }
1721
1722 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
1723                         const TileInfo *const tile,
1724                         TOKENEXTRA **tp, int mi_row, int mi_col,
1725                         int output_enabled, BLOCK_SIZE bsize,
1726                         PICK_MODE_CONTEXT *ctx) {
1727   MACROBLOCK *const x = &td->mb;
1728   set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
1729   update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
1730
1731 #if CONFIG_VP9_TEMPORAL_DENOISING
1732   if (cpi->oxcf.noise_sensitivity > 0 && output_enabled &&
1733       cpi->common.frame_type != KEY_FRAME) {
1734     vp9_denoiser_denoise(&cpi->denoiser, x, mi_row, mi_col,
1735                          MAX(BLOCK_8X8, bsize), ctx);
1736   }
1737 #endif
1738
1739   encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
1740   update_stats(&cpi->common, td);
1741
1742   (*tp)->token = EOSB_TOKEN;
1743   (*tp)++;
1744 }
1745
1746 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
1747                          const TileInfo *const tile,
1748                          TOKENEXTRA **tp, int mi_row, int mi_col,
1749                          int output_enabled, BLOCK_SIZE bsize,
1750                          PC_TREE *pc_tree) {
1751   VP9_COMMON *const cm = &cpi->common;
1752   MACROBLOCK *const x = &td->mb;
1753   MACROBLOCKD *const xd = &x->e_mbd;
1754
1755   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
1756   int ctx;
1757   PARTITION_TYPE partition;
1758   BLOCK_SIZE subsize;
1759
1760   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1761     return;
1762
1763   if (bsize >= BLOCK_8X8) {
1764     const int idx_str = xd->mi_stride * mi_row + mi_col;
1765     MODE_INFO ** mi_8x8 = cm->mi_grid_visible + idx_str;
1766     ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
1767     subsize = mi_8x8[0]->mbmi.sb_type;
1768   } else {
1769     ctx = 0;
1770     subsize = BLOCK_4X4;
1771   }
1772
1773   partition = partition_lookup[bsl][subsize];
1774   if (output_enabled && bsize != BLOCK_4X4)
1775     td->counts->partition[ctx][partition]++;
1776
1777   switch (partition) {
1778     case PARTITION_NONE:
1779       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1780                   &pc_tree->none);
1781       break;
1782     case PARTITION_VERT:
1783       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1784                   &pc_tree->vertical[0]);
1785       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
1786         encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1787                     subsize, &pc_tree->vertical[1]);
1788       }
1789       break;
1790     case PARTITION_HORZ:
1791       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1792                   &pc_tree->horizontal[0]);
1793       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
1794         encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1795                     subsize, &pc_tree->horizontal[1]);
1796       }
1797       break;
1798     case PARTITION_SPLIT:
1799       subsize = get_subsize(bsize, PARTITION_SPLIT);
1800       encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1801                    pc_tree->split[0]);
1802       encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1803                    subsize, pc_tree->split[1]);
1804       encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1805                    subsize, pc_tree->split[2]);
1806       encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
1807                    output_enabled, subsize, pc_tree->split[3]);
1808       break;
1809     default:
1810       assert(0 && "Invalid partition type.");
1811       break;
1812   }
1813
1814   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
1815     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
1816 }
1817
1818 static void rd_use_partition(VP9_COMP *cpi,
1819                              ThreadData *td,
1820                              TileDataEnc *tile_data,
1821                              MODE_INFO **mi_8x8, TOKENEXTRA **tp,
1822                              int mi_row, int mi_col,
1823                              BLOCK_SIZE bsize,
1824                              int *rate, int64_t *dist,
1825                              int do_recon, PC_TREE *pc_tree) {
1826   VP9_COMMON *const cm = &cpi->common;
1827   TileInfo *const tile_info = &tile_data->tile_info;
1828   MACROBLOCK *const x = &td->mb;
1829   MACROBLOCKD *const xd = &x->e_mbd;
1830   const int mis = cm->mi_stride;
1831   const int bsl = b_width_log2_lookup[bsize];
1832   const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
1833   const int bss = (1 << bsl) / 4;
1834   int i, pl;
1835   PARTITION_TYPE partition = PARTITION_NONE;
1836   BLOCK_SIZE subsize;
1837   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1838   PARTITION_CONTEXT sl[8], sa[8];
1839   RD_COST last_part_rdc, none_rdc, chosen_rdc;
1840   BLOCK_SIZE sub_subsize = BLOCK_4X4;
1841   int splits_below = 0;
1842   BLOCK_SIZE bs_type = mi_8x8[0]->mbmi.sb_type;
1843   int do_partition_search = 1;
1844   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
1845
1846   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1847     return;
1848
1849   assert(num_4x4_blocks_wide_lookup[bsize] ==
1850          num_4x4_blocks_high_lookup[bsize]);
1851
1852   vp9_rd_cost_reset(&last_part_rdc);
1853   vp9_rd_cost_reset(&none_rdc);
1854   vp9_rd_cost_reset(&chosen_rdc);
1855
1856   partition = partition_lookup[bsl][bs_type];
1857   subsize = get_subsize(bsize, partition);
1858
1859   pc_tree->partitioning = partition;
1860   save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1861
1862   if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode) {
1863     set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1864     x->mb_energy = vp9_block_energy(cpi, x, bsize);
1865   }
1866
1867   if (do_partition_search &&
1868       cpi->sf.partition_search_type == SEARCH_PARTITION &&
1869       cpi->sf.adjust_partitioning_from_last_frame) {
1870     // Check if any of the sub blocks are further split.
1871     if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
1872       sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
1873       splits_below = 1;
1874       for (i = 0; i < 4; i++) {
1875         int jj = i >> 1, ii = i & 0x01;
1876         MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
1877         if (this_mi && this_mi->mbmi.sb_type >= sub_subsize) {
1878           splits_below = 0;
1879         }
1880       }
1881     }
1882
1883     // If partition is not none try none unless each of the 4 splits are split
1884     // even further..
1885     if (partition != PARTITION_NONE && !splits_below &&
1886         mi_row + (mi_step >> 1) < cm->mi_rows &&
1887         mi_col + (mi_step >> 1) < cm->mi_cols) {
1888       pc_tree->partitioning = PARTITION_NONE;
1889       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize,
1890                        ctx, INT64_MAX);
1891
1892       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
1893
1894       if (none_rdc.rate < INT_MAX) {
1895         none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
1896         none_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, none_rdc.rate,
1897                                  none_rdc.dist);
1898       }
1899
1900       restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1901       mi_8x8[0]->mbmi.sb_type = bs_type;
1902       pc_tree->partitioning = partition;
1903     }
1904   }
1905
1906   switch (partition) {
1907     case PARTITION_NONE:
1908       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1909                        bsize, ctx, INT64_MAX);
1910       break;
1911     case PARTITION_HORZ:
1912       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1913                        subsize, &pc_tree->horizontal[0],
1914                        INT64_MAX);
1915       if (last_part_rdc.rate != INT_MAX &&
1916           bsize >= BLOCK_8X8 && mi_row + (mi_step >> 1) < cm->mi_rows) {
1917         RD_COST tmp_rdc;
1918         PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
1919         vp9_rd_cost_init(&tmp_rdc);
1920         update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
1921         encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
1922         rd_pick_sb_modes(cpi, tile_data, x,
1923                          mi_row + (mi_step >> 1), mi_col, &tmp_rdc,
1924                          subsize, &pc_tree->horizontal[1], INT64_MAX);
1925         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1926           vp9_rd_cost_reset(&last_part_rdc);
1927           break;
1928         }
1929         last_part_rdc.rate += tmp_rdc.rate;
1930         last_part_rdc.dist += tmp_rdc.dist;
1931         last_part_rdc.rdcost += tmp_rdc.rdcost;
1932       }
1933       break;
1934     case PARTITION_VERT:
1935       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1936                        subsize, &pc_tree->vertical[0], INT64_MAX);
1937       if (last_part_rdc.rate != INT_MAX &&
1938           bsize >= BLOCK_8X8 && mi_col + (mi_step >> 1) < cm->mi_cols) {
1939         RD_COST tmp_rdc;
1940         PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
1941         vp9_rd_cost_init(&tmp_rdc);
1942         update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
1943         encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
1944         rd_pick_sb_modes(cpi, tile_data, x,
1945                          mi_row, mi_col + (mi_step >> 1), &tmp_rdc,
1946                          subsize, &pc_tree->vertical[bsize > BLOCK_8X8],
1947                          INT64_MAX);
1948         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1949           vp9_rd_cost_reset(&last_part_rdc);
1950           break;
1951         }
1952         last_part_rdc.rate += tmp_rdc.rate;
1953         last_part_rdc.dist += tmp_rdc.dist;
1954         last_part_rdc.rdcost += tmp_rdc.rdcost;
1955       }
1956       break;
1957     case PARTITION_SPLIT:
1958       if (bsize == BLOCK_8X8) {
1959         rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1960                          subsize, pc_tree->leaf_split[0], INT64_MAX);
1961         break;
1962       }
1963       last_part_rdc.rate = 0;
1964       last_part_rdc.dist = 0;
1965       last_part_rdc.rdcost = 0;
1966       for (i = 0; i < 4; i++) {
1967         int x_idx = (i & 1) * (mi_step >> 1);
1968         int y_idx = (i >> 1) * (mi_step >> 1);
1969         int jj = i >> 1, ii = i & 0x01;
1970         RD_COST tmp_rdc;
1971         if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
1972           continue;
1973
1974         vp9_rd_cost_init(&tmp_rdc);
1975         rd_use_partition(cpi, td, tile_data,
1976                          mi_8x8 + jj * bss * mis + ii * bss, tp,
1977                          mi_row + y_idx, mi_col + x_idx, subsize,
1978                          &tmp_rdc.rate, &tmp_rdc.dist,
1979                          i != 3, pc_tree->split[i]);
1980         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1981           vp9_rd_cost_reset(&last_part_rdc);
1982           break;
1983         }
1984         last_part_rdc.rate += tmp_rdc.rate;
1985         last_part_rdc.dist += tmp_rdc.dist;
1986       }
1987       break;
1988     default:
1989       assert(0);
1990       break;
1991   }
1992
1993   pl = partition_plane_context(xd, mi_row, mi_col, bsize);
1994   if (last_part_rdc.rate < INT_MAX) {
1995     last_part_rdc.rate += cpi->partition_cost[pl][partition];
1996     last_part_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
1997                                   last_part_rdc.rate, last_part_rdc.dist);
1998   }
1999
2000   if (do_partition_search
2001       && cpi->sf.adjust_partitioning_from_last_frame
2002       && cpi->sf.partition_search_type == SEARCH_PARTITION
2003       && partition != PARTITION_SPLIT && bsize > BLOCK_8X8
2004       && (mi_row + mi_step < cm->mi_rows ||
2005           mi_row + (mi_step >> 1) == cm->mi_rows)
2006       && (mi_col + mi_step < cm->mi_cols ||
2007           mi_col + (mi_step >> 1) == cm->mi_cols)) {
2008     BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2009     chosen_rdc.rate = 0;
2010     chosen_rdc.dist = 0;
2011     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2012     pc_tree->partitioning = PARTITION_SPLIT;
2013
2014     // Split partition.
2015     for (i = 0; i < 4; i++) {
2016       int x_idx = (i & 1) * (mi_step >> 1);
2017       int y_idx = (i >> 1) * (mi_step >> 1);
2018       RD_COST tmp_rdc;
2019       ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2020       PARTITION_CONTEXT sl[8], sa[8];
2021
2022       if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2023         continue;
2024
2025       save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2026       pc_tree->split[i]->partitioning = PARTITION_NONE;
2027       rd_pick_sb_modes(cpi, tile_data, x,
2028                        mi_row + y_idx, mi_col + x_idx, &tmp_rdc,
2029                        split_subsize, &pc_tree->split[i]->none, INT64_MAX);
2030
2031       restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2032
2033       if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2034         vp9_rd_cost_reset(&chosen_rdc);
2035         break;
2036       }
2037
2038       chosen_rdc.rate += tmp_rdc.rate;
2039       chosen_rdc.dist += tmp_rdc.dist;
2040
2041       if (i != 3)
2042         encode_sb(cpi, td, tile_info, tp,  mi_row + y_idx, mi_col + x_idx, 0,
2043                   split_subsize, pc_tree->split[i]);
2044
2045       pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2046                                    split_subsize);
2047       chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2048     }
2049     pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2050     if (chosen_rdc.rate < INT_MAX) {
2051       chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2052       chosen_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2053                                  chosen_rdc.rate, chosen_rdc.dist);
2054     }
2055   }
2056
2057   // If last_part is better set the partitioning to that.
2058   if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2059     mi_8x8[0]->mbmi.sb_type = bsize;
2060     if (bsize >= BLOCK_8X8)
2061       pc_tree->partitioning = partition;
2062     chosen_rdc = last_part_rdc;
2063   }
2064   // If none was better set the partitioning to that.
2065   if (none_rdc.rdcost < chosen_rdc.rdcost) {
2066     if (bsize >= BLOCK_8X8)
2067       pc_tree->partitioning = PARTITION_NONE;
2068     chosen_rdc = none_rdc;
2069   }
2070
2071   restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2072
2073   // We must have chosen a partitioning and encoding or we'll fail later on.
2074   // No other opportunities for success.
2075   if (bsize == BLOCK_64X64)
2076     assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2077
2078   if (do_recon) {
2079     int output_enabled = (bsize == BLOCK_64X64);
2080     encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2081               pc_tree);
2082   }
2083
2084   *rate = chosen_rdc.rate;
2085   *dist = chosen_rdc.dist;
2086 }
2087
2088 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2089   BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,
2090   BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,
2091   BLOCK_8X8,   BLOCK_8X8,   BLOCK_8X8,
2092   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
2093   BLOCK_16X16
2094 };
2095
2096 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2097   BLOCK_8X8,   BLOCK_16X16, BLOCK_16X16,
2098   BLOCK_16X16, BLOCK_32X32, BLOCK_32X32,
2099   BLOCK_32X32, BLOCK_64X64, BLOCK_64X64,
2100   BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2101   BLOCK_64X64
2102 };
2103
2104 // Look at all the mode_info entries for blocks that are part of this
2105 // partition and find the min and max values for sb_type.
2106 // At the moment this is designed to work on a 64x64 SB but could be
2107 // adjusted to use a size parameter.
2108 //
2109 // The min and max are assumed to have been initialized prior to calling this
2110 // function so repeat calls can accumulate a min and max of more than one sb64.
2111 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2112                                         BLOCK_SIZE *min_block_size,
2113                                         BLOCK_SIZE *max_block_size,
2114                                         int bs_hist[BLOCK_SIZES]) {
2115   int sb_width_in_blocks = MI_BLOCK_SIZE;
2116   int sb_height_in_blocks  = MI_BLOCK_SIZE;
2117   int i, j;
2118   int index = 0;
2119
2120   // Check the sb_type for each block that belongs to this region.
2121   for (i = 0; i < sb_height_in_blocks; ++i) {
2122     for (j = 0; j < sb_width_in_blocks; ++j) {
2123       MODE_INFO *mi = mi_8x8[index+j];
2124       BLOCK_SIZE sb_type = mi ? mi->mbmi.sb_type : 0;
2125       bs_hist[sb_type]++;
2126       *min_block_size = MIN(*min_block_size, sb_type);
2127       *max_block_size = MAX(*max_block_size, sb_type);
2128     }
2129     index += xd->mi_stride;
2130   }
2131 }
2132
2133 // Next square block size less or equal than current block size.
2134 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2135   BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2136   BLOCK_8X8, BLOCK_8X8, BLOCK_8X8,
2137   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
2138   BLOCK_32X32, BLOCK_32X32, BLOCK_32X32,
2139   BLOCK_64X64
2140 };
2141
2142 // Look at neighboring blocks and set a min and max partition size based on
2143 // what they chose.
2144 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2145                                     MACROBLOCKD *const xd,
2146                                     int mi_row, int mi_col,
2147                                     BLOCK_SIZE *min_block_size,
2148                                     BLOCK_SIZE *max_block_size) {
2149   VP9_COMMON *const cm = &cpi->common;
2150   MODE_INFO **mi = xd->mi;
2151   const int left_in_image = xd->left_available && mi[-1];
2152   const int above_in_image = xd->up_available && mi[-xd->mi_stride];
2153   const int row8x8_remaining = tile->mi_row_end - mi_row;
2154   const int col8x8_remaining = tile->mi_col_end - mi_col;
2155   int bh, bw;
2156   BLOCK_SIZE min_size = BLOCK_4X4;
2157   BLOCK_SIZE max_size = BLOCK_64X64;
2158   int i = 0;
2159   int bs_hist[BLOCK_SIZES] = {0};
2160
2161   // Trap case where we do not have a prediction.
2162   if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2163     // Default "min to max" and "max to min"
2164     min_size = BLOCK_64X64;
2165     max_size = BLOCK_4X4;
2166
2167     // NOTE: each call to get_sb_partition_size_range() uses the previous
2168     // passed in values for min and max as a starting point.
2169     // Find the min and max partition used in previous frame at this location
2170     if (cm->frame_type != KEY_FRAME) {
2171       MODE_INFO **prev_mi =
2172           &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2173       get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2174     }
2175     // Find the min and max partition sizes used in the left SB64
2176     if (left_in_image) {
2177       MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2178       get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2179                                   bs_hist);
2180     }
2181     // Find the min and max partition sizes used in the above SB64.
2182     if (above_in_image) {
2183       MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2184       get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2185                                   bs_hist);
2186     }
2187
2188     // adjust observed min and max
2189     if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2190       min_size = min_partition_size[min_size];
2191       max_size = max_partition_size[max_size];
2192     } else if (cpi->sf.auto_min_max_partition_size ==
2193                CONSTRAIN_NEIGHBORING_MIN_MAX) {
2194       // adjust the search range based on the histogram of the observed
2195       // partition sizes from left, above the previous co-located blocks
2196       int sum = 0;
2197       int first_moment = 0;
2198       int second_moment = 0;
2199       int var_unnormalized = 0;
2200
2201       for (i = 0; i < BLOCK_SIZES; i++) {
2202         sum += bs_hist[i];
2203         first_moment += bs_hist[i] * i;
2204         second_moment += bs_hist[i] * i * i;
2205       }
2206
2207       // if variance is small enough,
2208       // adjust the range around its mean size, which gives a tighter range
2209       var_unnormalized = second_moment - first_moment * first_moment / sum;
2210       if (var_unnormalized <= 4 * sum) {
2211         int mean = first_moment / sum;
2212         min_size = min_partition_size[mean];
2213         max_size = max_partition_size[mean];
2214       } else {
2215         min_size = min_partition_size[min_size];
2216         max_size = max_partition_size[max_size];
2217       }
2218     }
2219   }
2220
2221   // Check border cases where max and min from neighbors may not be legal.
2222   max_size = find_partition_size(max_size,
2223                                  row8x8_remaining, col8x8_remaining,
2224                                  &bh, &bw);
2225   min_size = MIN(min_size, max_size);
2226
2227   // When use_square_partition_only is true, make sure at least one square
2228   // partition is allowed by selecting the next smaller square size as
2229   // *min_block_size.
2230   if (cpi->sf.use_square_partition_only &&
2231       next_square_size[max_size] < min_size) {
2232      min_size = next_square_size[max_size];
2233   }
2234
2235   *min_block_size = min_size;
2236   *max_block_size = max_size;
2237 }
2238
2239 static void auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2240                                  MACROBLOCKD *const xd,
2241                                  int mi_row, int mi_col,
2242                                  BLOCK_SIZE *min_block_size,
2243                                  BLOCK_SIZE *max_block_size) {
2244   VP9_COMMON *const cm = &cpi->common;
2245   MODE_INFO **mi_8x8 = xd->mi;
2246   const int left_in_image = xd->left_available && mi_8x8[-1];
2247   const int above_in_image = xd->up_available && mi_8x8[-xd->mi_stride];
2248   int row8x8_remaining = tile->mi_row_end - mi_row;
2249   int col8x8_remaining = tile->mi_col_end - mi_col;
2250   int bh, bw;
2251   BLOCK_SIZE min_size = BLOCK_32X32;
2252   BLOCK_SIZE max_size = BLOCK_8X8;
2253   int bsl = mi_width_log2_lookup[BLOCK_64X64];
2254   const int search_range_ctrl = (((mi_row + mi_col) >> bsl) +
2255                        get_chessboard_index(cm->current_video_frame)) & 0x1;
2256   // Trap case where we do not have a prediction.
2257   if (search_range_ctrl &&
2258       (left_in_image || above_in_image || cm->frame_type != KEY_FRAME)) {
2259     int block;
2260     MODE_INFO **mi;
2261     BLOCK_SIZE sb_type;
2262
2263     // Find the min and max partition sizes used in the left SB64.
2264     if (left_in_image) {
2265       MODE_INFO *cur_mi;
2266       mi = &mi_8x8[-1];
2267       for (block = 0; block < MI_BLOCK_SIZE; ++block) {
2268         cur_mi = mi[block * xd->mi_stride];
2269         sb_type = cur_mi ? cur_mi->mbmi.sb_type : 0;
2270         min_size = MIN(min_size, sb_type);
2271         max_size = MAX(max_size, sb_type);
2272       }
2273     }
2274     // Find the min and max partition sizes used in the above SB64.
2275     if (above_in_image) {
2276       mi = &mi_8x8[-xd->mi_stride * MI_BLOCK_SIZE];
2277       for (block = 0; block < MI_BLOCK_SIZE; ++block) {
2278         sb_type = mi[block] ? mi[block]->mbmi.sb_type : 0;
2279         min_size = MIN(min_size, sb_type);
2280         max_size = MAX(max_size, sb_type);
2281       }
2282     }
2283
2284     min_size = min_partition_size[min_size];
2285     max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
2286                                    &bh, &bw);
2287     min_size = MIN(min_size, max_size);
2288     min_size = MAX(min_size, BLOCK_8X8);
2289     max_size = MIN(max_size, BLOCK_32X32);
2290   } else {
2291     min_size = BLOCK_8X8;
2292     max_size = BLOCK_32X32;
2293   }
2294
2295   *min_block_size = min_size;
2296   *max_block_size = max_size;
2297 }
2298
2299 // TODO(jingning) refactor functions setting partition search range
2300 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd,
2301                                 int mi_row, int mi_col, BLOCK_SIZE bsize,
2302                                 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
2303   int mi_width  = num_8x8_blocks_wide_lookup[bsize];
2304   int mi_height = num_8x8_blocks_high_lookup[bsize];
2305   int idx, idy;
2306
2307   MODE_INFO *mi;
2308   const int idx_str = cm->mi_stride * mi_row + mi_col;
2309   MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
2310   BLOCK_SIZE bs, min_size, max_size;
2311
2312   min_size = BLOCK_64X64;
2313   max_size = BLOCK_4X4;
2314
2315   if (prev_mi) {
2316     for (idy = 0; idy < mi_height; ++idy) {
2317       for (idx = 0; idx < mi_width; ++idx) {
2318         mi = prev_mi[idy * cm->mi_stride + idx];
2319         bs = mi ? mi->mbmi.sb_type : bsize;
2320         min_size = MIN(min_size, bs);
2321         max_size = MAX(max_size, bs);
2322       }
2323     }
2324   }
2325
2326   if (xd->left_available) {
2327     for (idy = 0; idy < mi_height; ++idy) {
2328       mi = xd->mi[idy * cm->mi_stride - 1];
2329       bs = mi ? mi->mbmi.sb_type : bsize;
2330       min_size = MIN(min_size, bs);
2331       max_size = MAX(max_size, bs);
2332     }
2333   }
2334
2335   if (xd->up_available) {
2336     for (idx = 0; idx < mi_width; ++idx) {
2337       mi = xd->mi[idx - cm->mi_stride];
2338       bs = mi ? mi->mbmi.sb_type : bsize;
2339       min_size = MIN(min_size, bs);
2340       max_size = MAX(max_size, bs);
2341     }
2342   }
2343
2344   if (min_size == max_size) {
2345     min_size = min_partition_size[min_size];
2346     max_size = max_partition_size[max_size];
2347   }
2348
2349   *min_bs = min_size;
2350   *max_bs = max_size;
2351 }
2352
2353 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2354   vpx_memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
2355 }
2356
2357 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2358   vpx_memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
2359 }
2360
2361 #if CONFIG_FP_MB_STATS
2362 const int num_16x16_blocks_wide_lookup[BLOCK_SIZES] =
2363   {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 4, 4};
2364 const int num_16x16_blocks_high_lookup[BLOCK_SIZES] =
2365   {1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 4, 2, 4};
2366 const int qindex_skip_threshold_lookup[BLOCK_SIZES] =
2367   {0, 10, 10, 30, 40, 40, 60, 80, 80, 90, 100, 100, 120};
2368 const int qindex_split_threshold_lookup[BLOCK_SIZES] =
2369   {0, 3, 3, 7, 15, 15, 30, 40, 40, 60, 80, 80, 120};
2370 const int complexity_16x16_blocks_threshold[BLOCK_SIZES] =
2371   {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 6};
2372
2373 typedef enum {
2374   MV_ZERO = 0,
2375   MV_LEFT = 1,
2376   MV_UP = 2,
2377   MV_RIGHT = 3,
2378   MV_DOWN = 4,
2379   MV_INVALID
2380 } MOTION_DIRECTION;
2381
2382 static INLINE MOTION_DIRECTION get_motion_direction_fp(uint8_t fp_byte) {
2383   if (fp_byte & FPMB_MOTION_ZERO_MASK) {
2384     return MV_ZERO;
2385   } else if (fp_byte & FPMB_MOTION_LEFT_MASK) {
2386     return MV_LEFT;
2387   } else if (fp_byte & FPMB_MOTION_RIGHT_MASK) {
2388     return MV_RIGHT;
2389   } else if (fp_byte & FPMB_MOTION_UP_MASK) {
2390     return MV_UP;
2391   } else {
2392     return MV_DOWN;
2393   }
2394 }
2395
2396 static INLINE int get_motion_inconsistency(MOTION_DIRECTION this_mv,
2397                                            MOTION_DIRECTION that_mv) {
2398   if (this_mv == that_mv) {
2399     return 0;
2400   } else {
2401     return abs(this_mv - that_mv) == 2 ? 2 : 1;
2402   }
2403 }
2404 #endif
2405
2406 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
2407 // unlikely to be selected depending on previous rate-distortion optimization
2408 // results, for encoding speed-up.
2409 static void rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
2410                               TileDataEnc *tile_data,
2411                               TOKENEXTRA **tp, int mi_row, int mi_col,
2412                               BLOCK_SIZE bsize, RD_COST *rd_cost,
2413                               int64_t best_rd, PC_TREE *pc_tree) {
2414   VP9_COMMON *const cm = &cpi->common;
2415   TileInfo *const tile_info = &tile_data->tile_info;
2416   MACROBLOCK *const x = &td->mb;
2417   MACROBLOCKD *const xd = &x->e_mbd;
2418   const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
2419   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2420   PARTITION_CONTEXT sl[8], sa[8];
2421   TOKENEXTRA *tp_orig = *tp;
2422   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2423   int i, pl;
2424   BLOCK_SIZE subsize;
2425   RD_COST this_rdc, sum_rdc, best_rdc;
2426   int do_split = bsize >= BLOCK_8X8;
2427   int do_rect = 1;
2428
2429   // Override skipping rectangular partition operations for edge blocks
2430   const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
2431   const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
2432   const int xss = x->e_mbd.plane[1].subsampling_x;
2433   const int yss = x->e_mbd.plane[1].subsampling_y;
2434
2435   BLOCK_SIZE min_size = x->min_partition_size;
2436   BLOCK_SIZE max_size = x->max_partition_size;
2437
2438 #if CONFIG_FP_MB_STATS
2439   unsigned int src_diff_var = UINT_MAX;
2440   int none_complexity = 0;
2441 #endif
2442
2443   int partition_none_allowed = !force_horz_split && !force_vert_split;
2444   int partition_horz_allowed = !force_vert_split && yss <= xss &&
2445                                bsize >= BLOCK_8X8;
2446   int partition_vert_allowed = !force_horz_split && xss <= yss &&
2447                                bsize >= BLOCK_8X8;
2448   (void) *tp_orig;
2449
2450   assert(num_8x8_blocks_wide_lookup[bsize] ==
2451              num_8x8_blocks_high_lookup[bsize]);
2452
2453   vp9_rd_cost_init(&this_rdc);
2454   vp9_rd_cost_init(&sum_rdc);
2455   vp9_rd_cost_reset(&best_rdc);
2456   best_rdc.rdcost = best_rd;
2457
2458   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2459
2460   if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode)
2461     x->mb_energy = vp9_block_energy(cpi, x, bsize);
2462
2463   if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
2464     int cb_partition_search_ctrl = ((pc_tree->index == 0 || pc_tree->index == 3)
2465         + get_chessboard_index(cm->current_video_frame)) & 0x1;
2466
2467     if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
2468       set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
2469   }
2470
2471   // Determine partition types in search according to the speed features.
2472   // The threshold set here has to be of square block size.
2473   if (cpi->sf.auto_min_max_partition_size) {
2474     partition_none_allowed &= (bsize <= max_size && bsize >= min_size);
2475     partition_horz_allowed &= ((bsize <= max_size && bsize > min_size) ||
2476                                 force_horz_split);
2477     partition_vert_allowed &= ((bsize <= max_size && bsize > min_size) ||
2478                                 force_vert_split);
2479     do_split &= bsize > min_size;
2480   }
2481   if (cpi->sf.use_square_partition_only) {
2482     partition_horz_allowed &= force_horz_split;
2483     partition_vert_allowed &= force_vert_split;
2484   }
2485
2486   save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2487
2488 #if CONFIG_FP_MB_STATS
2489   if (cpi->use_fp_mb_stats) {
2490     set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2491     src_diff_var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src,
2492                                                   mi_row, mi_col, bsize);
2493   }
2494 #endif
2495
2496 #if CONFIG_FP_MB_STATS
2497   // Decide whether we shall split directly and skip searching NONE by using
2498   // the first pass block statistics
2499   if (cpi->use_fp_mb_stats && bsize >= BLOCK_32X32 && do_split &&
2500       partition_none_allowed && src_diff_var > 4 &&
2501       cm->base_qindex < qindex_split_threshold_lookup[bsize]) {
2502     int mb_row = mi_row >> 1;
2503     int mb_col = mi_col >> 1;
2504     int mb_row_end =
2505         MIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
2506     int mb_col_end =
2507         MIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
2508     int r, c;
2509
2510     // compute a complexity measure, basically measure inconsistency of motion
2511     // vectors obtained from the first pass in the current block
2512     for (r = mb_row; r < mb_row_end ; r++) {
2513       for (c = mb_col; c < mb_col_end; c++) {
2514         const int mb_index = r * cm->mb_cols + c;
2515
2516         MOTION_DIRECTION this_mv;
2517         MOTION_DIRECTION right_mv;
2518         MOTION_DIRECTION bottom_mv;
2519
2520         this_mv =
2521             get_motion_direction_fp(cpi->twopass.this_frame_mb_stats[mb_index]);
2522
2523         // to its right
2524         if (c != mb_col_end - 1) {
2525           right_mv = get_motion_direction_fp(
2526               cpi->twopass.this_frame_mb_stats[mb_index + 1]);
2527           none_complexity += get_motion_inconsistency(this_mv, right_mv);
2528         }
2529
2530         // to its bottom
2531         if (r != mb_row_end - 1) {
2532           bottom_mv = get_motion_direction_fp(
2533               cpi->twopass.this_frame_mb_stats[mb_index + cm->mb_cols]);
2534           none_complexity += get_motion_inconsistency(this_mv, bottom_mv);
2535         }
2536
2537         // do not count its left and top neighbors to avoid double counting
2538       }
2539     }
2540
2541     if (none_complexity > complexity_16x16_blocks_threshold[bsize]) {
2542       partition_none_allowed = 0;
2543     }
2544   }
2545 #endif
2546
2547   // PARTITION_NONE
2548   if (partition_none_allowed) {
2549     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col,
2550                      &this_rdc, bsize, ctx, best_rdc.rdcost);
2551     if (this_rdc.rate != INT_MAX) {
2552       if (bsize >= BLOCK_8X8) {
2553         pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2554         this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2555         this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2556                                  this_rdc.rate, this_rdc.dist);
2557       }
2558
2559       if (this_rdc.rdcost < best_rdc.rdcost) {
2560         int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_dist_thr;
2561         int rate_breakout_thr = cpi->sf.partition_search_breakout_rate_thr;
2562
2563         best_rdc = this_rdc;
2564         if (bsize >= BLOCK_8X8)
2565           pc_tree->partitioning = PARTITION_NONE;
2566
2567         // Adjust dist breakout threshold according to the partition size.
2568         dist_breakout_thr >>= 8 - (b_width_log2_lookup[bsize] +
2569             b_height_log2_lookup[bsize]);
2570
2571         rate_breakout_thr *= num_pels_log2_lookup[bsize];
2572
2573         // If all y, u, v transform blocks in this partition are skippable, and
2574         // the dist & rate are within the thresholds, the partition search is
2575         // terminated for current branch of the partition search tree.
2576         // The dist & rate thresholds are set to 0 at speed 0 to disable the
2577         // early termination at that speed.
2578         if (!x->e_mbd.lossless &&
2579             (ctx->skippable && best_rdc.dist < dist_breakout_thr &&
2580             best_rdc.rate < rate_breakout_thr)) {
2581           do_split = 0;
2582           do_rect = 0;
2583         }
2584
2585 #if CONFIG_FP_MB_STATS
2586         // Check if every 16x16 first pass block statistics has zero
2587         // motion and the corresponding first pass residue is small enough.
2588         // If that is the case, check the difference variance between the
2589         // current frame and the last frame. If the variance is small enough,
2590         // stop further splitting in RD optimization
2591         if (cpi->use_fp_mb_stats && do_split != 0 &&
2592             cm->base_qindex > qindex_skip_threshold_lookup[bsize]) {
2593           int mb_row = mi_row >> 1;
2594           int mb_col = mi_col >> 1;
2595           int mb_row_end =
2596               MIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
2597           int mb_col_end =
2598               MIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
2599           int r, c;
2600
2601           int skip = 1;
2602           for (r = mb_row; r < mb_row_end; r++) {
2603             for (c = mb_col; c < mb_col_end; c++) {
2604               const int mb_index = r * cm->mb_cols + c;
2605               if (!(cpi->twopass.this_frame_mb_stats[mb_index] &
2606                     FPMB_MOTION_ZERO_MASK) ||
2607                   !(cpi->twopass.this_frame_mb_stats[mb_index] &
2608                     FPMB_ERROR_SMALL_MASK)) {
2609                 skip = 0;
2610                 break;
2611               }
2612             }
2613             if (skip == 0) {
2614               break;
2615             }
2616           }
2617           if (skip) {
2618             if (src_diff_var == UINT_MAX) {
2619               set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2620               src_diff_var = get_sby_perpixel_diff_variance(
2621                   cpi, &x->plane[0].src, mi_row, mi_col, bsize);
2622             }
2623             if (src_diff_var < 8) {
2624               do_split = 0;
2625               do_rect = 0;
2626             }
2627           }
2628         }
2629 #endif
2630       }
2631     }
2632     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2633   }
2634
2635   // store estimated motion vector
2636   if (cpi->sf.adaptive_motion_search)
2637     store_pred_mv(x, ctx);
2638
2639   // PARTITION_SPLIT
2640   // TODO(jingning): use the motion vectors given by the above search as
2641   // the starting point of motion search in the following partition type check.
2642   if (do_split) {
2643     subsize = get_subsize(bsize, PARTITION_SPLIT);
2644     if (bsize == BLOCK_8X8) {
2645       i = 4;
2646       if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
2647         pc_tree->leaf_split[0]->pred_interp_filter =
2648             ctx->mic.mbmi.interp_filter;
2649       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2650                        pc_tree->leaf_split[0], best_rdc.rdcost);
2651       if (sum_rdc.rate == INT_MAX)
2652         sum_rdc.rdcost = INT64_MAX;
2653     } else {
2654       for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
2655       const int x_idx = (i & 1) * mi_step;
2656       const int y_idx = (i >> 1) * mi_step;
2657
2658         if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
2659           continue;
2660
2661         if (cpi->sf.adaptive_motion_search)
2662           load_pred_mv(x, ctx);
2663
2664         pc_tree->split[i]->index = i;
2665         rd_pick_partition(cpi, td, tile_data, tp,
2666                           mi_row + y_idx, mi_col + x_idx,
2667                           subsize, &this_rdc,
2668                           best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
2669
2670         if (this_rdc.rate == INT_MAX) {
2671           sum_rdc.rdcost = INT64_MAX;
2672           break;
2673         } else {
2674           sum_rdc.rate += this_rdc.rate;
2675           sum_rdc.dist += this_rdc.dist;
2676           sum_rdc.rdcost += this_rdc.rdcost;
2677         }
2678       }
2679     }
2680
2681     if (sum_rdc.rdcost < best_rdc.rdcost && i == 4) {
2682       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2683       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2684       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2685                               sum_rdc.rate, sum_rdc.dist);
2686
2687       if (sum_rdc.rdcost < best_rdc.rdcost) {
2688         best_rdc = sum_rdc;
2689         pc_tree->partitioning = PARTITION_SPLIT;
2690       }
2691     } else {
2692       // skip rectangular partition test when larger block size
2693       // gives better rd cost
2694       if (cpi->sf.less_rectangular_check)
2695         do_rect &= !partition_none_allowed;
2696     }
2697     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2698   }
2699
2700   // PARTITION_HORZ
2701   if (partition_horz_allowed && do_rect) {
2702     subsize = get_subsize(bsize, PARTITION_HORZ);
2703     if (cpi->sf.adaptive_motion_search)
2704       load_pred_mv(x, ctx);
2705     if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2706         partition_none_allowed)
2707       pc_tree->horizontal[0].pred_interp_filter =
2708           ctx->mic.mbmi.interp_filter;
2709     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2710                      &pc_tree->horizontal[0], best_rdc.rdcost);
2711
2712     if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
2713         bsize > BLOCK_8X8) {
2714       PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2715       update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2716       encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2717
2718       if (cpi->sf.adaptive_motion_search)
2719         load_pred_mv(x, ctx);
2720       if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2721           partition_none_allowed)
2722         pc_tree->horizontal[1].pred_interp_filter =
2723             ctx->mic.mbmi.interp_filter;
2724       rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col,
2725                        &this_rdc, subsize, &pc_tree->horizontal[1],
2726                        best_rdc.rdcost - sum_rdc.rdcost);
2727       if (this_rdc.rate == INT_MAX) {
2728         sum_rdc.rdcost = INT64_MAX;
2729       } else {
2730         sum_rdc.rate += this_rdc.rate;
2731         sum_rdc.dist += this_rdc.dist;
2732         sum_rdc.rdcost += this_rdc.rdcost;
2733       }
2734     }
2735
2736     if (sum_rdc.rdcost < best_rdc.rdcost) {
2737       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2738       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
2739       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
2740       if (sum_rdc.rdcost < best_rdc.rdcost) {
2741         best_rdc = sum_rdc;
2742         pc_tree->partitioning = PARTITION_HORZ;
2743       }
2744     }
2745     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2746   }
2747   // PARTITION_VERT
2748   if (partition_vert_allowed && do_rect) {
2749     subsize = get_subsize(bsize, PARTITION_VERT);
2750
2751     if (cpi->sf.adaptive_motion_search)
2752       load_pred_mv(x, ctx);
2753     if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2754         partition_none_allowed)
2755       pc_tree->vertical[0].pred_interp_filter =
2756           ctx->mic.mbmi.interp_filter;
2757     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2758                      &pc_tree->vertical[0], best_rdc.rdcost);
2759     if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
2760         bsize > BLOCK_8X8) {
2761       update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
2762       encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
2763                         &pc_tree->vertical[0]);
2764
2765       if (cpi->sf.adaptive_motion_search)
2766         load_pred_mv(x, ctx);
2767       if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2768           partition_none_allowed)
2769         pc_tree->vertical[1].pred_interp_filter =
2770             ctx->mic.mbmi.interp_filter;
2771       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step,
2772                        &this_rdc, subsize,
2773                        &pc_tree->vertical[1], best_rdc.rdcost - sum_rdc.rdcost);
2774       if (this_rdc.rate == INT_MAX) {
2775         sum_rdc.rdcost = INT64_MAX;
2776       } else {
2777         sum_rdc.rate += this_rdc.rate;
2778         sum_rdc.dist += this_rdc.dist;
2779         sum_rdc.rdcost += this_rdc.rdcost;
2780       }
2781     }
2782
2783     if (sum_rdc.rdcost < best_rdc.rdcost) {
2784       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2785       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
2786       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2787                               sum_rdc.rate, sum_rdc.dist);
2788       if (sum_rdc.rdcost < best_rdc.rdcost) {
2789         best_rdc = sum_rdc;
2790         pc_tree->partitioning = PARTITION_VERT;
2791       }
2792     }
2793     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2794   }
2795
2796   // TODO(jbb): This code added so that we avoid static analysis
2797   // warning related to the fact that best_rd isn't used after this
2798   // point.  This code should be refactored so that the duplicate
2799   // checks occur in some sub function and thus are used...
2800   (void) best_rd;
2801   *rd_cost = best_rdc;
2802
2803
2804   if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX &&
2805       pc_tree->index != 3) {
2806     int output_enabled = (bsize == BLOCK_64X64);
2807     encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
2808               bsize, pc_tree);
2809   }
2810
2811   if (bsize == BLOCK_64X64) {
2812     assert(tp_orig < *tp);
2813     assert(best_rdc.rate < INT_MAX);
2814     assert(best_rdc.dist < INT64_MAX);
2815   } else {
2816     assert(tp_orig == *tp);
2817   }
2818 }
2819
2820 static void encode_rd_sb_row(VP9_COMP *cpi,
2821                              ThreadData *td,
2822                              TileDataEnc *tile_data,
2823                              int mi_row,
2824                              TOKENEXTRA **tp) {
2825   VP9_COMMON *const cm = &cpi->common;
2826   TileInfo *const tile_info = &tile_data->tile_info;
2827   MACROBLOCK *const x = &td->mb;
2828   MACROBLOCKD *const xd = &x->e_mbd;
2829   SPEED_FEATURES *const sf = &cpi->sf;
2830   int mi_col;
2831
2832   // Initialize the left context for the new SB row
2833   vpx_memset(&xd->left_context, 0, sizeof(xd->left_context));
2834   vpx_memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
2835
2836   // Code each SB in the row
2837   for (mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
2838        mi_col += MI_BLOCK_SIZE) {
2839     const struct segmentation *const seg = &cm->seg;
2840     int dummy_rate;
2841     int64_t dummy_dist;
2842     RD_COST dummy_rdc;
2843     int i;
2844     int seg_skip = 0;
2845
2846     const int idx_str = cm->mi_stride * mi_row + mi_col;
2847     MODE_INFO **mi = cm->mi_grid_visible + idx_str;
2848
2849     if (sf->adaptive_pred_interp_filter) {
2850       for (i = 0; i < 64; ++i)
2851         td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
2852
2853       for (i = 0; i < 64; ++i) {
2854         td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
2855         td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
2856         td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
2857         td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
2858       }
2859     }
2860
2861     vp9_zero(x->pred_mv);
2862     td->pc_root->index = 0;
2863
2864     if (seg->enabled) {
2865       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
2866                                                  : cm->last_frame_seg_map;
2867       int segment_id = vp9_get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
2868       seg_skip = vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP);
2869     }
2870
2871     x->source_variance = UINT_MAX;
2872     if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
2873       const BLOCK_SIZE bsize =
2874           seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
2875       set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2876       set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
2877       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2878                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2879     } else if (cpi->partition_search_skippable_frame) {
2880       BLOCK_SIZE bsize;
2881       set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2882       bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col);
2883       set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
2884       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2885                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2886     } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
2887                cm->frame_type != KEY_FRAME) {
2888       choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
2889       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2890                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2891     } else {
2892       // If required set upper and lower partition size limits
2893       if (sf->auto_min_max_partition_size) {
2894         set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2895         rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
2896                                 &x->min_partition_size,
2897                                 &x->max_partition_size);
2898       }
2899       rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
2900                         &dummy_rdc, INT64_MAX, td->pc_root);
2901     }
2902   }
2903 }
2904
2905 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
2906   MACROBLOCK *const x = &cpi->td.mb;
2907   VP9_COMMON *const cm = &cpi->common;
2908   MACROBLOCKD *const xd = &x->e_mbd;
2909   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2910
2911   // Copy data over into macro block data structures.
2912   vp9_setup_src_planes(x, cpi->Source, 0, 0);
2913
2914   vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
2915
2916   // Note: this memset assumes above_context[0], [1] and [2]
2917   // are allocated as part of the same buffer.
2918   vpx_memset(xd->above_context[0], 0,
2919              sizeof(*xd->above_context[0]) *
2920              2 * aligned_mi_cols * MAX_MB_PLANE);
2921   vpx_memset(xd->above_seg_context, 0,
2922              sizeof(*xd->above_seg_context) * aligned_mi_cols);
2923 }
2924
2925 static int check_dual_ref_flags(VP9_COMP *cpi) {
2926   const int ref_flags = cpi->ref_frame_flags;
2927
2928   if (vp9_segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
2929     return 0;
2930   } else {
2931     return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG)
2932         + !!(ref_flags & VP9_ALT_FLAG)) >= 2;
2933   }
2934 }
2935
2936 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
2937   int mi_row, mi_col;
2938   const int mis = cm->mi_stride;
2939   MODE_INFO **mi_ptr = cm->mi_grid_visible;
2940
2941   for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
2942     for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
2943       if (mi_ptr[mi_col]->mbmi.tx_size > max_tx_size)
2944         mi_ptr[mi_col]->mbmi.tx_size = max_tx_size;
2945     }
2946   }
2947 }
2948
2949 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
2950   if (frame_is_intra_only(&cpi->common))
2951     return INTRA_FRAME;
2952   else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
2953     return ALTREF_FRAME;
2954   else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
2955     return GOLDEN_FRAME;
2956   else
2957     return LAST_FRAME;
2958 }
2959
2960 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
2961   if (xd->lossless)
2962     return ONLY_4X4;
2963   if (cpi->common.frame_type == KEY_FRAME &&
2964       cpi->sf.use_nonrd_pick_mode &&
2965       cpi->sf.partition_search_type == VAR_BASED_PARTITION)
2966     return ALLOW_16X16;
2967   if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
2968     return ALLOW_32X32;
2969   else if (cpi->sf.tx_size_search_method == USE_FULL_RD||
2970            cpi->sf.tx_size_search_method == USE_TX_8X8)
2971     return TX_MODE_SELECT;
2972   else
2973     return cpi->common.tx_mode;
2974 }
2975
2976 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
2977                                      RD_COST *rd_cost, BLOCK_SIZE bsize,
2978                                      PICK_MODE_CONTEXT *ctx) {
2979   if (bsize < BLOCK_16X16)
2980     vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
2981   else
2982     vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
2983 }
2984
2985 static void nonrd_pick_sb_modes(VP9_COMP *cpi,
2986                                 TileDataEnc *tile_data, MACROBLOCK *const x,
2987                                 int mi_row, int mi_col, RD_COST *rd_cost,
2988                                 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
2989   VP9_COMMON *const cm = &cpi->common;
2990   TileInfo *const tile_info = &tile_data->tile_info;
2991   MACROBLOCKD *const xd = &x->e_mbd;
2992   MB_MODE_INFO *mbmi;
2993   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2994   mbmi = &xd->mi[0]->mbmi;
2995   mbmi->sb_type = bsize;
2996
2997   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
2998     if (cyclic_refresh_segment_id_boosted(mbmi->segment_id))
2999       x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
3000
3001   if (cm->frame_type == KEY_FRAME)
3002     hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
3003   else if (vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP))
3004     set_mode_info_seg_skip(x, cm->tx_mode, rd_cost, bsize);
3005   else if (bsize >= BLOCK_8X8)
3006     vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col,
3007                         rd_cost, bsize, ctx);
3008   else
3009     vp9_pick_inter_mode_sub8x8(cpi, x, tile_data, mi_row, mi_col,
3010                                rd_cost, bsize, ctx);
3011
3012   duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
3013
3014   if (rd_cost->rate == INT_MAX)
3015     vp9_rd_cost_reset(rd_cost);
3016
3017   ctx->rate = rd_cost->rate;
3018   ctx->dist = rd_cost->dist;
3019 }
3020
3021 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x,
3022                               int mi_row, int mi_col,
3023                               BLOCK_SIZE bsize,
3024                               PC_TREE *pc_tree) {
3025   MACROBLOCKD *xd = &x->e_mbd;
3026   int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
3027   PARTITION_TYPE partition = pc_tree->partitioning;
3028   BLOCK_SIZE subsize = get_subsize(bsize, partition);
3029
3030   assert(bsize >= BLOCK_8X8);
3031
3032   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
3033     return;
3034
3035   switch (partition) {
3036     case PARTITION_NONE:
3037       set_mode_info_offsets(cm, xd, mi_row, mi_col);
3038       *(xd->mi[0]) = pc_tree->none.mic;
3039       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
3040       break;
3041     case PARTITION_VERT:
3042       set_mode_info_offsets(cm, xd, mi_row, mi_col);
3043       *(xd->mi[0]) = pc_tree->vertical[0].mic;
3044       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
3045
3046       if (mi_col + hbs < cm->mi_cols) {
3047         set_mode_info_offsets(cm, xd, mi_row, mi_col + hbs);
3048         *(xd->mi[0]) = pc_tree->vertical[1].mic;
3049         duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
3050       }
3051       break;
3052     case PARTITION_HORZ:
3053       set_mode_info_offsets(cm, xd, mi_row, mi_col);
3054       *(xd->mi[0]) = pc_tree->horizontal[0].mic;
3055       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
3056       if (mi_row + hbs < cm->mi_rows) {
3057         set_mode_info_offsets(cm, xd, mi_row + hbs, mi_col);
3058         *(xd->mi[0]) = pc_tree->horizontal[1].mic;
3059         duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
3060       }
3061       break;
3062     case PARTITION_SPLIT: {
3063       fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
3064       fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
3065                         pc_tree->split[1]);
3066       fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
3067                         pc_tree->split[2]);
3068       fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
3069                         pc_tree->split[3]);
3070       break;
3071     }
3072     default:
3073       break;
3074   }
3075 }
3076
3077 // Reset the prediction pixel ready flag recursively.
3078 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
3079   pc_tree->none.pred_pixel_ready = 0;
3080   pc_tree->horizontal[0].pred_pixel_ready = 0;
3081   pc_tree->horizontal[1].pred_pixel_ready = 0;
3082   pc_tree->vertical[0].pred_pixel_ready = 0;
3083   pc_tree->vertical[1].pred_pixel_ready = 0;
3084
3085   if (bsize > BLOCK_8X8) {
3086     BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3087     int i;
3088     for (i = 0; i < 4; ++i)
3089       pred_pixel_ready_reset(pc_tree->split[i], subsize);
3090   }
3091 }
3092
3093 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3094                                  TileDataEnc *tile_data,
3095                                  TOKENEXTRA **tp, int mi_row,
3096                                  int mi_col, BLOCK_SIZE bsize, RD_COST *rd_cost,
3097                                  int do_recon, int64_t best_rd,
3098                                  PC_TREE *pc_tree) {
3099   const SPEED_FEATURES *const sf = &cpi->sf;
3100   VP9_COMMON *const cm = &cpi->common;
3101   TileInfo *const tile_info = &tile_data->tile_info;
3102   MACROBLOCK *const x = &td->mb;
3103   MACROBLOCKD *const xd = &x->e_mbd;
3104   const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
3105   TOKENEXTRA *tp_orig = *tp;
3106   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
3107   int i;
3108   BLOCK_SIZE subsize = bsize;
3109   RD_COST this_rdc, sum_rdc, best_rdc;
3110   int do_split = bsize >= BLOCK_8X8;
3111   int do_rect = 1;
3112   // Override skipping rectangular partition operations for edge blocks
3113   const int force_horz_split = (mi_row + ms >= cm->mi_rows);
3114   const int force_vert_split = (mi_col + ms >= cm->mi_cols);
3115   const int xss = x->e_mbd.plane[1].subsampling_x;
3116   const int yss = x->e_mbd.plane[1].subsampling_y;
3117
3118   int partition_none_allowed = !force_horz_split && !force_vert_split;
3119   int partition_horz_allowed = !force_vert_split && yss <= xss &&
3120                                bsize >= BLOCK_8X8;
3121   int partition_vert_allowed = !force_horz_split && xss <= yss &&
3122                                bsize >= BLOCK_8X8;
3123   (void) *tp_orig;
3124
3125   assert(num_8x8_blocks_wide_lookup[bsize] ==
3126              num_8x8_blocks_high_lookup[bsize]);
3127
3128   vp9_rd_cost_init(&sum_rdc);
3129   vp9_rd_cost_reset(&best_rdc);
3130   best_rdc.rdcost = best_rd;
3131
3132   // Determine partition types in search according to the speed features.
3133   // The threshold set here has to be of square block size.
3134   if (sf->auto_min_max_partition_size) {
3135     partition_none_allowed &= (bsize <= x->max_partition_size &&
3136                                bsize >= x->min_partition_size);
3137     partition_horz_allowed &= ((bsize <= x->max_partition_size &&
3138                                 bsize > x->min_partition_size) ||
3139                                 force_horz_split);
3140     partition_vert_allowed &= ((bsize <= x->max_partition_size &&
3141                                 bsize > x->min_partition_size) ||
3142                                 force_vert_split);
3143     do_split &= bsize > x->min_partition_size;
3144   }
3145   if (sf->use_square_partition_only) {
3146     partition_horz_allowed &= force_horz_split;
3147     partition_vert_allowed &= force_vert_split;
3148   }
3149
3150   ctx->pred_pixel_ready = !(partition_vert_allowed ||
3151                             partition_horz_allowed ||
3152                             do_split);
3153
3154   // PARTITION_NONE
3155   if (partition_none_allowed) {
3156     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col,
3157                         &this_rdc, bsize, ctx);
3158     ctx->mic.mbmi = xd->mi[0]->mbmi;
3159     ctx->skip_txfm[0] = x->skip_txfm[0];
3160     ctx->skip = x->skip;
3161
3162     if (this_rdc.rate != INT_MAX) {
3163       int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3164       this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3165       this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3166                               this_rdc.rate, this_rdc.dist);
3167       if (this_rdc.rdcost < best_rdc.rdcost) {
3168         int64_t dist_breakout_thr = sf->partition_search_breakout_dist_thr;
3169         int64_t rate_breakout_thr = sf->partition_search_breakout_rate_thr;
3170
3171         dist_breakout_thr >>= 8 - (b_width_log2_lookup[bsize] +
3172             b_height_log2_lookup[bsize]);
3173
3174         rate_breakout_thr *= num_pels_log2_lookup[bsize];
3175
3176         best_rdc = this_rdc;
3177         if (bsize >= BLOCK_8X8)
3178           pc_tree->partitioning = PARTITION_NONE;
3179
3180         if (!x->e_mbd.lossless &&
3181             this_rdc.rate < rate_breakout_thr &&
3182             this_rdc.dist < dist_breakout_thr) {
3183           do_split = 0;
3184           do_rect = 0;
3185         }
3186       }
3187     }
3188   }
3189
3190   // store estimated motion vector
3191   store_pred_mv(x, ctx);
3192
3193   // PARTITION_SPLIT
3194   if (do_split) {
3195     int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3196     sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
3197     sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
3198     subsize = get_subsize(bsize, PARTITION_SPLIT);
3199     for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
3200       const int x_idx = (i & 1) * ms;
3201       const int y_idx = (i >> 1) * ms;
3202
3203       if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
3204         continue;
3205       load_pred_mv(x, ctx);
3206       nonrd_pick_partition(cpi, td, tile_data, tp,
3207                            mi_row + y_idx, mi_col + x_idx,
3208                            subsize, &this_rdc, 0,
3209                            best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
3210
3211       if (this_rdc.rate == INT_MAX) {
3212         vp9_rd_cost_reset(&sum_rdc);
3213       } else {
3214         sum_rdc.rate += this_rdc.rate;
3215         sum_rdc.dist += this_rdc.dist;
3216         sum_rdc.rdcost += this_rdc.rdcost;
3217       }
3218     }
3219
3220     if (sum_rdc.rdcost < best_rdc.rdcost) {
3221       best_rdc = sum_rdc;
3222       pc_tree->partitioning = PARTITION_SPLIT;
3223     } else {
3224       // skip rectangular partition test when larger block size
3225       // gives better rd cost
3226       if (sf->less_rectangular_check)
3227         do_rect &= !partition_none_allowed;
3228     }
3229   }
3230
3231   // PARTITION_HORZ
3232   if (partition_horz_allowed && do_rect) {
3233     subsize = get_subsize(bsize, PARTITION_HORZ);
3234     if (sf->adaptive_motion_search)
3235       load_pred_mv(x, ctx);
3236     pc_tree->horizontal[0].pred_pixel_ready = 1;
3237     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
3238                         &pc_tree->horizontal[0]);
3239
3240     pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3241     pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3242     pc_tree->horizontal[0].skip = x->skip;
3243
3244     if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
3245       load_pred_mv(x, ctx);
3246       pc_tree->horizontal[1].pred_pixel_ready = 1;
3247       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col,
3248                           &this_rdc, subsize,
3249                           &pc_tree->horizontal[1]);
3250
3251       pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3252       pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3253       pc_tree->horizontal[1].skip = x->skip;
3254
3255       if (this_rdc.rate == INT_MAX) {
3256         vp9_rd_cost_reset(&sum_rdc);
3257       } else {
3258         int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3259         this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
3260         sum_rdc.rate += this_rdc.rate;
3261         sum_rdc.dist += this_rdc.dist;
3262         sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3263                                 sum_rdc.rate, sum_rdc.dist);
3264       }
3265     }
3266
3267     if (sum_rdc.rdcost < best_rdc.rdcost) {
3268       best_rdc = sum_rdc;
3269       pc_tree->partitioning = PARTITION_HORZ;
3270     } else {
3271       pred_pixel_ready_reset(pc_tree, bsize);
3272     }
3273   }
3274
3275   // PARTITION_VERT
3276   if (partition_vert_allowed && do_rect) {
3277     subsize = get_subsize(bsize, PARTITION_VERT);
3278     if (sf->adaptive_motion_search)
3279       load_pred_mv(x, ctx);
3280     pc_tree->vertical[0].pred_pixel_ready = 1;
3281     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
3282                         &pc_tree->vertical[0]);
3283     pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3284     pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3285     pc_tree->vertical[0].skip = x->skip;
3286
3287     if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
3288       load_pred_mv(x, ctx);
3289       pc_tree->vertical[1].pred_pixel_ready = 1;
3290       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms,
3291                           &this_rdc, subsize,
3292                           &pc_tree->vertical[1]);
3293       pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3294       pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3295       pc_tree->vertical[1].skip = x->skip;
3296
3297       if (this_rdc.rate == INT_MAX) {
3298         vp9_rd_cost_reset(&sum_rdc);
3299       } else {
3300         int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3301         sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
3302         sum_rdc.rate += this_rdc.rate;
3303         sum_rdc.dist += this_rdc.dist;
3304         sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3305                                 sum_rdc.rate, sum_rdc.dist);
3306       }
3307     }
3308
3309     if (sum_rdc.rdcost < best_rdc.rdcost) {
3310       best_rdc = sum_rdc;
3311       pc_tree->partitioning = PARTITION_VERT;
3312     } else {
3313       pred_pixel_ready_reset(pc_tree, bsize);
3314     }
3315   }
3316
3317   *rd_cost = best_rdc;
3318
3319   if (best_rdc.rate == INT_MAX) {
3320     vp9_rd_cost_reset(rd_cost);
3321     return;
3322   }
3323
3324   // update mode info array
3325   fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
3326
3327   if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
3328     int output_enabled = (bsize == BLOCK_64X64);
3329     encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3330                  bsize, pc_tree);
3331   }
3332
3333   if (bsize == BLOCK_64X64 && do_recon) {
3334     assert(tp_orig < *tp);
3335     assert(best_rdc.rate < INT_MAX);
3336     assert(best_rdc.dist < INT64_MAX);
3337   } else {
3338     assert(tp_orig == *tp);
3339   }
3340 }
3341
3342 static void nonrd_select_partition(VP9_COMP *cpi,
3343                                    ThreadData *td,
3344                                    TileDataEnc *tile_data,
3345                                    MODE_INFO **mi,
3346                                    TOKENEXTRA **tp,
3347                                    int mi_row, int mi_col,
3348                                    BLOCK_SIZE bsize, int output_enabled,
3349                                    RD_COST *rd_cost, PC_TREE *pc_tree) {
3350   VP9_COMMON *const cm = &cpi->common;
3351   TileInfo *const tile_info = &tile_data->tile_info;
3352   MACROBLOCK *const x = &td->mb;
3353   MACROBLOCKD *const xd = &x->e_mbd;
3354   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
3355   const int mis = cm->mi_stride;
3356   PARTITION_TYPE partition;
3357   BLOCK_SIZE subsize;
3358   RD_COST this_rdc;
3359
3360   vp9_rd_cost_reset(&this_rdc);
3361   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
3362     return;
3363
3364   subsize = (bsize >= BLOCK_8X8) ? mi[0]->mbmi.sb_type : BLOCK_4X4;
3365   partition = partition_lookup[bsl][subsize];
3366
3367   if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
3368       subsize >= BLOCK_16X16) {
3369     x->max_partition_size = BLOCK_32X32;
3370     x->min_partition_size = BLOCK_8X8;
3371     nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize,
3372                          rd_cost, 0, INT64_MAX, pc_tree);
3373   } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
3374     x->max_partition_size = BLOCK_16X16;
3375     x->min_partition_size = BLOCK_8X8;
3376     nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize,
3377                          rd_cost, 0, INT64_MAX, pc_tree);
3378   } else {
3379     switch (partition) {
3380       case PARTITION_NONE:
3381         pc_tree->none.pred_pixel_ready = 1;
3382         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3383                             subsize, &pc_tree->none);
3384         pc_tree->none.mic.mbmi = xd->mi[0]->mbmi;
3385         pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
3386         pc_tree->none.skip = x->skip;
3387         break;
3388       case PARTITION_VERT:
3389         pc_tree->vertical[0].pred_pixel_ready = 1;
3390         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3391                             subsize, &pc_tree->vertical[0]);
3392         pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3393         pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3394         pc_tree->vertical[0].skip = x->skip;
3395         if (mi_col + hbs < cm->mi_cols) {
3396           pc_tree->vertical[1].pred_pixel_ready = 1;
3397           nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
3398                               &this_rdc, subsize, &pc_tree->vertical[1]);
3399           pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3400           pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3401           pc_tree->vertical[1].skip = x->skip;
3402           if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3403               rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3404             rd_cost->rate += this_rdc.rate;
3405             rd_cost->dist += this_rdc.dist;
3406           }
3407         }
3408         break;
3409       case PARTITION_HORZ:
3410         pc_tree->horizontal[0].pred_pixel_ready = 1;
3411         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3412                             subsize, &pc_tree->horizontal[0]);
3413         pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3414         pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3415         pc_tree->horizontal[0].skip = x->skip;
3416         if (mi_row + hbs < cm->mi_rows) {
3417           pc_tree->horizontal[1].pred_pixel_ready = 1;
3418           nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
3419                               &this_rdc, subsize, &pc_tree->horizontal[1]);
3420           pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3421           pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3422           pc_tree->horizontal[1].skip = x->skip;
3423           if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3424               rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3425             rd_cost->rate += this_rdc.rate;
3426             rd_cost->dist += this_rdc.dist;
3427           }
3428         }
3429         break;
3430       case PARTITION_SPLIT:
3431         subsize = get_subsize(bsize, PARTITION_SPLIT);
3432         nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3433                                subsize, output_enabled, rd_cost,
3434                                pc_tree->split[0]);
3435         nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp,
3436                                mi_row, mi_col + hbs, subsize, output_enabled,
3437                                &this_rdc, pc_tree->split[1]);
3438         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3439             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3440           rd_cost->rate += this_rdc.rate;
3441           rd_cost->dist += this_rdc.dist;
3442         }
3443         nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
3444                                mi_row + hbs, mi_col, subsize, output_enabled,
3445                                &this_rdc, pc_tree->split[2]);
3446         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3447             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3448           rd_cost->rate += this_rdc.rate;
3449           rd_cost->dist += this_rdc.dist;
3450         }
3451         nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
3452                                mi_row + hbs, mi_col + hbs, subsize,
3453                                output_enabled, &this_rdc, pc_tree->split[3]);
3454         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3455             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3456           rd_cost->rate += this_rdc.rate;
3457           rd_cost->dist += this_rdc.dist;
3458         }
3459         break;
3460       default:
3461         assert(0 && "Invalid partition type.");
3462         break;
3463     }
3464   }
3465
3466   if (bsize == BLOCK_64X64 && output_enabled)
3467     encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
3468 }
3469
3470
3471 static void nonrd_use_partition(VP9_COMP *cpi,
3472                                 ThreadData *td,
3473                                 TileDataEnc *tile_data,
3474                                 MODE_INFO **mi,
3475                                 TOKENEXTRA **tp,
3476                                 int mi_row, int mi_col,
3477                                 BLOCK_SIZE bsize, int output_enabled,
3478                                 RD_COST *dummy_cost, PC_TREE *pc_tree) {
3479   VP9_COMMON *const cm = &cpi->common;
3480   TileInfo *tile_info = &tile_data->tile_info;
3481   MACROBLOCK *const x = &td->mb;
3482   MACROBLOCKD *const xd = &x->e_mbd;
3483   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
3484   const int mis = cm->mi_stride;
3485   PARTITION_TYPE partition;
3486   BLOCK_SIZE subsize;
3487
3488   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
3489     return;
3490
3491   subsize = (bsize >= BLOCK_8X8) ? mi[0]->mbmi.sb_type : BLOCK_4X4;
3492   partition = partition_lookup[bsl][subsize];
3493
3494   if (output_enabled && bsize != BLOCK_4X4) {
3495     int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
3496     td->counts->partition[ctx][partition]++;
3497   }
3498
3499   switch (partition) {
3500     case PARTITION_NONE:
3501       pc_tree->none.pred_pixel_ready = 1;
3502       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3503                           subsize, &pc_tree->none);
3504       pc_tree->none.mic.mbmi = xd->mi[0]->mbmi;
3505       pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
3506       pc_tree->none.skip = x->skip;
3507       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3508                   subsize, &pc_tree->none);
3509       break;
3510     case PARTITION_VERT:
3511       pc_tree->vertical[0].pred_pixel_ready = 1;
3512       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3513                           subsize, &pc_tree->vertical[0]);
3514       pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3515       pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3516       pc_tree->vertical[0].skip = x->skip;
3517       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3518                   subsize, &pc_tree->vertical[0]);
3519       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
3520         pc_tree->vertical[1].pred_pixel_ready = 1;
3521         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
3522                             dummy_cost, subsize, &pc_tree->vertical[1]);
3523         pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3524         pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3525         pc_tree->vertical[1].skip = x->skip;
3526         encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
3527                     output_enabled, subsize, &pc_tree->vertical[1]);
3528       }
3529       break;
3530     case PARTITION_HORZ:
3531       pc_tree->horizontal[0].pred_pixel_ready = 1;
3532       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3533                           subsize, &pc_tree->horizontal[0]);
3534       pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3535       pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3536       pc_tree->horizontal[0].skip = x->skip;
3537       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3538                   subsize, &pc_tree->horizontal[0]);
3539
3540       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
3541         pc_tree->horizontal[1].pred_pixel_ready = 1;
3542         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
3543                             dummy_cost, subsize, &pc_tree->horizontal[1]);
3544         pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3545         pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3546         pc_tree->horizontal[1].skip = x->skip;
3547         encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
3548                     output_enabled, subsize, &pc_tree->horizontal[1]);
3549       }
3550       break;
3551     case PARTITION_SPLIT:
3552       subsize = get_subsize(bsize, PARTITION_SPLIT);
3553       if (bsize == BLOCK_8X8) {
3554         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3555                             subsize, pc_tree->leaf_split[0]);
3556         encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col,
3557                     output_enabled, subsize, pc_tree->leaf_split[0]);
3558       } else {
3559         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3560                             subsize, output_enabled, dummy_cost,
3561                             pc_tree->split[0]);
3562         nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp,
3563                             mi_row, mi_col + hbs, subsize, output_enabled,
3564                             dummy_cost, pc_tree->split[1]);
3565         nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
3566                             mi_row + hbs, mi_col, subsize, output_enabled,
3567                             dummy_cost, pc_tree->split[2]);
3568         nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
3569                             mi_row + hbs, mi_col + hbs, subsize, output_enabled,
3570                             dummy_cost, pc_tree->split[3]);
3571       }
3572       break;
3573     default:
3574       assert(0 && "Invalid partition type.");
3575       break;
3576   }
3577
3578   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
3579     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
3580 }
3581
3582 static void encode_nonrd_sb_row(VP9_COMP *cpi,
3583                                 ThreadData *td,
3584                                 TileDataEnc *tile_data,
3585                                 int mi_row,
3586                                 TOKENEXTRA **tp) {
3587   SPEED_FEATURES *const sf = &cpi->sf;
3588   VP9_COMMON *const cm = &cpi->common;
3589   TileInfo *const tile_info = &tile_data->tile_info;
3590   MACROBLOCK *const x = &td->mb;
3591   MACROBLOCKD *const xd = &x->e_mbd;
3592   int mi_col;
3593
3594   // Initialize the left context for the new SB row
3595   vpx_memset(&xd->left_context, 0, sizeof(xd->left_context));
3596   vpx_memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
3597
3598   // Code each SB in the row
3599   for (mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
3600        mi_col += MI_BLOCK_SIZE) {
3601     const struct segmentation *const seg = &cm->seg;
3602     RD_COST dummy_rdc;
3603     const int idx_str = cm->mi_stride * mi_row + mi_col;
3604     MODE_INFO **mi = cm->mi_grid_visible + idx_str;
3605     PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
3606     BLOCK_SIZE bsize = BLOCK_64X64;
3607     int seg_skip = 0;
3608     x->source_variance = UINT_MAX;
3609     vp9_zero(x->pred_mv);
3610     vp9_rd_cost_init(&dummy_rdc);
3611     x->color_sensitivity[0] = 0;
3612     x->color_sensitivity[1] = 0;
3613
3614     if (seg->enabled) {
3615       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
3616                                                  : cm->last_frame_seg_map;
3617       int segment_id = vp9_get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
3618       seg_skip = vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP);
3619       if (seg_skip) {
3620         partition_search_type = FIXED_PARTITION;
3621       }
3622     }
3623
3624     // Set the partition type of the 64X64 block
3625     switch (partition_search_type) {
3626       case VAR_BASED_PARTITION:
3627         // TODO(jingning, marpan): The mode decision and encoding process
3628         // support both intra and inter sub8x8 block coding for RTC mode.
3629         // Tune the thresholds accordingly to use sub8x8 block coding for
3630         // coding performance improvement.
3631         choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
3632         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3633                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3634         break;
3635       case SOURCE_VAR_BASED_PARTITION:
3636         set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
3637         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3638                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3639         break;
3640       case FIXED_PARTITION:
3641         if (!seg_skip)
3642           bsize = sf->always_this_block_size;
3643         set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
3644         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3645                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3646         break;
3647       case REFERENCE_PARTITION:
3648         set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
3649         if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
3650             xd->mi[0]->mbmi.segment_id) {
3651           x->max_partition_size = BLOCK_64X64;
3652           x->min_partition_size = BLOCK_8X8;
3653           nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
3654                                BLOCK_64X64, &dummy_rdc, 1,
3655                                INT64_MAX, td->pc_root);
3656         } else {
3657           choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
3658           nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3659                                  BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3660         }
3661
3662         break;
3663       default:
3664         assert(0);
3665         break;
3666     }
3667   }
3668 }
3669 // end RTC play code
3670
3671 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
3672   const SPEED_FEATURES *const sf = &cpi->sf;
3673   const VP9_COMMON *const cm = &cpi->common;
3674
3675   const uint8_t *src = cpi->Source->y_buffer;
3676   const uint8_t *last_src = cpi->Last_Source->y_buffer;
3677   const int src_stride = cpi->Source->y_stride;
3678   const int last_stride = cpi->Last_Source->y_stride;
3679
3680   // Pick cutoff threshold
3681   const int cutoff = (MIN(cm->width, cm->height) >= 720) ?
3682       (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100) :
3683       (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
3684   DECLARE_ALIGNED_ARRAY(16, int, hist, VAR_HIST_BINS);
3685   diff *var16 = cpi->source_diff_var;
3686
3687   int sum = 0;
3688   int i, j;
3689
3690   vpx_memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
3691
3692   for (i = 0; i < cm->mb_rows; i++) {
3693     for (j = 0; j < cm->mb_cols; j++) {
3694 #if CONFIG_VP9_HIGHBITDEPTH
3695       if (cm->use_highbitdepth) {
3696         switch (cm->bit_depth) {
3697           case VPX_BITS_8:
3698             vp9_highbd_get16x16var(src, src_stride, last_src, last_stride,
3699                                    &var16->sse, &var16->sum);
3700             break;
3701           case VPX_BITS_10:
3702             vp9_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
3703                                     &var16->sse, &var16->sum);
3704             break;
3705           case VPX_BITS_12:
3706             vp9_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
3707                                       &var16->sse, &var16->sum);
3708             break;
3709           default:
3710             assert(0 && "cm->bit_depth should be VPX_BITS_8, VPX_BITS_10"
3711                    " or VPX_BITS_12");
3712             return -1;
3713         }
3714       } else {
3715         vp9_get16x16var(src, src_stride, last_src, last_stride,
3716                         &var16->sse, &var16->sum);
3717       }
3718 #else
3719       vp9_get16x16var(src, src_stride, last_src, last_stride,
3720                       &var16->sse, &var16->sum);
3721 #endif  // CONFIG_VP9_HIGHBITDEPTH
3722       var16->var = var16->sse -
3723           (((uint32_t)var16->sum * var16->sum) >> 8);
3724
3725       if (var16->var >= VAR_HIST_MAX_BG_VAR)
3726         hist[VAR_HIST_BINS - 1]++;
3727       else
3728         hist[var16->var / VAR_HIST_FACTOR]++;
3729
3730       src += 16;
3731       last_src += 16;
3732       var16++;
3733     }
3734
3735     src = src - cm->mb_cols * 16 + 16 * src_stride;
3736     last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
3737   }
3738
3739   cpi->source_var_thresh = 0;
3740
3741   if (hist[VAR_HIST_BINS - 1] < cutoff) {
3742     for (i = 0; i < VAR_HIST_BINS - 1; i++) {
3743       sum += hist[i];
3744
3745       if (sum > cutoff) {
3746         cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
3747         return 0;
3748       }
3749     }
3750   }
3751
3752   return sf->search_type_check_frequency;
3753 }
3754
3755 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
3756   VP9_COMMON *const cm = &cpi->common;
3757   SPEED_FEATURES *const sf = &cpi->sf;
3758
3759   if (cm->frame_type == KEY_FRAME) {
3760     // For key frame, use SEARCH_PARTITION.
3761     sf->partition_search_type = SEARCH_PARTITION;
3762   } else if (cm->intra_only) {
3763     sf->partition_search_type = FIXED_PARTITION;
3764   } else {
3765     if (cm->last_width != cm->width || cm->last_height != cm->height) {
3766       if (cpi->source_diff_var)
3767         vpx_free(cpi->source_diff_var);
3768
3769       CHECK_MEM_ERROR(cm, cpi->source_diff_var,
3770                       vpx_calloc(cm->MBs, sizeof(diff)));
3771     }
3772
3773     if (!cpi->frames_till_next_var_check)
3774       cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
3775
3776     if (cpi->frames_till_next_var_check > 0) {
3777       sf->partition_search_type = FIXED_PARTITION;
3778       cpi->frames_till_next_var_check--;
3779     }
3780   }
3781 }
3782
3783 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
3784   unsigned int intra_count = 0, inter_count = 0;
3785   int j;
3786
3787   for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
3788     intra_count += td->counts->intra_inter[j][0];
3789     inter_count += td->counts->intra_inter[j][1];
3790   }
3791
3792   return (intra_count << 2) < inter_count &&
3793          cm->frame_type != KEY_FRAME &&
3794          cm->show_frame;
3795 }
3796
3797 void vp9_init_tile_data(VP9_COMP *cpi) {
3798   VP9_COMMON *const cm = &cpi->common;
3799   const int tile_cols = 1 << cm->log2_tile_cols;
3800   const int tile_rows = 1 << cm->log2_tile_rows;
3801   int tile_col, tile_row;
3802   TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
3803   int tile_tok = 0;
3804
3805   if (cpi->tile_data == NULL) {
3806     CHECK_MEM_ERROR(cm, cpi->tile_data,
3807         vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
3808     for (tile_row = 0; tile_row < tile_rows; ++tile_row)
3809       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
3810         TileDataEnc *tile_data =
3811             &cpi->tile_data[tile_row * tile_cols + tile_col];
3812         int i, j;
3813         for (i = 0; i < BLOCK_SIZES; ++i) {
3814           for (j = 0; j < MAX_MODES; ++j) {
3815             tile_data->thresh_freq_fact[i][j] = 32;
3816             tile_data->mode_map[i][j] = j;
3817           }
3818         }
3819       }
3820   }
3821
3822   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
3823     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
3824       TileInfo *tile_info =
3825           &cpi->tile_data[tile_row * tile_cols + tile_col].tile_info;
3826       vp9_tile_init(tile_info, cm, tile_row, tile_col);
3827
3828       cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
3829       pre_tok = cpi->tile_tok[tile_row][tile_col];
3830       tile_tok = allocated_tokens(*tile_info);
3831     }
3832   }
3833 }
3834
3835 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td,
3836                      int tile_row, int tile_col) {
3837   VP9_COMMON *const cm = &cpi->common;
3838   const int tile_cols = 1 << cm->log2_tile_cols;
3839   TileDataEnc *this_tile =
3840       &cpi->tile_data[tile_row * tile_cols + tile_col];
3841   const TileInfo * const tile_info = &this_tile->tile_info;
3842   TOKENEXTRA *tok = cpi->tile_tok[tile_row][tile_col];
3843   int mi_row;
3844
3845   for (mi_row = tile_info->mi_row_start; mi_row < tile_info->mi_row_end;
3846        mi_row += MI_BLOCK_SIZE) {
3847     if (cpi->sf.use_nonrd_pick_mode)
3848       encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
3849     else
3850       encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
3851   }
3852   cpi->tok_count[tile_row][tile_col] =
3853       (unsigned int)(tok - cpi->tile_tok[tile_row][tile_col]);
3854   assert(tok - cpi->tile_tok[tile_row][tile_col] <=
3855       allocated_tokens(*tile_info));
3856 }
3857
3858 static void encode_tiles(VP9_COMP *cpi) {
3859   VP9_COMMON *const cm = &cpi->common;
3860   const int tile_cols = 1 << cm->log2_tile_cols;
3861   const int tile_rows = 1 << cm->log2_tile_rows;
3862   int tile_col, tile_row;
3863
3864   vp9_init_tile_data(cpi);
3865
3866   for (tile_row = 0; tile_row < tile_rows; ++tile_row)
3867     for (tile_col = 0; tile_col < tile_cols; ++tile_col)
3868       vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
3869 }
3870
3871 #if CONFIG_FP_MB_STATS
3872 static int input_fpmb_stats(FIRSTPASS_MB_STATS *firstpass_mb_stats,
3873                             VP9_COMMON *cm, uint8_t **this_frame_mb_stats) {
3874   uint8_t *mb_stats_in = firstpass_mb_stats->mb_stats_start +
3875       cm->current_video_frame * cm->MBs * sizeof(uint8_t);
3876
3877   if (mb_stats_in > firstpass_mb_stats->mb_stats_end)
3878     return EOF;
3879
3880   *this_frame_mb_stats = mb_stats_in;
3881
3882   return 1;
3883 }
3884 #endif
3885
3886 static void encode_frame_internal(VP9_COMP *cpi) {
3887   SPEED_FEATURES *const sf = &cpi->sf;
3888   RD_OPT *const rd_opt = &cpi->rd;
3889   ThreadData *const td = &cpi->td;
3890   MACROBLOCK *const x = &td->mb;
3891   VP9_COMMON *const cm = &cpi->common;
3892   MACROBLOCKD *const xd = &x->e_mbd;
3893   RD_COUNTS *const rdc = &cpi->td.rd_counts;
3894
3895   xd->mi = cm->mi_grid_visible;
3896   xd->mi[0] = cm->mi;
3897
3898   vp9_zero(*td->counts);
3899   vp9_zero(rdc->coef_counts);
3900   vp9_zero(rdc->comp_pred_diff);
3901   vp9_zero(rdc->filter_diff);
3902   vp9_zero(rdc->tx_select_diff);
3903   vp9_zero(rd_opt->tx_select_threshes);
3904
3905   xd->lossless = cm->base_qindex == 0 &&
3906                  cm->y_dc_delta_q == 0 &&
3907                  cm->uv_dc_delta_q == 0 &&
3908                  cm->uv_ac_delta_q == 0;
3909
3910 #if CONFIG_VP9_HIGHBITDEPTH
3911   if (cm->use_highbitdepth)
3912     x->fwd_txm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vp9_highbd_fdct4x4;
3913   else
3914     x->fwd_txm4x4 = xd->lossless ? vp9_fwht4x4 : vp9_fdct4x4;
3915   x->highbd_itxm_add = xd->lossless ? vp9_highbd_iwht4x4_add :
3916                                       vp9_highbd_idct4x4_add;
3917 #else
3918   x->fwd_txm4x4 = xd->lossless ? vp9_fwht4x4 : vp9_fdct4x4;
3919 #endif  // CONFIG_VP9_HIGHBITDEPTH
3920   x->itxm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
3921
3922   if (xd->lossless)
3923     x->optimize = 0;
3924
3925   cm->tx_mode = select_tx_mode(cpi, xd);
3926
3927   vp9_frame_init_quantizer(cpi);
3928
3929   vp9_initialize_rd_consts(cpi);
3930   vp9_initialize_me_consts(cpi, x, cm->base_qindex);
3931   init_encode_frame_mb_context(cpi);
3932   cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
3933                            cm->width == cm->last_width &&
3934                            cm->height == cm->last_height &&
3935                            !cm->intra_only &&
3936                            cm->last_show_frame;
3937   // Special case: set prev_mi to NULL when the previous mode info
3938   // context cannot be used.
3939   cm->prev_mi = cm->use_prev_frame_mvs ?
3940                 cm->prev_mip + cm->mi_stride + 1 : NULL;
3941
3942   x->quant_fp = cpi->sf.use_quant_fp;
3943   vp9_zero(x->skip_txfm);
3944   if (sf->use_nonrd_pick_mode) {
3945     // Initialize internal buffer pointers for rtc coding, where non-RD
3946     // mode decision is used and hence no buffer pointer swap needed.
3947     int i;
3948     struct macroblock_plane *const p = x->plane;
3949     struct macroblockd_plane *const pd = xd->plane;
3950     PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
3951
3952     for (i = 0; i < MAX_MB_PLANE; ++i) {
3953       p[i].coeff = ctx->coeff_pbuf[i][0];
3954       p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
3955       pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
3956       p[i].eobs = ctx->eobs_pbuf[i][0];
3957     }
3958     vp9_zero(x->zcoeff_blk);
3959
3960     if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0)
3961       cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
3962
3963     if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
3964       source_var_based_partition_search_method(cpi);
3965   }
3966
3967   {
3968     struct vpx_usec_timer emr_timer;
3969     vpx_usec_timer_start(&emr_timer);
3970
3971 #if CONFIG_FP_MB_STATS
3972   if (cpi->use_fp_mb_stats) {
3973     input_fpmb_stats(&cpi->twopass.firstpass_mb_stats, cm,
3974                      &cpi->twopass.this_frame_mb_stats);
3975   }
3976 #endif
3977
3978     // If allowed, encoding tiles in parallel with one thread handling one tile.
3979     if (MIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
3980       vp9_encode_tiles_mt(cpi);
3981     else
3982       encode_tiles(cpi);
3983
3984     vpx_usec_timer_mark(&emr_timer);
3985     cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
3986   }
3987
3988   sf->skip_encode_frame = sf->skip_encode_sb ?
3989       get_skip_encode_frame(cm, td) : 0;
3990
3991 #if 0
3992   // Keep record of the total distortion this time around for future use
3993   cpi->last_frame_distortion = cpi->frame_distortion;
3994 #endif
3995 }
3996
3997 static INTERP_FILTER get_interp_filter(
3998     const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
3999   if (!is_alt_ref &&
4000       threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
4001       threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
4002       threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
4003     return EIGHTTAP_SMOOTH;
4004   } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
4005              threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
4006     return EIGHTTAP_SHARP;
4007   } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
4008     return EIGHTTAP;
4009   } else {
4010     return SWITCHABLE;
4011   }
4012 }
4013
4014 void vp9_encode_frame(VP9_COMP *cpi) {
4015   VP9_COMMON *const cm = &cpi->common;
4016
4017   // In the longer term the encoder should be generalized to match the
4018   // decoder such that we allow compound where one of the 3 buffers has a
4019   // different sign bias and that buffer is then the fixed ref. However, this
4020   // requires further work in the rd loop. For now the only supported encoder
4021   // side behavior is where the ALT ref buffer has opposite sign bias to
4022   // the other two.
4023   if (!frame_is_intra_only(cm)) {
4024     if ((cm->ref_frame_sign_bias[ALTREF_FRAME] ==
4025              cm->ref_frame_sign_bias[GOLDEN_FRAME]) ||
4026         (cm->ref_frame_sign_bias[ALTREF_FRAME] ==
4027              cm->ref_frame_sign_bias[LAST_FRAME])) {
4028       cpi->allow_comp_inter_inter = 0;
4029     } else {
4030       cpi->allow_comp_inter_inter = 1;
4031       cm->comp_fixed_ref = ALTREF_FRAME;
4032       cm->comp_var_ref[0] = LAST_FRAME;
4033       cm->comp_var_ref[1] = GOLDEN_FRAME;
4034     }
4035   }
4036
4037   if (cpi->sf.frame_parameter_update) {
4038     int i;
4039     RD_OPT *const rd_opt = &cpi->rd;
4040     FRAME_COUNTS *counts = cpi->td.counts;
4041     RD_COUNTS *const rdc = &cpi->td.rd_counts;
4042
4043     // This code does a single RD pass over the whole frame assuming
4044     // either compound, single or hybrid prediction as per whatever has
4045     // worked best for that type of frame in the past.
4046     // It also predicts whether another coding mode would have worked
4047     // better that this coding mode. If that is the case, it remembers
4048     // that for subsequent frames.
4049     // It does the same analysis for transform size selection also.
4050     const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
4051     int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
4052     int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
4053     int *const tx_thrs = rd_opt->tx_select_threshes[frame_type];
4054     const int is_alt_ref = frame_type == ALTREF_FRAME;
4055
4056     /* prediction (compound, single or hybrid) mode selection */
4057     if (is_alt_ref || !cpi->allow_comp_inter_inter)
4058       cm->reference_mode = SINGLE_REFERENCE;
4059     else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
4060              mode_thrs[COMPOUND_REFERENCE] >
4061                  mode_thrs[REFERENCE_MODE_SELECT] &&
4062              check_dual_ref_flags(cpi) &&
4063              cpi->static_mb_pct == 100)
4064       cm->reference_mode = COMPOUND_REFERENCE;
4065     else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
4066       cm->reference_mode = SINGLE_REFERENCE;
4067     else
4068       cm->reference_mode = REFERENCE_MODE_SELECT;
4069
4070     if (cm->interp_filter == SWITCHABLE)
4071       cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
4072
4073     encode_frame_internal(cpi);
4074
4075     for (i = 0; i < REFERENCE_MODES; ++i)
4076       mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
4077
4078     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
4079       filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
4080
4081     for (i = 0; i < TX_MODES; ++i) {
4082       int64_t pd = rdc->tx_select_diff[i];
4083       if (i == TX_MODE_SELECT)
4084         pd -= RDCOST(cpi->td.mb.rdmult, cpi->td.mb.rddiv, 2048 * (TX_SIZES - 1),
4085                      0);
4086       tx_thrs[i] = (tx_thrs[i] + (int)(pd / cm->MBs)) / 2;
4087     }
4088
4089     if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4090       int single_count_zero = 0;
4091       int comp_count_zero = 0;
4092
4093       for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
4094         single_count_zero += counts->comp_inter[i][0];
4095         comp_count_zero += counts->comp_inter[i][1];
4096       }
4097
4098       if (comp_count_zero == 0) {
4099         cm->reference_mode = SINGLE_REFERENCE;
4100         vp9_zero(counts->comp_inter);
4101       } else if (single_count_zero == 0) {
4102         cm->reference_mode = COMPOUND_REFERENCE;
4103         vp9_zero(counts->comp_inter);
4104       }
4105     }
4106
4107     if (cm->tx_mode == TX_MODE_SELECT) {
4108       int count4x4 = 0;
4109       int count8x8_lp = 0, count8x8_8x8p = 0;
4110       int count16x16_16x16p = 0, count16x16_lp = 0;
4111       int count32x32 = 0;
4112
4113       for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
4114         count4x4 += counts->tx.p32x32[i][TX_4X4];
4115         count4x4 += counts->tx.p16x16[i][TX_4X4];
4116         count4x4 += counts->tx.p8x8[i][TX_4X4];
4117
4118         count8x8_lp += counts->tx.p32x32[i][TX_8X8];
4119         count8x8_lp += counts->tx.p16x16[i][TX_8X8];
4120         count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
4121
4122         count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
4123         count16x16_lp += counts->tx.p32x32[i][TX_16X16];
4124         count32x32 += counts->tx.p32x32[i][TX_32X32];
4125       }
4126       if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
4127           count32x32 == 0) {
4128         cm->tx_mode = ALLOW_8X8;
4129         reset_skip_tx_size(cm, TX_8X8);
4130       } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
4131                  count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
4132         cm->tx_mode = ONLY_4X4;
4133         reset_skip_tx_size(cm, TX_4X4);
4134       } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
4135         cm->tx_mode = ALLOW_32X32;
4136       } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
4137         cm->tx_mode = ALLOW_16X16;
4138         reset_skip_tx_size(cm, TX_16X16);
4139       }
4140     }
4141   } else {
4142     cm->reference_mode = SINGLE_REFERENCE;
4143     encode_frame_internal(cpi);
4144   }
4145 }
4146
4147 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
4148   const PREDICTION_MODE y_mode = mi->mbmi.mode;
4149   const PREDICTION_MODE uv_mode = mi->mbmi.uv_mode;
4150   const BLOCK_SIZE bsize = mi->mbmi.sb_type;
4151
4152   if (bsize < BLOCK_8X8) {
4153     int idx, idy;
4154     const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
4155     const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
4156     for (idy = 0; idy < 2; idy += num_4x4_h)
4157       for (idx = 0; idx < 2; idx += num_4x4_w)
4158         ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
4159   } else {
4160     ++counts->y_mode[size_group_lookup[bsize]][y_mode];
4161   }
4162
4163   ++counts->uv_mode[y_mode][uv_mode];
4164 }
4165
4166 static void encode_superblock(VP9_COMP *cpi, ThreadData *td,
4167                               TOKENEXTRA **t, int output_enabled,
4168                               int mi_row, int mi_col, BLOCK_SIZE bsize,
4169                               PICK_MODE_CONTEXT *ctx) {
4170   VP9_COMMON *const cm = &cpi->common;
4171   MACROBLOCK *const x = &td->mb;
4172   MACROBLOCKD *const xd = &x->e_mbd;
4173   MODE_INFO **mi_8x8 = xd->mi;
4174   MODE_INFO *mi = mi_8x8[0];
4175   MB_MODE_INFO *mbmi = &mi->mbmi;
4176   const int seg_skip = vp9_segfeature_active(&cm->seg, mbmi->segment_id,
4177                                              SEG_LVL_SKIP);
4178   const int mis = cm->mi_stride;
4179   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
4180   const int mi_height = num_8x8_blocks_high_lookup[bsize];
4181
4182   x->skip_recode = !x->select_tx_size && mbmi->sb_type >= BLOCK_8X8 &&
4183                    cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
4184                    cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
4185                    cpi->sf.allow_skip_recode;
4186
4187   if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
4188     vpx_memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
4189
4190   x->skip_optimize = ctx->is_coded;
4191   ctx->is_coded = 1;
4192   x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
4193   x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
4194                     x->q_index < QIDX_SKIP_THRESH);
4195
4196   if (x->skip_encode)
4197     return;
4198
4199   set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
4200
4201   if (!is_inter_block(mbmi)) {
4202     int plane;
4203     mbmi->skip = 1;
4204     for (plane = 0; plane < MAX_MB_PLANE; ++plane)
4205       vp9_encode_intra_block_plane(x, MAX(bsize, BLOCK_8X8), plane);
4206     if (output_enabled)
4207       sum_intra_stats(td->counts, mi);
4208     vp9_tokenize_sb(cpi, td, t, !output_enabled, MAX(bsize, BLOCK_8X8));
4209   } else {
4210     int ref;
4211     const int is_compound = has_second_ref(mbmi);
4212     for (ref = 0; ref < 1 + is_compound; ++ref) {
4213       YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi,
4214                                                      mbmi->ref_frame[ref]);
4215       assert(cfg != NULL);
4216       vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
4217                            &xd->block_refs[ref]->sf);
4218     }
4219     if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
4220       vp9_build_inter_predictors_sby(xd, mi_row, mi_col, MAX(bsize, BLOCK_8X8));
4221
4222     vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col, MAX(bsize, BLOCK_8X8));
4223
4224     vp9_encode_sb(x, MAX(bsize, BLOCK_8X8));
4225     vp9_tokenize_sb(cpi, td, t, !output_enabled, MAX(bsize, BLOCK_8X8));
4226   }
4227
4228   if (output_enabled) {
4229     if (cm->tx_mode == TX_MODE_SELECT &&
4230         mbmi->sb_type >= BLOCK_8X8  &&
4231         !(is_inter_block(mbmi) && (mbmi->skip || seg_skip))) {
4232       ++get_tx_counts(max_txsize_lookup[bsize], vp9_get_tx_size_context(xd),
4233                       &td->counts->tx)[mbmi->tx_size];
4234     } else {
4235       int x, y;
4236       TX_SIZE tx_size;
4237       // The new intra coding scheme requires no change of transform size
4238       if (is_inter_block(&mi->mbmi)) {
4239         tx_size = MIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
4240                       max_txsize_lookup[bsize]);
4241       } else {
4242         tx_size = (bsize >= BLOCK_8X8) ? mbmi->tx_size : TX_4X4;
4243       }
4244
4245       for (y = 0; y < mi_height; y++)
4246         for (x = 0; x < mi_width; x++)
4247           if (mi_col + x < cm->mi_cols && mi_row + y < cm->mi_rows)
4248             mi_8x8[mis * y + x]->mbmi.tx_size = tx_size;
4249     }
4250     ++td->counts->tx.tx_totals[mbmi->tx_size];
4251     ++td->counts->tx.tx_totals[get_uv_tx_size(mbmi, &xd->plane[1])];
4252   }
4253 }