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