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