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