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