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