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