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