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