Merge "Changes to use of rectangular partitions."
[platform/upstream/libvpx.git] / vp9 / encoder / vp9_encodeframe.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <limits.h>
12 #include <math.h>
13 #include <stdio.h>
14
15 #include "./vp9_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 "vp9/common/vp9_common.h"
23 #include "vp9/common/vp9_entropy.h"
24 #include "vp9/common/vp9_entropymode.h"
25 #include "vp9/common/vp9_idct.h"
26 #include "vp9/common/vp9_mvref_common.h"
27 #include "vp9/common/vp9_pred_common.h"
28 #include "vp9/common/vp9_quant_common.h"
29 #include "vp9/common/vp9_reconintra.h"
30 #include "vp9/common/vp9_reconinter.h"
31 #include "vp9/common/vp9_seg_common.h"
32 #include "vp9/common/vp9_systemdependent.h"
33 #include "vp9/common/vp9_tile_common.h"
34
35 #include "vp9/encoder/vp9_aq_complexity.h"
36 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
37 #include "vp9/encoder/vp9_aq_variance.h"
38 #include "vp9/encoder/vp9_encodeframe.h"
39 #include "vp9/encoder/vp9_encodemb.h"
40 #include "vp9/encoder/vp9_encodemv.h"
41 #include "vp9/encoder/vp9_ethread.h"
42 #include "vp9/encoder/vp9_extend.h"
43 #include "vp9/encoder/vp9_pickmode.h"
44 #include "vp9/encoder/vp9_rd.h"
45 #include "vp9/encoder/vp9_rdopt.h"
46 #include "vp9/encoder/vp9_segmentation.h"
47 #include "vp9/encoder/vp9_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 vp9_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 vp9_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   vp9_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   vp9_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     vp9_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 vp9_append_sub8x8_mvs_for_idx() and vp9_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 vp9_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         vp9_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
551                               d + y8_idx * dp + x8_idx, dp,
552                               &min, &max);
553       } else {
554         vp9_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
555                        d + y8_idx * dp + x8_idx, dp,
556                        &min, &max);
557       }
558 #else
559       vp9_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 = vp9_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
592         if (!is_key_frame)
593           d_avg = vp9_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
594       } else {
595         s_avg = vp9_avg_4x4(s + y4_idx * sp + x4_idx, sp);
596         if (!is_key_frame)
597           d_avg = vp9_avg_4x4(d + y4_idx * dp + x4_idx, dp);
598       }
599 #else
600       s_avg = vp9_avg_4x4(s + y4_idx * sp + x4_idx, sp);
601       if (!is_key_frame)
602         d_avg = vp9_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 = vp9_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
631         if (!is_key_frame)
632           d_avg = vp9_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
633       } else {
634         s_avg = vp9_avg_8x8(s + y8_idx * sp + x8_idx, sp);
635         if (!is_key_frame)
636           d_avg = vp9_avg_8x8(d + y8_idx * dp + x8_idx, dp);
637       }
638 #else
639       s_avg = vp9_avg_8x8(s + y8_idx * sp + x8_idx, sp);
640       if (!is_key_frame)
641         d_avg = vp9_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 = vp9_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       vp9_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     vp9_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 = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col);
740     if (y_sad_g < y_sad) {
741       vp9_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     vp9_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       vp9_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     vp9_init_plane_quantizers(cpi, x);
1041
1042   // FIXME(rbultje) I'm pretty sure this should go to the end of this block
1043   // (i.e. after the output_enabled)
1044   if (bsize < BLOCK_32X32) {
1045     if (bsize < BLOCK_16X16)
1046       ctx->tx_rd_diff[ALLOW_16X16] = ctx->tx_rd_diff[ALLOW_8X8];
1047     ctx->tx_rd_diff[ALLOW_32X32] = ctx->tx_rd_diff[ALLOW_16X16];
1048   }
1049
1050   if (is_inter_block(mbmi) && mbmi->sb_type < BLOCK_8X8) {
1051     mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1052     mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1053   }
1054
1055   x->skip = ctx->skip;
1056   memcpy(x->zcoeff_blk[mbmi->tx_size], ctx->zcoeff_blk,
1057          sizeof(uint8_t) * ctx->num_4x4_blk);
1058
1059   if (!output_enabled)
1060     return;
1061
1062   if (!segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
1063     for (i = 0; i < TX_MODES; i++)
1064       rdc->tx_select_diff[i] += ctx->tx_rd_diff[i];
1065   }
1066
1067 #if CONFIG_INTERNAL_STATS
1068   if (frame_is_intra_only(cm)) {
1069     static const int kf_mode_index[] = {
1070       THR_DC        /*DC_PRED*/,
1071       THR_V_PRED    /*V_PRED*/,
1072       THR_H_PRED    /*H_PRED*/,
1073       THR_D45_PRED  /*D45_PRED*/,
1074       THR_D135_PRED /*D135_PRED*/,
1075       THR_D117_PRED /*D117_PRED*/,
1076       THR_D153_PRED /*D153_PRED*/,
1077       THR_D207_PRED /*D207_PRED*/,
1078       THR_D63_PRED  /*D63_PRED*/,
1079       THR_TM        /*TM_PRED*/,
1080     };
1081     ++cpi->mode_chosen_counts[kf_mode_index[mbmi->mode]];
1082   } else {
1083     // Note how often each mode chosen as best
1084     ++cpi->mode_chosen_counts[ctx->best_mode_index];
1085   }
1086 #endif
1087   if (!frame_is_intra_only(cm)) {
1088     if (is_inter_block(mbmi)) {
1089       vp9_update_mv_count(td);
1090
1091       if (cm->interp_filter == SWITCHABLE) {
1092         const int ctx = vp9_get_pred_context_switchable_interp(xd);
1093         ++td->counts->switchable_interp[ctx][mbmi->interp_filter];
1094       }
1095     }
1096
1097     rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1098     rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1099     rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1100
1101     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1102       rdc->filter_diff[i] += ctx->best_filter_diff[i];
1103   }
1104
1105   for (h = 0; h < y_mis; ++h) {
1106     MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1107     for (w = 0; w < x_mis; ++w) {
1108       MV_REF *const mv = frame_mv + w;
1109       mv->ref_frame[0] = mi->mbmi.ref_frame[0];
1110       mv->ref_frame[1] = mi->mbmi.ref_frame[1];
1111       mv->mv[0].as_int = mi->mbmi.mv[0].as_int;
1112       mv->mv[1].as_int = mi->mbmi.mv[1].as_int;
1113     }
1114   }
1115 }
1116
1117 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1118                           int mi_row, int mi_col) {
1119   uint8_t *const buffers[3] = {src->y_buffer, src->u_buffer, src->v_buffer };
1120   const int strides[3] = {src->y_stride, src->uv_stride, src->uv_stride };
1121   int i;
1122
1123   // Set current frame pointer.
1124   x->e_mbd.cur_buf = src;
1125
1126   for (i = 0; i < MAX_MB_PLANE; i++)
1127     setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1128                      NULL, x->e_mbd.plane[i].subsampling_x,
1129                      x->e_mbd.plane[i].subsampling_y);
1130 }
1131
1132 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1133                                    RD_COST *rd_cost, BLOCK_SIZE bsize) {
1134   MACROBLOCKD *const xd = &x->e_mbd;
1135   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
1136   INTERP_FILTER filter_ref;
1137
1138   if (xd->up_available)
1139     filter_ref = xd->mi[-xd->mi_stride]->mbmi.interp_filter;
1140   else if (xd->left_available)
1141     filter_ref = xd->mi[-1]->mbmi.interp_filter;
1142   else
1143     filter_ref = EIGHTTAP;
1144
1145   mbmi->sb_type = bsize;
1146   mbmi->mode = ZEROMV;
1147   mbmi->tx_size = MIN(max_txsize_lookup[bsize],
1148                       tx_mode_to_biggest_tx_size[tx_mode]);
1149   mbmi->skip = 1;
1150   mbmi->uv_mode = DC_PRED;
1151   mbmi->ref_frame[0] = LAST_FRAME;
1152   mbmi->ref_frame[1] = NONE;
1153   mbmi->mv[0].as_int = 0;
1154   mbmi->interp_filter = filter_ref;
1155
1156   xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1157   x->skip = 1;
1158
1159   vp9_rd_cost_init(rd_cost);
1160 }
1161
1162 static int set_segment_rdmult(VP9_COMP *const cpi,
1163                                MACROBLOCK *const x,
1164                                int8_t segment_id) {
1165   int segment_qindex;
1166   VP9_COMMON *const cm = &cpi->common;
1167   vp9_init_plane_quantizers(cpi, x);
1168   vp9_clear_system_state();
1169   segment_qindex = vp9_get_qindex(&cm->seg, segment_id,
1170                                   cm->base_qindex);
1171   return vp9_compute_rd_mult(cpi, segment_qindex + cm->y_dc_delta_q);
1172 }
1173
1174 static void rd_pick_sb_modes(VP9_COMP *cpi,
1175                              TileDataEnc *tile_data,
1176                              MACROBLOCK *const x,
1177                              int mi_row, int mi_col, RD_COST *rd_cost,
1178                              BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
1179                              int64_t best_rd) {
1180   VP9_COMMON *const cm = &cpi->common;
1181   TileInfo *const tile_info = &tile_data->tile_info;
1182   MACROBLOCKD *const xd = &x->e_mbd;
1183   MB_MODE_INFO *mbmi;
1184   struct macroblock_plane *const p = x->plane;
1185   struct macroblockd_plane *const pd = xd->plane;
1186   const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1187   int i, orig_rdmult;
1188
1189   vp9_clear_system_state();
1190
1191   // Use the lower precision, but faster, 32x32 fdct for mode selection.
1192   x->use_lp32x32fdct = 1;
1193
1194   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1195   mbmi = &xd->mi[0]->mbmi;
1196   mbmi->sb_type = bsize;
1197
1198   for (i = 0; i < MAX_MB_PLANE; ++i) {
1199     p[i].coeff = ctx->coeff_pbuf[i][0];
1200     p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1201     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1202     p[i].eobs = ctx->eobs_pbuf[i][0];
1203   }
1204   ctx->is_coded = 0;
1205   ctx->skippable = 0;
1206   ctx->pred_pixel_ready = 0;
1207   x->skip_recode = 0;
1208
1209   // Set to zero to make sure we do not use the previous encoded frame stats
1210   mbmi->skip = 0;
1211
1212 #if CONFIG_VP9_HIGHBITDEPTH
1213   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1214     x->source_variance =
1215         vp9_high_get_sby_perpixel_variance(cpi, &x->plane[0].src,
1216                                            bsize, xd->bd);
1217   } else {
1218     x->source_variance =
1219       vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1220   }
1221 #else
1222   x->source_variance =
1223     vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1224 #endif  // CONFIG_VP9_HIGHBITDEPTH
1225
1226   // Save rdmult before it might be changed, so it can be restored later.
1227   orig_rdmult = x->rdmult;
1228
1229   if (aq_mode == VARIANCE_AQ) {
1230     const int energy = bsize <= BLOCK_16X16 ? x->mb_energy
1231                                             : vp9_block_energy(cpi, x, bsize);
1232     if (cm->frame_type == KEY_FRAME ||
1233         cpi->refresh_alt_ref_frame ||
1234         (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
1235       mbmi->segment_id = vp9_vaq_segment_id(energy);
1236     } else {
1237       const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map
1238                                                     : cm->last_frame_seg_map;
1239       mbmi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1240     }
1241     x->rdmult = set_segment_rdmult(cpi, x, mbmi->segment_id);
1242   } else if (aq_mode == COMPLEXITY_AQ) {
1243     x->rdmult = set_segment_rdmult(cpi, x, mbmi->segment_id);
1244   } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1245     const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map
1246                                                   : cm->last_frame_seg_map;
1247     // If segment is boosted, use rdmult for that segment.
1248     if (cyclic_refresh_segment_id_boosted(
1249             get_segment_id(cm, map, bsize, mi_row, mi_col)))
1250       x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1251   }
1252
1253   // Find best coding mode & reconstruct the MB so it is available
1254   // as a predictor for MBs that follow in the SB
1255   if (frame_is_intra_only(cm)) {
1256     vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
1257   } else {
1258     if (bsize >= BLOCK_8X8) {
1259       if (segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP))
1260         vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
1261                                            ctx, best_rd);
1262       else
1263         vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col,
1264                                   rd_cost, bsize, ctx, best_rd);
1265     } else {
1266       vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col,
1267                                     rd_cost, bsize, ctx, best_rd);
1268     }
1269   }
1270
1271
1272   // Examine the resulting rate and for AQ mode 2 make a segment choice.
1273   if ((rd_cost->rate != INT_MAX) &&
1274       (aq_mode == COMPLEXITY_AQ) && (bsize >= BLOCK_16X16) &&
1275       (cm->frame_type == KEY_FRAME ||
1276        cpi->refresh_alt_ref_frame ||
1277        (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
1278     vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
1279   }
1280
1281   x->rdmult = orig_rdmult;
1282
1283   // TODO(jingning) The rate-distortion optimization flow needs to be
1284   // refactored to provide proper exit/return handle.
1285   if (rd_cost->rate == INT_MAX)
1286     rd_cost->rdcost = INT64_MAX;
1287
1288   ctx->rate = rd_cost->rate;
1289   ctx->dist = rd_cost->dist;
1290 }
1291
1292 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
1293   const MACROBLOCK *x = &td->mb;
1294   const MACROBLOCKD *const xd = &x->e_mbd;
1295   const MODE_INFO *const mi = xd->mi[0];
1296   const MB_MODE_INFO *const mbmi = &mi->mbmi;
1297   const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
1298   const BLOCK_SIZE bsize = mbmi->sb_type;
1299
1300   if (!frame_is_intra_only(cm)) {
1301     FRAME_COUNTS *const counts = td->counts;
1302     const int inter_block = is_inter_block(mbmi);
1303     const int seg_ref_active = segfeature_active(&cm->seg, mbmi->segment_id,
1304                                                  SEG_LVL_REF_FRAME);
1305     if (!seg_ref_active) {
1306       counts->intra_inter[vp9_get_intra_inter_context(xd)][inter_block]++;
1307       // If the segment reference feature is enabled we have only a single
1308       // reference frame allowed for the segment so exclude it from
1309       // the reference frame counts used to work out probabilities.
1310       if (inter_block) {
1311         const MV_REFERENCE_FRAME ref0 = mbmi->ref_frame[0];
1312         if (cm->reference_mode == REFERENCE_MODE_SELECT)
1313           counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
1314                             [has_second_ref(mbmi)]++;
1315
1316         if (has_second_ref(mbmi)) {
1317           counts->comp_ref[vp9_get_pred_context_comp_ref_p(cm, xd)]
1318                           [ref0 == GOLDEN_FRAME]++;
1319         } else {
1320           counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
1321                             [ref0 != LAST_FRAME]++;
1322           if (ref0 != LAST_FRAME)
1323             counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
1324                               [ref0 != GOLDEN_FRAME]++;
1325         }
1326       }
1327     }
1328     if (inter_block &&
1329         !segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
1330       const int mode_ctx = mbmi_ext->mode_context[mbmi->ref_frame[0]];
1331       if (bsize >= BLOCK_8X8) {
1332         const PREDICTION_MODE mode = mbmi->mode;
1333         ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
1334       } else {
1335         const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
1336         const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
1337         int idx, idy;
1338         for (idy = 0; idy < 2; idy += num_4x4_h) {
1339           for (idx = 0; idx < 2; idx += num_4x4_w) {
1340             const int j = idy * 2 + idx;
1341             const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
1342             ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
1343           }
1344         }
1345       }
1346     }
1347   }
1348 }
1349
1350 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
1351                             ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
1352                             ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
1353                             PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
1354                             BLOCK_SIZE bsize) {
1355   MACROBLOCKD *const xd = &x->e_mbd;
1356   int p;
1357   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1358   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1359   int mi_width = num_8x8_blocks_wide_lookup[bsize];
1360   int mi_height = num_8x8_blocks_high_lookup[bsize];
1361   for (p = 0; p < MAX_MB_PLANE; p++) {
1362     memcpy(
1363         xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
1364         a + num_4x4_blocks_wide * p,
1365         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
1366         xd->plane[p].subsampling_x);
1367     memcpy(
1368         xd->left_context[p]
1369             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
1370         l + num_4x4_blocks_high * p,
1371         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
1372         xd->plane[p].subsampling_y);
1373   }
1374   memcpy(xd->above_seg_context + mi_col, sa,
1375          sizeof(*xd->above_seg_context) * mi_width);
1376   memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
1377          sizeof(xd->left_seg_context[0]) * mi_height);
1378 }
1379
1380 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
1381                          ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
1382                          ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
1383                          PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
1384                          BLOCK_SIZE bsize) {
1385   const MACROBLOCKD *const xd = &x->e_mbd;
1386   int p;
1387   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1388   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1389   int mi_width = num_8x8_blocks_wide_lookup[bsize];
1390   int mi_height = num_8x8_blocks_high_lookup[bsize];
1391
1392   // buffer the above/left context information of the block in search.
1393   for (p = 0; p < MAX_MB_PLANE; ++p) {
1394     memcpy(
1395         a + num_4x4_blocks_wide * p,
1396         xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
1397         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
1398         xd->plane[p].subsampling_x);
1399     memcpy(
1400         l + num_4x4_blocks_high * p,
1401         xd->left_context[p]
1402             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
1403         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
1404         xd->plane[p].subsampling_y);
1405   }
1406   memcpy(sa, xd->above_seg_context + mi_col,
1407          sizeof(*xd->above_seg_context) * mi_width);
1408   memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
1409          sizeof(xd->left_seg_context[0]) * mi_height);
1410 }
1411
1412 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile,
1413                      ThreadData *td,
1414                      TOKENEXTRA **tp, int mi_row, int mi_col,
1415                      int output_enabled, BLOCK_SIZE bsize,
1416                      PICK_MODE_CONTEXT *ctx) {
1417   MACROBLOCK *const x = &td->mb;
1418   set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
1419   update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
1420   encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
1421
1422   if (output_enabled) {
1423     update_stats(&cpi->common, td);
1424
1425     (*tp)->token = EOSB_TOKEN;
1426     (*tp)++;
1427   }
1428 }
1429
1430 static void encode_sb(VP9_COMP *cpi, ThreadData *td,
1431                       const TileInfo *const tile,
1432                       TOKENEXTRA **tp, int mi_row, int mi_col,
1433                       int output_enabled, BLOCK_SIZE bsize,
1434                       PC_TREE *pc_tree) {
1435   VP9_COMMON *const cm = &cpi->common;
1436   MACROBLOCK *const x = &td->mb;
1437   MACROBLOCKD *const xd = &x->e_mbd;
1438
1439   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
1440   int ctx;
1441   PARTITION_TYPE partition;
1442   BLOCK_SIZE subsize = bsize;
1443
1444   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1445     return;
1446
1447   if (bsize >= BLOCK_8X8) {
1448     ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
1449     subsize = get_subsize(bsize, pc_tree->partitioning);
1450   } else {
1451     ctx = 0;
1452     subsize = BLOCK_4X4;
1453   }
1454
1455   partition = partition_lookup[bsl][subsize];
1456   if (output_enabled && bsize != BLOCK_4X4)
1457     td->counts->partition[ctx][partition]++;
1458
1459   switch (partition) {
1460     case PARTITION_NONE:
1461       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1462                &pc_tree->none);
1463       break;
1464     case PARTITION_VERT:
1465       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1466                &pc_tree->vertical[0]);
1467       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
1468         encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
1469                  subsize, &pc_tree->vertical[1]);
1470       }
1471       break;
1472     case PARTITION_HORZ:
1473       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1474                &pc_tree->horizontal[0]);
1475       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
1476         encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
1477                  subsize, &pc_tree->horizontal[1]);
1478       }
1479       break;
1480     case PARTITION_SPLIT:
1481       if (bsize == BLOCK_8X8) {
1482         encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1483                  pc_tree->leaf_split[0]);
1484       } else {
1485         encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1486                   pc_tree->split[0]);
1487         encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1488                   subsize, pc_tree->split[1]);
1489         encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1490                   subsize, pc_tree->split[2]);
1491         encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
1492                   subsize, pc_tree->split[3]);
1493       }
1494       break;
1495     default:
1496       assert(0 && "Invalid partition type.");
1497       break;
1498   }
1499
1500   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
1501     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
1502 }
1503
1504 // Check to see if the given partition size is allowed for a specified number
1505 // of 8x8 block rows and columns remaining in the image.
1506 // If not then return the largest allowed partition size
1507 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize,
1508                                       int rows_left, int cols_left,
1509                                       int *bh, int *bw) {
1510   if (rows_left <= 0 || cols_left <= 0) {
1511     return MIN(bsize, BLOCK_8X8);
1512   } else {
1513     for (; bsize > 0; bsize -= 3) {
1514       *bh = num_8x8_blocks_high_lookup[bsize];
1515       *bw = num_8x8_blocks_wide_lookup[bsize];
1516       if ((*bh <= rows_left) && (*bw <= cols_left)) {
1517         break;
1518       }
1519     }
1520   }
1521   return bsize;
1522 }
1523
1524 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis,
1525     int bh_in, int bw_in, int row8x8_remaining, int col8x8_remaining,
1526     BLOCK_SIZE bsize, MODE_INFO **mi_8x8) {
1527   int bh = bh_in;
1528   int r, c;
1529   for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
1530     int bw = bw_in;
1531     for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
1532       const int index = r * mis + c;
1533       mi_8x8[index] = mi + index;
1534       mi_8x8[index]->mbmi.sb_type = find_partition_size(bsize,
1535           row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
1536     }
1537   }
1538 }
1539
1540 // This function attempts to set all mode info entries in a given SB64
1541 // to the same block partition size.
1542 // However, at the bottom and right borders of the image the requested size
1543 // may not be allowed in which case this code attempts to choose the largest
1544 // allowable partition.
1545 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1546                                    MODE_INFO **mi_8x8, int mi_row, int mi_col,
1547                                    BLOCK_SIZE bsize) {
1548   VP9_COMMON *const cm = &cpi->common;
1549   const int mis = cm->mi_stride;
1550   const int row8x8_remaining = tile->mi_row_end - mi_row;
1551   const int col8x8_remaining = tile->mi_col_end - mi_col;
1552   int block_row, block_col;
1553   MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
1554   int bh = num_8x8_blocks_high_lookup[bsize];
1555   int bw = num_8x8_blocks_wide_lookup[bsize];
1556
1557   assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
1558
1559   // Apply the requested partition size to the SB64 if it is all "in image"
1560   if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
1561       (row8x8_remaining >= MI_BLOCK_SIZE)) {
1562     for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
1563       for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
1564         int index = block_row * mis + block_col;
1565         mi_8x8[index] = mi_upper_left + index;
1566         mi_8x8[index]->mbmi.sb_type = bsize;
1567       }
1568     }
1569   } else {
1570     // Else this is a partial SB64.
1571     set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
1572         col8x8_remaining, bsize, mi_8x8);
1573   }
1574 }
1575
1576 static const struct {
1577   int row;
1578   int col;
1579 } coord_lookup[16] = {
1580     // 32x32 index = 0
1581     {0, 0}, {0, 2}, {2, 0}, {2, 2},
1582     // 32x32 index = 1
1583     {0, 4}, {0, 6}, {2, 4}, {2, 6},
1584     // 32x32 index = 2
1585     {4, 0}, {4, 2}, {6, 0}, {6, 2},
1586     // 32x32 index = 3
1587     {4, 4}, {4, 6}, {6, 4}, {6, 6},
1588 };
1589
1590 static void set_source_var_based_partition(VP9_COMP *cpi,
1591                                            const TileInfo *const tile,
1592                                            MACROBLOCK *const x,
1593                                            MODE_INFO **mi_8x8,
1594                                            int mi_row, int mi_col) {
1595   VP9_COMMON *const cm = &cpi->common;
1596   const int mis = cm->mi_stride;
1597   const int row8x8_remaining = tile->mi_row_end - mi_row;
1598   const int col8x8_remaining = tile->mi_col_end - mi_col;
1599   MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
1600
1601   vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
1602
1603   assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
1604
1605   // In-image SB64
1606   if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
1607       (row8x8_remaining >= MI_BLOCK_SIZE)) {
1608     int i, j;
1609     int index;
1610     diff d32[4];
1611     const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
1612     int is_larger_better = 0;
1613     int use32x32 = 0;
1614     unsigned int thr = cpi->source_var_thresh;
1615
1616     memset(d32, 0, 4 * sizeof(diff));
1617
1618     for (i = 0; i < 4; i++) {
1619       diff *d16[4];
1620
1621       for (j = 0; j < 4; j++) {
1622         int b_mi_row = coord_lookup[i * 4 + j].row;
1623         int b_mi_col = coord_lookup[i * 4 + j].col;
1624         int boffset = b_mi_row / 2 * cm->mb_cols +
1625                       b_mi_col / 2;
1626
1627         d16[j] = cpi->source_diff_var + offset + boffset;
1628
1629         index = b_mi_row * mis + b_mi_col;
1630         mi_8x8[index] = mi_upper_left + index;
1631         mi_8x8[index]->mbmi.sb_type = BLOCK_16X16;
1632
1633         // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
1634         // size to further improve quality.
1635       }
1636
1637       is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
1638           (d16[2]->var < thr) && (d16[3]->var < thr);
1639
1640       // Use 32x32 partition
1641       if (is_larger_better) {
1642         use32x32 += 1;
1643
1644         for (j = 0; j < 4; j++) {
1645           d32[i].sse += d16[j]->sse;
1646           d32[i].sum += d16[j]->sum;
1647         }
1648
1649         d32[i].var = d32[i].sse - (((int64_t)d32[i].sum * d32[i].sum) >> 10);
1650
1651         index = coord_lookup[i*4].row * mis + coord_lookup[i*4].col;
1652         mi_8x8[index] = mi_upper_left + index;
1653         mi_8x8[index]->mbmi.sb_type = BLOCK_32X32;
1654       }
1655     }
1656
1657     if (use32x32 == 4) {
1658       thr <<= 1;
1659       is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
1660           (d32[2].var < thr) && (d32[3].var < thr);
1661
1662       // Use 64x64 partition
1663       if (is_larger_better) {
1664         mi_8x8[0] = mi_upper_left;
1665         mi_8x8[0]->mbmi.sb_type = BLOCK_64X64;
1666       }
1667     }
1668   } else {   // partial in-image SB64
1669     int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
1670     int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
1671     set_partial_b64x64_partition(mi_upper_left, mis, bh, bw,
1672         row8x8_remaining, col8x8_remaining, BLOCK_16X16, mi_8x8);
1673   }
1674 }
1675
1676 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
1677                             PICK_MODE_CONTEXT *ctx,
1678                             int mi_row, int mi_col, int bsize) {
1679   VP9_COMMON *const cm = &cpi->common;
1680   MACROBLOCK *const x = &td->mb;
1681   MACROBLOCKD *const xd = &x->e_mbd;
1682   MODE_INFO *const mi = xd->mi[0];
1683   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
1684   const struct segmentation *const seg = &cm->seg;
1685   const int bw = num_8x8_blocks_wide_lookup[mi->mbmi.sb_type];
1686   const int bh = num_8x8_blocks_high_lookup[mi->mbmi.sb_type];
1687   const int x_mis = MIN(bw, cm->mi_cols - mi_col);
1688   const int y_mis = MIN(bh, cm->mi_rows - mi_row);
1689
1690   *(xd->mi[0]) = ctx->mic;
1691   *(x->mbmi_ext) = ctx->mbmi_ext;
1692
1693   if (seg->enabled && cpi->oxcf.aq_mode) {
1694     // For in frame complexity AQ or variance AQ, copy segment_id from
1695     // segmentation_map.
1696     if (cpi->oxcf.aq_mode == COMPLEXITY_AQ ||
1697         cpi->oxcf.aq_mode == VARIANCE_AQ ) {
1698       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
1699                                                  : cm->last_frame_seg_map;
1700       mbmi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1701     } else {
1702     // Setting segmentation map for cyclic_refresh.
1703       vp9_cyclic_refresh_update_segment(cpi, mbmi, mi_row, mi_col, bsize,
1704                                         ctx->rate, ctx->dist, x->skip);
1705     }
1706     vp9_init_plane_quantizers(cpi, x);
1707   }
1708
1709   if (is_inter_block(mbmi)) {
1710     vp9_update_mv_count(td);
1711     if (cm->interp_filter == SWITCHABLE) {
1712       const int pred_ctx = vp9_get_pred_context_switchable_interp(xd);
1713       ++td->counts->switchable_interp[pred_ctx][mbmi->interp_filter];
1714     }
1715
1716     if (mbmi->sb_type < BLOCK_8X8) {
1717       mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1718       mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1719     }
1720   }
1721
1722   if (cm->use_prev_frame_mvs) {
1723     MV_REF *const frame_mvs =
1724         cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1725     int w, h;
1726
1727     for (h = 0; h < y_mis; ++h) {
1728       MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1729       for (w = 0; w < x_mis; ++w) {
1730         MV_REF *const mv = frame_mv + w;
1731         mv->ref_frame[0] = mi->mbmi.ref_frame[0];
1732         mv->ref_frame[1] = mi->mbmi.ref_frame[1];
1733         mv->mv[0].as_int = mi->mbmi.mv[0].as_int;
1734         mv->mv[1].as_int = mi->mbmi.mv[1].as_int;
1735       }
1736     }
1737   }
1738
1739   x->skip = ctx->skip;
1740   x->skip_txfm[0] = mbmi->segment_id ? 0 : ctx->skip_txfm[0];
1741 }
1742
1743 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
1744                         const TileInfo *const tile,
1745                         TOKENEXTRA **tp, int mi_row, int mi_col,
1746                         int output_enabled, BLOCK_SIZE bsize,
1747                         PICK_MODE_CONTEXT *ctx) {
1748   MACROBLOCK *const x = &td->mb;
1749   set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
1750   update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
1751
1752 #if CONFIG_VP9_TEMPORAL_DENOISING
1753   if (cpi->oxcf.noise_sensitivity > 0 && output_enabled &&
1754       cpi->common.frame_type != KEY_FRAME) {
1755     vp9_denoiser_denoise(&cpi->denoiser, x, mi_row, mi_col,
1756                          MAX(BLOCK_8X8, bsize), ctx);
1757   }
1758 #endif
1759
1760   encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
1761   update_stats(&cpi->common, td);
1762
1763   (*tp)->token = EOSB_TOKEN;
1764   (*tp)++;
1765 }
1766
1767 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
1768                          const TileInfo *const tile,
1769                          TOKENEXTRA **tp, int mi_row, int mi_col,
1770                          int output_enabled, BLOCK_SIZE bsize,
1771                          PC_TREE *pc_tree) {
1772   VP9_COMMON *const cm = &cpi->common;
1773   MACROBLOCK *const x = &td->mb;
1774   MACROBLOCKD *const xd = &x->e_mbd;
1775
1776   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
1777   int ctx;
1778   PARTITION_TYPE partition;
1779   BLOCK_SIZE subsize;
1780
1781   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1782     return;
1783
1784   if (bsize >= BLOCK_8X8) {
1785     const int idx_str = xd->mi_stride * mi_row + mi_col;
1786     MODE_INFO ** mi_8x8 = cm->mi_grid_visible + idx_str;
1787     ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
1788     subsize = mi_8x8[0]->mbmi.sb_type;
1789   } else {
1790     ctx = 0;
1791     subsize = BLOCK_4X4;
1792   }
1793
1794   partition = partition_lookup[bsl][subsize];
1795   if (output_enabled && bsize != BLOCK_4X4)
1796     td->counts->partition[ctx][partition]++;
1797
1798   switch (partition) {
1799     case PARTITION_NONE:
1800       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1801                   &pc_tree->none);
1802       break;
1803     case PARTITION_VERT:
1804       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1805                   &pc_tree->vertical[0]);
1806       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
1807         encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1808                     subsize, &pc_tree->vertical[1]);
1809       }
1810       break;
1811     case PARTITION_HORZ:
1812       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1813                   &pc_tree->horizontal[0]);
1814       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
1815         encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1816                     subsize, &pc_tree->horizontal[1]);
1817       }
1818       break;
1819     case PARTITION_SPLIT:
1820       subsize = get_subsize(bsize, PARTITION_SPLIT);
1821       encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1822                    pc_tree->split[0]);
1823       encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1824                    subsize, pc_tree->split[1]);
1825       encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1826                    subsize, pc_tree->split[2]);
1827       encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
1828                    output_enabled, subsize, pc_tree->split[3]);
1829       break;
1830     default:
1831       assert(0 && "Invalid partition type.");
1832       break;
1833   }
1834
1835   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
1836     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
1837 }
1838
1839 static void rd_use_partition(VP9_COMP *cpi,
1840                              ThreadData *td,
1841                              TileDataEnc *tile_data,
1842                              MODE_INFO **mi_8x8, TOKENEXTRA **tp,
1843                              int mi_row, int mi_col,
1844                              BLOCK_SIZE bsize,
1845                              int *rate, int64_t *dist,
1846                              int do_recon, PC_TREE *pc_tree) {
1847   VP9_COMMON *const cm = &cpi->common;
1848   TileInfo *const tile_info = &tile_data->tile_info;
1849   MACROBLOCK *const x = &td->mb;
1850   MACROBLOCKD *const xd = &x->e_mbd;
1851   const int mis = cm->mi_stride;
1852   const int bsl = b_width_log2_lookup[bsize];
1853   const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
1854   const int bss = (1 << bsl) / 4;
1855   int i, pl;
1856   PARTITION_TYPE partition = PARTITION_NONE;
1857   BLOCK_SIZE subsize;
1858   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1859   PARTITION_CONTEXT sl[8], sa[8];
1860   RD_COST last_part_rdc, none_rdc, chosen_rdc;
1861   BLOCK_SIZE sub_subsize = BLOCK_4X4;
1862   int splits_below = 0;
1863   BLOCK_SIZE bs_type = mi_8x8[0]->mbmi.sb_type;
1864   int do_partition_search = 1;
1865   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
1866
1867   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1868     return;
1869
1870   assert(num_4x4_blocks_wide_lookup[bsize] ==
1871          num_4x4_blocks_high_lookup[bsize]);
1872
1873   vp9_rd_cost_reset(&last_part_rdc);
1874   vp9_rd_cost_reset(&none_rdc);
1875   vp9_rd_cost_reset(&chosen_rdc);
1876
1877   partition = partition_lookup[bsl][bs_type];
1878   subsize = get_subsize(bsize, partition);
1879
1880   pc_tree->partitioning = partition;
1881   save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1882
1883   if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode) {
1884     set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1885     x->mb_energy = vp9_block_energy(cpi, x, bsize);
1886   }
1887
1888   if (do_partition_search &&
1889       cpi->sf.partition_search_type == SEARCH_PARTITION &&
1890       cpi->sf.adjust_partitioning_from_last_frame) {
1891     // Check if any of the sub blocks are further split.
1892     if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
1893       sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
1894       splits_below = 1;
1895       for (i = 0; i < 4; i++) {
1896         int jj = i >> 1, ii = i & 0x01;
1897         MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
1898         if (this_mi && this_mi->mbmi.sb_type >= sub_subsize) {
1899           splits_below = 0;
1900         }
1901       }
1902     }
1903
1904     // If partition is not none try none unless each of the 4 splits are split
1905     // even further..
1906     if (partition != PARTITION_NONE && !splits_below &&
1907         mi_row + (mi_step >> 1) < cm->mi_rows &&
1908         mi_col + (mi_step >> 1) < cm->mi_cols) {
1909       pc_tree->partitioning = PARTITION_NONE;
1910       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize,
1911                        ctx, INT64_MAX);
1912
1913       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
1914
1915       if (none_rdc.rate < INT_MAX) {
1916         none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
1917         none_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, none_rdc.rate,
1918                                  none_rdc.dist);
1919       }
1920
1921       restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1922       mi_8x8[0]->mbmi.sb_type = bs_type;
1923       pc_tree->partitioning = partition;
1924     }
1925   }
1926
1927   switch (partition) {
1928     case PARTITION_NONE:
1929       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1930                        bsize, ctx, INT64_MAX);
1931       break;
1932     case PARTITION_HORZ:
1933       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1934                        subsize, &pc_tree->horizontal[0],
1935                        INT64_MAX);
1936       if (last_part_rdc.rate != INT_MAX &&
1937           bsize >= BLOCK_8X8 && mi_row + (mi_step >> 1) < cm->mi_rows) {
1938         RD_COST tmp_rdc;
1939         PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
1940         vp9_rd_cost_init(&tmp_rdc);
1941         update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
1942         encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
1943         rd_pick_sb_modes(cpi, tile_data, x,
1944                          mi_row + (mi_step >> 1), mi_col, &tmp_rdc,
1945                          subsize, &pc_tree->horizontal[1], INT64_MAX);
1946         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1947           vp9_rd_cost_reset(&last_part_rdc);
1948           break;
1949         }
1950         last_part_rdc.rate += tmp_rdc.rate;
1951         last_part_rdc.dist += tmp_rdc.dist;
1952         last_part_rdc.rdcost += tmp_rdc.rdcost;
1953       }
1954       break;
1955     case PARTITION_VERT:
1956       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1957                        subsize, &pc_tree->vertical[0], INT64_MAX);
1958       if (last_part_rdc.rate != INT_MAX &&
1959           bsize >= BLOCK_8X8 && mi_col + (mi_step >> 1) < cm->mi_cols) {
1960         RD_COST tmp_rdc;
1961         PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
1962         vp9_rd_cost_init(&tmp_rdc);
1963         update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
1964         encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
1965         rd_pick_sb_modes(cpi, tile_data, x,
1966                          mi_row, mi_col + (mi_step >> 1), &tmp_rdc,
1967                          subsize, &pc_tree->vertical[bsize > BLOCK_8X8],
1968                          INT64_MAX);
1969         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1970           vp9_rd_cost_reset(&last_part_rdc);
1971           break;
1972         }
1973         last_part_rdc.rate += tmp_rdc.rate;
1974         last_part_rdc.dist += tmp_rdc.dist;
1975         last_part_rdc.rdcost += tmp_rdc.rdcost;
1976       }
1977       break;
1978     case PARTITION_SPLIT:
1979       if (bsize == BLOCK_8X8) {
1980         rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1981                          subsize, pc_tree->leaf_split[0], INT64_MAX);
1982         break;
1983       }
1984       last_part_rdc.rate = 0;
1985       last_part_rdc.dist = 0;
1986       last_part_rdc.rdcost = 0;
1987       for (i = 0; i < 4; i++) {
1988         int x_idx = (i & 1) * (mi_step >> 1);
1989         int y_idx = (i >> 1) * (mi_step >> 1);
1990         int jj = i >> 1, ii = i & 0x01;
1991         RD_COST tmp_rdc;
1992         if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
1993           continue;
1994
1995         vp9_rd_cost_init(&tmp_rdc);
1996         rd_use_partition(cpi, td, tile_data,
1997                          mi_8x8 + jj * bss * mis + ii * bss, tp,
1998                          mi_row + y_idx, mi_col + x_idx, subsize,
1999                          &tmp_rdc.rate, &tmp_rdc.dist,
2000                          i != 3, pc_tree->split[i]);
2001         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2002           vp9_rd_cost_reset(&last_part_rdc);
2003           break;
2004         }
2005         last_part_rdc.rate += tmp_rdc.rate;
2006         last_part_rdc.dist += tmp_rdc.dist;
2007       }
2008       break;
2009     default:
2010       assert(0);
2011       break;
2012   }
2013
2014   pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2015   if (last_part_rdc.rate < INT_MAX) {
2016     last_part_rdc.rate += cpi->partition_cost[pl][partition];
2017     last_part_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2018                                   last_part_rdc.rate, last_part_rdc.dist);
2019   }
2020
2021   if (do_partition_search
2022       && cpi->sf.adjust_partitioning_from_last_frame
2023       && cpi->sf.partition_search_type == SEARCH_PARTITION
2024       && partition != PARTITION_SPLIT && bsize > BLOCK_8X8
2025       && (mi_row + mi_step < cm->mi_rows ||
2026           mi_row + (mi_step >> 1) == cm->mi_rows)
2027       && (mi_col + mi_step < cm->mi_cols ||
2028           mi_col + (mi_step >> 1) == cm->mi_cols)) {
2029     BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2030     chosen_rdc.rate = 0;
2031     chosen_rdc.dist = 0;
2032     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2033     pc_tree->partitioning = PARTITION_SPLIT;
2034
2035     // Split partition.
2036     for (i = 0; i < 4; i++) {
2037       int x_idx = (i & 1) * (mi_step >> 1);
2038       int y_idx = (i >> 1) * (mi_step >> 1);
2039       RD_COST tmp_rdc;
2040       ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2041       PARTITION_CONTEXT sl[8], sa[8];
2042
2043       if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2044         continue;
2045
2046       save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2047       pc_tree->split[i]->partitioning = PARTITION_NONE;
2048       rd_pick_sb_modes(cpi, tile_data, x,
2049                        mi_row + y_idx, mi_col + x_idx, &tmp_rdc,
2050                        split_subsize, &pc_tree->split[i]->none, INT64_MAX);
2051
2052       restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2053
2054       if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2055         vp9_rd_cost_reset(&chosen_rdc);
2056         break;
2057       }
2058
2059       chosen_rdc.rate += tmp_rdc.rate;
2060       chosen_rdc.dist += tmp_rdc.dist;
2061
2062       if (i != 3)
2063         encode_sb(cpi, td, tile_info, tp,  mi_row + y_idx, mi_col + x_idx, 0,
2064                   split_subsize, pc_tree->split[i]);
2065
2066       pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2067                                    split_subsize);
2068       chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2069     }
2070     pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2071     if (chosen_rdc.rate < INT_MAX) {
2072       chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2073       chosen_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2074                                  chosen_rdc.rate, chosen_rdc.dist);
2075     }
2076   }
2077
2078   // If last_part is better set the partitioning to that.
2079   if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2080     mi_8x8[0]->mbmi.sb_type = bsize;
2081     if (bsize >= BLOCK_8X8)
2082       pc_tree->partitioning = partition;
2083     chosen_rdc = last_part_rdc;
2084   }
2085   // If none was better set the partitioning to that.
2086   if (none_rdc.rdcost < chosen_rdc.rdcost) {
2087     if (bsize >= BLOCK_8X8)
2088       pc_tree->partitioning = PARTITION_NONE;
2089     chosen_rdc = none_rdc;
2090   }
2091
2092   restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2093
2094   // We must have chosen a partitioning and encoding or we'll fail later on.
2095   // No other opportunities for success.
2096   if (bsize == BLOCK_64X64)
2097     assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2098
2099   if (do_recon) {
2100     int output_enabled = (bsize == BLOCK_64X64);
2101     encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2102               pc_tree);
2103   }
2104
2105   *rate = chosen_rdc.rate;
2106   *dist = chosen_rdc.dist;
2107 }
2108
2109 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2110   BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,
2111   BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,
2112   BLOCK_8X8,   BLOCK_8X8,   BLOCK_8X8,
2113   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
2114   BLOCK_16X16
2115 };
2116
2117 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2118   BLOCK_8X8,   BLOCK_16X16, BLOCK_16X16,
2119   BLOCK_16X16, BLOCK_32X32, BLOCK_32X32,
2120   BLOCK_32X32, BLOCK_64X64, BLOCK_64X64,
2121   BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2122   BLOCK_64X64
2123 };
2124
2125
2126 // Look at all the mode_info entries for blocks that are part of this
2127 // partition and find the min and max values for sb_type.
2128 // At the moment this is designed to work on a 64x64 SB but could be
2129 // adjusted to use a size parameter.
2130 //
2131 // The min and max are assumed to have been initialized prior to calling this
2132 // function so repeat calls can accumulate a min and max of more than one sb64.
2133 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2134                                         BLOCK_SIZE *min_block_size,
2135                                         BLOCK_SIZE *max_block_size,
2136                                         int bs_hist[BLOCK_SIZES]) {
2137   int sb_width_in_blocks = MI_BLOCK_SIZE;
2138   int sb_height_in_blocks  = MI_BLOCK_SIZE;
2139   int i, j;
2140   int index = 0;
2141
2142   // Check the sb_type for each block that belongs to this region.
2143   for (i = 0; i < sb_height_in_blocks; ++i) {
2144     for (j = 0; j < sb_width_in_blocks; ++j) {
2145       MODE_INFO *mi = mi_8x8[index+j];
2146       BLOCK_SIZE sb_type = mi ? mi->mbmi.sb_type : 0;
2147       bs_hist[sb_type]++;
2148       *min_block_size = MIN(*min_block_size, sb_type);
2149       *max_block_size = MAX(*max_block_size, sb_type);
2150     }
2151     index += xd->mi_stride;
2152   }
2153 }
2154
2155 // Next square block size less or equal than current block size.
2156 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2157   BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2158   BLOCK_8X8, BLOCK_8X8, BLOCK_8X8,
2159   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
2160   BLOCK_32X32, BLOCK_32X32, BLOCK_32X32,
2161   BLOCK_64X64
2162 };
2163
2164 // Look at neighboring blocks and set a min and max partition size based on
2165 // what they chose.
2166 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2167                                     MACROBLOCKD *const xd,
2168                                     int mi_row, int mi_col,
2169                                     BLOCK_SIZE *min_block_size,
2170                                     BLOCK_SIZE *max_block_size) {
2171   VP9_COMMON *const cm = &cpi->common;
2172   MODE_INFO **mi = xd->mi;
2173   const int left_in_image = xd->left_available && mi[-1];
2174   const int above_in_image = xd->up_available && mi[-xd->mi_stride];
2175   const int row8x8_remaining = tile->mi_row_end - mi_row;
2176   const int col8x8_remaining = tile->mi_col_end - mi_col;
2177   int bh, bw;
2178   BLOCK_SIZE min_size = BLOCK_4X4;
2179   BLOCK_SIZE max_size = BLOCK_64X64;
2180   int bs_hist[BLOCK_SIZES] = {0};
2181
2182   // Trap case where we do not have a prediction.
2183   if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2184     // Default "min to max" and "max to min"
2185     min_size = BLOCK_64X64;
2186     max_size = BLOCK_4X4;
2187
2188     // NOTE: each call to get_sb_partition_size_range() uses the previous
2189     // passed in values for min and max as a starting point.
2190     // Find the min and max partition used in previous frame at this location
2191     if (cm->frame_type != KEY_FRAME) {
2192       MODE_INFO **prev_mi =
2193           &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2194       get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2195     }
2196     // Find the min and max partition sizes used in the left SB64
2197     if (left_in_image) {
2198       MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2199       get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2200                                   bs_hist);
2201     }
2202     // Find the min and max partition sizes used in the above SB64.
2203     if (above_in_image) {
2204       MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2205       get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2206                                   bs_hist);
2207     }
2208
2209     // Adjust observed min and max for "relaxed" auto partition case.
2210     if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2211       min_size = min_partition_size[min_size];
2212       max_size = max_partition_size[max_size];
2213     }
2214   }
2215
2216   // Check border cases where max and min from neighbors may not be legal.
2217   max_size = find_partition_size(max_size,
2218                                  row8x8_remaining, col8x8_remaining,
2219                                  &bh, &bw);
2220   // Test for blocks at the edge of the active image.
2221   // This may be the actual edge of the image or where there are formatting
2222   // bars.
2223   if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
2224     min_size = BLOCK_4X4;
2225   } else {
2226     min_size = MIN(cpi->sf.rd_auto_partition_min_limit,
2227                    MIN(min_size, max_size));
2228   }
2229
2230   // When use_square_partition_only is true, make sure at least one square
2231   // partition is allowed by selecting the next smaller square size as
2232   // *min_block_size.
2233   if (cpi->sf.use_square_partition_only &&
2234       next_square_size[max_size] < min_size) {
2235      min_size = next_square_size[max_size];
2236   }
2237
2238   *min_block_size = min_size;
2239   *max_block_size = max_size;
2240 }
2241
2242 // TODO(jingning) refactor functions setting partition search range
2243 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd,
2244                                 int mi_row, int mi_col, BLOCK_SIZE bsize,
2245                                 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
2246   int mi_width  = num_8x8_blocks_wide_lookup[bsize];
2247   int mi_height = num_8x8_blocks_high_lookup[bsize];
2248   int idx, idy;
2249
2250   MODE_INFO *mi;
2251   const int idx_str = cm->mi_stride * mi_row + mi_col;
2252   MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
2253   BLOCK_SIZE bs, min_size, max_size;
2254
2255   min_size = BLOCK_64X64;
2256   max_size = BLOCK_4X4;
2257
2258   if (prev_mi) {
2259     for (idy = 0; idy < mi_height; ++idy) {
2260       for (idx = 0; idx < mi_width; ++idx) {
2261         mi = prev_mi[idy * cm->mi_stride + idx];
2262         bs = mi ? mi->mbmi.sb_type : bsize;
2263         min_size = MIN(min_size, bs);
2264         max_size = MAX(max_size, bs);
2265       }
2266     }
2267   }
2268
2269   if (xd->left_available) {
2270     for (idy = 0; idy < mi_height; ++idy) {
2271       mi = xd->mi[idy * cm->mi_stride - 1];
2272       bs = mi ? mi->mbmi.sb_type : bsize;
2273       min_size = MIN(min_size, bs);
2274       max_size = MAX(max_size, bs);
2275     }
2276   }
2277
2278   if (xd->up_available) {
2279     for (idx = 0; idx < mi_width; ++idx) {
2280       mi = xd->mi[idx - cm->mi_stride];
2281       bs = mi ? mi->mbmi.sb_type : bsize;
2282       min_size = MIN(min_size, bs);
2283       max_size = MAX(max_size, bs);
2284     }
2285   }
2286
2287   if (min_size == max_size) {
2288     min_size = min_partition_size[min_size];
2289     max_size = max_partition_size[max_size];
2290   }
2291
2292   *min_bs = min_size;
2293   *max_bs = max_size;
2294 }
2295
2296 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2297   memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
2298 }
2299
2300 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2301   memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
2302 }
2303
2304 #if CONFIG_FP_MB_STATS
2305 const int num_16x16_blocks_wide_lookup[BLOCK_SIZES] =
2306   {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 4, 4};
2307 const int num_16x16_blocks_high_lookup[BLOCK_SIZES] =
2308   {1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 4, 2, 4};
2309 const int qindex_skip_threshold_lookup[BLOCK_SIZES] =
2310   {0, 10, 10, 30, 40, 40, 60, 80, 80, 90, 100, 100, 120};
2311 const int qindex_split_threshold_lookup[BLOCK_SIZES] =
2312   {0, 3, 3, 7, 15, 15, 30, 40, 40, 60, 80, 80, 120};
2313 const int complexity_16x16_blocks_threshold[BLOCK_SIZES] =
2314   {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 6};
2315
2316 typedef enum {
2317   MV_ZERO = 0,
2318   MV_LEFT = 1,
2319   MV_UP = 2,
2320   MV_RIGHT = 3,
2321   MV_DOWN = 4,
2322   MV_INVALID
2323 } MOTION_DIRECTION;
2324
2325 static INLINE MOTION_DIRECTION get_motion_direction_fp(uint8_t fp_byte) {
2326   if (fp_byte & FPMB_MOTION_ZERO_MASK) {
2327     return MV_ZERO;
2328   } else if (fp_byte & FPMB_MOTION_LEFT_MASK) {
2329     return MV_LEFT;
2330   } else if (fp_byte & FPMB_MOTION_RIGHT_MASK) {
2331     return MV_RIGHT;
2332   } else if (fp_byte & FPMB_MOTION_UP_MASK) {
2333     return MV_UP;
2334   } else {
2335     return MV_DOWN;
2336   }
2337 }
2338
2339 static INLINE int get_motion_inconsistency(MOTION_DIRECTION this_mv,
2340                                            MOTION_DIRECTION that_mv) {
2341   if (this_mv == that_mv) {
2342     return 0;
2343   } else {
2344     return abs(this_mv - that_mv) == 2 ? 2 : 1;
2345   }
2346 }
2347 #endif
2348
2349 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
2350 // unlikely to be selected depending on previous rate-distortion optimization
2351 // results, for encoding speed-up.
2352 static void rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
2353                               TileDataEnc *tile_data,
2354                               TOKENEXTRA **tp, int mi_row, int mi_col,
2355                               BLOCK_SIZE bsize, RD_COST *rd_cost,
2356                               int64_t best_rd, PC_TREE *pc_tree) {
2357   VP9_COMMON *const cm = &cpi->common;
2358   TileInfo *const tile_info = &tile_data->tile_info;
2359   MACROBLOCK *const x = &td->mb;
2360   MACROBLOCKD *const xd = &x->e_mbd;
2361   const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
2362   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2363   PARTITION_CONTEXT sl[8], sa[8];
2364   TOKENEXTRA *tp_orig = *tp;
2365   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2366   int i, pl;
2367   BLOCK_SIZE subsize;
2368   RD_COST this_rdc, sum_rdc, best_rdc;
2369   int do_split = bsize >= BLOCK_8X8;
2370   int do_rect = 1;
2371
2372   // Override skipping rectangular partition operations for edge blocks
2373   const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
2374   const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
2375   const int xss = x->e_mbd.plane[1].subsampling_x;
2376   const int yss = x->e_mbd.plane[1].subsampling_y;
2377
2378   BLOCK_SIZE min_size = x->min_partition_size;
2379   BLOCK_SIZE max_size = x->max_partition_size;
2380
2381 #if CONFIG_FP_MB_STATS
2382   unsigned int src_diff_var = UINT_MAX;
2383   int none_complexity = 0;
2384 #endif
2385
2386   int partition_none_allowed = !force_horz_split && !force_vert_split;
2387   int partition_horz_allowed = !force_vert_split && yss <= xss &&
2388                                bsize >= BLOCK_8X8;
2389   int partition_vert_allowed = !force_horz_split && xss <= yss &&
2390                                bsize >= BLOCK_8X8;
2391   (void) *tp_orig;
2392
2393   assert(num_8x8_blocks_wide_lookup[bsize] ==
2394              num_8x8_blocks_high_lookup[bsize]);
2395
2396   vp9_rd_cost_init(&this_rdc);
2397   vp9_rd_cost_init(&sum_rdc);
2398   vp9_rd_cost_reset(&best_rdc);
2399   best_rdc.rdcost = best_rd;
2400
2401   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2402
2403   if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode)
2404     x->mb_energy = vp9_block_energy(cpi, x, bsize);
2405
2406   if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
2407     int cb_partition_search_ctrl = ((pc_tree->index == 0 || pc_tree->index == 3)
2408         + get_chessboard_index(cm->current_video_frame)) & 0x1;
2409
2410     if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
2411       set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
2412   }
2413
2414   // Determine partition types in search according to the speed features.
2415   // The threshold set here has to be of square block size.
2416   if (cpi->sf.auto_min_max_partition_size) {
2417     partition_none_allowed &= (bsize <= max_size && bsize >= min_size);
2418     partition_horz_allowed &= ((bsize <= max_size && bsize > min_size) ||
2419                                 force_horz_split);
2420     partition_vert_allowed &= ((bsize <= max_size && bsize > min_size) ||
2421                                 force_vert_split);
2422     do_split &= bsize > min_size;
2423   }
2424   if (cpi->sf.use_square_partition_only) {
2425     partition_horz_allowed &= force_horz_split;
2426     partition_vert_allowed &= force_vert_split;
2427   }
2428
2429   save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2430
2431 #if CONFIG_FP_MB_STATS
2432   if (cpi->use_fp_mb_stats) {
2433     set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2434     src_diff_var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src,
2435                                                   mi_row, mi_col, bsize);
2436   }
2437 #endif
2438
2439 #if CONFIG_FP_MB_STATS
2440   // Decide whether we shall split directly and skip searching NONE by using
2441   // the first pass block statistics
2442   if (cpi->use_fp_mb_stats && bsize >= BLOCK_32X32 && do_split &&
2443       partition_none_allowed && src_diff_var > 4 &&
2444       cm->base_qindex < qindex_split_threshold_lookup[bsize]) {
2445     int mb_row = mi_row >> 1;
2446     int mb_col = mi_col >> 1;
2447     int mb_row_end =
2448         MIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
2449     int mb_col_end =
2450         MIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
2451     int r, c;
2452
2453     // compute a complexity measure, basically measure inconsistency of motion
2454     // vectors obtained from the first pass in the current block
2455     for (r = mb_row; r < mb_row_end ; r++) {
2456       for (c = mb_col; c < mb_col_end; c++) {
2457         const int mb_index = r * cm->mb_cols + c;
2458
2459         MOTION_DIRECTION this_mv;
2460         MOTION_DIRECTION right_mv;
2461         MOTION_DIRECTION bottom_mv;
2462
2463         this_mv =
2464             get_motion_direction_fp(cpi->twopass.this_frame_mb_stats[mb_index]);
2465
2466         // to its right
2467         if (c != mb_col_end - 1) {
2468           right_mv = get_motion_direction_fp(
2469               cpi->twopass.this_frame_mb_stats[mb_index + 1]);
2470           none_complexity += get_motion_inconsistency(this_mv, right_mv);
2471         }
2472
2473         // to its bottom
2474         if (r != mb_row_end - 1) {
2475           bottom_mv = get_motion_direction_fp(
2476               cpi->twopass.this_frame_mb_stats[mb_index + cm->mb_cols]);
2477           none_complexity += get_motion_inconsistency(this_mv, bottom_mv);
2478         }
2479
2480         // do not count its left and top neighbors to avoid double counting
2481       }
2482     }
2483
2484     if (none_complexity > complexity_16x16_blocks_threshold[bsize]) {
2485       partition_none_allowed = 0;
2486     }
2487   }
2488 #endif
2489
2490   // PARTITION_NONE
2491   if (partition_none_allowed) {
2492     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col,
2493                      &this_rdc, bsize, ctx, best_rdc.rdcost);
2494     if (this_rdc.rate != INT_MAX) {
2495       if (bsize >= BLOCK_8X8) {
2496         pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2497         this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2498         this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2499                                  this_rdc.rate, this_rdc.dist);
2500       }
2501
2502       if (this_rdc.rdcost < best_rdc.rdcost) {
2503         int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_dist_thr;
2504         int rate_breakout_thr = cpi->sf.partition_search_breakout_rate_thr;
2505
2506         best_rdc = this_rdc;
2507         if (bsize >= BLOCK_8X8)
2508           pc_tree->partitioning = PARTITION_NONE;
2509
2510         // Adjust dist breakout threshold according to the partition size.
2511         dist_breakout_thr >>= 8 - (b_width_log2_lookup[bsize] +
2512             b_height_log2_lookup[bsize]);
2513
2514         rate_breakout_thr *= num_pels_log2_lookup[bsize];
2515
2516         // If all y, u, v transform blocks in this partition are skippable, and
2517         // the dist & rate are within the thresholds, the partition search is
2518         // terminated for current branch of the partition search tree.
2519         // The dist & rate thresholds are set to 0 at speed 0 to disable the
2520         // early termination at that speed.
2521         if (!x->e_mbd.lossless &&
2522             (ctx->skippable && best_rdc.dist < dist_breakout_thr &&
2523             best_rdc.rate < rate_breakout_thr)) {
2524           do_split = 0;
2525           do_rect = 0;
2526         }
2527
2528 #if CONFIG_FP_MB_STATS
2529         // Check if every 16x16 first pass block statistics has zero
2530         // motion and the corresponding first pass residue is small enough.
2531         // If that is the case, check the difference variance between the
2532         // current frame and the last frame. If the variance is small enough,
2533         // stop further splitting in RD optimization
2534         if (cpi->use_fp_mb_stats && do_split != 0 &&
2535             cm->base_qindex > qindex_skip_threshold_lookup[bsize]) {
2536           int mb_row = mi_row >> 1;
2537           int mb_col = mi_col >> 1;
2538           int mb_row_end =
2539               MIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
2540           int mb_col_end =
2541               MIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
2542           int r, c;
2543
2544           int skip = 1;
2545           for (r = mb_row; r < mb_row_end; r++) {
2546             for (c = mb_col; c < mb_col_end; c++) {
2547               const int mb_index = r * cm->mb_cols + c;
2548               if (!(cpi->twopass.this_frame_mb_stats[mb_index] &
2549                     FPMB_MOTION_ZERO_MASK) ||
2550                   !(cpi->twopass.this_frame_mb_stats[mb_index] &
2551                     FPMB_ERROR_SMALL_MASK)) {
2552                 skip = 0;
2553                 break;
2554               }
2555             }
2556             if (skip == 0) {
2557               break;
2558             }
2559           }
2560           if (skip) {
2561             if (src_diff_var == UINT_MAX) {
2562               set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2563               src_diff_var = get_sby_perpixel_diff_variance(
2564                   cpi, &x->plane[0].src, mi_row, mi_col, bsize);
2565             }
2566             if (src_diff_var < 8) {
2567               do_split = 0;
2568               do_rect = 0;
2569             }
2570           }
2571         }
2572 #endif
2573       }
2574     }
2575     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2576   }
2577
2578   // store estimated motion vector
2579   if (cpi->sf.adaptive_motion_search)
2580     store_pred_mv(x, ctx);
2581
2582   // PARTITION_SPLIT
2583   // TODO(jingning): use the motion vectors given by the above search as
2584   // the starting point of motion search in the following partition type check.
2585   if (do_split) {
2586     subsize = get_subsize(bsize, PARTITION_SPLIT);
2587     if (bsize == BLOCK_8X8) {
2588       i = 4;
2589       if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
2590         pc_tree->leaf_split[0]->pred_interp_filter =
2591             ctx->mic.mbmi.interp_filter;
2592       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2593                        pc_tree->leaf_split[0], best_rdc.rdcost);
2594       if (sum_rdc.rate == INT_MAX)
2595         sum_rdc.rdcost = INT64_MAX;
2596     } else {
2597       for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
2598       const int x_idx = (i & 1) * mi_step;
2599       const int y_idx = (i >> 1) * mi_step;
2600
2601         if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
2602           continue;
2603
2604         if (cpi->sf.adaptive_motion_search)
2605           load_pred_mv(x, ctx);
2606
2607         pc_tree->split[i]->index = i;
2608         rd_pick_partition(cpi, td, tile_data, tp,
2609                           mi_row + y_idx, mi_col + x_idx,
2610                           subsize, &this_rdc,
2611                           best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
2612
2613         if (this_rdc.rate == INT_MAX) {
2614           sum_rdc.rdcost = INT64_MAX;
2615           break;
2616         } else {
2617           sum_rdc.rate += this_rdc.rate;
2618           sum_rdc.dist += this_rdc.dist;
2619           sum_rdc.rdcost += this_rdc.rdcost;
2620         }
2621       }
2622     }
2623
2624     if (sum_rdc.rdcost < best_rdc.rdcost && i == 4) {
2625       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2626       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2627       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2628                               sum_rdc.rate, sum_rdc.dist);
2629
2630       if (sum_rdc.rdcost < best_rdc.rdcost) {
2631         best_rdc = sum_rdc;
2632         pc_tree->partitioning = PARTITION_SPLIT;
2633       }
2634     } else {
2635       // skip rectangular partition test when larger block size
2636       // gives better rd cost
2637       if (cpi->sf.less_rectangular_check)
2638         do_rect &= !partition_none_allowed;
2639     }
2640     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2641   }
2642
2643   // PARTITION_HORZ
2644   if (partition_horz_allowed &&
2645       (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
2646       subsize = get_subsize(bsize, PARTITION_HORZ);
2647     if (cpi->sf.adaptive_motion_search)
2648       load_pred_mv(x, ctx);
2649     if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2650         partition_none_allowed)
2651       pc_tree->horizontal[0].pred_interp_filter =
2652           ctx->mic.mbmi.interp_filter;
2653     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2654                      &pc_tree->horizontal[0], best_rdc.rdcost);
2655
2656     if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
2657         bsize > BLOCK_8X8) {
2658       PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2659       update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2660       encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2661
2662       if (cpi->sf.adaptive_motion_search)
2663         load_pred_mv(x, ctx);
2664       if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2665           partition_none_allowed)
2666         pc_tree->horizontal[1].pred_interp_filter =
2667             ctx->mic.mbmi.interp_filter;
2668       rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col,
2669                        &this_rdc, subsize, &pc_tree->horizontal[1],
2670                        best_rdc.rdcost - sum_rdc.rdcost);
2671       if (this_rdc.rate == INT_MAX) {
2672         sum_rdc.rdcost = INT64_MAX;
2673       } else {
2674         sum_rdc.rate += this_rdc.rate;
2675         sum_rdc.dist += this_rdc.dist;
2676         sum_rdc.rdcost += this_rdc.rdcost;
2677       }
2678     }
2679
2680     if (sum_rdc.rdcost < best_rdc.rdcost) {
2681       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2682       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
2683       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
2684       if (sum_rdc.rdcost < best_rdc.rdcost) {
2685         best_rdc = sum_rdc;
2686         pc_tree->partitioning = PARTITION_HORZ;
2687       }
2688     }
2689     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2690   }
2691   // PARTITION_VERT
2692   if (partition_vert_allowed &&
2693       (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
2694       subsize = get_subsize(bsize, PARTITION_VERT);
2695
2696     if (cpi->sf.adaptive_motion_search)
2697       load_pred_mv(x, ctx);
2698     if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2699         partition_none_allowed)
2700       pc_tree->vertical[0].pred_interp_filter =
2701           ctx->mic.mbmi.interp_filter;
2702     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2703                      &pc_tree->vertical[0], best_rdc.rdcost);
2704     if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
2705         bsize > BLOCK_8X8) {
2706       update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
2707       encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
2708                         &pc_tree->vertical[0]);
2709
2710       if (cpi->sf.adaptive_motion_search)
2711         load_pred_mv(x, ctx);
2712       if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2713           partition_none_allowed)
2714         pc_tree->vertical[1].pred_interp_filter =
2715             ctx->mic.mbmi.interp_filter;
2716       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step,
2717                        &this_rdc, subsize,
2718                        &pc_tree->vertical[1], best_rdc.rdcost - sum_rdc.rdcost);
2719       if (this_rdc.rate == INT_MAX) {
2720         sum_rdc.rdcost = INT64_MAX;
2721       } else {
2722         sum_rdc.rate += this_rdc.rate;
2723         sum_rdc.dist += this_rdc.dist;
2724         sum_rdc.rdcost += this_rdc.rdcost;
2725       }
2726     }
2727
2728     if (sum_rdc.rdcost < best_rdc.rdcost) {
2729       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2730       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
2731       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2732                               sum_rdc.rate, sum_rdc.dist);
2733       if (sum_rdc.rdcost < best_rdc.rdcost) {
2734         best_rdc = sum_rdc;
2735         pc_tree->partitioning = PARTITION_VERT;
2736       }
2737     }
2738     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2739   }
2740
2741   // TODO(jbb): This code added so that we avoid static analysis
2742   // warning related to the fact that best_rd isn't used after this
2743   // point.  This code should be refactored so that the duplicate
2744   // checks occur in some sub function and thus are used...
2745   (void) best_rd;
2746   *rd_cost = best_rdc;
2747
2748
2749   if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX &&
2750       pc_tree->index != 3) {
2751     int output_enabled = (bsize == BLOCK_64X64);
2752     encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
2753               bsize, pc_tree);
2754   }
2755
2756   if (bsize == BLOCK_64X64) {
2757     assert(tp_orig < *tp);
2758     assert(best_rdc.rate < INT_MAX);
2759     assert(best_rdc.dist < INT64_MAX);
2760   } else {
2761     assert(tp_orig == *tp);
2762   }
2763 }
2764
2765 static void encode_rd_sb_row(VP9_COMP *cpi,
2766                              ThreadData *td,
2767                              TileDataEnc *tile_data,
2768                              int mi_row,
2769                              TOKENEXTRA **tp) {
2770   VP9_COMMON *const cm = &cpi->common;
2771   TileInfo *const tile_info = &tile_data->tile_info;
2772   MACROBLOCK *const x = &td->mb;
2773   MACROBLOCKD *const xd = &x->e_mbd;
2774   SPEED_FEATURES *const sf = &cpi->sf;
2775   int mi_col;
2776
2777   // Initialize the left context for the new SB row
2778   memset(&xd->left_context, 0, sizeof(xd->left_context));
2779   memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
2780
2781   // Code each SB in the row
2782   for (mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
2783        mi_col += MI_BLOCK_SIZE) {
2784     const struct segmentation *const seg = &cm->seg;
2785     int dummy_rate;
2786     int64_t dummy_dist;
2787     RD_COST dummy_rdc;
2788     int i;
2789     int seg_skip = 0;
2790
2791     const int idx_str = cm->mi_stride * mi_row + mi_col;
2792     MODE_INFO **mi = cm->mi_grid_visible + idx_str;
2793
2794     if (sf->adaptive_pred_interp_filter) {
2795       for (i = 0; i < 64; ++i)
2796         td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
2797
2798       for (i = 0; i < 64; ++i) {
2799         td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
2800         td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
2801         td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
2802         td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
2803       }
2804     }
2805
2806     vp9_zero(x->pred_mv);
2807     td->pc_root->index = 0;
2808
2809     if (seg->enabled) {
2810       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
2811                                                  : cm->last_frame_seg_map;
2812       int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
2813       seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
2814     }
2815
2816     x->source_variance = UINT_MAX;
2817     if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
2818       const BLOCK_SIZE bsize =
2819           seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
2820       set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2821       set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
2822       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2823                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2824     } else if (cpi->partition_search_skippable_frame) {
2825       BLOCK_SIZE bsize;
2826       set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2827       bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col);
2828       set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
2829       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2830                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2831     } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
2832                cm->frame_type != KEY_FRAME) {
2833       choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
2834       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2835                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2836     } else {
2837       // If required set upper and lower partition size limits
2838       if (sf->auto_min_max_partition_size) {
2839         set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2840         rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
2841                                 &x->min_partition_size,
2842                                 &x->max_partition_size);
2843       }
2844       rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
2845                         &dummy_rdc, INT64_MAX, td->pc_root);
2846     }
2847   }
2848 }
2849
2850 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
2851   MACROBLOCK *const x = &cpi->td.mb;
2852   VP9_COMMON *const cm = &cpi->common;
2853   MACROBLOCKD *const xd = &x->e_mbd;
2854   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2855
2856   // Copy data over into macro block data structures.
2857   vp9_setup_src_planes(x, cpi->Source, 0, 0);
2858
2859   vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
2860
2861   // Note: this memset assumes above_context[0], [1] and [2]
2862   // are allocated as part of the same buffer.
2863   memset(xd->above_context[0], 0,
2864          sizeof(*xd->above_context[0]) *
2865          2 * aligned_mi_cols * MAX_MB_PLANE);
2866   memset(xd->above_seg_context, 0,
2867          sizeof(*xd->above_seg_context) * aligned_mi_cols);
2868 }
2869
2870 static int check_dual_ref_flags(VP9_COMP *cpi) {
2871   const int ref_flags = cpi->ref_frame_flags;
2872
2873   if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
2874     return 0;
2875   } else {
2876     return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG)
2877         + !!(ref_flags & VP9_ALT_FLAG)) >= 2;
2878   }
2879 }
2880
2881 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
2882   int mi_row, mi_col;
2883   const int mis = cm->mi_stride;
2884   MODE_INFO **mi_ptr = cm->mi_grid_visible;
2885
2886   for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
2887     for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
2888       if (mi_ptr[mi_col]->mbmi.tx_size > max_tx_size)
2889         mi_ptr[mi_col]->mbmi.tx_size = max_tx_size;
2890     }
2891   }
2892 }
2893
2894 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
2895   if (frame_is_intra_only(&cpi->common))
2896     return INTRA_FRAME;
2897   else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
2898     return ALTREF_FRAME;
2899   else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
2900     return GOLDEN_FRAME;
2901   else
2902     return LAST_FRAME;
2903 }
2904
2905 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
2906   if (xd->lossless)
2907     return ONLY_4X4;
2908   if (cpi->common.frame_type == KEY_FRAME &&
2909       cpi->sf.use_nonrd_pick_mode)
2910     return ALLOW_16X16;
2911   if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
2912     return ALLOW_32X32;
2913   else if (cpi->sf.tx_size_search_method == USE_FULL_RD||
2914            cpi->sf.tx_size_search_method == USE_TX_8X8)
2915     return TX_MODE_SELECT;
2916   else
2917     return cpi->common.tx_mode;
2918 }
2919
2920 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
2921                                      RD_COST *rd_cost, BLOCK_SIZE bsize,
2922                                      PICK_MODE_CONTEXT *ctx) {
2923   if (bsize < BLOCK_16X16)
2924     vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
2925   else
2926     vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
2927 }
2928
2929 static void nonrd_pick_sb_modes(VP9_COMP *cpi,
2930                                 TileDataEnc *tile_data, MACROBLOCK *const x,
2931                                 int mi_row, int mi_col, RD_COST *rd_cost,
2932                                 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
2933   VP9_COMMON *const cm = &cpi->common;
2934   TileInfo *const tile_info = &tile_data->tile_info;
2935   MACROBLOCKD *const xd = &x->e_mbd;
2936   MB_MODE_INFO *mbmi;
2937   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2938   mbmi = &xd->mi[0]->mbmi;
2939   mbmi->sb_type = bsize;
2940
2941   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
2942     if (cyclic_refresh_segment_id_boosted(mbmi->segment_id))
2943       x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
2944
2945   if (cm->frame_type == KEY_FRAME)
2946     hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
2947   else if (segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP))
2948     set_mode_info_seg_skip(x, cm->tx_mode, rd_cost, bsize);
2949   else if (bsize >= BLOCK_8X8)
2950     vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col,
2951                         rd_cost, bsize, ctx);
2952   else
2953     vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col,
2954                                rd_cost, bsize, ctx);
2955
2956   duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
2957
2958   if (rd_cost->rate == INT_MAX)
2959     vp9_rd_cost_reset(rd_cost);
2960
2961   ctx->rate = rd_cost->rate;
2962   ctx->dist = rd_cost->dist;
2963 }
2964
2965 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x,
2966                               int mi_row, int mi_col,
2967                               BLOCK_SIZE bsize,
2968                               PC_TREE *pc_tree) {
2969   MACROBLOCKD *xd = &x->e_mbd;
2970   int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2971   PARTITION_TYPE partition = pc_tree->partitioning;
2972   BLOCK_SIZE subsize = get_subsize(bsize, partition);
2973
2974   assert(bsize >= BLOCK_8X8);
2975
2976   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
2977     return;
2978
2979   switch (partition) {
2980     case PARTITION_NONE:
2981       set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
2982       *(xd->mi[0]) = pc_tree->none.mic;
2983       *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
2984       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
2985       break;
2986     case PARTITION_VERT:
2987       set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
2988       *(xd->mi[0]) = pc_tree->vertical[0].mic;
2989       *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
2990       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
2991
2992       if (mi_col + hbs < cm->mi_cols) {
2993         set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
2994         *(xd->mi[0]) = pc_tree->vertical[1].mic;
2995         *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
2996         duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
2997       }
2998       break;
2999     case PARTITION_HORZ:
3000       set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
3001       *(xd->mi[0]) = pc_tree->horizontal[0].mic;
3002       *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
3003       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
3004       if (mi_row + hbs < cm->mi_rows) {
3005         set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
3006         *(xd->mi[0]) = pc_tree->horizontal[1].mic;
3007         *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
3008         duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
3009       }
3010       break;
3011     case PARTITION_SPLIT: {
3012       fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
3013       fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
3014                         pc_tree->split[1]);
3015       fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
3016                         pc_tree->split[2]);
3017       fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
3018                         pc_tree->split[3]);
3019       break;
3020     }
3021     default:
3022       break;
3023   }
3024 }
3025
3026 // Reset the prediction pixel ready flag recursively.
3027 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
3028   pc_tree->none.pred_pixel_ready = 0;
3029   pc_tree->horizontal[0].pred_pixel_ready = 0;
3030   pc_tree->horizontal[1].pred_pixel_ready = 0;
3031   pc_tree->vertical[0].pred_pixel_ready = 0;
3032   pc_tree->vertical[1].pred_pixel_ready = 0;
3033
3034   if (bsize > BLOCK_8X8) {
3035     BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3036     int i;
3037     for (i = 0; i < 4; ++i)
3038       pred_pixel_ready_reset(pc_tree->split[i], subsize);
3039   }
3040 }
3041
3042 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3043                                  TileDataEnc *tile_data,
3044                                  TOKENEXTRA **tp, int mi_row,
3045                                  int mi_col, BLOCK_SIZE bsize, RD_COST *rd_cost,
3046                                  int do_recon, int64_t best_rd,
3047                                  PC_TREE *pc_tree) {
3048   const SPEED_FEATURES *const sf = &cpi->sf;
3049   VP9_COMMON *const cm = &cpi->common;
3050   TileInfo *const tile_info = &tile_data->tile_info;
3051   MACROBLOCK *const x = &td->mb;
3052   MACROBLOCKD *const xd = &x->e_mbd;
3053   const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
3054   TOKENEXTRA *tp_orig = *tp;
3055   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
3056   int i;
3057   BLOCK_SIZE subsize = bsize;
3058   RD_COST this_rdc, sum_rdc, best_rdc;
3059   int do_split = bsize >= BLOCK_8X8;
3060   int do_rect = 1;
3061   // Override skipping rectangular partition operations for edge blocks
3062   const int force_horz_split = (mi_row + ms >= cm->mi_rows);
3063   const int force_vert_split = (mi_col + ms >= cm->mi_cols);
3064   const int xss = x->e_mbd.plane[1].subsampling_x;
3065   const int yss = x->e_mbd.plane[1].subsampling_y;
3066
3067   int partition_none_allowed = !force_horz_split && !force_vert_split;
3068   int partition_horz_allowed = !force_vert_split && yss <= xss &&
3069                                bsize >= BLOCK_8X8;
3070   int partition_vert_allowed = !force_horz_split && xss <= yss &&
3071                                bsize >= BLOCK_8X8;
3072   (void) *tp_orig;
3073
3074   assert(num_8x8_blocks_wide_lookup[bsize] ==
3075              num_8x8_blocks_high_lookup[bsize]);
3076
3077   vp9_rd_cost_init(&sum_rdc);
3078   vp9_rd_cost_reset(&best_rdc);
3079   best_rdc.rdcost = best_rd;
3080
3081   // Determine partition types in search according to the speed features.
3082   // The threshold set here has to be of square block size.
3083   if (sf->auto_min_max_partition_size) {
3084     partition_none_allowed &= (bsize <= x->max_partition_size &&
3085                                bsize >= x->min_partition_size);
3086     partition_horz_allowed &= ((bsize <= x->max_partition_size &&
3087                                 bsize > x->min_partition_size) ||
3088                                 force_horz_split);
3089     partition_vert_allowed &= ((bsize <= x->max_partition_size &&
3090                                 bsize > x->min_partition_size) ||
3091                                 force_vert_split);
3092     do_split &= bsize > x->min_partition_size;
3093   }
3094   if (sf->use_square_partition_only) {
3095     partition_horz_allowed &= force_horz_split;
3096     partition_vert_allowed &= force_vert_split;
3097   }
3098
3099   ctx->pred_pixel_ready = !(partition_vert_allowed ||
3100                             partition_horz_allowed ||
3101                             do_split);
3102
3103   // PARTITION_NONE
3104   if (partition_none_allowed) {
3105     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col,
3106                         &this_rdc, bsize, ctx);
3107     ctx->mic.mbmi = xd->mi[0]->mbmi;
3108     ctx->mbmi_ext = *x->mbmi_ext;
3109     ctx->skip_txfm[0] = x->skip_txfm[0];
3110     ctx->skip = x->skip;
3111
3112     if (this_rdc.rate != INT_MAX) {
3113       int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3114       this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3115       this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3116                               this_rdc.rate, this_rdc.dist);
3117       if (this_rdc.rdcost < best_rdc.rdcost) {
3118         int64_t dist_breakout_thr = sf->partition_search_breakout_dist_thr;
3119         int64_t rate_breakout_thr = sf->partition_search_breakout_rate_thr;
3120
3121         dist_breakout_thr >>= 8 - (b_width_log2_lookup[bsize] +
3122             b_height_log2_lookup[bsize]);
3123
3124         rate_breakout_thr *= num_pels_log2_lookup[bsize];
3125
3126         best_rdc = this_rdc;
3127         if (bsize >= BLOCK_8X8)
3128           pc_tree->partitioning = PARTITION_NONE;
3129
3130         if (!x->e_mbd.lossless &&
3131             this_rdc.rate < rate_breakout_thr &&
3132             this_rdc.dist < dist_breakout_thr) {
3133           do_split = 0;
3134           do_rect = 0;
3135         }
3136       }
3137     }
3138   }
3139
3140   // store estimated motion vector
3141   store_pred_mv(x, ctx);
3142
3143   // PARTITION_SPLIT
3144   if (do_split) {
3145     int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3146     sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
3147     sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
3148     subsize = get_subsize(bsize, PARTITION_SPLIT);
3149     for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
3150       const int x_idx = (i & 1) * ms;
3151       const int y_idx = (i >> 1) * ms;
3152
3153       if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
3154         continue;
3155       load_pred_mv(x, ctx);
3156       nonrd_pick_partition(cpi, td, tile_data, tp,
3157                            mi_row + y_idx, mi_col + x_idx,
3158                            subsize, &this_rdc, 0,
3159                            best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
3160
3161       if (this_rdc.rate == INT_MAX) {
3162         vp9_rd_cost_reset(&sum_rdc);
3163       } else {
3164         sum_rdc.rate += this_rdc.rate;
3165         sum_rdc.dist += this_rdc.dist;
3166         sum_rdc.rdcost += this_rdc.rdcost;
3167       }
3168     }
3169
3170     if (sum_rdc.rdcost < best_rdc.rdcost) {
3171       best_rdc = sum_rdc;
3172       pc_tree->partitioning = PARTITION_SPLIT;
3173     } else {
3174       // skip rectangular partition test when larger block size
3175       // gives better rd cost
3176       if (sf->less_rectangular_check)
3177         do_rect &= !partition_none_allowed;
3178     }
3179   }
3180
3181   // PARTITION_HORZ
3182   if (partition_horz_allowed && do_rect) {
3183     subsize = get_subsize(bsize, PARTITION_HORZ);
3184     if (sf->adaptive_motion_search)
3185       load_pred_mv(x, ctx);
3186     pc_tree->horizontal[0].pred_pixel_ready = 1;
3187     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
3188                         &pc_tree->horizontal[0]);
3189
3190     pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3191     pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
3192     pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3193     pc_tree->horizontal[0].skip = x->skip;
3194
3195     if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
3196       load_pred_mv(x, ctx);
3197       pc_tree->horizontal[1].pred_pixel_ready = 1;
3198       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col,
3199                           &this_rdc, subsize,
3200                           &pc_tree->horizontal[1]);
3201
3202       pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3203       pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
3204       pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3205       pc_tree->horizontal[1].skip = x->skip;
3206
3207       if (this_rdc.rate == INT_MAX) {
3208         vp9_rd_cost_reset(&sum_rdc);
3209       } else {
3210         int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3211         this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
3212         sum_rdc.rate += this_rdc.rate;
3213         sum_rdc.dist += this_rdc.dist;
3214         sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3215                                 sum_rdc.rate, sum_rdc.dist);
3216       }
3217     }
3218
3219     if (sum_rdc.rdcost < best_rdc.rdcost) {
3220       best_rdc = sum_rdc;
3221       pc_tree->partitioning = PARTITION_HORZ;
3222     } else {
3223       pred_pixel_ready_reset(pc_tree, bsize);
3224     }
3225   }
3226
3227   // PARTITION_VERT
3228   if (partition_vert_allowed && do_rect) {
3229     subsize = get_subsize(bsize, PARTITION_VERT);
3230     if (sf->adaptive_motion_search)
3231       load_pred_mv(x, ctx);
3232     pc_tree->vertical[0].pred_pixel_ready = 1;
3233     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
3234                         &pc_tree->vertical[0]);
3235     pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3236     pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
3237     pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3238     pc_tree->vertical[0].skip = x->skip;
3239
3240     if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
3241       load_pred_mv(x, ctx);
3242       pc_tree->vertical[1].pred_pixel_ready = 1;
3243       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms,
3244                           &this_rdc, subsize,
3245                           &pc_tree->vertical[1]);
3246       pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3247       pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
3248       pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3249       pc_tree->vertical[1].skip = x->skip;
3250
3251       if (this_rdc.rate == INT_MAX) {
3252         vp9_rd_cost_reset(&sum_rdc);
3253       } else {
3254         int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3255         sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
3256         sum_rdc.rate += this_rdc.rate;
3257         sum_rdc.dist += this_rdc.dist;
3258         sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3259                                 sum_rdc.rate, sum_rdc.dist);
3260       }
3261     }
3262
3263     if (sum_rdc.rdcost < best_rdc.rdcost) {
3264       best_rdc = sum_rdc;
3265       pc_tree->partitioning = PARTITION_VERT;
3266     } else {
3267       pred_pixel_ready_reset(pc_tree, bsize);
3268     }
3269   }
3270
3271   *rd_cost = best_rdc;
3272
3273   if (best_rdc.rate == INT_MAX) {
3274     vp9_rd_cost_reset(rd_cost);
3275     return;
3276   }
3277
3278   // update mode info array
3279   fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
3280
3281   if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
3282     int output_enabled = (bsize == BLOCK_64X64);
3283     encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3284                  bsize, pc_tree);
3285   }
3286
3287   if (bsize == BLOCK_64X64 && do_recon) {
3288     assert(tp_orig < *tp);
3289     assert(best_rdc.rate < INT_MAX);
3290     assert(best_rdc.dist < INT64_MAX);
3291   } else {
3292     assert(tp_orig == *tp);
3293   }
3294 }
3295
3296 static void nonrd_select_partition(VP9_COMP *cpi,
3297                                    ThreadData *td,
3298                                    TileDataEnc *tile_data,
3299                                    MODE_INFO **mi,
3300                                    TOKENEXTRA **tp,
3301                                    int mi_row, int mi_col,
3302                                    BLOCK_SIZE bsize, int output_enabled,
3303                                    RD_COST *rd_cost, PC_TREE *pc_tree) {
3304   VP9_COMMON *const cm = &cpi->common;
3305   TileInfo *const tile_info = &tile_data->tile_info;
3306   MACROBLOCK *const x = &td->mb;
3307   MACROBLOCKD *const xd = &x->e_mbd;
3308   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
3309   const int mis = cm->mi_stride;
3310   PARTITION_TYPE partition;
3311   BLOCK_SIZE subsize;
3312   RD_COST this_rdc;
3313
3314   vp9_rd_cost_reset(&this_rdc);
3315   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
3316     return;
3317
3318   subsize = (bsize >= BLOCK_8X8) ? mi[0]->mbmi.sb_type : BLOCK_4X4;
3319   partition = partition_lookup[bsl][subsize];
3320
3321   if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
3322     x->max_partition_size = BLOCK_32X32;
3323     x->min_partition_size = BLOCK_16X16;
3324     nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize,
3325                          rd_cost, 0, INT64_MAX, pc_tree);
3326   } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
3327              subsize >= BLOCK_16X16) {
3328     x->max_partition_size = BLOCK_32X32;
3329     x->min_partition_size = BLOCK_8X8;
3330     nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize,
3331                          rd_cost, 0, INT64_MAX, pc_tree);
3332   } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
3333     x->max_partition_size = BLOCK_16X16;
3334     x->min_partition_size = BLOCK_8X8;
3335     nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize,
3336                          rd_cost, 0, INT64_MAX, pc_tree);
3337   } else {
3338     switch (partition) {
3339       case PARTITION_NONE:
3340         pc_tree->none.pred_pixel_ready = 1;
3341         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3342                             subsize, &pc_tree->none);
3343         pc_tree->none.mic.mbmi = xd->mi[0]->mbmi;
3344         pc_tree->none.mbmi_ext = *x->mbmi_ext;
3345         pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
3346         pc_tree->none.skip = x->skip;
3347         break;
3348       case PARTITION_VERT:
3349         pc_tree->vertical[0].pred_pixel_ready = 1;
3350         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3351                             subsize, &pc_tree->vertical[0]);
3352         pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3353         pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
3354         pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3355         pc_tree->vertical[0].skip = x->skip;
3356         if (mi_col + hbs < cm->mi_cols) {
3357           pc_tree->vertical[1].pred_pixel_ready = 1;
3358           nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
3359                               &this_rdc, subsize, &pc_tree->vertical[1]);
3360           pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3361           pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
3362           pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3363           pc_tree->vertical[1].skip = x->skip;
3364           if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3365               rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3366             rd_cost->rate += this_rdc.rate;
3367             rd_cost->dist += this_rdc.dist;
3368           }
3369         }
3370         break;
3371       case PARTITION_HORZ:
3372         pc_tree->horizontal[0].pred_pixel_ready = 1;
3373         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3374                             subsize, &pc_tree->horizontal[0]);
3375         pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3376         pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
3377         pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3378         pc_tree->horizontal[0].skip = x->skip;
3379         if (mi_row + hbs < cm->mi_rows) {
3380           pc_tree->horizontal[1].pred_pixel_ready = 1;
3381           nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
3382                               &this_rdc, subsize, &pc_tree->horizontal[1]);
3383           pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3384           pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
3385           pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3386           pc_tree->horizontal[1].skip = x->skip;
3387           if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3388               rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3389             rd_cost->rate += this_rdc.rate;
3390             rd_cost->dist += this_rdc.dist;
3391           }
3392         }
3393         break;
3394       case PARTITION_SPLIT:
3395         subsize = get_subsize(bsize, PARTITION_SPLIT);
3396         nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3397                                subsize, output_enabled, rd_cost,
3398                                pc_tree->split[0]);
3399         nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp,
3400                                mi_row, mi_col + hbs, subsize, output_enabled,
3401                                &this_rdc, pc_tree->split[1]);
3402         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3403             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3404           rd_cost->rate += this_rdc.rate;
3405           rd_cost->dist += this_rdc.dist;
3406         }
3407         nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
3408                                mi_row + hbs, mi_col, subsize, output_enabled,
3409                                &this_rdc, pc_tree->split[2]);
3410         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3411             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3412           rd_cost->rate += this_rdc.rate;
3413           rd_cost->dist += this_rdc.dist;
3414         }
3415         nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
3416                                mi_row + hbs, mi_col + hbs, subsize,
3417                                output_enabled, &this_rdc, pc_tree->split[3]);
3418         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3419             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3420           rd_cost->rate += this_rdc.rate;
3421           rd_cost->dist += this_rdc.dist;
3422         }
3423         break;
3424       default:
3425         assert(0 && "Invalid partition type.");
3426         break;
3427     }
3428   }
3429
3430   if (bsize == BLOCK_64X64 && output_enabled)
3431     encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
3432 }
3433
3434
3435 static void nonrd_use_partition(VP9_COMP *cpi,
3436                                 ThreadData *td,
3437                                 TileDataEnc *tile_data,
3438                                 MODE_INFO **mi,
3439                                 TOKENEXTRA **tp,
3440                                 int mi_row, int mi_col,
3441                                 BLOCK_SIZE bsize, int output_enabled,
3442                                 RD_COST *dummy_cost, PC_TREE *pc_tree) {
3443   VP9_COMMON *const cm = &cpi->common;
3444   TileInfo *tile_info = &tile_data->tile_info;
3445   MACROBLOCK *const x = &td->mb;
3446   MACROBLOCKD *const xd = &x->e_mbd;
3447   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
3448   const int mis = cm->mi_stride;
3449   PARTITION_TYPE partition;
3450   BLOCK_SIZE subsize;
3451
3452   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
3453     return;
3454
3455   subsize = (bsize >= BLOCK_8X8) ? mi[0]->mbmi.sb_type : BLOCK_4X4;
3456   partition = partition_lookup[bsl][subsize];
3457
3458   if (output_enabled && bsize != BLOCK_4X4) {
3459     int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
3460     td->counts->partition[ctx][partition]++;
3461   }
3462
3463   switch (partition) {
3464     case PARTITION_NONE:
3465       pc_tree->none.pred_pixel_ready = 1;
3466       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3467                           subsize, &pc_tree->none);
3468       pc_tree->none.mic.mbmi = xd->mi[0]->mbmi;
3469       pc_tree->none.mbmi_ext = *x->mbmi_ext;
3470       pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
3471       pc_tree->none.skip = x->skip;
3472       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3473                   subsize, &pc_tree->none);
3474       break;
3475     case PARTITION_VERT:
3476       pc_tree->vertical[0].pred_pixel_ready = 1;
3477       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3478                           subsize, &pc_tree->vertical[0]);
3479       pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3480       pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
3481       pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3482       pc_tree->vertical[0].skip = x->skip;
3483       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3484                   subsize, &pc_tree->vertical[0]);
3485       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
3486         pc_tree->vertical[1].pred_pixel_ready = 1;
3487         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
3488                             dummy_cost, subsize, &pc_tree->vertical[1]);
3489         pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3490         pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
3491         pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3492         pc_tree->vertical[1].skip = x->skip;
3493         encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
3494                     output_enabled, subsize, &pc_tree->vertical[1]);
3495       }
3496       break;
3497     case PARTITION_HORZ:
3498       pc_tree->horizontal[0].pred_pixel_ready = 1;
3499       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3500                           subsize, &pc_tree->horizontal[0]);
3501       pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3502       pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
3503       pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3504       pc_tree->horizontal[0].skip = x->skip;
3505       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3506                   subsize, &pc_tree->horizontal[0]);
3507
3508       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
3509         pc_tree->horizontal[1].pred_pixel_ready = 1;
3510         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
3511                             dummy_cost, subsize, &pc_tree->horizontal[1]);
3512         pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3513         pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
3514         pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3515         pc_tree->horizontal[1].skip = x->skip;
3516         encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
3517                     output_enabled, subsize, &pc_tree->horizontal[1]);
3518       }
3519       break;
3520     case PARTITION_SPLIT:
3521       subsize = get_subsize(bsize, PARTITION_SPLIT);
3522       if (bsize == BLOCK_8X8) {
3523         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3524                             subsize, pc_tree->leaf_split[0]);
3525         encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col,
3526                     output_enabled, subsize, pc_tree->leaf_split[0]);
3527       } else {
3528         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3529                             subsize, output_enabled, dummy_cost,
3530                             pc_tree->split[0]);
3531         nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp,
3532                             mi_row, mi_col + hbs, subsize, output_enabled,
3533                             dummy_cost, pc_tree->split[1]);
3534         nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
3535                             mi_row + hbs, mi_col, subsize, output_enabled,
3536                             dummy_cost, pc_tree->split[2]);
3537         nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
3538                             mi_row + hbs, mi_col + hbs, subsize, output_enabled,
3539                             dummy_cost, pc_tree->split[3]);
3540       }
3541       break;
3542     default:
3543       assert(0 && "Invalid partition type.");
3544       break;
3545   }
3546
3547   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
3548     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
3549 }
3550
3551 static void encode_nonrd_sb_row(VP9_COMP *cpi,
3552                                 ThreadData *td,
3553                                 TileDataEnc *tile_data,
3554                                 int mi_row,
3555                                 TOKENEXTRA **tp) {
3556   SPEED_FEATURES *const sf = &cpi->sf;
3557   VP9_COMMON *const cm = &cpi->common;
3558   TileInfo *const tile_info = &tile_data->tile_info;
3559   MACROBLOCK *const x = &td->mb;
3560   MACROBLOCKD *const xd = &x->e_mbd;
3561   int mi_col;
3562
3563   // Initialize the left context for the new SB row
3564   memset(&xd->left_context, 0, sizeof(xd->left_context));
3565   memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
3566
3567   // Code each SB in the row
3568   for (mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
3569        mi_col += MI_BLOCK_SIZE) {
3570     const struct segmentation *const seg = &cm->seg;
3571     RD_COST dummy_rdc;
3572     const int idx_str = cm->mi_stride * mi_row + mi_col;
3573     MODE_INFO **mi = cm->mi_grid_visible + idx_str;
3574     PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
3575     BLOCK_SIZE bsize = BLOCK_64X64;
3576     int seg_skip = 0;
3577     x->source_variance = UINT_MAX;
3578     vp9_zero(x->pred_mv);
3579     vp9_rd_cost_init(&dummy_rdc);
3580     x->color_sensitivity[0] = 0;
3581     x->color_sensitivity[1] = 0;
3582
3583     if (seg->enabled) {
3584       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
3585                                                  : cm->last_frame_seg_map;
3586       int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
3587       seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
3588       if (seg_skip) {
3589         partition_search_type = FIXED_PARTITION;
3590       }
3591     }
3592
3593     // Set the partition type of the 64X64 block
3594     switch (partition_search_type) {
3595       case VAR_BASED_PARTITION:
3596         // TODO(jingning, marpan): The mode decision and encoding process
3597         // support both intra and inter sub8x8 block coding for RTC mode.
3598         // Tune the thresholds accordingly to use sub8x8 block coding for
3599         // coding performance improvement.
3600         choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
3601         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3602                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3603         break;
3604       case SOURCE_VAR_BASED_PARTITION:
3605         set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
3606         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3607                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3608         break;
3609       case FIXED_PARTITION:
3610         if (!seg_skip)
3611           bsize = sf->always_this_block_size;
3612         set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
3613         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3614                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3615         break;
3616       case REFERENCE_PARTITION:
3617         set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
3618         if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
3619             xd->mi[0]->mbmi.segment_id) {
3620           // Use lower max_partition_size for low resoultions.
3621           if (cm->width <= 352 && cm->height <= 288)
3622             x->max_partition_size = BLOCK_32X32;
3623           else
3624             x->max_partition_size = BLOCK_64X64;
3625           x->min_partition_size = BLOCK_8X8;
3626           nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
3627                                BLOCK_64X64, &dummy_rdc, 1,
3628                                INT64_MAX, td->pc_root);
3629         } else {
3630           choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
3631           // TODO(marpan): Seems like nonrd_select_partition does not support
3632           // 4x4 partition. Since 4x4 is used on key frame, use this switch
3633           // for now.
3634           if (cm->frame_type == KEY_FRAME)
3635             nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3636                                 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3637           else
3638             nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3639                                    BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3640         }
3641
3642         break;
3643       default:
3644         assert(0);
3645         break;
3646     }
3647   }
3648 }
3649 // end RTC play code
3650
3651 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
3652   const SPEED_FEATURES *const sf = &cpi->sf;
3653   const VP9_COMMON *const cm = &cpi->common;
3654
3655   const uint8_t *src = cpi->Source->y_buffer;
3656   const uint8_t *last_src = cpi->Last_Source->y_buffer;
3657   const int src_stride = cpi->Source->y_stride;
3658   const int last_stride = cpi->Last_Source->y_stride;
3659
3660   // Pick cutoff threshold
3661   const int cutoff = (MIN(cm->width, cm->height) >= 720) ?
3662       (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100) :
3663       (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
3664   DECLARE_ALIGNED(16, int, hist[VAR_HIST_BINS]);
3665   diff *var16 = cpi->source_diff_var;
3666
3667   int sum = 0;
3668   int i, j;
3669
3670   memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
3671
3672   for (i = 0; i < cm->mb_rows; i++) {
3673     for (j = 0; j < cm->mb_cols; j++) {
3674 #if CONFIG_VP9_HIGHBITDEPTH
3675       if (cm->use_highbitdepth) {
3676         switch (cm->bit_depth) {
3677           case VPX_BITS_8:
3678             vpx_highbd_8_get16x16var(src, src_stride, last_src, last_stride,
3679                                    &var16->sse, &var16->sum);
3680             break;
3681           case VPX_BITS_10:
3682             vpx_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
3683                                     &var16->sse, &var16->sum);
3684             break;
3685           case VPX_BITS_12:
3686             vpx_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
3687                                       &var16->sse, &var16->sum);
3688             break;
3689           default:
3690             assert(0 && "cm->bit_depth should be VPX_BITS_8, VPX_BITS_10"
3691                    " or VPX_BITS_12");
3692             return -1;
3693         }
3694       } else {
3695         vpx_get16x16var(src, src_stride, last_src, last_stride,
3696                         &var16->sse, &var16->sum);
3697       }
3698 #else
3699       vpx_get16x16var(src, src_stride, last_src, last_stride,
3700                       &var16->sse, &var16->sum);
3701 #endif  // CONFIG_VP9_HIGHBITDEPTH
3702       var16->var = var16->sse -
3703           (((uint32_t)var16->sum * var16->sum) >> 8);
3704
3705       if (var16->var >= VAR_HIST_MAX_BG_VAR)
3706         hist[VAR_HIST_BINS - 1]++;
3707       else
3708         hist[var16->var / VAR_HIST_FACTOR]++;
3709
3710       src += 16;
3711       last_src += 16;
3712       var16++;
3713     }
3714
3715     src = src - cm->mb_cols * 16 + 16 * src_stride;
3716     last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
3717   }
3718
3719   cpi->source_var_thresh = 0;
3720
3721   if (hist[VAR_HIST_BINS - 1] < cutoff) {
3722     for (i = 0; i < VAR_HIST_BINS - 1; i++) {
3723       sum += hist[i];
3724
3725       if (sum > cutoff) {
3726         cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
3727         return 0;
3728       }
3729     }
3730   }
3731
3732   return sf->search_type_check_frequency;
3733 }
3734
3735 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
3736   VP9_COMMON *const cm = &cpi->common;
3737   SPEED_FEATURES *const sf = &cpi->sf;
3738
3739   if (cm->frame_type == KEY_FRAME) {
3740     // For key frame, use SEARCH_PARTITION.
3741     sf->partition_search_type = SEARCH_PARTITION;
3742   } else if (cm->intra_only) {
3743     sf->partition_search_type = FIXED_PARTITION;
3744   } else {
3745     if (cm->last_width != cm->width || cm->last_height != cm->height) {
3746       if (cpi->source_diff_var)
3747         vpx_free(cpi->source_diff_var);
3748
3749       CHECK_MEM_ERROR(cm, cpi->source_diff_var,
3750                       vpx_calloc(cm->MBs, sizeof(diff)));
3751     }
3752
3753     if (!cpi->frames_till_next_var_check)
3754       cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
3755
3756     if (cpi->frames_till_next_var_check > 0) {
3757       sf->partition_search_type = FIXED_PARTITION;
3758       cpi->frames_till_next_var_check--;
3759     }
3760   }
3761 }
3762
3763 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
3764   unsigned int intra_count = 0, inter_count = 0;
3765   int j;
3766
3767   for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
3768     intra_count += td->counts->intra_inter[j][0];
3769     inter_count += td->counts->intra_inter[j][1];
3770   }
3771
3772   return (intra_count << 2) < inter_count &&
3773          cm->frame_type != KEY_FRAME &&
3774          cm->show_frame;
3775 }
3776
3777 void vp9_init_tile_data(VP9_COMP *cpi) {
3778   VP9_COMMON *const cm = &cpi->common;
3779   const int tile_cols = 1 << cm->log2_tile_cols;
3780   const int tile_rows = 1 << cm->log2_tile_rows;
3781   int tile_col, tile_row;
3782   TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
3783   int tile_tok = 0;
3784
3785   if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
3786     if (cpi->tile_data != NULL)
3787       vpx_free(cpi->tile_data);
3788     CHECK_MEM_ERROR(cm, cpi->tile_data,
3789         vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
3790     cpi->allocated_tiles = tile_cols * tile_rows;
3791
3792     for (tile_row = 0; tile_row < tile_rows; ++tile_row)
3793       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
3794         TileDataEnc *tile_data =
3795             &cpi->tile_data[tile_row * tile_cols + tile_col];
3796         int i, j;
3797         for (i = 0; i < BLOCK_SIZES; ++i) {
3798           for (j = 0; j < MAX_MODES; ++j) {
3799             tile_data->thresh_freq_fact[i][j] = 32;
3800             tile_data->mode_map[i][j] = j;
3801           }
3802         }
3803       }
3804   }
3805
3806   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
3807     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
3808       TileInfo *tile_info =
3809           &cpi->tile_data[tile_row * tile_cols + tile_col].tile_info;
3810       vp9_tile_init(tile_info, cm, tile_row, tile_col);
3811
3812       cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
3813       pre_tok = cpi->tile_tok[tile_row][tile_col];
3814       tile_tok = allocated_tokens(*tile_info);
3815     }
3816   }
3817 }
3818
3819 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td,
3820                      int tile_row, int tile_col) {
3821   VP9_COMMON *const cm = &cpi->common;
3822   const int tile_cols = 1 << cm->log2_tile_cols;
3823   TileDataEnc *this_tile =
3824       &cpi->tile_data[tile_row * tile_cols + tile_col];
3825   const TileInfo * const tile_info = &this_tile->tile_info;
3826   TOKENEXTRA *tok = cpi->tile_tok[tile_row][tile_col];
3827   int mi_row;
3828
3829   for (mi_row = tile_info->mi_row_start; mi_row < tile_info->mi_row_end;
3830        mi_row += MI_BLOCK_SIZE) {
3831     if (cpi->sf.use_nonrd_pick_mode)
3832       encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
3833     else
3834       encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
3835   }
3836   cpi->tok_count[tile_row][tile_col] =
3837       (unsigned int)(tok - cpi->tile_tok[tile_row][tile_col]);
3838   assert(tok - cpi->tile_tok[tile_row][tile_col] <=
3839       allocated_tokens(*tile_info));
3840 }
3841
3842 static void encode_tiles(VP9_COMP *cpi) {
3843   VP9_COMMON *const cm = &cpi->common;
3844   const int tile_cols = 1 << cm->log2_tile_cols;
3845   const int tile_rows = 1 << cm->log2_tile_rows;
3846   int tile_col, tile_row;
3847
3848   vp9_init_tile_data(cpi);
3849
3850   for (tile_row = 0; tile_row < tile_rows; ++tile_row)
3851     for (tile_col = 0; tile_col < tile_cols; ++tile_col)
3852       vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
3853 }
3854
3855 #if CONFIG_FP_MB_STATS
3856 static int input_fpmb_stats(FIRSTPASS_MB_STATS *firstpass_mb_stats,
3857                             VP9_COMMON *cm, uint8_t **this_frame_mb_stats) {
3858   uint8_t *mb_stats_in = firstpass_mb_stats->mb_stats_start +
3859       cm->current_video_frame * cm->MBs * sizeof(uint8_t);
3860
3861   if (mb_stats_in > firstpass_mb_stats->mb_stats_end)
3862     return EOF;
3863
3864   *this_frame_mb_stats = mb_stats_in;
3865
3866   return 1;
3867 }
3868 #endif
3869
3870 static void encode_frame_internal(VP9_COMP *cpi) {
3871   SPEED_FEATURES *const sf = &cpi->sf;
3872   RD_OPT *const rd_opt = &cpi->rd;
3873   ThreadData *const td = &cpi->td;
3874   MACROBLOCK *const x = &td->mb;
3875   VP9_COMMON *const cm = &cpi->common;
3876   MACROBLOCKD *const xd = &x->e_mbd;
3877   RD_COUNTS *const rdc = &cpi->td.rd_counts;
3878
3879   xd->mi = cm->mi_grid_visible;
3880   xd->mi[0] = cm->mi;
3881
3882   vp9_zero(*td->counts);
3883   vp9_zero(rdc->coef_counts);
3884   vp9_zero(rdc->comp_pred_diff);
3885   vp9_zero(rdc->filter_diff);
3886   vp9_zero(rdc->tx_select_diff);
3887   vp9_zero(rd_opt->tx_select_threshes);
3888
3889   xd->lossless = cm->base_qindex == 0 &&
3890                  cm->y_dc_delta_q == 0 &&
3891                  cm->uv_dc_delta_q == 0 &&
3892                  cm->uv_ac_delta_q == 0;
3893
3894 #if CONFIG_VP9_HIGHBITDEPTH
3895   if (cm->use_highbitdepth)
3896     x->fwd_txm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vp9_highbd_fdct4x4;
3897   else
3898     x->fwd_txm4x4 = xd->lossless ? vp9_fwht4x4 : vp9_fdct4x4;
3899   x->highbd_itxm_add = xd->lossless ? vp9_highbd_iwht4x4_add :
3900                                       vp9_highbd_idct4x4_add;
3901 #else
3902   x->fwd_txm4x4 = xd->lossless ? vp9_fwht4x4 : vp9_fdct4x4;
3903 #endif  // CONFIG_VP9_HIGHBITDEPTH
3904   x->itxm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
3905
3906   if (xd->lossless)
3907     x->optimize = 0;
3908
3909   cm->tx_mode = select_tx_mode(cpi, xd);
3910
3911   vp9_frame_init_quantizer(cpi);
3912
3913   vp9_initialize_rd_consts(cpi);
3914   vp9_initialize_me_consts(cpi, x, cm->base_qindex);
3915   init_encode_frame_mb_context(cpi);
3916   cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
3917                            cm->width == cm->last_width &&
3918                            cm->height == cm->last_height &&
3919                            !cm->intra_only &&
3920                            cm->last_show_frame;
3921   // Special case: set prev_mi to NULL when the previous mode info
3922   // context cannot be used.
3923   cm->prev_mi = cm->use_prev_frame_mvs ?
3924                 cm->prev_mip + cm->mi_stride + 1 : NULL;
3925
3926   x->quant_fp = cpi->sf.use_quant_fp;
3927   vp9_zero(x->skip_txfm);
3928   if (sf->use_nonrd_pick_mode) {
3929     // Initialize internal buffer pointers for rtc coding, where non-RD
3930     // mode decision is used and hence no buffer pointer swap needed.
3931     int i;
3932     struct macroblock_plane *const p = x->plane;
3933     struct macroblockd_plane *const pd = xd->plane;
3934     PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
3935
3936     for (i = 0; i < MAX_MB_PLANE; ++i) {
3937       p[i].coeff = ctx->coeff_pbuf[i][0];
3938       p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
3939       pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
3940       p[i].eobs = ctx->eobs_pbuf[i][0];
3941     }
3942     vp9_zero(x->zcoeff_blk);
3943
3944     if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0)
3945       cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
3946
3947     if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
3948       source_var_based_partition_search_method(cpi);
3949   }
3950
3951   {
3952     struct vpx_usec_timer emr_timer;
3953     vpx_usec_timer_start(&emr_timer);
3954
3955 #if CONFIG_FP_MB_STATS
3956   if (cpi->use_fp_mb_stats) {
3957     input_fpmb_stats(&cpi->twopass.firstpass_mb_stats, cm,
3958                      &cpi->twopass.this_frame_mb_stats);
3959   }
3960 #endif
3961
3962     // If allowed, encoding tiles in parallel with one thread handling one tile.
3963     if (MIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
3964       vp9_encode_tiles_mt(cpi);
3965     else
3966       encode_tiles(cpi);
3967
3968     vpx_usec_timer_mark(&emr_timer);
3969     cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
3970   }
3971
3972   sf->skip_encode_frame = sf->skip_encode_sb ?
3973       get_skip_encode_frame(cm, td) : 0;
3974
3975 #if 0
3976   // Keep record of the total distortion this time around for future use
3977   cpi->last_frame_distortion = cpi->frame_distortion;
3978 #endif
3979 }
3980
3981 static INTERP_FILTER get_interp_filter(
3982     const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
3983   if (!is_alt_ref &&
3984       threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
3985       threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
3986       threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
3987     return EIGHTTAP_SMOOTH;
3988   } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
3989              threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
3990     return EIGHTTAP_SHARP;
3991   } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
3992     return EIGHTTAP;
3993   } else {
3994     return SWITCHABLE;
3995   }
3996 }
3997
3998 void vp9_encode_frame(VP9_COMP *cpi) {
3999   VP9_COMMON *const cm = &cpi->common;
4000
4001   // In the longer term the encoder should be generalized to match the
4002   // decoder such that we allow compound where one of the 3 buffers has a
4003   // different sign bias and that buffer is then the fixed ref. However, this
4004   // requires further work in the rd loop. For now the only supported encoder
4005   // side behavior is where the ALT ref buffer has opposite sign bias to
4006   // the other two.
4007   if (!frame_is_intra_only(cm)) {
4008     if ((cm->ref_frame_sign_bias[ALTREF_FRAME] ==
4009              cm->ref_frame_sign_bias[GOLDEN_FRAME]) ||
4010         (cm->ref_frame_sign_bias[ALTREF_FRAME] ==
4011              cm->ref_frame_sign_bias[LAST_FRAME])) {
4012       cpi->allow_comp_inter_inter = 0;
4013     } else {
4014       cpi->allow_comp_inter_inter = 1;
4015       cm->comp_fixed_ref = ALTREF_FRAME;
4016       cm->comp_var_ref[0] = LAST_FRAME;
4017       cm->comp_var_ref[1] = GOLDEN_FRAME;
4018     }
4019   }
4020
4021   if (cpi->sf.frame_parameter_update) {
4022     int i;
4023     RD_OPT *const rd_opt = &cpi->rd;
4024     FRAME_COUNTS *counts = cpi->td.counts;
4025     RD_COUNTS *const rdc = &cpi->td.rd_counts;
4026
4027     // This code does a single RD pass over the whole frame assuming
4028     // either compound, single or hybrid prediction as per whatever has
4029     // worked best for that type of frame in the past.
4030     // It also predicts whether another coding mode would have worked
4031     // better that this coding mode. If that is the case, it remembers
4032     // that for subsequent frames.
4033     // It does the same analysis for transform size selection also.
4034     const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
4035     int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
4036     int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
4037     int *const tx_thrs = rd_opt->tx_select_threshes[frame_type];
4038     const int is_alt_ref = frame_type == ALTREF_FRAME;
4039
4040     /* prediction (compound, single or hybrid) mode selection */
4041     if (is_alt_ref || !cpi->allow_comp_inter_inter)
4042       cm->reference_mode = SINGLE_REFERENCE;
4043     else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
4044              mode_thrs[COMPOUND_REFERENCE] >
4045                  mode_thrs[REFERENCE_MODE_SELECT] &&
4046              check_dual_ref_flags(cpi) &&
4047              cpi->static_mb_pct == 100)
4048       cm->reference_mode = COMPOUND_REFERENCE;
4049     else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
4050       cm->reference_mode = SINGLE_REFERENCE;
4051     else
4052       cm->reference_mode = REFERENCE_MODE_SELECT;
4053
4054     if (cm->interp_filter == SWITCHABLE)
4055       cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
4056
4057     encode_frame_internal(cpi);
4058
4059     for (i = 0; i < REFERENCE_MODES; ++i)
4060       mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
4061
4062     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
4063       filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
4064
4065     for (i = 0; i < TX_MODES; ++i) {
4066       int64_t pd = rdc->tx_select_diff[i];
4067       if (i == TX_MODE_SELECT)
4068         pd -= RDCOST(cpi->td.mb.rdmult, cpi->td.mb.rddiv, 2048 * (TX_SIZES - 1),
4069                      0);
4070       tx_thrs[i] = (tx_thrs[i] + (int)(pd / cm->MBs)) / 2;
4071     }
4072
4073     if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4074       int single_count_zero = 0;
4075       int comp_count_zero = 0;
4076
4077       for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
4078         single_count_zero += counts->comp_inter[i][0];
4079         comp_count_zero += counts->comp_inter[i][1];
4080       }
4081
4082       if (comp_count_zero == 0) {
4083         cm->reference_mode = SINGLE_REFERENCE;
4084         vp9_zero(counts->comp_inter);
4085       } else if (single_count_zero == 0) {
4086         cm->reference_mode = COMPOUND_REFERENCE;
4087         vp9_zero(counts->comp_inter);
4088       }
4089     }
4090
4091     if (cm->tx_mode == TX_MODE_SELECT) {
4092       int count4x4 = 0;
4093       int count8x8_lp = 0, count8x8_8x8p = 0;
4094       int count16x16_16x16p = 0, count16x16_lp = 0;
4095       int count32x32 = 0;
4096
4097       for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
4098         count4x4 += counts->tx.p32x32[i][TX_4X4];
4099         count4x4 += counts->tx.p16x16[i][TX_4X4];
4100         count4x4 += counts->tx.p8x8[i][TX_4X4];
4101
4102         count8x8_lp += counts->tx.p32x32[i][TX_8X8];
4103         count8x8_lp += counts->tx.p16x16[i][TX_8X8];
4104         count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
4105
4106         count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
4107         count16x16_lp += counts->tx.p32x32[i][TX_16X16];
4108         count32x32 += counts->tx.p32x32[i][TX_32X32];
4109       }
4110       if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
4111           count32x32 == 0) {
4112         cm->tx_mode = ALLOW_8X8;
4113         reset_skip_tx_size(cm, TX_8X8);
4114       } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
4115                  count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
4116         cm->tx_mode = ONLY_4X4;
4117         reset_skip_tx_size(cm, TX_4X4);
4118       } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
4119         cm->tx_mode = ALLOW_32X32;
4120       } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
4121         cm->tx_mode = ALLOW_16X16;
4122         reset_skip_tx_size(cm, TX_16X16);
4123       }
4124     }
4125   } else {
4126     cm->reference_mode = SINGLE_REFERENCE;
4127     encode_frame_internal(cpi);
4128   }
4129 }
4130
4131 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
4132   const PREDICTION_MODE y_mode = mi->mbmi.mode;
4133   const PREDICTION_MODE uv_mode = mi->mbmi.uv_mode;
4134   const BLOCK_SIZE bsize = mi->mbmi.sb_type;
4135
4136   if (bsize < BLOCK_8X8) {
4137     int idx, idy;
4138     const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
4139     const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
4140     for (idy = 0; idy < 2; idy += num_4x4_h)
4141       for (idx = 0; idx < 2; idx += num_4x4_w)
4142         ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
4143   } else {
4144     ++counts->y_mode[size_group_lookup[bsize]][y_mode];
4145   }
4146
4147   ++counts->uv_mode[y_mode][uv_mode];
4148 }
4149
4150 static void encode_superblock(VP9_COMP *cpi, ThreadData *td,
4151                               TOKENEXTRA **t, int output_enabled,
4152                               int mi_row, int mi_col, BLOCK_SIZE bsize,
4153                               PICK_MODE_CONTEXT *ctx) {
4154   VP9_COMMON *const cm = &cpi->common;
4155   MACROBLOCK *const x = &td->mb;
4156   MACROBLOCKD *const xd = &x->e_mbd;
4157   MODE_INFO **mi_8x8 = xd->mi;
4158   MODE_INFO *mi = mi_8x8[0];
4159   MB_MODE_INFO *mbmi = &mi->mbmi;
4160   const int seg_skip = segfeature_active(&cm->seg, mbmi->segment_id,
4161                                          SEG_LVL_SKIP);
4162   const int mis = cm->mi_stride;
4163   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
4164   const int mi_height = num_8x8_blocks_high_lookup[bsize];
4165
4166   x->skip_recode = !x->select_tx_size && mbmi->sb_type >= BLOCK_8X8 &&
4167                    cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
4168                    cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
4169                    cpi->sf.allow_skip_recode;
4170
4171   if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
4172     memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
4173
4174   x->skip_optimize = ctx->is_coded;
4175   ctx->is_coded = 1;
4176   x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
4177   x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
4178                     x->q_index < QIDX_SKIP_THRESH);
4179
4180   if (x->skip_encode)
4181     return;
4182
4183   set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
4184
4185   if (!is_inter_block(mbmi)) {
4186     int plane;
4187     mbmi->skip = 1;
4188     for (plane = 0; plane < MAX_MB_PLANE; ++plane)
4189       vp9_encode_intra_block_plane(x, MAX(bsize, BLOCK_8X8), plane);
4190     if (output_enabled)
4191       sum_intra_stats(td->counts, mi);
4192     vp9_tokenize_sb(cpi, td, t, !output_enabled, MAX(bsize, BLOCK_8X8));
4193   } else {
4194     int ref;
4195     const int is_compound = has_second_ref(mbmi);
4196     for (ref = 0; ref < 1 + is_compound; ++ref) {
4197       YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi,
4198                                                      mbmi->ref_frame[ref]);
4199       assert(cfg != NULL);
4200       vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
4201                            &xd->block_refs[ref]->sf);
4202     }
4203     if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
4204       vp9_build_inter_predictors_sby(xd, mi_row, mi_col, MAX(bsize, BLOCK_8X8));
4205
4206     vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col, MAX(bsize, BLOCK_8X8));
4207
4208     vp9_encode_sb(x, MAX(bsize, BLOCK_8X8));
4209     vp9_tokenize_sb(cpi, td, t, !output_enabled, MAX(bsize, BLOCK_8X8));
4210   }
4211
4212   if (output_enabled) {
4213     if (cm->tx_mode == TX_MODE_SELECT &&
4214         mbmi->sb_type >= BLOCK_8X8  &&
4215         !(is_inter_block(mbmi) && (mbmi->skip || seg_skip))) {
4216       ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
4217                       &td->counts->tx)[mbmi->tx_size];
4218     } else {
4219       int x, y;
4220       TX_SIZE tx_size;
4221       // The new intra coding scheme requires no change of transform size
4222       if (is_inter_block(&mi->mbmi)) {
4223         tx_size = MIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
4224                       max_txsize_lookup[bsize]);
4225       } else {
4226         tx_size = (bsize >= BLOCK_8X8) ? mbmi->tx_size : TX_4X4;
4227       }
4228
4229       for (y = 0; y < mi_height; y++)
4230         for (x = 0; x < mi_width; x++)
4231           if (mi_col + x < cm->mi_cols && mi_row + y < cm->mi_rows)
4232             mi_8x8[mis * y + x]->mbmi.tx_size = tx_size;
4233     }
4234     ++td->counts->tx.tx_totals[mbmi->tx_size];
4235     ++td->counts->tx.tx_totals[get_uv_tx_size(mbmi, &xd->plane[1])];
4236   }
4237 }