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