configure: add --extra-cxxflags option
[platform/upstream/libvpx.git] / vp10 / encoder / 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 "./vp10_rtcd.h"
16 #include "./vpx_dsp_rtcd.h"
17 #include "./vpx_config.h"
18
19 #include "vpx_dsp/vpx_dsp_common.h"
20 #include "vpx_ports/mem.h"
21 #include "vpx_ports/vpx_timer.h"
22 #include "vpx_ports/system_state.h"
23
24 #include "vp10/common/common.h"
25 #include "vp10/common/entropy.h"
26 #include "vp10/common/entropymode.h"
27 #include "vp10/common/idct.h"
28 #include "vp10/common/mvref_common.h"
29 #include "vp10/common/pred_common.h"
30 #include "vp10/common/quant_common.h"
31 #include "vp10/common/reconintra.h"
32 #include "vp10/common/reconinter.h"
33 #include "vp10/common/seg_common.h"
34 #include "vp10/common/tile_common.h"
35
36 #include "vp10/encoder/aq_complexity.h"
37 #include "vp10/encoder/aq_cyclicrefresh.h"
38 #include "vp10/encoder/aq_variance.h"
39 #include "vp10/encoder/encodeframe.h"
40 #include "vp10/encoder/encodemb.h"
41 #include "vp10/encoder/encodemv.h"
42 #include "vp10/encoder/ethread.h"
43 #include "vp10/encoder/extend.h"
44 #include "vp10/encoder/rd.h"
45 #include "vp10/encoder/rdopt.h"
46 #include "vp10/encoder/segmentation.h"
47 #include "vp10/encoder/tokenize.h"
48
49 static void encode_superblock(VP10_COMP *cpi, ThreadData * td,
50                               TOKENEXTRA **t, int output_enabled,
51                               int mi_row, int mi_col, BLOCK_SIZE bsize,
52                               PICK_MODE_CONTEXT *ctx);
53
54 // This is used as a reference when computing the source variance for the
55 //  purposes of activity masking.
56 // Eventually this should be replaced by custom no-reference routines,
57 //  which will be faster.
58 static const uint8_t VP9_VAR_OFFS[64] = {
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     128, 128, 128, 128, 128, 128, 128, 128
67 };
68
69 #if CONFIG_VP9_HIGHBITDEPTH
70 static const uint16_t VP9_HIGH_VAR_OFFS_8[64] = {
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     128, 128, 128, 128, 128, 128, 128, 128
79 };
80
81 static const uint16_t VP9_HIGH_VAR_OFFS_10[64] = {
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     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4
90 };
91
92 static const uint16_t VP9_HIGH_VAR_OFFS_12[64] = {
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     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16
101 };
102 #endif  // CONFIG_VP9_HIGHBITDEPTH
103
104 unsigned int vp10_get_sby_perpixel_variance(VP10_COMP *cpi,
105                                            const struct buf_2d *ref,
106                                            BLOCK_SIZE bs) {
107   unsigned int sse;
108   const unsigned int var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
109                                               VP9_VAR_OFFS, 0, &sse);
110   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
111 }
112
113 #if CONFIG_VP9_HIGHBITDEPTH
114 unsigned int vp10_high_get_sby_perpixel_variance(
115     VP10_COMP *cpi, const struct buf_2d *ref, BLOCK_SIZE bs, int bd) {
116   unsigned int var, sse;
117   switch (bd) {
118     case 10:
119       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
120                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10),
121                                0, &sse);
122       break;
123     case 12:
124       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
125                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12),
126                                0, &sse);
127       break;
128     case 8:
129     default:
130       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
131                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8),
132                                0, &sse);
133       break;
134   }
135   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
136 }
137 #endif  // CONFIG_VP9_HIGHBITDEPTH
138
139 static unsigned int get_sby_perpixel_diff_variance(VP10_COMP *cpi,
140                                                    const struct buf_2d *ref,
141                                                    int mi_row, int mi_col,
142                                                    BLOCK_SIZE bs) {
143   unsigned int sse, var;
144   uint8_t *last_y;
145   const YV12_BUFFER_CONFIG *last = get_ref_frame_buffer(cpi, LAST_FRAME);
146
147   assert(last != NULL);
148   last_y =
149       &last->y_buffer[mi_row * MI_SIZE * last->y_stride + mi_col * MI_SIZE];
150   var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride, last_y, last->y_stride, &sse);
151   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
152 }
153
154 static BLOCK_SIZE get_rd_var_based_fixed_partition(VP10_COMP *cpi,
155                                                    MACROBLOCK *x,
156                                                    int mi_row,
157                                                    int mi_col) {
158   unsigned int var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src,
159                                                     mi_row, mi_col,
160                                                     BLOCK_64X64);
161   if (var < 8)
162     return BLOCK_64X64;
163   else if (var < 128)
164     return BLOCK_32X32;
165   else if (var < 2048)
166     return BLOCK_16X16;
167   else
168     return BLOCK_8X8;
169 }
170
171 // Lighter version of set_offsets that only sets the mode info
172 // pointers.
173 static INLINE void set_mode_info_offsets(VP10_COMMON *const cm,
174                                          MACROBLOCK *const x,
175                                          MACROBLOCKD *const xd,
176                                          int mi_row,
177                                          int mi_col) {
178   const int idx_str = xd->mi_stride * mi_row + mi_col;
179   xd->mi = cm->mi_grid_visible + idx_str;
180   xd->mi[0] = cm->mi + idx_str;
181   x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
182 }
183
184 static void set_offsets(VP10_COMP *cpi, const TileInfo *const tile,
185                         MACROBLOCK *const x, int mi_row, int mi_col,
186                         BLOCK_SIZE bsize) {
187   VP10_COMMON *const cm = &cpi->common;
188   MACROBLOCKD *const xd = &x->e_mbd;
189   MB_MODE_INFO *mbmi;
190   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
191   const int mi_height = num_8x8_blocks_high_lookup[bsize];
192   const struct segmentation *const seg = &cm->seg;
193
194   set_skip_context(xd, mi_row, mi_col);
195
196   set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
197
198   mbmi = &xd->mi[0]->mbmi;
199
200   // Set up destination pointers.
201   vp10_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
202
203   // Set up limit values for MV components.
204   // Mv beyond the range do not produce new/different prediction block.
205   x->mv_row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
206   x->mv_col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
207   x->mv_row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
208   x->mv_col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
209
210   // Set up distance of MB to edge of frame in 1/8th pel units.
211   assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
212   set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width,
213                  cm->mi_rows, cm->mi_cols);
214
215   // Set up source buffers.
216   vp10_setup_src_planes(x, cpi->Source, mi_row, mi_col);
217
218   // R/D setup.
219   x->rddiv = cpi->rd.RDDIV;
220   x->rdmult = cpi->rd.RDMULT;
221
222   // Setup segment ID.
223   if (seg->enabled) {
224     if (cpi->oxcf.aq_mode != VARIANCE_AQ) {
225       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
226                                                  : cm->last_frame_seg_map;
227       mbmi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
228     }
229     vp10_init_plane_quantizers(cpi, x);
230
231     x->encode_breakout = cpi->segment_encode_breakout[mbmi->segment_id];
232   } else {
233     mbmi->segment_id = 0;
234     x->encode_breakout = cpi->encode_breakout;
235   }
236
237   // required by vp10_append_sub8x8_mvs_for_idx() and vp10_find_best_ref_mvs()
238   xd->tile = *tile;
239 }
240
241 static void set_block_size(VP10_COMP * const cpi,
242                            MACROBLOCK *const x,
243                            MACROBLOCKD *const xd,
244                            int mi_row, int mi_col,
245                            BLOCK_SIZE bsize) {
246   if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
247     set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
248     xd->mi[0]->mbmi.sb_type = bsize;
249   }
250 }
251
252 typedef struct {
253   int64_t sum_square_error;
254   int64_t sum_error;
255   int log2_count;
256   int variance;
257 } var;
258
259 typedef struct {
260   var none;
261   var horz[2];
262   var vert[2];
263 } partition_variance;
264
265 typedef struct {
266   partition_variance part_variances;
267   var split[4];
268 } v4x4;
269
270 typedef struct {
271   partition_variance part_variances;
272   v4x4 split[4];
273 } v8x8;
274
275 typedef struct {
276   partition_variance part_variances;
277   v8x8 split[4];
278 } v16x16;
279
280 typedef struct {
281   partition_variance part_variances;
282   v16x16 split[4];
283 } v32x32;
284
285 typedef struct {
286   partition_variance part_variances;
287   v32x32 split[4];
288 } v64x64;
289
290 typedef struct {
291   partition_variance *part_variances;
292   var *split[4];
293 } variance_node;
294
295 typedef enum {
296   V16X16,
297   V32X32,
298   V64X64,
299 } TREE_LEVEL;
300
301 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
302   int i;
303   node->part_variances = NULL;
304   switch (bsize) {
305     case BLOCK_64X64: {
306       v64x64 *vt = (v64x64 *) data;
307       node->part_variances = &vt->part_variances;
308       for (i = 0; i < 4; i++)
309         node->split[i] = &vt->split[i].part_variances.none;
310       break;
311     }
312     case BLOCK_32X32: {
313       v32x32 *vt = (v32x32 *) data;
314       node->part_variances = &vt->part_variances;
315       for (i = 0; i < 4; i++)
316         node->split[i] = &vt->split[i].part_variances.none;
317       break;
318     }
319     case BLOCK_16X16: {
320       v16x16 *vt = (v16x16 *) data;
321       node->part_variances = &vt->part_variances;
322       for (i = 0; i < 4; i++)
323         node->split[i] = &vt->split[i].part_variances.none;
324       break;
325     }
326     case BLOCK_8X8: {
327       v8x8 *vt = (v8x8 *) data;
328       node->part_variances = &vt->part_variances;
329       for (i = 0; i < 4; i++)
330         node->split[i] = &vt->split[i].part_variances.none;
331       break;
332     }
333     case BLOCK_4X4: {
334       v4x4 *vt = (v4x4 *) data;
335       node->part_variances = &vt->part_variances;
336       for (i = 0; i < 4; i++)
337         node->split[i] = &vt->split[i];
338       break;
339     }
340     default: {
341       assert(0);
342       break;
343     }
344   }
345 }
346
347 // Set variance values given sum square error, sum error, count.
348 static void fill_variance(int64_t s2, int64_t s, int c, var *v) {
349   v->sum_square_error = s2;
350   v->sum_error = s;
351   v->log2_count = c;
352 }
353
354 static void get_variance(var *v) {
355   v->variance = (int)(256 * (v->sum_square_error -
356       ((v->sum_error * v->sum_error) >> v->log2_count)) >> v->log2_count);
357 }
358
359 static void sum_2_variances(const var *a, const var *b, var *r) {
360   assert(a->log2_count == b->log2_count);
361   fill_variance(a->sum_square_error + b->sum_square_error,
362                 a->sum_error + b->sum_error, a->log2_count + 1, r);
363 }
364
365 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
366   variance_node node;
367   memset(&node, 0, sizeof(node));
368   tree_to_node(data, bsize, &node);
369   sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
370   sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
371   sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
372   sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
373   sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
374                   &node.part_variances->none);
375 }
376
377 static int set_vt_partitioning(VP10_COMP *cpi,
378                                MACROBLOCK *const x,
379                                MACROBLOCKD *const xd,
380                                void *data,
381                                BLOCK_SIZE bsize,
382                                int mi_row,
383                                int mi_col,
384                                int64_t threshold,
385                                BLOCK_SIZE bsize_min,
386                                int force_split) {
387   VP10_COMMON * const cm = &cpi->common;
388   variance_node vt;
389   const int block_width = num_8x8_blocks_wide_lookup[bsize];
390   const int block_height = num_8x8_blocks_high_lookup[bsize];
391   const int low_res = (cm->width <= 352 && cm->height <= 288);
392
393   assert(block_height == block_width);
394   tree_to_node(data, bsize, &vt);
395
396   if (force_split == 1)
397     return 0;
398
399   // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
400   // variance is below threshold, otherwise split will be selected.
401   // No check for vert/horiz split as too few samples for variance.
402   if (bsize == bsize_min) {
403     // Variance already computed to set the force_split.
404     if (low_res || cm->frame_type == KEY_FRAME)
405       get_variance(&vt.part_variances->none);
406     if (mi_col + block_width / 2 < cm->mi_cols &&
407         mi_row + block_height / 2 < cm->mi_rows &&
408         vt.part_variances->none.variance < threshold) {
409       set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
410       return 1;
411     }
412     return 0;
413   } else if (bsize > bsize_min) {
414     // Variance already computed to set the force_split.
415     if (low_res || cm->frame_type == KEY_FRAME)
416       get_variance(&vt.part_variances->none);
417     // For key frame: take split for bsize above 32X32 or very high variance.
418     if (cm->frame_type == KEY_FRAME &&
419         (bsize > BLOCK_32X32 ||
420         vt.part_variances->none.variance > (threshold << 4))) {
421       return 0;
422     }
423     // If variance is low, take the bsize (no split).
424     if (mi_col + block_width / 2 < cm->mi_cols &&
425         mi_row + block_height / 2 < cm->mi_rows &&
426         vt.part_variances->none.variance < threshold) {
427       set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
428       return 1;
429     }
430
431     // Check vertical split.
432     if (mi_row + block_height / 2 < cm->mi_rows) {
433       BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
434       get_variance(&vt.part_variances->vert[0]);
435       get_variance(&vt.part_variances->vert[1]);
436       if (vt.part_variances->vert[0].variance < threshold &&
437           vt.part_variances->vert[1].variance < threshold &&
438           get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
439         set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
440         set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
441         return 1;
442       }
443     }
444     // Check horizontal split.
445     if (mi_col + block_width / 2 < cm->mi_cols) {
446       BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
447       get_variance(&vt.part_variances->horz[0]);
448       get_variance(&vt.part_variances->horz[1]);
449       if (vt.part_variances->horz[0].variance < threshold &&
450           vt.part_variances->horz[1].variance < threshold &&
451           get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
452         set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
453         set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
454         return 1;
455       }
456     }
457
458     return 0;
459   }
460   return 0;
461 }
462
463 // Set the variance split thresholds for following the block sizes:
464 // 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
465 // 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
466 // currently only used on key frame.
467 static void set_vbp_thresholds(VP10_COMP *cpi, int64_t thresholds[], int q) {
468   VP10_COMMON *const cm = &cpi->common;
469   const int is_key_frame = (cm->frame_type == KEY_FRAME);
470   const int threshold_multiplier = is_key_frame ? 20 : 1;
471   const int64_t threshold_base = (int64_t)(threshold_multiplier *
472       cpi->y_dequant[q][1]);
473   if (is_key_frame) {
474     thresholds[0] = threshold_base;
475     thresholds[1] = threshold_base >> 2;
476     thresholds[2] = threshold_base >> 2;
477     thresholds[3] = threshold_base << 2;
478   } else {
479     thresholds[1] = threshold_base;
480     if (cm->width <= 352 && cm->height <= 288) {
481       thresholds[0] = threshold_base >> 2;
482       thresholds[2] = threshold_base << 3;
483     } else {
484       thresholds[0] = threshold_base;
485       thresholds[1] = (5 * threshold_base) >> 2;
486       if (cm->width >= 1920 && cm->height >= 1080)
487         thresholds[1] = (7 * threshold_base) >> 2;
488       thresholds[2] = threshold_base << cpi->oxcf.speed;
489     }
490   }
491 }
492
493 void vp10_set_variance_partition_thresholds(VP10_COMP *cpi, int q) {
494   VP10_COMMON *const cm = &cpi->common;
495   SPEED_FEATURES *const sf = &cpi->sf;
496   const int is_key_frame = (cm->frame_type == KEY_FRAME);
497   if (sf->partition_search_type != VAR_BASED_PARTITION &&
498       sf->partition_search_type != REFERENCE_PARTITION) {
499     return;
500   } else {
501     set_vbp_thresholds(cpi, cpi->vbp_thresholds, q);
502     // The thresholds below are not changed locally.
503     if (is_key_frame) {
504       cpi->vbp_threshold_sad = 0;
505       cpi->vbp_bsize_min = BLOCK_8X8;
506     } else {
507       if (cm->width <= 352 && cm->height <= 288)
508         cpi->vbp_threshold_sad = 100;
509       else
510         cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000 ?
511             (cpi->y_dequant[q][1] << 1) : 1000;
512       cpi->vbp_bsize_min = BLOCK_16X16;
513     }
514     cpi->vbp_threshold_minmax = 15 + (q >> 3);
515   }
516 }
517
518 // Compute the minmax over the 8x8 subblocks.
519 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
520                               int dp, int x16_idx, int y16_idx,
521 #if CONFIG_VP9_HIGHBITDEPTH
522                               int highbd_flag,
523 #endif
524                               int pixels_wide,
525                               int pixels_high) {
526   int k;
527   int minmax_max = 0;
528   int minmax_min = 255;
529   // Loop over the 4 8x8 subblocks.
530   for (k = 0; k < 4; k++) {
531     int x8_idx = x16_idx + ((k & 1) << 3);
532     int y8_idx = y16_idx + ((k >> 1) << 3);
533     int min = 0;
534     int max = 0;
535     if (x8_idx < pixels_wide && y8_idx < pixels_high) {
536 #if CONFIG_VP9_HIGHBITDEPTH
537       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
538         vp10_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
539                               d + y8_idx * dp + x8_idx, dp,
540                               &min, &max);
541       } else {
542         vp10_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
543                        d + y8_idx * dp + x8_idx, dp,
544                        &min, &max);
545       }
546 #else
547       vp10_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
548                      d + y8_idx * dp + x8_idx, dp,
549                      &min, &max);
550 #endif
551       if ((max - min) > minmax_max)
552         minmax_max = (max - min);
553       if ((max - min) < minmax_min)
554         minmax_min = (max - min);
555     }
556   }
557   return (minmax_max - minmax_min);
558 }
559
560 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
561                                  int dp, int x8_idx, int y8_idx, v8x8 *vst,
562 #if CONFIG_VP9_HIGHBITDEPTH
563                                  int highbd_flag,
564 #endif
565                                  int pixels_wide,
566                                  int pixels_high,
567                                  int is_key_frame) {
568   int k;
569   for (k = 0; k < 4; k++) {
570     int x4_idx = x8_idx + ((k & 1) << 2);
571     int y4_idx = y8_idx + ((k >> 1) << 2);
572     unsigned int sse = 0;
573     int sum = 0;
574     if (x4_idx < pixels_wide && y4_idx < pixels_high) {
575       int s_avg;
576       int d_avg = 128;
577 #if CONFIG_VP9_HIGHBITDEPTH
578       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
579         s_avg = vp10_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
580         if (!is_key_frame)
581           d_avg = vp10_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
582       } else {
583         s_avg = vp10_avg_4x4(s + y4_idx * sp + x4_idx, sp);
584         if (!is_key_frame)
585           d_avg = vp10_avg_4x4(d + y4_idx * dp + x4_idx, dp);
586       }
587 #else
588       s_avg = vp10_avg_4x4(s + y4_idx * sp + x4_idx, sp);
589       if (!is_key_frame)
590         d_avg = vp10_avg_4x4(d + y4_idx * dp + x4_idx, dp);
591 #endif
592       sum = s_avg - d_avg;
593       sse = sum * sum;
594     }
595     fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
596   }
597 }
598
599 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
600                                  int dp, int x16_idx, int y16_idx, v16x16 *vst,
601 #if CONFIG_VP9_HIGHBITDEPTH
602                                  int highbd_flag,
603 #endif
604                                  int pixels_wide,
605                                  int pixels_high,
606                                  int is_key_frame) {
607   int k;
608   for (k = 0; k < 4; k++) {
609     int x8_idx = x16_idx + ((k & 1) << 3);
610     int y8_idx = y16_idx + ((k >> 1) << 3);
611     unsigned int sse = 0;
612     int sum = 0;
613     if (x8_idx < pixels_wide && y8_idx < pixels_high) {
614       int s_avg;
615       int d_avg = 128;
616 #if CONFIG_VP9_HIGHBITDEPTH
617       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
618         s_avg = vp10_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
619         if (!is_key_frame)
620           d_avg = vp10_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
621       } else {
622         s_avg = vp10_avg_8x8(s + y8_idx * sp + x8_idx, sp);
623         if (!is_key_frame)
624           d_avg = vp10_avg_8x8(d + y8_idx * dp + x8_idx, dp);
625       }
626 #else
627       s_avg = vp10_avg_8x8(s + y8_idx * sp + x8_idx, sp);
628       if (!is_key_frame)
629         d_avg = vp10_avg_8x8(d + y8_idx * dp + x8_idx, dp);
630 #endif
631       sum = s_avg - d_avg;
632       sse = sum * sum;
633     }
634     fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
635   }
636 }
637
638 // This function chooses partitioning based on the variance between source and
639 // reconstructed last, where variance is computed for down-sampled inputs.
640 static int choose_partitioning(VP10_COMP *cpi,
641                                 const TileInfo *const tile,
642                                 MACROBLOCK *x,
643                                 int mi_row, int mi_col) {
644   VP10_COMMON * const cm = &cpi->common;
645   MACROBLOCKD *xd = &x->e_mbd;
646   int i, j, k, m;
647   v64x64 vt;
648   v16x16 vt2[16];
649   int force_split[21];
650   uint8_t *s;
651   const uint8_t *d;
652   int sp;
653   int dp;
654   int pixels_wide = 64, pixels_high = 64;
655   int64_t thresholds[4] = {cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
656       cpi->vbp_thresholds[2], cpi->vbp_thresholds[3]};
657
658   // Always use 4x4 partition for key frame.
659   const int is_key_frame = (cm->frame_type == KEY_FRAME);
660   const int use_4x4_partition = is_key_frame;
661   const int low_res = (cm->width <= 352 && cm->height <= 288);
662   int variance4x4downsample[16];
663
664   int segment_id = CR_SEGMENT_ID_BASE;
665   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled) {
666     const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map :
667                                                     cm->last_frame_seg_map;
668     segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
669
670     if (cyclic_refresh_segment_id_boosted(segment_id)) {
671       int q = vp10_get_qindex(&cm->seg, segment_id, cm->base_qindex);
672       set_vbp_thresholds(cpi, thresholds, q);
673     }
674   }
675
676   set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
677
678   if (xd->mb_to_right_edge < 0)
679     pixels_wide += (xd->mb_to_right_edge >> 3);
680   if (xd->mb_to_bottom_edge < 0)
681     pixels_high += (xd->mb_to_bottom_edge >> 3);
682
683   s = x->plane[0].src.buf;
684   sp = x->plane[0].src.stride;
685
686   if (!is_key_frame) {
687     MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
688     unsigned int uv_sad;
689     const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
690
691     const YV12_BUFFER_CONFIG *yv12_g = NULL;
692     unsigned int y_sad, y_sad_g;
693     const BLOCK_SIZE bsize = BLOCK_32X32
694         + (mi_col + 4 < cm->mi_cols) * 2 + (mi_row + 4 < cm->mi_rows);
695
696     assert(yv12 != NULL);
697     yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
698
699     if (yv12_g && yv12_g != yv12) {
700       vp10_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
701                            &cm->frame_refs[GOLDEN_FRAME - 1].sf);
702       y_sad_g = cpi->fn_ptr[bsize].sdf(x->plane[0].src.buf,
703                                        x->plane[0].src.stride,
704                                        xd->plane[0].pre[0].buf,
705                                        xd->plane[0].pre[0].stride);
706     } else {
707       y_sad_g = UINT_MAX;
708     }
709
710     vp10_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
711                          &cm->frame_refs[LAST_FRAME - 1].sf);
712     mbmi->ref_frame[0] = LAST_FRAME;
713     mbmi->ref_frame[1] = NONE;
714     mbmi->sb_type = BLOCK_64X64;
715     mbmi->mv[0].as_int = 0;
716     mbmi->interp_filter = BILINEAR;
717
718     y_sad = vp10_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col);
719     if (y_sad_g < y_sad) {
720       vp10_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
721                            &cm->frame_refs[GOLDEN_FRAME - 1].sf);
722       mbmi->ref_frame[0] = GOLDEN_FRAME;
723       mbmi->mv[0].as_int = 0;
724       y_sad = y_sad_g;
725     } else {
726       x->pred_mv[LAST_FRAME] = mbmi->mv[0].as_mv;
727     }
728
729     vp10_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
730
731     for (i = 1; i <= 2; ++i) {
732       struct macroblock_plane  *p = &x->plane[i];
733       struct macroblockd_plane *pd = &xd->plane[i];
734       const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
735
736       if (bs == BLOCK_INVALID)
737         uv_sad = UINT_MAX;
738       else
739         uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride,
740                                      pd->dst.buf, pd->dst.stride);
741
742       x->color_sensitivity[i - 1] = uv_sad > (y_sad >> 2);
743     }
744
745     d = xd->plane[0].dst.buf;
746     dp = xd->plane[0].dst.stride;
747
748     // If the y_sad is very small, take 64x64 as partition and exit.
749     // Don't check on boosted segment for now, as 64x64 is suppressed there.
750     if (segment_id == CR_SEGMENT_ID_BASE &&
751         y_sad < cpi->vbp_threshold_sad) {
752       const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
753       const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
754       if (mi_col + block_width / 2 < cm->mi_cols &&
755           mi_row + block_height / 2 < cm->mi_rows) {
756         set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
757         return 0;
758       }
759     }
760   } else {
761     d = VP9_VAR_OFFS;
762     dp = 0;
763 #if CONFIG_VP9_HIGHBITDEPTH
764     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
765       switch (xd->bd) {
766         case 10:
767           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10);
768           break;
769         case 12:
770           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12);
771           break;
772         case 8:
773         default:
774           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8);
775           break;
776       }
777     }
778 #endif  // CONFIG_VP9_HIGHBITDEPTH
779   }
780
781   // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
782   // 5-20 for the 16x16 blocks.
783   force_split[0] = 0;
784   // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
785   // for splits.
786   for (i = 0; i < 4; i++) {
787     const int x32_idx = ((i & 1) << 5);
788     const int y32_idx = ((i >> 1) << 5);
789     const int i2 = i << 2;
790     force_split[i + 1] = 0;
791     for (j = 0; j < 4; j++) {
792       const int x16_idx = x32_idx + ((j & 1) << 4);
793       const int y16_idx = y32_idx + ((j >> 1) << 4);
794       const int split_index = 5 + i2 + j;
795       v16x16 *vst = &vt.split[i].split[j];
796       force_split[split_index] = 0;
797       variance4x4downsample[i2 + j] = 0;
798       if (!is_key_frame) {
799         fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
800 #if CONFIG_VP9_HIGHBITDEPTH
801                             xd->cur_buf->flags,
802 #endif
803                             pixels_wide,
804                             pixels_high,
805                             is_key_frame);
806         fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
807         get_variance(&vt.split[i].split[j].part_variances.none);
808         if (vt.split[i].split[j].part_variances.none.variance >
809             thresholds[2]) {
810           // 16X16 variance is above threshold for split, so force split to 8x8
811           // for this 16x16 block (this also forces splits for upper levels).
812           force_split[split_index] = 1;
813           force_split[i + 1] = 1;
814           force_split[0] = 1;
815         } else if (vt.split[i].split[j].part_variances.none.variance >
816                    thresholds[1] &&
817                    !cyclic_refresh_segment_id_boosted(segment_id)) {
818           // We have some nominal amount of 16x16 variance (based on average),
819           // compute the minmax over the 8x8 sub-blocks, and if above threshold,
820           // force split to 8x8 block for this 16x16 block.
821           int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
822 #if CONFIG_VP9_HIGHBITDEPTH
823                                           xd->cur_buf->flags,
824 #endif
825                                           pixels_wide, pixels_high);
826           if (minmax > cpi->vbp_threshold_minmax) {
827             force_split[split_index] = 1;
828             force_split[i + 1] = 1;
829             force_split[0] = 1;
830           }
831         }
832       }
833       if (is_key_frame || (low_res &&
834           vt.split[i].split[j].part_variances.none.variance >
835           (thresholds[1] << 1))) {
836         force_split[split_index] = 0;
837         // Go down to 4x4 down-sampling for variance.
838         variance4x4downsample[i2 + j] = 1;
839         for (k = 0; k < 4; k++) {
840           int x8_idx = x16_idx + ((k & 1) << 3);
841           int y8_idx = y16_idx + ((k >> 1) << 3);
842           v8x8 *vst2 = is_key_frame ? &vst->split[k] :
843               &vt2[i2 + j].split[k];
844           fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
845 #if CONFIG_VP9_HIGHBITDEPTH
846                                xd->cur_buf->flags,
847 #endif
848                                pixels_wide,
849                                pixels_high,
850                                is_key_frame);
851         }
852       }
853     }
854   }
855
856   // Fill the rest of the variance tree by summing split partition values.
857   for (i = 0; i < 4; i++) {
858     const int i2 = i << 2;
859     for (j = 0; j < 4; j++) {
860       if (variance4x4downsample[i2 + j] == 1) {
861         v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] :
862             &vt.split[i].split[j];
863         for (m = 0; m < 4; m++)
864           fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
865         fill_variance_tree(vtemp, BLOCK_16X16);
866       }
867     }
868     fill_variance_tree(&vt.split[i], BLOCK_32X32);
869     // If variance of this 32x32 block is above the threshold, force the block
870     // to split. This also forces a split on the upper (64x64) level.
871     if (!force_split[i + 1]) {
872       get_variance(&vt.split[i].part_variances.none);
873       if (vt.split[i].part_variances.none.variance > thresholds[1]) {
874         force_split[i + 1] = 1;
875         force_split[0] = 1;
876       }
877     }
878   }
879   if (!force_split[0]) {
880     fill_variance_tree(&vt, BLOCK_64X64);
881     get_variance(&vt.part_variances.none);
882   }
883
884   // Now go through the entire structure, splitting every block size until
885   // we get to one that's got a variance lower than our threshold.
886   if ( mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
887       !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
888                            thresholds[0], BLOCK_16X16, force_split[0])) {
889     for (i = 0; i < 4; ++i) {
890       const int x32_idx = ((i & 1) << 2);
891       const int y32_idx = ((i >> 1) << 2);
892       const int i2 = i << 2;
893       if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
894                                (mi_row + y32_idx), (mi_col + x32_idx),
895                                thresholds[1], BLOCK_16X16,
896                                force_split[i + 1])) {
897         for (j = 0; j < 4; ++j) {
898           const int x16_idx = ((j & 1) << 1);
899           const int y16_idx = ((j >> 1) << 1);
900           // For inter frames: if variance4x4downsample[] == 1 for this 16x16
901           // block, then the variance is based on 4x4 down-sampling, so use vt2
902           // in set_vt_partioning(), otherwise use vt.
903           v16x16 *vtemp = (!is_key_frame &&
904                            variance4x4downsample[i2 + j] == 1) ?
905                            &vt2[i2 + j] : &vt.split[i].split[j];
906           if (!set_vt_partitioning(cpi, x, xd, vtemp, BLOCK_16X16,
907                                    mi_row + y32_idx + y16_idx,
908                                    mi_col + x32_idx + x16_idx,
909                                    thresholds[2],
910                                    cpi->vbp_bsize_min,
911                                    force_split[5 + i2  + j])) {
912             for (k = 0; k < 4; ++k) {
913               const int x8_idx = (k & 1);
914               const int y8_idx = (k >> 1);
915               if (use_4x4_partition) {
916                 if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
917                                          BLOCK_8X8,
918                                          mi_row + y32_idx + y16_idx + y8_idx,
919                                          mi_col + x32_idx + x16_idx + x8_idx,
920                                          thresholds[3], BLOCK_8X8, 0)) {
921                   set_block_size(cpi, x, xd,
922                                  (mi_row + y32_idx + y16_idx + y8_idx),
923                                  (mi_col + x32_idx + x16_idx + x8_idx),
924                                  BLOCK_4X4);
925                 }
926               } else {
927                 set_block_size(cpi, x, xd,
928                                (mi_row + y32_idx + y16_idx + y8_idx),
929                                (mi_col + x32_idx + x16_idx + x8_idx),
930                                BLOCK_8X8);
931               }
932             }
933           }
934         }
935       }
936     }
937   }
938   return 0;
939 }
940
941 static void update_state(VP10_COMP *cpi, ThreadData *td,
942                          PICK_MODE_CONTEXT *ctx,
943                          int mi_row, int mi_col, BLOCK_SIZE bsize,
944                          int output_enabled) {
945   int i, x_idx, y;
946   VP10_COMMON *const cm = &cpi->common;
947   RD_COUNTS *const rdc = &td->rd_counts;
948   MACROBLOCK *const x = &td->mb;
949   MACROBLOCKD *const xd = &x->e_mbd;
950   struct macroblock_plane *const p = x->plane;
951   struct macroblockd_plane *const pd = xd->plane;
952   MODE_INFO *mi = &ctx->mic;
953   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
954   MODE_INFO *mi_addr = xd->mi[0];
955   const struct segmentation *const seg = &cm->seg;
956   const int bw = num_8x8_blocks_wide_lookup[mi->mbmi.sb_type];
957   const int bh = num_8x8_blocks_high_lookup[mi->mbmi.sb_type];
958   const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
959   const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
960   MV_REF *const frame_mvs =
961       cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
962   int w, h;
963
964   const int mis = cm->mi_stride;
965   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
966   const int mi_height = num_8x8_blocks_high_lookup[bsize];
967   int max_plane;
968
969   assert(mi->mbmi.sb_type == bsize);
970
971   *mi_addr = *mi;
972   *x->mbmi_ext = ctx->mbmi_ext;
973
974   // If segmentation in use
975   if (seg->enabled) {
976     // For in frame complexity AQ copy the segment id from the segment map.
977     if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
978       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
979                                                  : cm->last_frame_seg_map;
980       mi_addr->mbmi.segment_id =
981         get_segment_id(cm, map, bsize, mi_row, mi_col);
982     }
983     // Else for cyclic refresh mode update the segment map, set the segment id
984     // and then update the quantizer.
985     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
986       vp10_cyclic_refresh_update_segment(cpi, &xd->mi[0]->mbmi, mi_row,
987                                         mi_col, bsize, ctx->rate, ctx->dist,
988                                         x->skip);
989     }
990   }
991
992   max_plane = is_inter_block(mbmi) ? MAX_MB_PLANE : 1;
993   for (i = 0; i < max_plane; ++i) {
994     p[i].coeff = ctx->coeff_pbuf[i][1];
995     p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
996     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
997     p[i].eobs = ctx->eobs_pbuf[i][1];
998   }
999
1000   for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1001     p[i].coeff = ctx->coeff_pbuf[i][2];
1002     p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1003     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1004     p[i].eobs = ctx->eobs_pbuf[i][2];
1005   }
1006
1007   // Restore the coding context of the MB to that that was in place
1008   // when the mode was picked for it
1009   for (y = 0; y < mi_height; y++)
1010     for (x_idx = 0; x_idx < mi_width; x_idx++)
1011       if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx
1012         && (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1013         xd->mi[x_idx + y * mis] = mi_addr;
1014       }
1015
1016   if (cpi->oxcf.aq_mode)
1017     vp10_init_plane_quantizers(cpi, x);
1018
1019   if (is_inter_block(mbmi) && mbmi->sb_type < BLOCK_8X8) {
1020     mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1021     mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1022   }
1023
1024   x->skip = ctx->skip;
1025   memcpy(x->zcoeff_blk[mbmi->tx_size], ctx->zcoeff_blk,
1026          sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1027
1028   if (!output_enabled)
1029     return;
1030
1031 #if CONFIG_INTERNAL_STATS
1032   if (frame_is_intra_only(cm)) {
1033     static const int kf_mode_index[] = {
1034       THR_DC        /*DC_PRED*/,
1035       THR_V_PRED    /*V_PRED*/,
1036       THR_H_PRED    /*H_PRED*/,
1037       THR_D45_PRED  /*D45_PRED*/,
1038       THR_D135_PRED /*D135_PRED*/,
1039       THR_D117_PRED /*D117_PRED*/,
1040       THR_D153_PRED /*D153_PRED*/,
1041       THR_D207_PRED /*D207_PRED*/,
1042       THR_D63_PRED  /*D63_PRED*/,
1043       THR_TM        /*TM_PRED*/,
1044     };
1045     ++cpi->mode_chosen_counts[kf_mode_index[mbmi->mode]];
1046   } else {
1047     // Note how often each mode chosen as best
1048     ++cpi->mode_chosen_counts[ctx->best_mode_index];
1049   }
1050 #endif
1051   if (!frame_is_intra_only(cm)) {
1052     if (is_inter_block(mbmi)) {
1053       vp10_update_mv_count(td);
1054
1055       if (cm->interp_filter == SWITCHABLE) {
1056         const int ctx = vp10_get_pred_context_switchable_interp(xd);
1057         ++td->counts->switchable_interp[ctx][mbmi->interp_filter];
1058       }
1059     }
1060
1061     rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1062     rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1063     rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1064
1065     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1066       rdc->filter_diff[i] += ctx->best_filter_diff[i];
1067   }
1068
1069   for (h = 0; h < y_mis; ++h) {
1070     MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1071     for (w = 0; w < x_mis; ++w) {
1072       MV_REF *const mv = frame_mv + w;
1073       mv->ref_frame[0] = mi->mbmi.ref_frame[0];
1074       mv->ref_frame[1] = mi->mbmi.ref_frame[1];
1075       mv->mv[0].as_int = mi->mbmi.mv[0].as_int;
1076       mv->mv[1].as_int = mi->mbmi.mv[1].as_int;
1077     }
1078   }
1079 }
1080
1081 void vp10_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1082                           int mi_row, int mi_col) {
1083   uint8_t *const buffers[3] = {src->y_buffer, src->u_buffer, src->v_buffer };
1084   const int strides[3] = {src->y_stride, src->uv_stride, src->uv_stride };
1085   int i;
1086
1087   // Set current frame pointer.
1088   x->e_mbd.cur_buf = src;
1089
1090   for (i = 0; i < MAX_MB_PLANE; i++)
1091     setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1092                      NULL, x->e_mbd.plane[i].subsampling_x,
1093                      x->e_mbd.plane[i].subsampling_y);
1094 }
1095
1096 static int set_segment_rdmult(VP10_COMP *const cpi,
1097                                MACROBLOCK *const x,
1098                                int8_t segment_id) {
1099   int segment_qindex;
1100   VP10_COMMON *const cm = &cpi->common;
1101   vp10_init_plane_quantizers(cpi, x);
1102   vpx_clear_system_state();
1103   segment_qindex = vp10_get_qindex(&cm->seg, segment_id,
1104                                   cm->base_qindex);
1105   return vp10_compute_rd_mult(cpi, segment_qindex + cm->y_dc_delta_q);
1106 }
1107
1108 static void rd_pick_sb_modes(VP10_COMP *cpi,
1109                              TileDataEnc *tile_data,
1110                              MACROBLOCK *const x,
1111                              int mi_row, int mi_col, RD_COST *rd_cost,
1112                              BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
1113                              int64_t best_rd) {
1114   VP10_COMMON *const cm = &cpi->common;
1115   TileInfo *const tile_info = &tile_data->tile_info;
1116   MACROBLOCKD *const xd = &x->e_mbd;
1117   MB_MODE_INFO *mbmi;
1118   struct macroblock_plane *const p = x->plane;
1119   struct macroblockd_plane *const pd = xd->plane;
1120   const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1121   int i, orig_rdmult;
1122
1123   vpx_clear_system_state();
1124
1125   // Use the lower precision, but faster, 32x32 fdct for mode selection.
1126   x->use_lp32x32fdct = 1;
1127
1128   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1129   mbmi = &xd->mi[0]->mbmi;
1130   mbmi->sb_type = bsize;
1131
1132   for (i = 0; i < MAX_MB_PLANE; ++i) {
1133     p[i].coeff = ctx->coeff_pbuf[i][0];
1134     p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1135     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1136     p[i].eobs = ctx->eobs_pbuf[i][0];
1137   }
1138   ctx->is_coded = 0;
1139   ctx->skippable = 0;
1140   ctx->pred_pixel_ready = 0;
1141   x->skip_recode = 0;
1142
1143   // Set to zero to make sure we do not use the previous encoded frame stats
1144   mbmi->skip = 0;
1145
1146 #if CONFIG_VP9_HIGHBITDEPTH
1147   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1148     x->source_variance =
1149         vp10_high_get_sby_perpixel_variance(cpi, &x->plane[0].src,
1150                                            bsize, xd->bd);
1151   } else {
1152     x->source_variance =
1153       vp10_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1154   }
1155 #else
1156   x->source_variance =
1157     vp10_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1158 #endif  // CONFIG_VP9_HIGHBITDEPTH
1159
1160   // Save rdmult before it might be changed, so it can be restored later.
1161   orig_rdmult = x->rdmult;
1162
1163   if (aq_mode == VARIANCE_AQ) {
1164     const int energy = bsize <= BLOCK_16X16 ? x->mb_energy
1165                                             : vp10_block_energy(cpi, x, bsize);
1166     if (cm->frame_type == KEY_FRAME ||
1167         cpi->refresh_alt_ref_frame ||
1168         (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
1169       mbmi->segment_id = vp10_vaq_segment_id(energy);
1170     } else {
1171       const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map
1172                                                     : cm->last_frame_seg_map;
1173       mbmi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1174     }
1175     x->rdmult = set_segment_rdmult(cpi, x, mbmi->segment_id);
1176   } else if (aq_mode == COMPLEXITY_AQ) {
1177     x->rdmult = set_segment_rdmult(cpi, x, mbmi->segment_id);
1178   } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1179     const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map
1180                                                   : cm->last_frame_seg_map;
1181     // If segment is boosted, use rdmult for that segment.
1182     if (cyclic_refresh_segment_id_boosted(
1183             get_segment_id(cm, map, bsize, mi_row, mi_col)))
1184       x->rdmult = vp10_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1185   }
1186
1187   // Find best coding mode & reconstruct the MB so it is available
1188   // as a predictor for MBs that follow in the SB
1189   if (frame_is_intra_only(cm)) {
1190     vp10_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
1191   } else {
1192     if (bsize >= BLOCK_8X8) {
1193       if (segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP))
1194         vp10_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
1195                                            ctx, best_rd);
1196       else
1197         vp10_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col,
1198                                   rd_cost, bsize, ctx, best_rd);
1199     } else {
1200       vp10_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col,
1201                                     rd_cost, bsize, ctx, best_rd);
1202     }
1203   }
1204
1205
1206   // Examine the resulting rate and for AQ mode 2 make a segment choice.
1207   if ((rd_cost->rate != INT_MAX) &&
1208       (aq_mode == COMPLEXITY_AQ) && (bsize >= BLOCK_16X16) &&
1209       (cm->frame_type == KEY_FRAME ||
1210        cpi->refresh_alt_ref_frame ||
1211        (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
1212     vp10_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
1213   }
1214
1215   x->rdmult = orig_rdmult;
1216
1217   // TODO(jingning) The rate-distortion optimization flow needs to be
1218   // refactored to provide proper exit/return handle.
1219   if (rd_cost->rate == INT_MAX)
1220     rd_cost->rdcost = INT64_MAX;
1221
1222   ctx->rate = rd_cost->rate;
1223   ctx->dist = rd_cost->dist;
1224 }
1225
1226 static void update_stats(VP10_COMMON *cm, ThreadData *td) {
1227   const MACROBLOCK *x = &td->mb;
1228   const MACROBLOCKD *const xd = &x->e_mbd;
1229   const MODE_INFO *const mi = xd->mi[0];
1230   const MB_MODE_INFO *const mbmi = &mi->mbmi;
1231   const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
1232   const BLOCK_SIZE bsize = mbmi->sb_type;
1233
1234   if (!frame_is_intra_only(cm)) {
1235     FRAME_COUNTS *const counts = td->counts;
1236     const int inter_block = is_inter_block(mbmi);
1237     const int seg_ref_active = segfeature_active(&cm->seg, mbmi->segment_id,
1238                                                  SEG_LVL_REF_FRAME);
1239     if (!seg_ref_active) {
1240       counts->intra_inter[vp10_get_intra_inter_context(xd)][inter_block]++;
1241       // If the segment reference feature is enabled we have only a single
1242       // reference frame allowed for the segment so exclude it from
1243       // the reference frame counts used to work out probabilities.
1244       if (inter_block) {
1245         const MV_REFERENCE_FRAME ref0 = mbmi->ref_frame[0];
1246         if (cm->reference_mode == REFERENCE_MODE_SELECT)
1247           counts->comp_inter[vp10_get_reference_mode_context(cm, xd)]
1248                             [has_second_ref(mbmi)]++;
1249
1250         if (has_second_ref(mbmi)) {
1251           counts->comp_ref[vp10_get_pred_context_comp_ref_p(cm, xd)]
1252                           [ref0 == GOLDEN_FRAME]++;
1253         } else {
1254           counts->single_ref[vp10_get_pred_context_single_ref_p1(xd)][0]
1255                             [ref0 != LAST_FRAME]++;
1256           if (ref0 != LAST_FRAME)
1257             counts->single_ref[vp10_get_pred_context_single_ref_p2(xd)][1]
1258                               [ref0 != GOLDEN_FRAME]++;
1259         }
1260       }
1261     }
1262     if (inter_block &&
1263         !segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
1264       const int mode_ctx = mbmi_ext->mode_context[mbmi->ref_frame[0]];
1265       if (bsize >= BLOCK_8X8) {
1266         const PREDICTION_MODE mode = mbmi->mode;
1267         ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
1268       } else {
1269         const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
1270         const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
1271         int idx, idy;
1272         for (idy = 0; idy < 2; idy += num_4x4_h) {
1273           for (idx = 0; idx < 2; idx += num_4x4_w) {
1274             const int j = idy * 2 + idx;
1275             const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
1276             ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
1277           }
1278         }
1279       }
1280     }
1281   }
1282 }
1283
1284 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
1285                             ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
1286                             ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
1287                             PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
1288                             BLOCK_SIZE bsize) {
1289   MACROBLOCKD *const xd = &x->e_mbd;
1290   int p;
1291   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1292   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1293   int mi_width = num_8x8_blocks_wide_lookup[bsize];
1294   int mi_height = num_8x8_blocks_high_lookup[bsize];
1295   for (p = 0; p < MAX_MB_PLANE; p++) {
1296     memcpy(
1297         xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
1298         a + num_4x4_blocks_wide * p,
1299         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
1300         xd->plane[p].subsampling_x);
1301     memcpy(
1302         xd->left_context[p]
1303             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
1304         l + num_4x4_blocks_high * p,
1305         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
1306         xd->plane[p].subsampling_y);
1307   }
1308   memcpy(xd->above_seg_context + mi_col, sa,
1309          sizeof(*xd->above_seg_context) * mi_width);
1310   memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
1311          sizeof(xd->left_seg_context[0]) * mi_height);
1312 }
1313
1314 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
1315                          ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
1316                          ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
1317                          PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
1318                          BLOCK_SIZE bsize) {
1319   const MACROBLOCKD *const xd = &x->e_mbd;
1320   int p;
1321   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1322   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1323   int mi_width = num_8x8_blocks_wide_lookup[bsize];
1324   int mi_height = num_8x8_blocks_high_lookup[bsize];
1325
1326   // buffer the above/left context information of the block in search.
1327   for (p = 0; p < MAX_MB_PLANE; ++p) {
1328     memcpy(
1329         a + num_4x4_blocks_wide * p,
1330         xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
1331         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
1332         xd->plane[p].subsampling_x);
1333     memcpy(
1334         l + num_4x4_blocks_high * p,
1335         xd->left_context[p]
1336             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
1337         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
1338         xd->plane[p].subsampling_y);
1339   }
1340   memcpy(sa, xd->above_seg_context + mi_col,
1341          sizeof(*xd->above_seg_context) * mi_width);
1342   memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
1343          sizeof(xd->left_seg_context[0]) * mi_height);
1344 }
1345
1346 static void encode_b(VP10_COMP *cpi, const TileInfo *const tile,
1347                      ThreadData *td,
1348                      TOKENEXTRA **tp, int mi_row, int mi_col,
1349                      int output_enabled, BLOCK_SIZE bsize,
1350                      PICK_MODE_CONTEXT *ctx) {
1351   MACROBLOCK *const x = &td->mb;
1352   set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
1353   update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
1354   encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
1355
1356   if (output_enabled) {
1357     update_stats(&cpi->common, td);
1358
1359     (*tp)->token = EOSB_TOKEN;
1360     (*tp)++;
1361   }
1362 }
1363
1364 static void encode_sb(VP10_COMP *cpi, ThreadData *td,
1365                       const TileInfo *const tile,
1366                       TOKENEXTRA **tp, int mi_row, int mi_col,
1367                       int output_enabled, BLOCK_SIZE bsize,
1368                       PC_TREE *pc_tree) {
1369   VP10_COMMON *const cm = &cpi->common;
1370   MACROBLOCK *const x = &td->mb;
1371   MACROBLOCKD *const xd = &x->e_mbd;
1372
1373   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
1374   int ctx;
1375   PARTITION_TYPE partition;
1376   BLOCK_SIZE subsize = bsize;
1377
1378   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1379     return;
1380
1381   if (bsize >= BLOCK_8X8) {
1382     ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
1383     subsize = get_subsize(bsize, pc_tree->partitioning);
1384   } else {
1385     ctx = 0;
1386     subsize = BLOCK_4X4;
1387   }
1388
1389   partition = partition_lookup[bsl][subsize];
1390   if (output_enabled && bsize != BLOCK_4X4)
1391     td->counts->partition[ctx][partition]++;
1392
1393   switch (partition) {
1394     case PARTITION_NONE:
1395       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1396                &pc_tree->none);
1397       break;
1398     case PARTITION_VERT:
1399       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1400                &pc_tree->vertical[0]);
1401       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
1402         encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
1403                  subsize, &pc_tree->vertical[1]);
1404       }
1405       break;
1406     case PARTITION_HORZ:
1407       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1408                &pc_tree->horizontal[0]);
1409       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
1410         encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
1411                  subsize, &pc_tree->horizontal[1]);
1412       }
1413       break;
1414     case PARTITION_SPLIT:
1415       if (bsize == BLOCK_8X8) {
1416         encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1417                  pc_tree->leaf_split[0]);
1418       } else {
1419         encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1420                   pc_tree->split[0]);
1421         encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1422                   subsize, pc_tree->split[1]);
1423         encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1424                   subsize, pc_tree->split[2]);
1425         encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
1426                   subsize, pc_tree->split[3]);
1427       }
1428       break;
1429     default:
1430       assert(0 && "Invalid partition type.");
1431       break;
1432   }
1433
1434   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
1435     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
1436 }
1437
1438 // Check to see if the given partition size is allowed for a specified number
1439 // of 8x8 block rows and columns remaining in the image.
1440 // If not then return the largest allowed partition size
1441 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize,
1442                                       int rows_left, int cols_left,
1443                                       int *bh, int *bw) {
1444   if (rows_left <= 0 || cols_left <= 0) {
1445     return VPXMIN(bsize, BLOCK_8X8);
1446   } else {
1447     for (; bsize > 0; bsize -= 3) {
1448       *bh = num_8x8_blocks_high_lookup[bsize];
1449       *bw = num_8x8_blocks_wide_lookup[bsize];
1450       if ((*bh <= rows_left) && (*bw <= cols_left)) {
1451         break;
1452       }
1453     }
1454   }
1455   return bsize;
1456 }
1457
1458 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis,
1459     int bh_in, int bw_in, int row8x8_remaining, int col8x8_remaining,
1460     BLOCK_SIZE bsize, MODE_INFO **mi_8x8) {
1461   int bh = bh_in;
1462   int r, c;
1463   for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
1464     int bw = bw_in;
1465     for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
1466       const int index = r * mis + c;
1467       mi_8x8[index] = mi + index;
1468       mi_8x8[index]->mbmi.sb_type = find_partition_size(bsize,
1469           row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
1470     }
1471   }
1472 }
1473
1474 // This function attempts to set all mode info entries in a given SB64
1475 // to the same block partition size.
1476 // However, at the bottom and right borders of the image the requested size
1477 // may not be allowed in which case this code attempts to choose the largest
1478 // allowable partition.
1479 static void set_fixed_partitioning(VP10_COMP *cpi, const TileInfo *const tile,
1480                                    MODE_INFO **mi_8x8, int mi_row, int mi_col,
1481                                    BLOCK_SIZE bsize) {
1482   VP10_COMMON *const cm = &cpi->common;
1483   const int mis = cm->mi_stride;
1484   const int row8x8_remaining = tile->mi_row_end - mi_row;
1485   const int col8x8_remaining = tile->mi_col_end - mi_col;
1486   int block_row, block_col;
1487   MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
1488   int bh = num_8x8_blocks_high_lookup[bsize];
1489   int bw = num_8x8_blocks_wide_lookup[bsize];
1490
1491   assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
1492
1493   // Apply the requested partition size to the SB64 if it is all "in image"
1494   if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
1495       (row8x8_remaining >= MI_BLOCK_SIZE)) {
1496     for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
1497       for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
1498         int index = block_row * mis + block_col;
1499         mi_8x8[index] = mi_upper_left + index;
1500         mi_8x8[index]->mbmi.sb_type = bsize;
1501       }
1502     }
1503   } else {
1504     // Else this is a partial SB64.
1505     set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
1506         col8x8_remaining, bsize, mi_8x8);
1507   }
1508 }
1509
1510 static void rd_use_partition(VP10_COMP *cpi,
1511                              ThreadData *td,
1512                              TileDataEnc *tile_data,
1513                              MODE_INFO **mi_8x8, TOKENEXTRA **tp,
1514                              int mi_row, int mi_col,
1515                              BLOCK_SIZE bsize,
1516                              int *rate, int64_t *dist,
1517                              int do_recon, PC_TREE *pc_tree) {
1518   VP10_COMMON *const cm = &cpi->common;
1519   TileInfo *const tile_info = &tile_data->tile_info;
1520   MACROBLOCK *const x = &td->mb;
1521   MACROBLOCKD *const xd = &x->e_mbd;
1522   const int mis = cm->mi_stride;
1523   const int bsl = b_width_log2_lookup[bsize];
1524   const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
1525   const int bss = (1 << bsl) / 4;
1526   int i, pl;
1527   PARTITION_TYPE partition = PARTITION_NONE;
1528   BLOCK_SIZE subsize;
1529   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1530   PARTITION_CONTEXT sl[8], sa[8];
1531   RD_COST last_part_rdc, none_rdc, chosen_rdc;
1532   BLOCK_SIZE sub_subsize = BLOCK_4X4;
1533   int splits_below = 0;
1534   BLOCK_SIZE bs_type = mi_8x8[0]->mbmi.sb_type;
1535   int do_partition_search = 1;
1536   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
1537
1538   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1539     return;
1540
1541   assert(num_4x4_blocks_wide_lookup[bsize] ==
1542          num_4x4_blocks_high_lookup[bsize]);
1543
1544   vp10_rd_cost_reset(&last_part_rdc);
1545   vp10_rd_cost_reset(&none_rdc);
1546   vp10_rd_cost_reset(&chosen_rdc);
1547
1548   partition = partition_lookup[bsl][bs_type];
1549   subsize = get_subsize(bsize, partition);
1550
1551   pc_tree->partitioning = partition;
1552   save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1553
1554   if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode) {
1555     set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1556     x->mb_energy = vp10_block_energy(cpi, x, bsize);
1557   }
1558
1559   if (do_partition_search &&
1560       cpi->sf.partition_search_type == SEARCH_PARTITION &&
1561       cpi->sf.adjust_partitioning_from_last_frame) {
1562     // Check if any of the sub blocks are further split.
1563     if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
1564       sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
1565       splits_below = 1;
1566       for (i = 0; i < 4; i++) {
1567         int jj = i >> 1, ii = i & 0x01;
1568         MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
1569         if (this_mi && this_mi->mbmi.sb_type >= sub_subsize) {
1570           splits_below = 0;
1571         }
1572       }
1573     }
1574
1575     // If partition is not none try none unless each of the 4 splits are split
1576     // even further..
1577     if (partition != PARTITION_NONE && !splits_below &&
1578         mi_row + (mi_step >> 1) < cm->mi_rows &&
1579         mi_col + (mi_step >> 1) < cm->mi_cols) {
1580       pc_tree->partitioning = PARTITION_NONE;
1581       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize,
1582                        ctx, INT64_MAX);
1583
1584       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
1585
1586       if (none_rdc.rate < INT_MAX) {
1587         none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
1588         none_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, none_rdc.rate,
1589                                  none_rdc.dist);
1590       }
1591
1592       restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1593       mi_8x8[0]->mbmi.sb_type = bs_type;
1594       pc_tree->partitioning = partition;
1595     }
1596   }
1597
1598   switch (partition) {
1599     case PARTITION_NONE:
1600       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1601                        bsize, ctx, INT64_MAX);
1602       break;
1603     case PARTITION_HORZ:
1604       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1605                        subsize, &pc_tree->horizontal[0],
1606                        INT64_MAX);
1607       if (last_part_rdc.rate != INT_MAX &&
1608           bsize >= BLOCK_8X8 && mi_row + (mi_step >> 1) < cm->mi_rows) {
1609         RD_COST tmp_rdc;
1610         PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
1611         vp10_rd_cost_init(&tmp_rdc);
1612         update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
1613         encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
1614         rd_pick_sb_modes(cpi, tile_data, x,
1615                          mi_row + (mi_step >> 1), mi_col, &tmp_rdc,
1616                          subsize, &pc_tree->horizontal[1], INT64_MAX);
1617         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1618           vp10_rd_cost_reset(&last_part_rdc);
1619           break;
1620         }
1621         last_part_rdc.rate += tmp_rdc.rate;
1622         last_part_rdc.dist += tmp_rdc.dist;
1623         last_part_rdc.rdcost += tmp_rdc.rdcost;
1624       }
1625       break;
1626     case PARTITION_VERT:
1627       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1628                        subsize, &pc_tree->vertical[0], INT64_MAX);
1629       if (last_part_rdc.rate != INT_MAX &&
1630           bsize >= BLOCK_8X8 && mi_col + (mi_step >> 1) < cm->mi_cols) {
1631         RD_COST tmp_rdc;
1632         PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
1633         vp10_rd_cost_init(&tmp_rdc);
1634         update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
1635         encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
1636         rd_pick_sb_modes(cpi, tile_data, x,
1637                          mi_row, mi_col + (mi_step >> 1), &tmp_rdc,
1638                          subsize, &pc_tree->vertical[bsize > BLOCK_8X8],
1639                          INT64_MAX);
1640         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1641           vp10_rd_cost_reset(&last_part_rdc);
1642           break;
1643         }
1644         last_part_rdc.rate += tmp_rdc.rate;
1645         last_part_rdc.dist += tmp_rdc.dist;
1646         last_part_rdc.rdcost += tmp_rdc.rdcost;
1647       }
1648       break;
1649     case PARTITION_SPLIT:
1650       if (bsize == BLOCK_8X8) {
1651         rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1652                          subsize, pc_tree->leaf_split[0], INT64_MAX);
1653         break;
1654       }
1655       last_part_rdc.rate = 0;
1656       last_part_rdc.dist = 0;
1657       last_part_rdc.rdcost = 0;
1658       for (i = 0; i < 4; i++) {
1659         int x_idx = (i & 1) * (mi_step >> 1);
1660         int y_idx = (i >> 1) * (mi_step >> 1);
1661         int jj = i >> 1, ii = i & 0x01;
1662         RD_COST tmp_rdc;
1663         if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
1664           continue;
1665
1666         vp10_rd_cost_init(&tmp_rdc);
1667         rd_use_partition(cpi, td, tile_data,
1668                          mi_8x8 + jj * bss * mis + ii * bss, tp,
1669                          mi_row + y_idx, mi_col + x_idx, subsize,
1670                          &tmp_rdc.rate, &tmp_rdc.dist,
1671                          i != 3, pc_tree->split[i]);
1672         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1673           vp10_rd_cost_reset(&last_part_rdc);
1674           break;
1675         }
1676         last_part_rdc.rate += tmp_rdc.rate;
1677         last_part_rdc.dist += tmp_rdc.dist;
1678       }
1679       break;
1680     default:
1681       assert(0);
1682       break;
1683   }
1684
1685   pl = partition_plane_context(xd, mi_row, mi_col, bsize);
1686   if (last_part_rdc.rate < INT_MAX) {
1687     last_part_rdc.rate += cpi->partition_cost[pl][partition];
1688     last_part_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
1689                                   last_part_rdc.rate, last_part_rdc.dist);
1690   }
1691
1692   if (do_partition_search
1693       && cpi->sf.adjust_partitioning_from_last_frame
1694       && cpi->sf.partition_search_type == SEARCH_PARTITION
1695       && partition != PARTITION_SPLIT && bsize > BLOCK_8X8
1696       && (mi_row + mi_step < cm->mi_rows ||
1697           mi_row + (mi_step >> 1) == cm->mi_rows)
1698       && (mi_col + mi_step < cm->mi_cols ||
1699           mi_col + (mi_step >> 1) == cm->mi_cols)) {
1700     BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
1701     chosen_rdc.rate = 0;
1702     chosen_rdc.dist = 0;
1703     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1704     pc_tree->partitioning = PARTITION_SPLIT;
1705
1706     // Split partition.
1707     for (i = 0; i < 4; i++) {
1708       int x_idx = (i & 1) * (mi_step >> 1);
1709       int y_idx = (i >> 1) * (mi_step >> 1);
1710       RD_COST tmp_rdc;
1711       ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1712       PARTITION_CONTEXT sl[8], sa[8];
1713
1714       if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
1715         continue;
1716
1717       save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1718       pc_tree->split[i]->partitioning = PARTITION_NONE;
1719       rd_pick_sb_modes(cpi, tile_data, x,
1720                        mi_row + y_idx, mi_col + x_idx, &tmp_rdc,
1721                        split_subsize, &pc_tree->split[i]->none, INT64_MAX);
1722
1723       restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1724
1725       if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1726         vp10_rd_cost_reset(&chosen_rdc);
1727         break;
1728       }
1729
1730       chosen_rdc.rate += tmp_rdc.rate;
1731       chosen_rdc.dist += tmp_rdc.dist;
1732
1733       if (i != 3)
1734         encode_sb(cpi, td, tile_info, tp,  mi_row + y_idx, mi_col + x_idx, 0,
1735                   split_subsize, pc_tree->split[i]);
1736
1737       pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
1738                                    split_subsize);
1739       chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
1740     }
1741     pl = partition_plane_context(xd, mi_row, mi_col, bsize);
1742     if (chosen_rdc.rate < INT_MAX) {
1743       chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
1744       chosen_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
1745                                  chosen_rdc.rate, chosen_rdc.dist);
1746     }
1747   }
1748
1749   // If last_part is better set the partitioning to that.
1750   if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
1751     mi_8x8[0]->mbmi.sb_type = bsize;
1752     if (bsize >= BLOCK_8X8)
1753       pc_tree->partitioning = partition;
1754     chosen_rdc = last_part_rdc;
1755   }
1756   // If none was better set the partitioning to that.
1757   if (none_rdc.rdcost < chosen_rdc.rdcost) {
1758     if (bsize >= BLOCK_8X8)
1759       pc_tree->partitioning = PARTITION_NONE;
1760     chosen_rdc = none_rdc;
1761   }
1762
1763   restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1764
1765   // We must have chosen a partitioning and encoding or we'll fail later on.
1766   // No other opportunities for success.
1767   if (bsize == BLOCK_64X64)
1768     assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
1769
1770   if (do_recon) {
1771     int output_enabled = (bsize == BLOCK_64X64);
1772     encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
1773               pc_tree);
1774   }
1775
1776   *rate = chosen_rdc.rate;
1777   *dist = chosen_rdc.dist;
1778 }
1779
1780 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
1781   BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,
1782   BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,
1783   BLOCK_8X8,   BLOCK_8X8,   BLOCK_8X8,
1784   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
1785   BLOCK_16X16
1786 };
1787
1788 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
1789   BLOCK_8X8,   BLOCK_16X16, BLOCK_16X16,
1790   BLOCK_16X16, BLOCK_32X32, BLOCK_32X32,
1791   BLOCK_32X32, BLOCK_64X64, BLOCK_64X64,
1792   BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
1793   BLOCK_64X64
1794 };
1795
1796
1797 // Look at all the mode_info entries for blocks that are part of this
1798 // partition and find the min and max values for sb_type.
1799 // At the moment this is designed to work on a 64x64 SB but could be
1800 // adjusted to use a size parameter.
1801 //
1802 // The min and max are assumed to have been initialized prior to calling this
1803 // function so repeat calls can accumulate a min and max of more than one sb64.
1804 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
1805                                         BLOCK_SIZE *min_block_size,
1806                                         BLOCK_SIZE *max_block_size,
1807                                         int bs_hist[BLOCK_SIZES]) {
1808   int sb_width_in_blocks = MI_BLOCK_SIZE;
1809   int sb_height_in_blocks  = MI_BLOCK_SIZE;
1810   int i, j;
1811   int index = 0;
1812
1813   // Check the sb_type for each block that belongs to this region.
1814   for (i = 0; i < sb_height_in_blocks; ++i) {
1815     for (j = 0; j < sb_width_in_blocks; ++j) {
1816       MODE_INFO *mi = mi_8x8[index+j];
1817       BLOCK_SIZE sb_type = mi ? mi->mbmi.sb_type : 0;
1818       bs_hist[sb_type]++;
1819       *min_block_size = VPXMIN(*min_block_size, sb_type);
1820       *max_block_size = VPXMAX(*max_block_size, sb_type);
1821     }
1822     index += xd->mi_stride;
1823   }
1824 }
1825
1826 // Next square block size less or equal than current block size.
1827 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
1828   BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
1829   BLOCK_8X8, BLOCK_8X8, BLOCK_8X8,
1830   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
1831   BLOCK_32X32, BLOCK_32X32, BLOCK_32X32,
1832   BLOCK_64X64
1833 };
1834
1835 // Look at neighboring blocks and set a min and max partition size based on
1836 // what they chose.
1837 static void rd_auto_partition_range(VP10_COMP *cpi, const TileInfo *const tile,
1838                                     MACROBLOCKD *const xd,
1839                                     int mi_row, int mi_col,
1840                                     BLOCK_SIZE *min_block_size,
1841                                     BLOCK_SIZE *max_block_size) {
1842   VP10_COMMON *const cm = &cpi->common;
1843   MODE_INFO **mi = xd->mi;
1844   const int left_in_image = xd->left_available && mi[-1];
1845   const int above_in_image = xd->up_available && mi[-xd->mi_stride];
1846   const int row8x8_remaining = tile->mi_row_end - mi_row;
1847   const int col8x8_remaining = tile->mi_col_end - mi_col;
1848   int bh, bw;
1849   BLOCK_SIZE min_size = BLOCK_4X4;
1850   BLOCK_SIZE max_size = BLOCK_64X64;
1851   int bs_hist[BLOCK_SIZES] = {0};
1852
1853   // Trap case where we do not have a prediction.
1854   if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
1855     // Default "min to max" and "max to min"
1856     min_size = BLOCK_64X64;
1857     max_size = BLOCK_4X4;
1858
1859     // NOTE: each call to get_sb_partition_size_range() uses the previous
1860     // passed in values for min and max as a starting point.
1861     // Find the min and max partition used in previous frame at this location
1862     if (cm->frame_type != KEY_FRAME) {
1863       MODE_INFO **prev_mi =
1864           &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
1865       get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
1866     }
1867     // Find the min and max partition sizes used in the left SB64
1868     if (left_in_image) {
1869       MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
1870       get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
1871                                   bs_hist);
1872     }
1873     // Find the min and max partition sizes used in the above SB64.
1874     if (above_in_image) {
1875       MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
1876       get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
1877                                   bs_hist);
1878     }
1879
1880     // Adjust observed min and max for "relaxed" auto partition case.
1881     if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
1882       min_size = min_partition_size[min_size];
1883       max_size = max_partition_size[max_size];
1884     }
1885   }
1886
1887   // Check border cases where max and min from neighbors may not be legal.
1888   max_size = find_partition_size(max_size,
1889                                  row8x8_remaining, col8x8_remaining,
1890                                  &bh, &bw);
1891   // Test for blocks at the edge of the active image.
1892   // This may be the actual edge of the image or where there are formatting
1893   // bars.
1894   if (vp10_active_edge_sb(cpi, mi_row, mi_col)) {
1895     min_size = BLOCK_4X4;
1896   } else {
1897     min_size =
1898         VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
1899   }
1900
1901   // When use_square_partition_only is true, make sure at least one square
1902   // partition is allowed by selecting the next smaller square size as
1903   // *min_block_size.
1904   if (cpi->sf.use_square_partition_only &&
1905       next_square_size[max_size] < min_size) {
1906      min_size = next_square_size[max_size];
1907   }
1908
1909   *min_block_size = min_size;
1910   *max_block_size = max_size;
1911 }
1912
1913 // TODO(jingning) refactor functions setting partition search range
1914 static void set_partition_range(VP10_COMMON *cm, MACROBLOCKD *xd,
1915                                 int mi_row, int mi_col, BLOCK_SIZE bsize,
1916                                 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
1917   int mi_width  = num_8x8_blocks_wide_lookup[bsize];
1918   int mi_height = num_8x8_blocks_high_lookup[bsize];
1919   int idx, idy;
1920
1921   MODE_INFO *mi;
1922   const int idx_str = cm->mi_stride * mi_row + mi_col;
1923   MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
1924   BLOCK_SIZE bs, min_size, max_size;
1925
1926   min_size = BLOCK_64X64;
1927   max_size = BLOCK_4X4;
1928
1929   if (prev_mi) {
1930     for (idy = 0; idy < mi_height; ++idy) {
1931       for (idx = 0; idx < mi_width; ++idx) {
1932         mi = prev_mi[idy * cm->mi_stride + idx];
1933         bs = mi ? mi->mbmi.sb_type : bsize;
1934         min_size = VPXMIN(min_size, bs);
1935         max_size = VPXMAX(max_size, bs);
1936       }
1937     }
1938   }
1939
1940   if (xd->left_available) {
1941     for (idy = 0; idy < mi_height; ++idy) {
1942       mi = xd->mi[idy * cm->mi_stride - 1];
1943       bs = mi ? mi->mbmi.sb_type : bsize;
1944       min_size = VPXMIN(min_size, bs);
1945       max_size = VPXMAX(max_size, bs);
1946     }
1947   }
1948
1949   if (xd->up_available) {
1950     for (idx = 0; idx < mi_width; ++idx) {
1951       mi = xd->mi[idx - cm->mi_stride];
1952       bs = mi ? mi->mbmi.sb_type : bsize;
1953       min_size = VPXMIN(min_size, bs);
1954       max_size = VPXMAX(max_size, bs);
1955     }
1956   }
1957
1958   if (min_size == max_size) {
1959     min_size = min_partition_size[min_size];
1960     max_size = max_partition_size[max_size];
1961   }
1962
1963   *min_bs = min_size;
1964   *max_bs = max_size;
1965 }
1966
1967 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
1968   memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
1969 }
1970
1971 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
1972   memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
1973 }
1974
1975 #if CONFIG_FP_MB_STATS
1976 const int num_16x16_blocks_wide_lookup[BLOCK_SIZES] =
1977   {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 4, 4};
1978 const int num_16x16_blocks_high_lookup[BLOCK_SIZES] =
1979   {1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 4, 2, 4};
1980 const int qindex_skip_threshold_lookup[BLOCK_SIZES] =
1981   {0, 10, 10, 30, 40, 40, 60, 80, 80, 90, 100, 100, 120};
1982 const int qindex_split_threshold_lookup[BLOCK_SIZES] =
1983   {0, 3, 3, 7, 15, 15, 30, 40, 40, 60, 80, 80, 120};
1984 const int complexity_16x16_blocks_threshold[BLOCK_SIZES] =
1985   {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 6};
1986
1987 typedef enum {
1988   MV_ZERO = 0,
1989   MV_LEFT = 1,
1990   MV_UP = 2,
1991   MV_RIGHT = 3,
1992   MV_DOWN = 4,
1993   MV_INVALID
1994 } MOTION_DIRECTION;
1995
1996 static INLINE MOTION_DIRECTION get_motion_direction_fp(uint8_t fp_byte) {
1997   if (fp_byte & FPMB_MOTION_ZERO_MASK) {
1998     return MV_ZERO;
1999   } else if (fp_byte & FPMB_MOTION_LEFT_MASK) {
2000     return MV_LEFT;
2001   } else if (fp_byte & FPMB_MOTION_RIGHT_MASK) {
2002     return MV_RIGHT;
2003   } else if (fp_byte & FPMB_MOTION_UP_MASK) {
2004     return MV_UP;
2005   } else {
2006     return MV_DOWN;
2007   }
2008 }
2009
2010 static INLINE int get_motion_inconsistency(MOTION_DIRECTION this_mv,
2011                                            MOTION_DIRECTION that_mv) {
2012   if (this_mv == that_mv) {
2013     return 0;
2014   } else {
2015     return abs(this_mv - that_mv) == 2 ? 2 : 1;
2016   }
2017 }
2018 #endif
2019
2020 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
2021 // unlikely to be selected depending on previous rate-distortion optimization
2022 // results, for encoding speed-up.
2023 static void rd_pick_partition(VP10_COMP *cpi, ThreadData *td,
2024                               TileDataEnc *tile_data,
2025                               TOKENEXTRA **tp, int mi_row, int mi_col,
2026                               BLOCK_SIZE bsize, RD_COST *rd_cost,
2027                               int64_t best_rd, PC_TREE *pc_tree) {
2028   VP10_COMMON *const cm = &cpi->common;
2029   TileInfo *const tile_info = &tile_data->tile_info;
2030   MACROBLOCK *const x = &td->mb;
2031   MACROBLOCKD *const xd = &x->e_mbd;
2032   const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
2033   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2034   PARTITION_CONTEXT sl[8], sa[8];
2035   TOKENEXTRA *tp_orig = *tp;
2036   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2037   int i, pl;
2038   BLOCK_SIZE subsize;
2039   RD_COST this_rdc, sum_rdc, best_rdc;
2040   int do_split = bsize >= BLOCK_8X8;
2041   int do_rect = 1;
2042
2043   // Override skipping rectangular partition operations for edge blocks
2044   const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
2045   const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
2046   const int xss = x->e_mbd.plane[1].subsampling_x;
2047   const int yss = x->e_mbd.plane[1].subsampling_y;
2048
2049   BLOCK_SIZE min_size = x->min_partition_size;
2050   BLOCK_SIZE max_size = x->max_partition_size;
2051
2052 #if CONFIG_FP_MB_STATS
2053   unsigned int src_diff_var = UINT_MAX;
2054   int none_complexity = 0;
2055 #endif
2056
2057   int partition_none_allowed = !force_horz_split && !force_vert_split;
2058   int partition_horz_allowed = !force_vert_split && yss <= xss &&
2059                                bsize >= BLOCK_8X8;
2060   int partition_vert_allowed = !force_horz_split && xss <= yss &&
2061                                bsize >= BLOCK_8X8;
2062   (void) *tp_orig;
2063
2064   assert(num_8x8_blocks_wide_lookup[bsize] ==
2065              num_8x8_blocks_high_lookup[bsize]);
2066
2067   vp10_rd_cost_init(&this_rdc);
2068   vp10_rd_cost_init(&sum_rdc);
2069   vp10_rd_cost_reset(&best_rdc);
2070   best_rdc.rdcost = best_rd;
2071
2072   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2073
2074   if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode)
2075     x->mb_energy = vp10_block_energy(cpi, x, bsize);
2076
2077   if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
2078     int cb_partition_search_ctrl = ((pc_tree->index == 0 || pc_tree->index == 3)
2079         + get_chessboard_index(cm->current_video_frame)) & 0x1;
2080
2081     if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
2082       set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
2083   }
2084
2085   // Determine partition types in search according to the speed features.
2086   // The threshold set here has to be of square block size.
2087   if (cpi->sf.auto_min_max_partition_size) {
2088     partition_none_allowed &= (bsize <= max_size && bsize >= min_size);
2089     partition_horz_allowed &= ((bsize <= max_size && bsize > min_size) ||
2090                                 force_horz_split);
2091     partition_vert_allowed &= ((bsize <= max_size && bsize > min_size) ||
2092                                 force_vert_split);
2093     do_split &= bsize > min_size;
2094   }
2095   if (cpi->sf.use_square_partition_only) {
2096     partition_horz_allowed &= force_horz_split;
2097     partition_vert_allowed &= force_vert_split;
2098   }
2099
2100   save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2101
2102 #if CONFIG_FP_MB_STATS
2103   if (cpi->use_fp_mb_stats) {
2104     set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2105     src_diff_var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src,
2106                                                   mi_row, mi_col, bsize);
2107   }
2108 #endif
2109
2110 #if CONFIG_FP_MB_STATS
2111   // Decide whether we shall split directly and skip searching NONE by using
2112   // the first pass block statistics
2113   if (cpi->use_fp_mb_stats && bsize >= BLOCK_32X32 && do_split &&
2114       partition_none_allowed && src_diff_var > 4 &&
2115       cm->base_qindex < qindex_split_threshold_lookup[bsize]) {
2116     int mb_row = mi_row >> 1;
2117     int mb_col = mi_col >> 1;
2118     int mb_row_end =
2119         VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
2120     int mb_col_end =
2121         VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
2122     int r, c;
2123
2124     // compute a complexity measure, basically measure inconsistency of motion
2125     // vectors obtained from the first pass in the current block
2126     for (r = mb_row; r < mb_row_end ; r++) {
2127       for (c = mb_col; c < mb_col_end; c++) {
2128         const int mb_index = r * cm->mb_cols + c;
2129
2130         MOTION_DIRECTION this_mv;
2131         MOTION_DIRECTION right_mv;
2132         MOTION_DIRECTION bottom_mv;
2133
2134         this_mv =
2135             get_motion_direction_fp(cpi->twopass.this_frame_mb_stats[mb_index]);
2136
2137         // to its right
2138         if (c != mb_col_end - 1) {
2139           right_mv = get_motion_direction_fp(
2140               cpi->twopass.this_frame_mb_stats[mb_index + 1]);
2141           none_complexity += get_motion_inconsistency(this_mv, right_mv);
2142         }
2143
2144         // to its bottom
2145         if (r != mb_row_end - 1) {
2146           bottom_mv = get_motion_direction_fp(
2147               cpi->twopass.this_frame_mb_stats[mb_index + cm->mb_cols]);
2148           none_complexity += get_motion_inconsistency(this_mv, bottom_mv);
2149         }
2150
2151         // do not count its left and top neighbors to avoid double counting
2152       }
2153     }
2154
2155     if (none_complexity > complexity_16x16_blocks_threshold[bsize]) {
2156       partition_none_allowed = 0;
2157     }
2158   }
2159 #endif
2160
2161   // PARTITION_NONE
2162   if (partition_none_allowed) {
2163     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col,
2164                      &this_rdc, bsize, ctx, best_rdc.rdcost);
2165     if (this_rdc.rate != INT_MAX) {
2166       if (bsize >= BLOCK_8X8) {
2167         pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2168         this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2169         this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2170                                  this_rdc.rate, this_rdc.dist);
2171       }
2172
2173       if (this_rdc.rdcost < best_rdc.rdcost) {
2174         int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_dist_thr;
2175         int rate_breakout_thr = cpi->sf.partition_search_breakout_rate_thr;
2176
2177         best_rdc = this_rdc;
2178         if (bsize >= BLOCK_8X8)
2179           pc_tree->partitioning = PARTITION_NONE;
2180
2181         // Adjust dist breakout threshold according to the partition size.
2182         dist_breakout_thr >>= 8 - (b_width_log2_lookup[bsize] +
2183             b_height_log2_lookup[bsize]);
2184
2185         rate_breakout_thr *= num_pels_log2_lookup[bsize];
2186
2187         // If all y, u, v transform blocks in this partition are skippable, and
2188         // the dist & rate are within the thresholds, the partition search is
2189         // terminated for current branch of the partition search tree.
2190         // The dist & rate thresholds are set to 0 at speed 0 to disable the
2191         // early termination at that speed.
2192         if (!x->e_mbd.lossless &&
2193             (ctx->skippable && best_rdc.dist < dist_breakout_thr &&
2194             best_rdc.rate < rate_breakout_thr)) {
2195           do_split = 0;
2196           do_rect = 0;
2197         }
2198
2199 #if CONFIG_FP_MB_STATS
2200         // Check if every 16x16 first pass block statistics has zero
2201         // motion and the corresponding first pass residue is small enough.
2202         // If that is the case, check the difference variance between the
2203         // current frame and the last frame. If the variance is small enough,
2204         // stop further splitting in RD optimization
2205         if (cpi->use_fp_mb_stats && do_split != 0 &&
2206             cm->base_qindex > qindex_skip_threshold_lookup[bsize]) {
2207           int mb_row = mi_row >> 1;
2208           int mb_col = mi_col >> 1;
2209           int mb_row_end =
2210               VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
2211           int mb_col_end =
2212               VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
2213           int r, c;
2214
2215           int skip = 1;
2216           for (r = mb_row; r < mb_row_end; r++) {
2217             for (c = mb_col; c < mb_col_end; c++) {
2218               const int mb_index = r * cm->mb_cols + c;
2219               if (!(cpi->twopass.this_frame_mb_stats[mb_index] &
2220                     FPMB_MOTION_ZERO_MASK) ||
2221                   !(cpi->twopass.this_frame_mb_stats[mb_index] &
2222                     FPMB_ERROR_SMALL_MASK)) {
2223                 skip = 0;
2224                 break;
2225               }
2226             }
2227             if (skip == 0) {
2228               break;
2229             }
2230           }
2231           if (skip) {
2232             if (src_diff_var == UINT_MAX) {
2233               set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2234               src_diff_var = get_sby_perpixel_diff_variance(
2235                   cpi, &x->plane[0].src, mi_row, mi_col, bsize);
2236             }
2237             if (src_diff_var < 8) {
2238               do_split = 0;
2239               do_rect = 0;
2240             }
2241           }
2242         }
2243 #endif
2244       }
2245     }
2246     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2247   }
2248
2249   // store estimated motion vector
2250   if (cpi->sf.adaptive_motion_search)
2251     store_pred_mv(x, ctx);
2252
2253   // PARTITION_SPLIT
2254   // TODO(jingning): use the motion vectors given by the above search as
2255   // the starting point of motion search in the following partition type check.
2256   if (do_split) {
2257     subsize = get_subsize(bsize, PARTITION_SPLIT);
2258     if (bsize == BLOCK_8X8) {
2259       i = 4;
2260       if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
2261         pc_tree->leaf_split[0]->pred_interp_filter =
2262             ctx->mic.mbmi.interp_filter;
2263       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2264                        pc_tree->leaf_split[0], best_rdc.rdcost);
2265       if (sum_rdc.rate == INT_MAX)
2266         sum_rdc.rdcost = INT64_MAX;
2267     } else {
2268       for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
2269       const int x_idx = (i & 1) * mi_step;
2270       const int y_idx = (i >> 1) * mi_step;
2271
2272         if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
2273           continue;
2274
2275         if (cpi->sf.adaptive_motion_search)
2276           load_pred_mv(x, ctx);
2277
2278         pc_tree->split[i]->index = i;
2279         rd_pick_partition(cpi, td, tile_data, tp,
2280                           mi_row + y_idx, mi_col + x_idx,
2281                           subsize, &this_rdc,
2282                           best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
2283
2284         if (this_rdc.rate == INT_MAX) {
2285           sum_rdc.rdcost = INT64_MAX;
2286           break;
2287         } else {
2288           sum_rdc.rate += this_rdc.rate;
2289           sum_rdc.dist += this_rdc.dist;
2290           sum_rdc.rdcost += this_rdc.rdcost;
2291         }
2292       }
2293     }
2294
2295     if (sum_rdc.rdcost < best_rdc.rdcost && i == 4) {
2296       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2297       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2298       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2299                               sum_rdc.rate, sum_rdc.dist);
2300
2301       if (sum_rdc.rdcost < best_rdc.rdcost) {
2302         best_rdc = sum_rdc;
2303         pc_tree->partitioning = PARTITION_SPLIT;
2304       }
2305     } else {
2306       // skip rectangular partition test when larger block size
2307       // gives better rd cost
2308       if (cpi->sf.less_rectangular_check)
2309         do_rect &= !partition_none_allowed;
2310     }
2311     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2312   }
2313
2314   // PARTITION_HORZ
2315   if (partition_horz_allowed &&
2316       (do_rect || vp10_active_h_edge(cpi, mi_row, mi_step))) {
2317       subsize = get_subsize(bsize, PARTITION_HORZ);
2318     if (cpi->sf.adaptive_motion_search)
2319       load_pred_mv(x, ctx);
2320     if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2321         partition_none_allowed)
2322       pc_tree->horizontal[0].pred_interp_filter =
2323           ctx->mic.mbmi.interp_filter;
2324     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2325                      &pc_tree->horizontal[0], best_rdc.rdcost);
2326
2327     if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
2328         bsize > BLOCK_8X8) {
2329       PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2330       update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2331       encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2332
2333       if (cpi->sf.adaptive_motion_search)
2334         load_pred_mv(x, ctx);
2335       if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2336           partition_none_allowed)
2337         pc_tree->horizontal[1].pred_interp_filter =
2338             ctx->mic.mbmi.interp_filter;
2339       rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col,
2340                        &this_rdc, subsize, &pc_tree->horizontal[1],
2341                        best_rdc.rdcost - sum_rdc.rdcost);
2342       if (this_rdc.rate == INT_MAX) {
2343         sum_rdc.rdcost = INT64_MAX;
2344       } else {
2345         sum_rdc.rate += this_rdc.rate;
2346         sum_rdc.dist += this_rdc.dist;
2347         sum_rdc.rdcost += this_rdc.rdcost;
2348       }
2349     }
2350
2351     if (sum_rdc.rdcost < best_rdc.rdcost) {
2352       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2353       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
2354       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
2355       if (sum_rdc.rdcost < best_rdc.rdcost) {
2356         best_rdc = sum_rdc;
2357         pc_tree->partitioning = PARTITION_HORZ;
2358       }
2359     }
2360     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2361   }
2362   // PARTITION_VERT
2363   if (partition_vert_allowed &&
2364       (do_rect || vp10_active_v_edge(cpi, mi_col, mi_step))) {
2365       subsize = get_subsize(bsize, PARTITION_VERT);
2366
2367     if (cpi->sf.adaptive_motion_search)
2368       load_pred_mv(x, ctx);
2369     if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2370         partition_none_allowed)
2371       pc_tree->vertical[0].pred_interp_filter =
2372           ctx->mic.mbmi.interp_filter;
2373     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2374                      &pc_tree->vertical[0], best_rdc.rdcost);
2375     if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
2376         bsize > BLOCK_8X8) {
2377       update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
2378       encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
2379                         &pc_tree->vertical[0]);
2380
2381       if (cpi->sf.adaptive_motion_search)
2382         load_pred_mv(x, ctx);
2383       if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2384           partition_none_allowed)
2385         pc_tree->vertical[1].pred_interp_filter =
2386             ctx->mic.mbmi.interp_filter;
2387       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step,
2388                        &this_rdc, subsize,
2389                        &pc_tree->vertical[1], best_rdc.rdcost - sum_rdc.rdcost);
2390       if (this_rdc.rate == INT_MAX) {
2391         sum_rdc.rdcost = INT64_MAX;
2392       } else {
2393         sum_rdc.rate += this_rdc.rate;
2394         sum_rdc.dist += this_rdc.dist;
2395         sum_rdc.rdcost += this_rdc.rdcost;
2396       }
2397     }
2398
2399     if (sum_rdc.rdcost < best_rdc.rdcost) {
2400       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2401       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
2402       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2403                               sum_rdc.rate, sum_rdc.dist);
2404       if (sum_rdc.rdcost < best_rdc.rdcost) {
2405         best_rdc = sum_rdc;
2406         pc_tree->partitioning = PARTITION_VERT;
2407       }
2408     }
2409     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2410   }
2411
2412   // TODO(jbb): This code added so that we avoid static analysis
2413   // warning related to the fact that best_rd isn't used after this
2414   // point.  This code should be refactored so that the duplicate
2415   // checks occur in some sub function and thus are used...
2416   (void) best_rd;
2417   *rd_cost = best_rdc;
2418
2419
2420   if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX &&
2421       pc_tree->index != 3) {
2422     int output_enabled = (bsize == BLOCK_64X64);
2423     encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
2424               bsize, pc_tree);
2425   }
2426
2427   if (bsize == BLOCK_64X64) {
2428     assert(tp_orig < *tp);
2429     assert(best_rdc.rate < INT_MAX);
2430     assert(best_rdc.dist < INT64_MAX);
2431   } else {
2432     assert(tp_orig == *tp);
2433   }
2434 }
2435
2436 static void encode_rd_sb_row(VP10_COMP *cpi,
2437                              ThreadData *td,
2438                              TileDataEnc *tile_data,
2439                              int mi_row,
2440                              TOKENEXTRA **tp) {
2441   VP10_COMMON *const cm = &cpi->common;
2442   TileInfo *const tile_info = &tile_data->tile_info;
2443   MACROBLOCK *const x = &td->mb;
2444   MACROBLOCKD *const xd = &x->e_mbd;
2445   SPEED_FEATURES *const sf = &cpi->sf;
2446   int mi_col;
2447
2448   // Initialize the left context for the new SB row
2449   memset(&xd->left_context, 0, sizeof(xd->left_context));
2450   memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
2451
2452   // Code each SB in the row
2453   for (mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
2454        mi_col += MI_BLOCK_SIZE) {
2455     const struct segmentation *const seg = &cm->seg;
2456     int dummy_rate;
2457     int64_t dummy_dist;
2458     RD_COST dummy_rdc;
2459     int i;
2460     int seg_skip = 0;
2461
2462     const int idx_str = cm->mi_stride * mi_row + mi_col;
2463     MODE_INFO **mi = cm->mi_grid_visible + idx_str;
2464
2465     if (sf->adaptive_pred_interp_filter) {
2466       for (i = 0; i < 64; ++i)
2467         td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
2468
2469       for (i = 0; i < 64; ++i) {
2470         td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
2471         td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
2472         td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
2473         td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
2474       }
2475     }
2476
2477     vp10_zero(x->pred_mv);
2478     td->pc_root->index = 0;
2479
2480     if (seg->enabled) {
2481       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
2482                                                  : cm->last_frame_seg_map;
2483       int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
2484       seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
2485     }
2486
2487     x->source_variance = UINT_MAX;
2488     if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
2489       const BLOCK_SIZE bsize =
2490           seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
2491       set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2492       set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
2493       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2494                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2495     } else if (cpi->partition_search_skippable_frame) {
2496       BLOCK_SIZE bsize;
2497       set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2498       bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col);
2499       set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
2500       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2501                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2502     } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
2503                cm->frame_type != KEY_FRAME) {
2504       choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
2505       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2506                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2507     } else {
2508       // If required set upper and lower partition size limits
2509       if (sf->auto_min_max_partition_size) {
2510         set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2511         rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
2512                                 &x->min_partition_size,
2513                                 &x->max_partition_size);
2514       }
2515       rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
2516                         &dummy_rdc, INT64_MAX, td->pc_root);
2517     }
2518   }
2519 }
2520
2521 static void init_encode_frame_mb_context(VP10_COMP *cpi) {
2522   MACROBLOCK *const x = &cpi->td.mb;
2523   VP10_COMMON *const cm = &cpi->common;
2524   MACROBLOCKD *const xd = &x->e_mbd;
2525   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2526
2527   // Copy data over into macro block data structures.
2528   vp10_setup_src_planes(x, cpi->Source, 0, 0);
2529
2530   vp10_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
2531
2532   // Note: this memset assumes above_context[0], [1] and [2]
2533   // are allocated as part of the same buffer.
2534   memset(xd->above_context[0], 0,
2535          sizeof(*xd->above_context[0]) *
2536          2 * aligned_mi_cols * MAX_MB_PLANE);
2537   memset(xd->above_seg_context, 0,
2538          sizeof(*xd->above_seg_context) * aligned_mi_cols);
2539 }
2540
2541 static int check_dual_ref_flags(VP10_COMP *cpi) {
2542   const int ref_flags = cpi->ref_frame_flags;
2543
2544   if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
2545     return 0;
2546   } else {
2547     return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG)
2548         + !!(ref_flags & VP9_ALT_FLAG)) >= 2;
2549   }
2550 }
2551
2552 static void reset_skip_tx_size(VP10_COMMON *cm, TX_SIZE max_tx_size) {
2553   int mi_row, mi_col;
2554   const int mis = cm->mi_stride;
2555   MODE_INFO **mi_ptr = cm->mi_grid_visible;
2556
2557   for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
2558     for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
2559       if (mi_ptr[mi_col]->mbmi.tx_size > max_tx_size)
2560         mi_ptr[mi_col]->mbmi.tx_size = max_tx_size;
2561     }
2562   }
2563 }
2564
2565 static MV_REFERENCE_FRAME get_frame_type(const VP10_COMP *cpi) {
2566   if (frame_is_intra_only(&cpi->common))
2567     return INTRA_FRAME;
2568   else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
2569     return ALTREF_FRAME;
2570   else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
2571     return GOLDEN_FRAME;
2572   else
2573     return LAST_FRAME;
2574 }
2575
2576 static TX_MODE select_tx_mode(const VP10_COMP *cpi, MACROBLOCKD *const xd) {
2577   if (xd->lossless)
2578     return ONLY_4X4;
2579   if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
2580     return ALLOW_32X32;
2581   else if (cpi->sf.tx_size_search_method == USE_FULL_RD||
2582            cpi->sf.tx_size_search_method == USE_TX_8X8)
2583     return TX_MODE_SELECT;
2584   else
2585     return cpi->common.tx_mode;
2586 }
2587
2588 void vp10_init_tile_data(VP10_COMP *cpi) {
2589   VP10_COMMON *const cm = &cpi->common;
2590   const int tile_cols = 1 << cm->log2_tile_cols;
2591   const int tile_rows = 1 << cm->log2_tile_rows;
2592   int tile_col, tile_row;
2593   TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
2594   int tile_tok = 0;
2595
2596   if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
2597     if (cpi->tile_data != NULL)
2598       vpx_free(cpi->tile_data);
2599     CHECK_MEM_ERROR(cm, cpi->tile_data,
2600         vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
2601     cpi->allocated_tiles = tile_cols * tile_rows;
2602
2603     for (tile_row = 0; tile_row < tile_rows; ++tile_row)
2604       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
2605         TileDataEnc *tile_data =
2606             &cpi->tile_data[tile_row * tile_cols + tile_col];
2607         int i, j;
2608         for (i = 0; i < BLOCK_SIZES; ++i) {
2609           for (j = 0; j < MAX_MODES; ++j) {
2610             tile_data->thresh_freq_fact[i][j] = 32;
2611             tile_data->mode_map[i][j] = j;
2612           }
2613         }
2614       }
2615   }
2616
2617   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
2618     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
2619       TileInfo *tile_info =
2620           &cpi->tile_data[tile_row * tile_cols + tile_col].tile_info;
2621       vp10_tile_init(tile_info, cm, tile_row, tile_col);
2622
2623       cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
2624       pre_tok = cpi->tile_tok[tile_row][tile_col];
2625       tile_tok = allocated_tokens(*tile_info);
2626     }
2627   }
2628 }
2629
2630 void vp10_encode_tile(VP10_COMP *cpi, ThreadData *td,
2631                      int tile_row, int tile_col) {
2632   VP10_COMMON *const cm = &cpi->common;
2633   const int tile_cols = 1 << cm->log2_tile_cols;
2634   TileDataEnc *this_tile =
2635       &cpi->tile_data[tile_row * tile_cols + tile_col];
2636   const TileInfo * const tile_info = &this_tile->tile_info;
2637   TOKENEXTRA *tok = cpi->tile_tok[tile_row][tile_col];
2638   int mi_row;
2639
2640   for (mi_row = tile_info->mi_row_start; mi_row < tile_info->mi_row_end;
2641        mi_row += MI_BLOCK_SIZE) {
2642     encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
2643   }
2644   cpi->tok_count[tile_row][tile_col] =
2645       (unsigned int)(tok - cpi->tile_tok[tile_row][tile_col]);
2646   assert(tok - cpi->tile_tok[tile_row][tile_col] <=
2647       allocated_tokens(*tile_info));
2648 }
2649
2650 static void encode_tiles(VP10_COMP *cpi) {
2651   VP10_COMMON *const cm = &cpi->common;
2652   const int tile_cols = 1 << cm->log2_tile_cols;
2653   const int tile_rows = 1 << cm->log2_tile_rows;
2654   int tile_col, tile_row;
2655
2656   vp10_init_tile_data(cpi);
2657
2658   for (tile_row = 0; tile_row < tile_rows; ++tile_row)
2659     for (tile_col = 0; tile_col < tile_cols; ++tile_col)
2660       vp10_encode_tile(cpi, &cpi->td, tile_row, tile_col);
2661 }
2662
2663 #if CONFIG_FP_MB_STATS
2664 static int input_fpmb_stats(FIRSTPASS_MB_STATS *firstpass_mb_stats,
2665                             VP10_COMMON *cm, uint8_t **this_frame_mb_stats) {
2666   uint8_t *mb_stats_in = firstpass_mb_stats->mb_stats_start +
2667       cm->current_video_frame * cm->MBs * sizeof(uint8_t);
2668
2669   if (mb_stats_in > firstpass_mb_stats->mb_stats_end)
2670     return EOF;
2671
2672   *this_frame_mb_stats = mb_stats_in;
2673
2674   return 1;
2675 }
2676 #endif
2677
2678 static void encode_frame_internal(VP10_COMP *cpi) {
2679   ThreadData *const td = &cpi->td;
2680   MACROBLOCK *const x = &td->mb;
2681   VP10_COMMON *const cm = &cpi->common;
2682   MACROBLOCKD *const xd = &x->e_mbd;
2683   RD_COUNTS *const rdc = &cpi->td.rd_counts;
2684
2685   xd->mi = cm->mi_grid_visible;
2686   xd->mi[0] = cm->mi;
2687
2688   vp10_zero(*td->counts);
2689   vp10_zero(rdc->coef_counts);
2690   vp10_zero(rdc->comp_pred_diff);
2691   vp10_zero(rdc->filter_diff);
2692
2693   xd->lossless = cm->base_qindex == 0 &&
2694                  cm->y_dc_delta_q == 0 &&
2695                  cm->uv_dc_delta_q == 0 &&
2696                  cm->uv_ac_delta_q == 0;
2697
2698 #if CONFIG_VP9_HIGHBITDEPTH
2699   if (cm->use_highbitdepth)
2700     x->fwd_txm4x4 = xd->lossless ? vp10_highbd_fwht4x4 : vpx_highbd_fdct4x4;
2701   else
2702     x->fwd_txm4x4 = xd->lossless ? vp10_fwht4x4 : vpx_fdct4x4;
2703   x->highbd_itxm_add = xd->lossless ? vp10_highbd_iwht4x4_add :
2704                                       vp10_highbd_idct4x4_add;
2705 #else
2706   x->fwd_txm4x4 = xd->lossless ? vp10_fwht4x4 : vpx_fdct4x4;
2707 #endif  // CONFIG_VP9_HIGHBITDEPTH
2708   x->itxm_add = xd->lossless ? vp10_iwht4x4_add : vp10_idct4x4_add;
2709
2710   if (xd->lossless)
2711     x->optimize = 0;
2712
2713   cm->tx_mode = select_tx_mode(cpi, xd);
2714
2715   vp10_frame_init_quantizer(cpi);
2716
2717   vp10_initialize_rd_consts(cpi);
2718   vp10_initialize_me_consts(cpi, x, cm->base_qindex);
2719   init_encode_frame_mb_context(cpi);
2720   cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2721                            cm->width == cm->last_width &&
2722                            cm->height == cm->last_height &&
2723                            !cm->intra_only &&
2724                            cm->last_show_frame;
2725   // Special case: set prev_mi to NULL when the previous mode info
2726   // context cannot be used.
2727   cm->prev_mi = cm->use_prev_frame_mvs ?
2728                 cm->prev_mip + cm->mi_stride + 1 : NULL;
2729
2730   x->quant_fp = cpi->sf.use_quant_fp;
2731   vp10_zero(x->skip_txfm);
2732
2733   {
2734     struct vpx_usec_timer emr_timer;
2735     vpx_usec_timer_start(&emr_timer);
2736
2737 #if CONFIG_FP_MB_STATS
2738   if (cpi->use_fp_mb_stats) {
2739     input_fpmb_stats(&cpi->twopass.firstpass_mb_stats, cm,
2740                      &cpi->twopass.this_frame_mb_stats);
2741   }
2742 #endif
2743
2744     // If allowed, encoding tiles in parallel with one thread handling one tile.
2745     if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
2746       vp10_encode_tiles_mt(cpi);
2747     else
2748       encode_tiles(cpi);
2749
2750     vpx_usec_timer_mark(&emr_timer);
2751     cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
2752   }
2753
2754 #if 0
2755   // Keep record of the total distortion this time around for future use
2756   cpi->last_frame_distortion = cpi->frame_distortion;
2757 #endif
2758 }
2759
2760 static INTERP_FILTER get_interp_filter(
2761     const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
2762   if (!is_alt_ref &&
2763       threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
2764       threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
2765       threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
2766     return EIGHTTAP_SMOOTH;
2767   } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
2768              threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
2769     return EIGHTTAP_SHARP;
2770   } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
2771     return EIGHTTAP;
2772   } else {
2773     return SWITCHABLE;
2774   }
2775 }
2776
2777 void vp10_encode_frame(VP10_COMP *cpi) {
2778   VP10_COMMON *const cm = &cpi->common;
2779
2780   // In the longer term the encoder should be generalized to match the
2781   // decoder such that we allow compound where one of the 3 buffers has a
2782   // different sign bias and that buffer is then the fixed ref. However, this
2783   // requires further work in the rd loop. For now the only supported encoder
2784   // side behavior is where the ALT ref buffer has opposite sign bias to
2785   // the other two.
2786   if (!frame_is_intra_only(cm)) {
2787     if ((cm->ref_frame_sign_bias[ALTREF_FRAME] ==
2788              cm->ref_frame_sign_bias[GOLDEN_FRAME]) ||
2789         (cm->ref_frame_sign_bias[ALTREF_FRAME] ==
2790              cm->ref_frame_sign_bias[LAST_FRAME])) {
2791       cpi->allow_comp_inter_inter = 0;
2792     } else {
2793       cpi->allow_comp_inter_inter = 1;
2794       cm->comp_fixed_ref = ALTREF_FRAME;
2795       cm->comp_var_ref[0] = LAST_FRAME;
2796       cm->comp_var_ref[1] = GOLDEN_FRAME;
2797     }
2798   }
2799
2800   if (cpi->sf.frame_parameter_update) {
2801     int i;
2802     RD_OPT *const rd_opt = &cpi->rd;
2803     FRAME_COUNTS *counts = cpi->td.counts;
2804     RD_COUNTS *const rdc = &cpi->td.rd_counts;
2805
2806     // This code does a single RD pass over the whole frame assuming
2807     // either compound, single or hybrid prediction as per whatever has
2808     // worked best for that type of frame in the past.
2809     // It also predicts whether another coding mode would have worked
2810     // better that this coding mode. If that is the case, it remembers
2811     // that for subsequent frames.
2812     // It does the same analysis for transform size selection also.
2813     const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
2814     int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
2815     int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
2816     const int is_alt_ref = frame_type == ALTREF_FRAME;
2817
2818     /* prediction (compound, single or hybrid) mode selection */
2819     if (is_alt_ref || !cpi->allow_comp_inter_inter)
2820       cm->reference_mode = SINGLE_REFERENCE;
2821     else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
2822              mode_thrs[COMPOUND_REFERENCE] >
2823                  mode_thrs[REFERENCE_MODE_SELECT] &&
2824              check_dual_ref_flags(cpi) &&
2825              cpi->static_mb_pct == 100)
2826       cm->reference_mode = COMPOUND_REFERENCE;
2827     else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
2828       cm->reference_mode = SINGLE_REFERENCE;
2829     else
2830       cm->reference_mode = REFERENCE_MODE_SELECT;
2831
2832     if (cm->interp_filter == SWITCHABLE)
2833       cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
2834
2835     encode_frame_internal(cpi);
2836
2837     for (i = 0; i < REFERENCE_MODES; ++i)
2838       mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
2839
2840     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
2841       filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
2842
2843     if (cm->reference_mode == REFERENCE_MODE_SELECT) {
2844       int single_count_zero = 0;
2845       int comp_count_zero = 0;
2846
2847       for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
2848         single_count_zero += counts->comp_inter[i][0];
2849         comp_count_zero += counts->comp_inter[i][1];
2850       }
2851
2852       if (comp_count_zero == 0) {
2853         cm->reference_mode = SINGLE_REFERENCE;
2854         vp10_zero(counts->comp_inter);
2855       } else if (single_count_zero == 0) {
2856         cm->reference_mode = COMPOUND_REFERENCE;
2857         vp10_zero(counts->comp_inter);
2858       }
2859     }
2860
2861     if (cm->tx_mode == TX_MODE_SELECT) {
2862       int count4x4 = 0;
2863       int count8x8_lp = 0, count8x8_8x8p = 0;
2864       int count16x16_16x16p = 0, count16x16_lp = 0;
2865       int count32x32 = 0;
2866
2867       for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
2868         count4x4 += counts->tx.p32x32[i][TX_4X4];
2869         count4x4 += counts->tx.p16x16[i][TX_4X4];
2870         count4x4 += counts->tx.p8x8[i][TX_4X4];
2871
2872         count8x8_lp += counts->tx.p32x32[i][TX_8X8];
2873         count8x8_lp += counts->tx.p16x16[i][TX_8X8];
2874         count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
2875
2876         count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
2877         count16x16_lp += counts->tx.p32x32[i][TX_16X16];
2878         count32x32 += counts->tx.p32x32[i][TX_32X32];
2879       }
2880       if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
2881           count32x32 == 0) {
2882         cm->tx_mode = ALLOW_8X8;
2883         reset_skip_tx_size(cm, TX_8X8);
2884       } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
2885                  count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
2886         cm->tx_mode = ONLY_4X4;
2887         reset_skip_tx_size(cm, TX_4X4);
2888       } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
2889         cm->tx_mode = ALLOW_32X32;
2890       } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
2891         cm->tx_mode = ALLOW_16X16;
2892         reset_skip_tx_size(cm, TX_16X16);
2893       }
2894     }
2895   } else {
2896     cm->reference_mode = SINGLE_REFERENCE;
2897     encode_frame_internal(cpi);
2898   }
2899 }
2900
2901 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
2902   const PREDICTION_MODE y_mode = mi->mbmi.mode;
2903   const PREDICTION_MODE uv_mode = mi->mbmi.uv_mode;
2904   const BLOCK_SIZE bsize = mi->mbmi.sb_type;
2905
2906   if (bsize < BLOCK_8X8) {
2907     int idx, idy;
2908     const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2909     const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2910     for (idy = 0; idy < 2; idy += num_4x4_h)
2911       for (idx = 0; idx < 2; idx += num_4x4_w)
2912         ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
2913   } else {
2914     ++counts->y_mode[size_group_lookup[bsize]][y_mode];
2915   }
2916
2917   ++counts->uv_mode[y_mode][uv_mode];
2918 }
2919
2920 static void encode_superblock(VP10_COMP *cpi, ThreadData *td,
2921                               TOKENEXTRA **t, int output_enabled,
2922                               int mi_row, int mi_col, BLOCK_SIZE bsize,
2923                               PICK_MODE_CONTEXT *ctx) {
2924   VP10_COMMON *const cm = &cpi->common;
2925   MACROBLOCK *const x = &td->mb;
2926   MACROBLOCKD *const xd = &x->e_mbd;
2927   MODE_INFO **mi_8x8 = xd->mi;
2928   MODE_INFO *mi = mi_8x8[0];
2929   MB_MODE_INFO *mbmi = &mi->mbmi;
2930   const int seg_skip = segfeature_active(&cm->seg, mbmi->segment_id,
2931                                          SEG_LVL_SKIP);
2932   const int mis = cm->mi_stride;
2933   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
2934   const int mi_height = num_8x8_blocks_high_lookup[bsize];
2935
2936   x->skip_recode = !x->select_tx_size && mbmi->sb_type >= BLOCK_8X8 &&
2937                    cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
2938                    cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
2939                    cpi->sf.allow_skip_recode;
2940
2941   if (!x->skip_recode)
2942     memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
2943
2944   x->skip_optimize = ctx->is_coded;
2945   ctx->is_coded = 1;
2946   x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
2947
2948   if (!is_inter_block(mbmi)) {
2949     int plane;
2950     mbmi->skip = 1;
2951     for (plane = 0; plane < MAX_MB_PLANE; ++plane)
2952       vp10_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane);
2953     if (output_enabled)
2954       sum_intra_stats(td->counts, mi);
2955     vp10_tokenize_sb(cpi, td, t, !output_enabled, VPXMAX(bsize, BLOCK_8X8));
2956   } else {
2957     int ref;
2958     const int is_compound = has_second_ref(mbmi);
2959     set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
2960     for (ref = 0; ref < 1 + is_compound; ++ref) {
2961       YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi,
2962                                                      mbmi->ref_frame[ref]);
2963       assert(cfg != NULL);
2964       vp10_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
2965                            &xd->block_refs[ref]->sf);
2966     }
2967     if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
2968       vp10_build_inter_predictors_sby(xd, mi_row, mi_col,
2969                                       VPXMAX(bsize, BLOCK_8X8));
2970
2971     vp10_build_inter_predictors_sbuv(xd, mi_row, mi_col,
2972                                      VPXMAX(bsize, BLOCK_8X8));
2973
2974     vp10_encode_sb(x, VPXMAX(bsize, BLOCK_8X8));
2975     vp10_tokenize_sb(cpi, td, t, !output_enabled, VPXMAX(bsize, BLOCK_8X8));
2976   }
2977
2978   if (output_enabled) {
2979     if (cm->tx_mode == TX_MODE_SELECT &&
2980         mbmi->sb_type >= BLOCK_8X8  &&
2981         !(is_inter_block(mbmi) && (mbmi->skip || seg_skip))) {
2982       ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
2983                       &td->counts->tx)[mbmi->tx_size];
2984     } else {
2985       int x, y;
2986       TX_SIZE tx_size;
2987       // The new intra coding scheme requires no change of transform size
2988       if (is_inter_block(&mi->mbmi)) {
2989         tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
2990                          max_txsize_lookup[bsize]);
2991       } else {
2992         tx_size = (bsize >= BLOCK_8X8) ? mbmi->tx_size : TX_4X4;
2993       }
2994
2995       for (y = 0; y < mi_height; y++)
2996         for (x = 0; x < mi_width; x++)
2997           if (mi_col + x < cm->mi_cols && mi_row + y < cm->mi_rows)
2998             mi_8x8[mis * y + x]->mbmi.tx_size = tx_size;
2999     }
3000     ++td->counts->tx.tx_totals[mbmi->tx_size];
3001     ++td->counts->tx.tx_totals[get_uv_tx_size(mbmi, &xd->plane[1])];
3002   }
3003 }