]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_encodeframe.c
Attempt to fix speed 4
[libvpx] / vp9 / encoder / vp9_encodeframe.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <limits.h>
12 #include <math.h>
13 #include <stdio.h>
14
15 #include "./vp9_rtcd.h"
16 #include "./vpx_config.h"
17
18 #include "vpx_ports/vpx_timer.h"
19
20 #include "vp9/common/vp9_common.h"
21 #include "vp9/common/vp9_entropy.h"
22 #include "vp9/common/vp9_entropymode.h"
23 #include "vp9/common/vp9_extend.h"
24 #include "vp9/common/vp9_findnearmv.h"
25 #include "vp9/common/vp9_mvref_common.h"
26 #include "vp9/common/vp9_pred_common.h"
27 #include "vp9/common/vp9_quant_common.h"
28 #include "vp9/common/vp9_reconintra.h"
29 #include "vp9/common/vp9_reconinter.h"
30 #include "vp9/common/vp9_seg_common.h"
31 #include "vp9/common/vp9_tile_common.h"
32
33 #include "vp9/encoder/vp9_encodeframe.h"
34 #include "vp9/encoder/vp9_encodeintra.h"
35 #include "vp9/encoder/vp9_encodemb.h"
36 #include "vp9/encoder/vp9_encodemv.h"
37 #include "vp9/encoder/vp9_onyx_int.h"
38 #include "vp9/encoder/vp9_rdopt.h"
39 #include "vp9/encoder/vp9_segmentation.h"
40 #include "vp9/encoder/vp9_tokenize.h"
41
42 #define DBG_PRNT_SEGMAP 0
43
44 // #define ENC_DEBUG
45 #ifdef ENC_DEBUG
46 int enc_debug = 0;
47 #endif
48
49 static void encode_superblock(VP9_COMP *cpi, TOKENEXTRA **t, int output_enabled,
50                               int mi_row, int mi_col, BLOCK_SIZE bsize);
51
52 static void adjust_act_zbin(VP9_COMP *cpi, MACROBLOCK *x);
53
54 /* activity_avg must be positive, or flat regions could get a zero weight
55  *  (infinite lambda), which confounds analysis.
56  * This also avoids the need for divide by zero checks in
57  *  vp9_activity_masking().
58  */
59 #define ACTIVITY_AVG_MIN (64)
60
61 /* Motion vector component magnitude threshold for defining fast motion. */
62 #define FAST_MOTION_MV_THRESH (24)
63
64 /* This is used as a reference when computing the source variance for the
65  *  purposes of activity masking.
66  * Eventually this should be replaced by custom no-reference routines,
67  *  which will be faster.
68  */
69 static const uint8_t VP9_VAR_OFFS[64] = {
70   128, 128, 128, 128, 128, 128, 128, 128,
71   128, 128, 128, 128, 128, 128, 128, 128,
72   128, 128, 128, 128, 128, 128, 128, 128,
73   128, 128, 128, 128, 128, 128, 128, 128,
74   128, 128, 128, 128, 128, 128, 128, 128,
75   128, 128, 128, 128, 128, 128, 128, 128,
76   128, 128, 128, 128, 128, 128, 128, 128,
77   128, 128, 128, 128, 128, 128, 128, 128
78 };
79
80 static unsigned int get_sby_perpixel_variance(VP9_COMP *cpi, MACROBLOCK *x,
81                                               BLOCK_SIZE bs) {
82   unsigned int var, sse;
83   var = cpi->fn_ptr[bs].vf(x->plane[0].src.buf,
84                            x->plane[0].src.stride,
85                            VP9_VAR_OFFS, 0, &sse);
86   return (var + (1 << (num_pels_log2_lookup[bs] - 1))) >>
87       num_pels_log2_lookup[bs];
88 }
89
90 // Original activity measure from Tim T's code.
91 static unsigned int tt_activity_measure(MACROBLOCK *x) {
92   unsigned int act;
93   unsigned int sse;
94   /* TODO: This could also be done over smaller areas (8x8), but that would
95    *  require extensive changes elsewhere, as lambda is assumed to be fixed
96    *  over an entire MB in most of the code.
97    * Another option is to compute four 8x8 variances, and pick a single
98    *  lambda using a non-linear combination (e.g., the smallest, or second
99    *  smallest, etc.).
100    */
101   act = vp9_variance16x16(x->plane[0].src.buf, x->plane[0].src.stride,
102                           VP9_VAR_OFFS, 0, &sse);
103   act <<= 4;
104
105   /* If the region is flat, lower the activity some more. */
106   if (act < 8 << 12)
107     act = act < 5 << 12 ? act : 5 << 12;
108
109   return act;
110 }
111
112 // Stub for alternative experimental activity measures.
113 static unsigned int alt_activity_measure(MACROBLOCK *x, int use_dc_pred) {
114   return vp9_encode_intra(x, use_dc_pred);
115 }
116 DECLARE_ALIGNED(16, static const uint8_t, vp9_64x64_zeros[64*64]) = {0};
117
118 // Measure the activity of the current macroblock
119 // What we measure here is TBD so abstracted to this function
120 #define ALT_ACT_MEASURE 1
121 static unsigned int mb_activity_measure(MACROBLOCK *x, int mb_row, int mb_col) {
122   unsigned int mb_activity;
123
124   if (ALT_ACT_MEASURE) {
125     int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
126
127     // Or use and alternative.
128     mb_activity = alt_activity_measure(x, use_dc_pred);
129   } else {
130     // Original activity measure from Tim T's code.
131     mb_activity = tt_activity_measure(x);
132   }
133
134   if (mb_activity < ACTIVITY_AVG_MIN)
135     mb_activity = ACTIVITY_AVG_MIN;
136
137   return mb_activity;
138 }
139
140 // Calculate an "average" mb activity value for the frame
141 #define ACT_MEDIAN 0
142 static void calc_av_activity(VP9_COMP *cpi, int64_t activity_sum) {
143 #if ACT_MEDIAN
144   // Find median: Simple n^2 algorithm for experimentation
145   {
146     unsigned int median;
147     unsigned int i, j;
148     unsigned int *sortlist;
149     unsigned int tmp;
150
151     // Create a list to sort to
152     CHECK_MEM_ERROR(&cpi->common, sortlist, vpx_calloc(sizeof(unsigned int),
153                     cpi->common.MBs));
154
155     // Copy map to sort list
156     vpx_memcpy(sortlist, cpi->mb_activity_map,
157         sizeof(unsigned int) * cpi->common.MBs);
158
159     // Ripple each value down to its correct position
160     for (i = 1; i < cpi->common.MBs; i ++) {
161       for (j = i; j > 0; j --) {
162         if (sortlist[j] < sortlist[j - 1]) {
163           // Swap values
164           tmp = sortlist[j - 1];
165           sortlist[j - 1] = sortlist[j];
166           sortlist[j] = tmp;
167         } else
168         break;
169       }
170     }
171
172     // Even number MBs so estimate median as mean of two either side.
173     median = (1 + sortlist[cpi->common.MBs >> 1] +
174         sortlist[(cpi->common.MBs >> 1) + 1]) >> 1;
175
176     cpi->activity_avg = median;
177
178     vpx_free(sortlist);
179   }
180 #else
181   // Simple mean for now
182   cpi->activity_avg = (unsigned int) (activity_sum / cpi->common.MBs);
183 #endif  // ACT_MEDIAN
184
185   if (cpi->activity_avg < ACTIVITY_AVG_MIN)
186     cpi->activity_avg = ACTIVITY_AVG_MIN;
187
188   // Experimental code: return fixed value normalized for several clips
189   if (ALT_ACT_MEASURE)
190     cpi->activity_avg = 100000;
191 }
192
193 #define USE_ACT_INDEX   0
194 #define OUTPUT_NORM_ACT_STATS   0
195
196 #if USE_ACT_INDEX
197 // Calculate an activity index for each mb
198 static void calc_activity_index(VP9_COMP *cpi, MACROBLOCK *x) {
199   VP9_COMMON *const cm = &cpi->common;
200   int mb_row, mb_col;
201
202   int64_t act;
203   int64_t a;
204   int64_t b;
205
206 #if OUTPUT_NORM_ACT_STATS
207   FILE *f = fopen("norm_act.stt", "a");
208   fprintf(f, "\n%12d\n", cpi->activity_avg);
209 #endif
210
211   // Reset pointers to start of activity map
212   x->mb_activity_ptr = cpi->mb_activity_map;
213
214   // Calculate normalized mb activity number.
215   for (mb_row = 0; mb_row < cm->mb_rows; mb_row++) {
216     // for each macroblock col in image
217     for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
218       // Read activity from the map
219       act = *(x->mb_activity_ptr);
220
221       // Calculate a normalized activity number
222       a = act + 4 * cpi->activity_avg;
223       b = 4 * act + cpi->activity_avg;
224
225       if (b >= a)
226       *(x->activity_ptr) = (int)((b + (a >> 1)) / a) - 1;
227       else
228       *(x->activity_ptr) = 1 - (int)((a + (b >> 1)) / b);
229
230 #if OUTPUT_NORM_ACT_STATS
231       fprintf(f, " %6d", *(x->mb_activity_ptr));
232 #endif
233       // Increment activity map pointers
234       x->mb_activity_ptr++;
235     }
236
237 #if OUTPUT_NORM_ACT_STATS
238     fprintf(f, "\n");
239 #endif
240
241   }
242
243 #if OUTPUT_NORM_ACT_STATS
244   fclose(f);
245 #endif
246
247 }
248 #endif  // USE_ACT_INDEX
249
250 // Loop through all MBs. Note activity of each, average activity and
251 // calculate a normalized activity for each
252 static void build_activity_map(VP9_COMP *cpi) {
253   MACROBLOCK * const x = &cpi->mb;
254   MACROBLOCKD *xd = &x->e_mbd;
255   VP9_COMMON * const cm = &cpi->common;
256
257 #if ALT_ACT_MEASURE
258   YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
259   int recon_yoffset;
260   int recon_y_stride = new_yv12->y_stride;
261 #endif
262
263   int mb_row, mb_col;
264   unsigned int mb_activity;
265   int64_t activity_sum = 0;
266
267   x->mb_activity_ptr = cpi->mb_activity_map;
268
269   // for each macroblock row in image
270   for (mb_row = 0; mb_row < cm->mb_rows; mb_row++) {
271 #if ALT_ACT_MEASURE
272     // reset above block coeffs
273     xd->up_available = (mb_row != 0);
274     recon_yoffset = (mb_row * recon_y_stride * 16);
275 #endif
276     // for each macroblock col in image
277     for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
278 #if ALT_ACT_MEASURE
279       xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
280       xd->left_available = (mb_col != 0);
281       recon_yoffset += 16;
282 #endif
283
284       // measure activity
285       mb_activity = mb_activity_measure(x, mb_row, mb_col);
286
287       // Keep frame sum
288       activity_sum += mb_activity;
289
290       // Store MB level activity details.
291       *x->mb_activity_ptr = mb_activity;
292
293       // Increment activity map pointer
294       x->mb_activity_ptr++;
295
296       // adjust to the next column of source macroblocks
297       x->plane[0].src.buf += 16;
298     }
299
300     // adjust to the next row of mbs
301     x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
302   }
303
304   // Calculate an "average" MB activity
305   calc_av_activity(cpi, activity_sum);
306
307 #if USE_ACT_INDEX
308   // Calculate an activity index number of each mb
309   calc_activity_index(cpi, x);
310 #endif
311
312 }
313
314 // Macroblock activity masking
315 void vp9_activity_masking(VP9_COMP *cpi, MACROBLOCK *x) {
316 #if USE_ACT_INDEX
317   x->rdmult += *(x->mb_activity_ptr) * (x->rdmult >> 2);
318   x->errorperbit = x->rdmult * 100 / (110 * x->rddiv);
319   x->errorperbit += (x->errorperbit == 0);
320 #else
321   int64_t a;
322   int64_t b;
323   int64_t act = *(x->mb_activity_ptr);
324
325   // Apply the masking to the RD multiplier.
326   a = act + (2 * cpi->activity_avg);
327   b = (2 * act) + cpi->activity_avg;
328
329   x->rdmult = (unsigned int) (((int64_t) x->rdmult * b + (a >> 1)) / a);
330   x->errorperbit = x->rdmult * 100 / (110 * x->rddiv);
331   x->errorperbit += (x->errorperbit == 0);
332 #endif
333
334   // Activity based Zbin adjustment
335   adjust_act_zbin(cpi, x);
336 }
337
338 static void update_state(VP9_COMP *cpi, PICK_MODE_CONTEXT *ctx,
339                          BLOCK_SIZE bsize, int output_enabled) {
340   int i, x_idx, y;
341   VP9_COMMON *const cm = &cpi->common;
342   MACROBLOCK *const x = &cpi->mb;
343   MACROBLOCKD *const xd = &x->e_mbd;
344   MODE_INFO *mi = &ctx->mic;
345   MB_MODE_INFO *const mbmi = &xd->mode_info_context->mbmi;
346
347   int mb_mode_index = ctx->best_mode_index;
348   const int mis = cm->mode_info_stride;
349   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
350   const int mi_height = num_8x8_blocks_high_lookup[bsize];
351
352   assert(mi->mbmi.mode < MB_MODE_COUNT);
353   assert(mb_mode_index < MAX_MODES);
354   assert(mi->mbmi.ref_frame[0] < MAX_REF_FRAMES);
355   assert(mi->mbmi.ref_frame[1] < MAX_REF_FRAMES);
356   assert(mi->mbmi.sb_type == bsize);
357
358   // Restore the coding context of the MB to that that was in place
359   // when the mode was picked for it
360   for (y = 0; y < mi_height; y++)
361     for (x_idx = 0; x_idx < mi_width; x_idx++)
362       if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx
363           && (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y)
364         xd->mode_info_context[x_idx + y * mis] = *mi;
365
366   // FIXME(rbultje) I'm pretty sure this should go to the end of this block
367   // (i.e. after the output_enabled)
368   if (bsize < BLOCK_32X32) {
369     if (bsize < BLOCK_16X16)
370       ctx->tx_rd_diff[ALLOW_16X16] = ctx->tx_rd_diff[ALLOW_8X8];
371     ctx->tx_rd_diff[ALLOW_32X32] = ctx->tx_rd_diff[ALLOW_16X16];
372   }
373
374   if (is_inter_block(mbmi) && mbmi->sb_type < BLOCK_8X8) {
375     *x->partition_info = ctx->partition_info;
376     mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
377     mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
378   }
379
380   x->skip = ctx->skip;
381   if (!output_enabled)
382     return;
383
384   if (!vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
385     for (i = 0; i < TX_MODES; i++)
386       cpi->rd_tx_select_diff[i] += ctx->tx_rd_diff[i];
387   }
388
389   if (cm->frame_type == KEY_FRAME) {
390     // Restore the coding modes to that held in the coding context
391     // if (mb_mode == I4X4_PRED)
392     //    for (i = 0; i < 16; i++)
393     //    {
394     //        xd->block[i].bmi.as_mode =
395     //                          xd->mode_info_context->bmi[i].as_mode;
396     //        assert(xd->mode_info_context->bmi[i].as_mode < MB_MODE_COUNT);
397     //    }
398 #if CONFIG_INTERNAL_STATS
399     static const int kf_mode_index[] = {
400       THR_DC /*DC_PRED*/,
401       THR_V_PRED /*V_PRED*/,
402       THR_H_PRED /*H_PRED*/,
403       THR_D45_PRED /*D45_PRED*/,
404       THR_D135_PRED /*D135_PRED*/,
405       THR_D117_PRED /*D117_PRED*/,
406       THR_D153_PRED /*D153_PRED*/,
407       THR_D207_PRED /*D207_PRED*/,
408       THR_D63_PRED /*D63_PRED*/,
409       THR_TM /*TM_PRED*/,
410       THR_B_PRED /*I4X4_PRED*/,
411     };
412     cpi->mode_chosen_counts[kf_mode_index[mi->mbmi.mode]]++;
413 #endif
414   } else {
415     // Note how often each mode chosen as best
416     cpi->mode_chosen_counts[mb_mode_index]++;
417     if (is_inter_block(mbmi)
418         && (mbmi->sb_type < BLOCK_8X8 || mbmi->mode == NEWMV)) {
419       int_mv best_mv, best_second_mv;
420       const MV_REFERENCE_FRAME rf1 = mbmi->ref_frame[0];
421       const MV_REFERENCE_FRAME rf2 = mbmi->ref_frame[1];
422       best_mv.as_int = ctx->best_ref_mv.as_int;
423       best_second_mv.as_int = ctx->second_best_ref_mv.as_int;
424       if (mbmi->mode == NEWMV) {
425         best_mv.as_int = mbmi->ref_mvs[rf1][0].as_int;
426         best_second_mv.as_int = mbmi->ref_mvs[rf2][0].as_int;
427       }
428       mbmi->best_mv.as_int = best_mv.as_int;
429       mbmi->best_second_mv.as_int = best_second_mv.as_int;
430       vp9_update_nmv_count(cpi, x, &best_mv, &best_second_mv);
431     }
432
433     if (bsize > BLOCK_8X8 && mbmi->mode == NEWMV) {
434       int i, j;
435       for (j = 0; j < mi_height; ++j)
436         for (i = 0; i < mi_width; ++i)
437           if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > i
438               && (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > j)
439             xd->mode_info_context[mis * j + i].mbmi = *mbmi;
440     }
441
442     if (cm->mcomp_filter_type == SWITCHABLE && is_inter_mode(mbmi->mode)) {
443       const int ctx = vp9_get_pred_context_switchable_interp(xd);
444       ++cm->counts.switchable_interp[ctx][mbmi->interp_filter];
445     }
446
447     cpi->rd_comp_pred_diff[SINGLE_PREDICTION_ONLY] += ctx->single_pred_diff;
448     cpi->rd_comp_pred_diff[COMP_PREDICTION_ONLY] += ctx->comp_pred_diff;
449     cpi->rd_comp_pred_diff[HYBRID_PREDICTION] += ctx->hybrid_pred_diff;
450
451     for (i = 0; i <= SWITCHABLE_FILTERS; i++)
452       cpi->rd_filter_diff[i] += ctx->best_filter_diff[i];
453   }
454 }
455
456 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
457                           int mb_row, int mb_col) {
458   uint8_t *buffers[4] = {src->y_buffer, src->u_buffer, src->v_buffer, src
459       ->alpha_buffer};
460   int strides[4] = {src->y_stride, src->uv_stride, src->uv_stride, src
461       ->alpha_stride};
462   int i;
463
464   for (i = 0; i < MAX_MB_PLANE; i++) {
465     setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mb_row, mb_col,
466                      NULL, x->e_mbd.plane[i].subsampling_x,
467                      x->e_mbd.plane[i].subsampling_y);
468   }
469 }
470
471 static void set_offsets(VP9_COMP *cpi, int mi_row, int mi_col,
472                         BLOCK_SIZE bsize) {
473   MACROBLOCK *const x = &cpi->mb;
474   VP9_COMMON *const cm = &cpi->common;
475   MACROBLOCKD *const xd = &x->e_mbd;
476   MB_MODE_INFO *mbmi;
477   const int dst_fb_idx = cm->new_fb_idx;
478   const int idx_str = xd->mode_info_stride * mi_row + mi_col;
479   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
480   const int mi_height = num_8x8_blocks_high_lookup[bsize];
481   const int mb_row = mi_row >> 1;
482   const int mb_col = mi_col >> 1;
483   const int idx_map = mb_row * cm->mb_cols + mb_col;
484   const struct segmentation *const seg = &cm->seg;
485
486   set_skip_context(cm, xd, mi_row, mi_col);
487   set_partition_seg_context(cm, xd, mi_row, mi_col);
488
489   // Activity map pointer
490   x->mb_activity_ptr = &cpi->mb_activity_map[idx_map];
491   x->active_ptr = cpi->active_map + idx_map;
492
493   /* pointers to mode info contexts */
494   x->partition_info = x->pi + idx_str;
495   xd->mode_info_context = cm->mi + idx_str;
496   mbmi = &xd->mode_info_context->mbmi;
497   // Special case: if prev_mi is NULL, the previous mode info context
498   // cannot be used.
499   xd->prev_mode_info_context = cm->prev_mi ? cm->prev_mi + idx_str : NULL;
500
501   // Set up destination pointers
502   setup_dst_planes(xd, &cm->yv12_fb[dst_fb_idx], mi_row, mi_col);
503
504   // Set up limit values for MV components
505   // mv beyond the range do not produce new/different prediction block
506   x->mv_row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
507   x->mv_col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
508   x->mv_row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
509   x->mv_col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
510
511   // Set up distance of MB to edge of frame in 1/8th pel units
512   assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
513   set_mi_row_col(cm, xd, mi_row, mi_height, mi_col, mi_width);
514
515   /* set up source buffers */
516   vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
517
518   /* R/D setup */
519   x->rddiv = cpi->RDDIV;
520   x->rdmult = cpi->RDMULT;
521
522   /* segment ID */
523   if (seg->enabled) {
524     uint8_t *map = seg->update_map ? cpi->segmentation_map
525                                    : cm->last_frame_seg_map;
526     mbmi->segment_id = vp9_get_segment_id(cm, map, bsize, mi_row, mi_col);
527
528     vp9_mb_init_quantizer(cpi, x);
529
530     if (seg->enabled && cpi->seg0_cnt > 0
531         && !vp9_segfeature_active(seg, 0, SEG_LVL_REF_FRAME)
532         && vp9_segfeature_active(seg, 1, SEG_LVL_REF_FRAME)) {
533       cpi->seg0_progress = (cpi->seg0_idx << 16) / cpi->seg0_cnt;
534     } else {
535       const int y = mb_row & ~3;
536       const int x = mb_col & ~3;
537       const int p16 = ((mb_row & 1) << 1) + (mb_col & 1);
538       const int p32 = ((mb_row & 2) << 2) + ((mb_col & 2) << 1);
539       const int tile_progress = cm->cur_tile_mi_col_start * cm->mb_rows >> 1;
540       const int mb_cols = (cm->cur_tile_mi_col_end - cm->cur_tile_mi_col_start)
541           >> 1;
542
543       cpi->seg0_progress = ((y * mb_cols + x * 4 + p32 + p16 + tile_progress)
544           << 16) / cm->MBs;
545     }
546
547     x->encode_breakout = cpi->segment_encode_breakout[mbmi->segment_id];
548   } else {
549     mbmi->segment_id = 0;
550     x->encode_breakout = cpi->oxcf.encode_breakout;
551   }
552 }
553
554 static void pick_sb_modes(VP9_COMP *cpi, int mi_row, int mi_col,
555                           int *totalrate, int64_t *totaldist,
556                           BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
557                           int64_t best_rd) {
558   VP9_COMMON *const cm = &cpi->common;
559   MACROBLOCK *const x = &cpi->mb;
560   MACROBLOCKD *const xd = &x->e_mbd;
561
562   // Use the lower precision, but faster, 32x32 fdct for mode selection.
563   x->use_lp32x32fdct = 1;
564
565   if (bsize < BLOCK_8X8) {
566     // When ab_index = 0 all sub-blocks are handled, so for ab_index != 0
567     // there is nothing to be done.
568     if (xd->ab_index != 0) {
569       *totalrate = 0;
570       *totaldist = 0;
571       return;
572     }
573   }
574
575   set_offsets(cpi, mi_row, mi_col, bsize);
576   xd->mode_info_context->mbmi.sb_type = bsize;
577
578   // Set to zero to make sure we do not use the previous encoded frame stats
579   xd->mode_info_context->mbmi.skip_coeff = 0;
580
581   x->source_variance = get_sby_perpixel_variance(cpi, x, bsize);
582
583   if (cpi->oxcf.tuning == VP8_TUNE_SSIM)
584     vp9_activity_masking(cpi, x);
585
586   // Find best coding mode & reconstruct the MB so it is available
587   // as a predictor for MBs that follow in the SB
588   if (cm->frame_type == KEY_FRAME)
589     vp9_rd_pick_intra_mode_sb(cpi, x, totalrate, totaldist, bsize, ctx,
590                               best_rd);
591   else
592     vp9_rd_pick_inter_mode_sb(cpi, x, mi_row, mi_col, totalrate, totaldist,
593                               bsize, ctx, best_rd);
594 }
595
596 static void update_stats(VP9_COMP *cpi) {
597   VP9_COMMON *const cm = &cpi->common;
598   MACROBLOCK *const x = &cpi->mb;
599   MACROBLOCKD *const xd = &x->e_mbd;
600   MODE_INFO *mi = xd->mode_info_context;
601   MB_MODE_INFO *const mbmi = &mi->mbmi;
602
603   if (cm->frame_type != KEY_FRAME) {
604     const int seg_ref_active = vp9_segfeature_active(&cm->seg, mbmi->segment_id,
605                                                      SEG_LVL_REF_FRAME);
606
607     if (!seg_ref_active)
608       cpi->intra_inter_count[vp9_get_pred_context_intra_inter(xd)]
609                             [is_inter_block(mbmi)]++;
610
611     // If the segment reference feature is enabled we have only a single
612     // reference frame allowed for the segment so exclude it from
613     // the reference frame counts used to work out probabilities.
614     if (is_inter_block(mbmi) && !seg_ref_active) {
615       if (cm->comp_pred_mode == HYBRID_PREDICTION)
616         cpi->comp_inter_count[vp9_get_pred_context_comp_inter_inter(cm, xd)]
617                              [has_second_ref(mbmi)]++;
618
619       if (has_second_ref(mbmi)) {
620         cpi->comp_ref_count[vp9_get_pred_context_comp_ref_p(cm, xd)]
621                            [mbmi->ref_frame[0] == GOLDEN_FRAME]++;
622       } else {
623         cpi->single_ref_count[vp9_get_pred_context_single_ref_p1(xd)][0]
624                              [mbmi->ref_frame[0] != LAST_FRAME]++;
625         if (mbmi->ref_frame[0] != LAST_FRAME)
626           cpi->single_ref_count[vp9_get_pred_context_single_ref_p2(xd)][1]
627                                [mbmi->ref_frame[0] != GOLDEN_FRAME]++;
628       }
629     }
630
631     // Count of last ref frame 0,0 usage
632     if (mbmi->mode == ZEROMV && mbmi->ref_frame[0] == LAST_FRAME)
633       cpi->inter_zz_count++;
634   }
635 }
636
637 // TODO(jingning): the variables used here are little complicated. need further
638 // refactoring on organizing the temporary buffers, when recursive
639 // partition down to 4x4 block size is enabled.
640 static PICK_MODE_CONTEXT *get_block_context(MACROBLOCK *x, BLOCK_SIZE bsize) {
641   MACROBLOCKD *const xd = &x->e_mbd;
642
643   switch (bsize) {
644     case BLOCK_64X64:
645       return &x->sb64_context;
646     case BLOCK_64X32:
647       return &x->sb64x32_context[xd->sb_index];
648     case BLOCK_32X64:
649       return &x->sb32x64_context[xd->sb_index];
650     case BLOCK_32X32:
651       return &x->sb32_context[xd->sb_index];
652     case BLOCK_32X16:
653       return &x->sb32x16_context[xd->sb_index][xd->mb_index];
654     case BLOCK_16X32:
655       return &x->sb16x32_context[xd->sb_index][xd->mb_index];
656     case BLOCK_16X16:
657       return &x->mb_context[xd->sb_index][xd->mb_index];
658     case BLOCK_16X8:
659       return &x->sb16x8_context[xd->sb_index][xd->mb_index][xd->b_index];
660     case BLOCK_8X16:
661       return &x->sb8x16_context[xd->sb_index][xd->mb_index][xd->b_index];
662     case BLOCK_8X8:
663       return &x->sb8x8_context[xd->sb_index][xd->mb_index][xd->b_index];
664     case BLOCK_8X4:
665       return &x->sb8x4_context[xd->sb_index][xd->mb_index][xd->b_index];
666     case BLOCK_4X8:
667       return &x->sb4x8_context[xd->sb_index][xd->mb_index][xd->b_index];
668     case BLOCK_4X4:
669       return &x->ab4x4_context[xd->sb_index][xd->mb_index][xd->b_index];
670     default:
671       assert(0);
672       return NULL ;
673   }
674 }
675
676 static BLOCK_SIZE *get_sb_partitioning(MACROBLOCK *x, BLOCK_SIZE bsize) {
677   MACROBLOCKD *const xd = &x->e_mbd;
678   switch (bsize) {
679     case BLOCK_64X64:
680       return &x->sb64_partitioning;
681     case BLOCK_32X32:
682       return &x->sb_partitioning[xd->sb_index];
683     case BLOCK_16X16:
684       return &x->mb_partitioning[xd->sb_index][xd->mb_index];
685     case BLOCK_8X8:
686       return &x->b_partitioning[xd->sb_index][xd->mb_index][xd->b_index];
687     default:
688       assert(0);
689       return NULL ;
690   }
691 }
692
693 static void restore_context(VP9_COMP *cpi, int mi_row, int mi_col,
694                             ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
695                             ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
696                             PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
697                             BLOCK_SIZE bsize) {
698   VP9_COMMON *const cm = &cpi->common;
699   MACROBLOCK *const x = &cpi->mb;
700   MACROBLOCKD *const xd = &x->e_mbd;
701   int p;
702   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
703   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
704   int mi_width = num_8x8_blocks_wide_lookup[bsize];
705   int mi_height = num_8x8_blocks_high_lookup[bsize];
706   for (p = 0; p < MAX_MB_PLANE; p++) {
707     vpx_memcpy(
708         cm->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
709         a + num_4x4_blocks_wide * p,
710         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
711         xd->plane[p].subsampling_x);
712     vpx_memcpy(
713         cm->left_context[p]
714             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
715         l + num_4x4_blocks_high * p,
716         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
717         xd->plane[p].subsampling_y);
718   }
719   vpx_memcpy(cm->above_seg_context + mi_col, sa,
720              sizeof(PARTITION_CONTEXT) * mi_width);
721   vpx_memcpy(cm->left_seg_context + (mi_row & MI_MASK), sl,
722              sizeof(PARTITION_CONTEXT) * mi_height);
723 }
724 static void save_context(VP9_COMP *cpi, int mi_row, int mi_col,
725                          ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
726                          ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
727                          PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
728                          BLOCK_SIZE bsize) {
729   const VP9_COMMON *const cm = &cpi->common;
730   const MACROBLOCK *const x = &cpi->mb;
731   const MACROBLOCKD *const xd = &x->e_mbd;
732   int p;
733   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
734   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
735   int mi_width = num_8x8_blocks_wide_lookup[bsize];
736   int mi_height = num_8x8_blocks_high_lookup[bsize];
737
738   // buffer the above/left context information of the block in search.
739   for (p = 0; p < MAX_MB_PLANE; ++p) {
740     vpx_memcpy(
741         a + num_4x4_blocks_wide * p,
742         cm->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
743         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
744         xd->plane[p].subsampling_x);
745     vpx_memcpy(
746         l + num_4x4_blocks_high * p,
747         cm->left_context[p]
748             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
749         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
750         xd->plane[p].subsampling_y);
751   }
752   vpx_memcpy(sa, cm->above_seg_context + mi_col,
753              sizeof(PARTITION_CONTEXT) * mi_width);
754   vpx_memcpy(sl, cm->left_seg_context + (mi_row & MI_MASK),
755              sizeof(PARTITION_CONTEXT) * mi_height);
756 }
757
758 static void encode_b(VP9_COMP *cpi, TOKENEXTRA **tp, int mi_row, int mi_col,
759                      int output_enabled, BLOCK_SIZE bsize, int sub_index) {
760   VP9_COMMON * const cm = &cpi->common;
761   MACROBLOCK * const x = &cpi->mb;
762   MACROBLOCKD * const xd = &x->e_mbd;
763
764   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
765     return;
766
767   if (sub_index != -1)
768     *get_sb_index(xd, bsize) = sub_index;
769
770   if (bsize < BLOCK_8X8) {
771     // When ab_index = 0 all sub-blocks are handled, so for ab_index != 0
772     // there is nothing to be done.
773     if (xd->ab_index > 0)
774       return;
775   }
776   set_offsets(cpi, mi_row, mi_col, bsize);
777   update_state(cpi, get_block_context(x, bsize), bsize, output_enabled);
778   encode_superblock(cpi, tp, output_enabled, mi_row, mi_col, bsize);
779
780   if (output_enabled) {
781     update_stats(cpi);
782
783     (*tp)->token = EOSB_TOKEN;
784     (*tp)++;
785   }
786 }
787
788 static void encode_sb(VP9_COMP *cpi, TOKENEXTRA **tp, int mi_row, int mi_col,
789                       int output_enabled, BLOCK_SIZE bsize) {
790   VP9_COMMON * const cm = &cpi->common;
791   MACROBLOCK * const x = &cpi->mb;
792   MACROBLOCKD * const xd = &x->e_mbd;
793   BLOCK_SIZE c1 = BLOCK_8X8;
794   const int bsl = b_width_log2(bsize), bs = (1 << bsl) / 4;
795   int UNINITIALIZED_IS_SAFE(pl);
796   PARTITION_TYPE partition;
797   BLOCK_SIZE subsize;
798   int i;
799
800   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
801     return;
802
803   c1 = BLOCK_4X4;
804   if (bsize >= BLOCK_8X8) {
805     set_partition_seg_context(cm, xd, mi_row, mi_col);
806     pl = partition_plane_context(xd, bsize);
807     c1 = *(get_sb_partitioning(x, bsize));
808   }
809   partition = partition_lookup[bsl][c1];
810
811   switch (partition) {
812     case PARTITION_NONE:
813       if (output_enabled && bsize >= BLOCK_8X8)
814         cpi->partition_count[pl][PARTITION_NONE]++;
815       encode_b(cpi, tp, mi_row, mi_col, output_enabled, c1, -1);
816       break;
817     case PARTITION_VERT:
818       if (output_enabled)
819         cpi->partition_count[pl][PARTITION_VERT]++;
820       encode_b(cpi, tp, mi_row, mi_col, output_enabled, c1, 0);
821       encode_b(cpi, tp, mi_row, mi_col + bs, output_enabled, c1, 1);
822       break;
823     case PARTITION_HORZ:
824       if (output_enabled)
825         cpi->partition_count[pl][PARTITION_HORZ]++;
826       encode_b(cpi, tp, mi_row, mi_col, output_enabled, c1, 0);
827       encode_b(cpi, tp, mi_row + bs, mi_col, output_enabled, c1, 1);
828       break;
829     case PARTITION_SPLIT:
830       subsize = get_subsize(bsize, PARTITION_SPLIT);
831
832       if (output_enabled)
833         cpi->partition_count[pl][PARTITION_SPLIT]++;
834
835       for (i = 0; i < 4; i++) {
836         const int x_idx = i & 1, y_idx = i >> 1;
837
838         *get_sb_index(xd, subsize) = i;
839         encode_sb(cpi, tp, mi_row + y_idx * bs, mi_col + x_idx * bs,
840                   output_enabled, subsize);
841       }
842       break;
843     default:
844       assert(0);
845       break;
846   }
847
848   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8) {
849     set_partition_seg_context(cm, xd, mi_row, mi_col);
850     update_partition_context(xd, c1, bsize);
851   }
852 }
853
854 // Check to see if the given partition size is allowed for a specified number
855 // of 8x8 block rows and columns remaining in the image.
856 // If not then return the largest allowed partition size
857 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize,
858                                       int rows_left, int cols_left,
859                                       int *bh, int *bw) {
860   if ((rows_left <= 0) || (cols_left <= 0)) {
861     return MIN(bsize, BLOCK_8X8);
862   } else {
863     for (; bsize > 0; --bsize) {
864       *bh = num_8x8_blocks_high_lookup[bsize];
865       *bw = num_8x8_blocks_wide_lookup[bsize];
866       if ((*bh <= rows_left) && (*bw <= cols_left)) {
867         break;
868       }
869     }
870   }
871   return bsize;
872 }
873
874 // This function attempts to set all mode info entries in a given SB64
875 // to the same block partition size.
876 // However, at the bottom and right borders of the image the requested size
877 // may not be allowed in which case this code attempts to choose the largest
878 // allowable partition.
879 static void set_partitioning(VP9_COMP *cpi, MODE_INFO *m,
880                              int mi_row, int mi_col) {
881   VP9_COMMON *const cm = &cpi->common;
882   BLOCK_SIZE bsize = cpi->sf.always_this_block_size;
883   const int mis = cm->mode_info_stride;
884   int row8x8_remaining = cm->cur_tile_mi_row_end - mi_row;
885   int col8x8_remaining = cm->cur_tile_mi_col_end - mi_col;
886   int block_row, block_col;
887
888   assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
889
890   // Apply the requested partition size to the SB64 if it is all "in image"
891   if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
892       (row8x8_remaining >= MI_BLOCK_SIZE)) {
893     for (block_row = 0; block_row < MI_BLOCK_SIZE; ++block_row) {
894       for (block_col = 0; block_col < MI_BLOCK_SIZE; ++block_col) {
895         m[block_row * mis + block_col].mbmi.sb_type = bsize;
896       }
897     }
898   } else {
899     // Else this is a partial SB64.
900     int bh = num_8x8_blocks_high_lookup[bsize];
901     int bw = num_8x8_blocks_wide_lookup[bsize];
902     int sub_block_row;
903     int sub_block_col;
904     int row_index;
905     int col_index;
906
907     for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
908       for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
909         // Find a partition size that fits
910         bsize = find_partition_size(cpi->sf.always_this_block_size,
911                                     (row8x8_remaining - block_row),
912                                     (col8x8_remaining - block_col), &bh, &bw);
913
914         // Set the mi entries for all 8x8 blocks within the selected size
915         for (sub_block_row = 0; sub_block_row < bh; ++sub_block_row) {
916           for (sub_block_col = 0; sub_block_col < bw; ++sub_block_col) {
917             row_index = block_row + sub_block_row;
918             col_index = block_col + sub_block_col;
919             m[row_index * mis + col_index].mbmi.sb_type = bsize;
920           }
921         }
922       }
923     }
924   }
925 }
926 static void copy_partitioning(VP9_COMP *cpi, MODE_INFO *m, MODE_INFO *p) {
927   VP9_COMMON *const cm = &cpi->common;
928   const int mis = cm->mode_info_stride;
929   int block_row, block_col;
930   for (block_row = 0; block_row < 8; ++block_row) {
931     for (block_col = 0; block_col < 8; ++block_col) {
932       m[block_row * mis + block_col].mbmi.sb_type =
933           p[block_row * mis + block_col].mbmi.sb_type;
934     }
935   }
936 }
937
938 static void set_block_size(VP9_COMMON * const cm, MODE_INFO *mi,
939                            BLOCK_SIZE bsize, int mis, int mi_row,
940                            int mi_col) {
941   int r, c;
942   const int bs = MAX(num_8x8_blocks_wide_lookup[bsize],
943                      num_8x8_blocks_high_lookup[bsize]);
944   MODE_INFO *const mi2 = &mi[mi_row * mis + mi_col];
945   for (r = 0; r < bs; r++)
946     for (c = 0; c < bs; c++)
947       if (mi_row + r < cm->mi_rows && mi_col + c < cm->mi_cols)
948         mi2[r * mis + c].mbmi.sb_type = bsize;
949 }
950
951 typedef struct {
952   int64_t sum_square_error;
953   int64_t sum_error;
954   int count;
955   int variance;
956 } var;
957
958 typedef struct {
959   var none;
960   var horz[2];
961   var vert[2];
962 } partition_variance;
963
964 #define VT(TYPE, BLOCKSIZE) \
965   typedef struct { \
966     partition_variance vt; \
967     BLOCKSIZE split[4]; } TYPE;
968
969 VT(v8x8, var)
970 VT(v16x16, v8x8)
971 VT(v32x32, v16x16)
972 VT(v64x64, v32x32)
973
974 typedef struct {
975   partition_variance *vt;
976   var *split[4];
977 } vt_node;
978
979 typedef enum {
980   V16X16,
981   V32X32,
982   V64X64,
983 } TREE_LEVEL;
984
985 static void tree_to_node(void *data, BLOCK_SIZE bsize, vt_node *node) {
986   int i;
987   switch (bsize) {
988     case BLOCK_64X64: {
989       v64x64 *vt = (v64x64 *) data;
990       node->vt = &vt->vt;
991       for (i = 0; i < 4; i++)
992         node->split[i] = &vt->split[i].vt.none;
993       break;
994     }
995     case BLOCK_32X32: {
996       v32x32 *vt = (v32x32 *) data;
997       node->vt = &vt->vt;
998       for (i = 0; i < 4; i++)
999         node->split[i] = &vt->split[i].vt.none;
1000       break;
1001     }
1002     case BLOCK_16X16: {
1003       v16x16 *vt = (v16x16 *) data;
1004       node->vt = &vt->vt;
1005       for (i = 0; i < 4; i++)
1006         node->split[i] = &vt->split[i].vt.none;
1007       break;
1008     }
1009     case BLOCK_8X8: {
1010       v8x8 *vt = (v8x8 *) data;
1011       node->vt = &vt->vt;
1012       for (i = 0; i < 4; i++)
1013         node->split[i] = &vt->split[i];
1014       break;
1015     }
1016     default:
1017       node->vt = 0;
1018       for (i = 0; i < 4; i++)
1019         node->split[i] = 0;
1020       assert(-1);
1021   }
1022 }
1023
1024 // Set variance values given sum square error, sum error, count.
1025 static void fill_variance(var *v, int64_t s2, int64_t s, int c) {
1026   v->sum_square_error = s2;
1027   v->sum_error = s;
1028   v->count = c;
1029   if (c > 0)
1030     v->variance = 256
1031         * (v->sum_square_error - v->sum_error * v->sum_error / v->count)
1032         / v->count;
1033   else
1034     v->variance = 0;
1035 }
1036
1037 // Combine 2 variance structures by summing the sum_error, sum_square_error,
1038 // and counts and then calculating the new variance.
1039 void sum_2_variances(var *r, var *a, var*b) {
1040   fill_variance(r, a->sum_square_error + b->sum_square_error,
1041                 a->sum_error + b->sum_error, a->count + b->count);
1042 }
1043
1044 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
1045   vt_node node;
1046   tree_to_node(data, bsize, &node);
1047   sum_2_variances(&node.vt->horz[0], node.split[0], node.split[1]);
1048   sum_2_variances(&node.vt->horz[1], node.split[2], node.split[3]);
1049   sum_2_variances(&node.vt->vert[0], node.split[0], node.split[2]);
1050   sum_2_variances(&node.vt->vert[1], node.split[1], node.split[3]);
1051   sum_2_variances(&node.vt->none, &node.vt->vert[0], &node.vt->vert[1]);
1052 }
1053
1054 #if PERFORM_RANDOM_PARTITIONING
1055 static int set_vt_partitioning(VP9_COMP *cpi, void *data, MODE_INFO *m,
1056     BLOCK_SIZE block_size, int mi_row,
1057     int mi_col, int mi_size) {
1058   VP9_COMMON * const cm = &cpi->common;
1059   vt_node vt;
1060   const int mis = cm->mode_info_stride;
1061   int64_t threshold = 4 * cpi->common.base_qindex * cpi->common.base_qindex;
1062
1063   tree_to_node(data, block_size, &vt);
1064
1065   // split none is available only if we have more than half a block size
1066   // in width and height inside the visible image
1067   if (mi_col + mi_size < cm->mi_cols && mi_row + mi_size < cm->mi_rows &&
1068       (rand() & 3) < 1) {
1069     set_block_size(cm, m, block_size, mis, mi_row, mi_col);
1070     return 1;
1071   }
1072
1073   // vertical split is available on all but the bottom border
1074   if (mi_row + mi_size < cm->mi_rows && vt.vt->vert[0].variance < threshold
1075       && (rand() & 3) < 1) {
1076     set_block_size(cm, m, get_subsize(block_size, PARTITION_VERT), mis, mi_row,
1077         mi_col);
1078     return 1;
1079   }
1080
1081   // horizontal split is available on all but the right border
1082   if (mi_col + mi_size < cm->mi_cols && vt.vt->horz[0].variance < threshold
1083       && (rand() & 3) < 1) {
1084     set_block_size(cm, m, get_subsize(block_size, PARTITION_HORZ), mis, mi_row,
1085         mi_col);
1086     return 1;
1087   }
1088
1089   return 0;
1090 }
1091
1092 #else  // !PERFORM_RANDOM_PARTITIONING
1093
1094 static int set_vt_partitioning(VP9_COMP *cpi, void *data, MODE_INFO *m,
1095                                BLOCK_SIZE bsize, int mi_row,
1096                                int mi_col, int mi_size) {
1097   VP9_COMMON * const cm = &cpi->common;
1098   vt_node vt;
1099   const int mis = cm->mode_info_stride;
1100   int64_t threshold = 50 * cpi->common.base_qindex;
1101
1102   tree_to_node(data, bsize, &vt);
1103
1104   // split none is available only if we have more than half a block size
1105   // in width and height inside the visible image
1106   if (mi_col + mi_size < cm->mi_cols && mi_row + mi_size < cm->mi_rows
1107       && vt.vt->none.variance < threshold) {
1108     set_block_size(cm, m, bsize, mis, mi_row, mi_col);
1109     return 1;
1110   }
1111
1112   // vertical split is available on all but the bottom border
1113   if (mi_row + mi_size < cm->mi_rows && vt.vt->vert[0].variance < threshold
1114       && vt.vt->vert[1].variance < threshold) {
1115     set_block_size(cm, m, get_subsize(bsize, PARTITION_VERT), mis, mi_row,
1116                    mi_col);
1117     return 1;
1118   }
1119
1120   // horizontal split is available on all but the right border
1121   if (mi_col + mi_size < cm->mi_cols && vt.vt->horz[0].variance < threshold
1122       && vt.vt->horz[1].variance < threshold) {
1123     set_block_size(cm, m, get_subsize(bsize, PARTITION_HORZ), mis, mi_row,
1124                    mi_col);
1125     return 1;
1126   }
1127
1128   return 0;
1129 }
1130 #endif  // PERFORM_RANDOM_PARTITIONING
1131
1132 static void choose_partitioning(VP9_COMP *cpi, MODE_INFO *m, int mi_row,
1133                                 int mi_col) {
1134   VP9_COMMON * const cm = &cpi->common;
1135   MACROBLOCK *x = &cpi->mb;
1136   MACROBLOCKD *xd = &cpi->mb.e_mbd;
1137   const int mis = cm->mode_info_stride;
1138   // TODO(JBB): More experimentation or testing of this threshold;
1139   int64_t threshold = 4;
1140   int i, j, k;
1141   v64x64 vt;
1142   unsigned char * s;
1143   int sp;
1144   const unsigned char * d;
1145   int dp;
1146   int pixels_wide = 64, pixels_high = 64;
1147
1148   vp9_zero(vt);
1149   set_offsets(cpi, mi_row, mi_col, BLOCK_64X64);
1150
1151   if (xd->mb_to_right_edge < 0)
1152     pixels_wide += (xd->mb_to_right_edge >> 3);
1153
1154   if (xd->mb_to_bottom_edge < 0)
1155     pixels_high += (xd->mb_to_bottom_edge >> 3);
1156
1157   s = x->plane[0].src.buf;
1158   sp = x->plane[0].src.stride;
1159
1160   // TODO(JBB): Clearly the higher the quantizer the fewer partitions we want
1161   // but this needs more experimentation.
1162   threshold = threshold * cpi->common.base_qindex * cpi->common.base_qindex;
1163
1164   d = vp9_64x64_zeros;
1165   dp = 64;
1166   if (cm->frame_type != KEY_FRAME) {
1167     int_mv nearest_mv, near_mv;
1168     const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, LAST_FRAME)];
1169     YV12_BUFFER_CONFIG *ref_fb = &cm->yv12_fb[idx];
1170     YV12_BUFFER_CONFIG *second_ref_fb = NULL;
1171
1172     setup_pre_planes(xd, 0, ref_fb, mi_row, mi_col,
1173                      &xd->scale_factor[0]);
1174     setup_pre_planes(xd, 1, second_ref_fb, mi_row, mi_col,
1175                      &xd->scale_factor[1]);
1176     xd->mode_info_context->mbmi.ref_frame[0] = LAST_FRAME;
1177     xd->mode_info_context->mbmi.sb_type = BLOCK_64X64;
1178     vp9_find_best_ref_mvs(xd, m->mbmi.ref_mvs[m->mbmi.ref_frame[0]],
1179                           &nearest_mv, &near_mv);
1180
1181     xd->mode_info_context->mbmi.mv[0] = nearest_mv;
1182     vp9_build_inter_predictors_sby(xd, mi_row, mi_col, BLOCK_64X64);
1183     d = xd->plane[0].dst.buf;
1184     dp = xd->plane[0].dst.stride;
1185   }
1186
1187   // Fill in the entire tree of 8x8 variances for splits.
1188   for (i = 0; i < 4; i++) {
1189     const int x32_idx = ((i & 1) << 5);
1190     const int y32_idx = ((i >> 1) << 5);
1191     for (j = 0; j < 4; j++) {
1192       const int x16_idx = x32_idx + ((j & 1) << 4);
1193       const int y16_idx = y32_idx + ((j >> 1) << 4);
1194       v16x16 *vst = &vt.split[i].split[j];
1195       for (k = 0; k < 4; k++) {
1196         int x_idx = x16_idx + ((k & 1) << 3);
1197         int y_idx = y16_idx + ((k >> 1) << 3);
1198         unsigned int sse = 0;
1199         int sum = 0;
1200         if (x_idx < pixels_wide && y_idx < pixels_high)
1201           vp9_get_sse_sum_8x8(s + y_idx * sp + x_idx, sp,
1202                               d + y_idx * dp + x_idx, dp, &sse, &sum);
1203         fill_variance(&vst->split[k].vt.none, sse, sum, 64);
1204       }
1205     }
1206   }
1207   // Fill the rest of the variance tree by summing the split partition
1208   // values.
1209   for (i = 0; i < 4; i++) {
1210     for (j = 0; j < 4; j++) {
1211       fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1212     }
1213     fill_variance_tree(&vt.split[i], BLOCK_32X32);
1214   }
1215   fill_variance_tree(&vt, BLOCK_64X64);
1216   // Now go through the entire structure,  splitting every block size until
1217   // we get to one that's got a variance lower than our threshold,  or we
1218   // hit 8x8.
1219   if (!set_vt_partitioning(cpi, &vt, m, BLOCK_64X64, mi_row, mi_col,
1220                            4)) {
1221     for (i = 0; i < 4; ++i) {
1222       const int x32_idx = ((i & 1) << 2);
1223       const int y32_idx = ((i >> 1) << 2);
1224       if (!set_vt_partitioning(cpi, &vt.split[i], m, BLOCK_32X32,
1225                                (mi_row + y32_idx), (mi_col + x32_idx), 2)) {
1226         for (j = 0; j < 4; ++j) {
1227           const int x16_idx = ((j & 1) << 1);
1228           const int y16_idx = ((j >> 1) << 1);
1229           if (!set_vt_partitioning(cpi, &vt.split[i].split[j], m,
1230                                    BLOCK_16X16,
1231                                    (mi_row + y32_idx + y16_idx),
1232                                    (mi_col + x32_idx + x16_idx), 1)) {
1233             for (k = 0; k < 4; ++k) {
1234               const int x8_idx = (k & 1);
1235               const int y8_idx = (k >> 1);
1236               set_block_size(cm, m, BLOCK_8X8, mis,
1237                              (mi_row + y32_idx + y16_idx + y8_idx),
1238                              (mi_col + x32_idx + x16_idx + x8_idx));
1239             }
1240           }
1241         }
1242       }
1243     }
1244   }
1245 }
1246
1247 static void rd_use_partition(VP9_COMP *cpi, MODE_INFO *m, TOKENEXTRA **tp,
1248                              int mi_row, int mi_col, BLOCK_SIZE bsize,
1249                              int *rate, int64_t *dist, int do_recon) {
1250   VP9_COMMON * const cm = &cpi->common;
1251   MACROBLOCK * const x = &cpi->mb;
1252   MACROBLOCKD *xd = &cpi->mb.e_mbd;
1253   const int mis = cm->mode_info_stride;
1254   int bsl = b_width_log2(bsize);
1255   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1256   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1257   int ms = num_4x4_blocks_wide / 2;
1258   int mh = num_4x4_blocks_high / 2;
1259   int bss = (1 << bsl) / 4;
1260   int i, pl;
1261   PARTITION_TYPE partition = PARTITION_NONE;
1262   BLOCK_SIZE subsize;
1263   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1264   PARTITION_CONTEXT sl[8], sa[8];
1265   int last_part_rate = INT_MAX;
1266   int64_t last_part_dist = INT_MAX;
1267   int split_rate = INT_MAX;
1268   int64_t split_dist = INT_MAX;
1269   int none_rate = INT_MAX;
1270   int64_t none_dist = INT_MAX;
1271   int chosen_rate = INT_MAX;
1272   int64_t chosen_dist = INT_MAX;
1273   BLOCK_SIZE sub_subsize = BLOCK_4X4;
1274   int splits_below = 0;
1275   BLOCK_SIZE bs_type = m->mbmi.sb_type;
1276
1277   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1278     return;
1279
1280   partition = partition_lookup[bsl][bs_type];
1281
1282   subsize = get_subsize(bsize, partition);
1283
1284   if (bsize < BLOCK_8X8) {
1285     // When ab_index = 0 all sub-blocks are handled, so for ab_index != 0
1286     // there is nothing to be done.
1287     if (xd->ab_index != 0) {
1288       *rate = 0;
1289       *dist = 0;
1290       return;
1291     }
1292   } else {
1293     *(get_sb_partitioning(x, bsize)) = subsize;
1294   }
1295   save_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1296
1297   x->fast_ms = 0;
1298   x->pred_mv.as_int = 0;
1299   x->subblock_ref = 0;
1300
1301   if (cpi->sf.adjust_partitioning_from_last_frame) {
1302     // Check if any of the sub blocks are further split.
1303     if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
1304       sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
1305       splits_below = 1;
1306       for (i = 0; i < 4; i++) {
1307         int jj = i >> 1, ii = i & 0x01;
1308         if (m[jj * bss * mis + ii * bss].mbmi.sb_type >= sub_subsize)  {
1309           splits_below = 0;
1310         }
1311       }
1312     }
1313
1314     // If partition is not none try none unless each of the 4 splits are split
1315     // even further..
1316     if (partition != PARTITION_NONE && !splits_below &&
1317         mi_row + (ms >> 1) < cm->mi_rows &&
1318         mi_col + (ms >> 1) < cm->mi_cols) {
1319       *(get_sb_partitioning(x, bsize)) = bsize;
1320       pick_sb_modes(cpi, mi_row, mi_col, &none_rate, &none_dist, bsize,
1321                     get_block_context(x, bsize), INT64_MAX);
1322
1323       set_partition_seg_context(cm, xd, mi_row, mi_col);
1324       pl = partition_plane_context(xd, bsize);
1325       none_rate += x->partition_cost[pl][PARTITION_NONE];
1326
1327       restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1328       m->mbmi.sb_type = bs_type;
1329       *(get_sb_partitioning(x, bsize)) = subsize;
1330     }
1331   }
1332
1333   switch (partition) {
1334     case PARTITION_NONE:
1335       pick_sb_modes(cpi, mi_row, mi_col, &last_part_rate, &last_part_dist,
1336                     bsize, get_block_context(x, bsize), INT64_MAX);
1337       break;
1338     case PARTITION_HORZ:
1339       *get_sb_index(xd, subsize) = 0;
1340       pick_sb_modes(cpi, mi_row, mi_col, &last_part_rate, &last_part_dist,
1341                     subsize, get_block_context(x, subsize), INT64_MAX);
1342       if (last_part_rate != INT_MAX &&
1343           bsize >= BLOCK_8X8 && mi_row + (mh >> 1) < cm->mi_rows) {
1344         int rt = 0;
1345         int64_t dt = 0;
1346         update_state(cpi, get_block_context(x, subsize), subsize, 0);
1347         encode_superblock(cpi, tp, 0, mi_row, mi_col, subsize);
1348         *get_sb_index(xd, subsize) = 1;
1349         pick_sb_modes(cpi, mi_row + (ms >> 1), mi_col, &rt, &dt, subsize,
1350                       get_block_context(x, subsize), INT64_MAX);
1351         if (rt == INT_MAX || dt == INT_MAX) {
1352           last_part_rate = INT_MAX;
1353           last_part_dist = INT_MAX;
1354           break;
1355         }
1356
1357         last_part_rate += rt;
1358         last_part_dist += dt;
1359       }
1360       break;
1361     case PARTITION_VERT:
1362       *get_sb_index(xd, subsize) = 0;
1363       pick_sb_modes(cpi, mi_row, mi_col, &last_part_rate, &last_part_dist,
1364                     subsize, get_block_context(x, subsize), INT64_MAX);
1365       if (last_part_rate != INT_MAX &&
1366           bsize >= BLOCK_8X8 && mi_col + (ms >> 1) < cm->mi_cols) {
1367         int rt = 0;
1368         int64_t dt = 0;
1369         update_state(cpi, get_block_context(x, subsize), subsize, 0);
1370         encode_superblock(cpi, tp, 0, mi_row, mi_col, subsize);
1371         *get_sb_index(xd, subsize) = 1;
1372         pick_sb_modes(cpi, mi_row, mi_col + (ms >> 1), &rt, &dt, subsize,
1373                       get_block_context(x, subsize), INT64_MAX);
1374         if (rt == INT_MAX || dt == INT_MAX) {
1375           last_part_rate = INT_MAX;
1376           last_part_dist = INT_MAX;
1377           break;
1378         }
1379         last_part_rate += rt;
1380         last_part_dist += dt;
1381       }
1382       break;
1383     case PARTITION_SPLIT:
1384       // Split partition.
1385       last_part_rate = 0;
1386       last_part_dist = 0;
1387       for (i = 0; i < 4; i++) {
1388         int x_idx = (i & 1) * (ms >> 1);
1389         int y_idx = (i >> 1) * (ms >> 1);
1390         int jj = i >> 1, ii = i & 0x01;
1391         int rt;
1392         int64_t dt;
1393
1394         if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
1395           continue;
1396
1397         *get_sb_index(xd, subsize) = i;
1398
1399         rd_use_partition(cpi, m + jj * bss * mis + ii * bss, tp, mi_row + y_idx,
1400                          mi_col + x_idx, subsize, &rt, &dt, i != 3);
1401         if (rt == INT_MAX || dt == INT_MAX) {
1402           last_part_rate = INT_MAX;
1403           last_part_dist = INT_MAX;
1404           break;
1405         }
1406         last_part_rate += rt;
1407         last_part_dist += dt;
1408       }
1409       break;
1410     default:
1411       assert(0);
1412   }
1413   set_partition_seg_context(cm, xd, mi_row, mi_col);
1414   pl = partition_plane_context(xd, bsize);
1415   if (last_part_rate < INT_MAX)
1416     last_part_rate += x->partition_cost[pl][partition];
1417
1418   if (cpi->sf.adjust_partitioning_from_last_frame
1419       && partition != PARTITION_SPLIT && bsize > BLOCK_8X8
1420       && (mi_row + ms < cm->mi_rows || mi_row + (ms >> 1) == cm->mi_rows)
1421       && (mi_col + ms < cm->mi_cols || mi_col + (ms >> 1) == cm->mi_cols)) {
1422     BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
1423     split_rate = 0;
1424     split_dist = 0;
1425     restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1426
1427     // Split partition.
1428     for (i = 0; i < 4; i++) {
1429       int x_idx = (i & 1) * (num_4x4_blocks_wide >> 2);
1430       int y_idx = (i >> 1) * (num_4x4_blocks_wide >> 2);
1431       int rt = 0;
1432       int64_t dt = 0;
1433       ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1434       PARTITION_CONTEXT sl[8], sa[8];
1435
1436       if ((mi_row + y_idx >= cm->mi_rows)
1437           || (mi_col + x_idx >= cm->mi_cols))
1438         continue;
1439
1440       *get_sb_index(xd, split_subsize) = i;
1441       *get_sb_partitioning(x, bsize) = split_subsize;
1442       *get_sb_partitioning(x, split_subsize) = split_subsize;
1443
1444       save_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1445
1446       pick_sb_modes(cpi, mi_row + y_idx, mi_col + x_idx, &rt, &dt,
1447                     split_subsize, get_block_context(x, split_subsize),
1448                     INT64_MAX);
1449
1450       restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1451
1452       if (rt == INT_MAX || dt == INT_MAX) {
1453         split_rate = INT_MAX;
1454         split_dist = INT_MAX;
1455         break;
1456       }
1457
1458       if (i != 3)
1459         encode_sb(cpi, tp,  mi_row + y_idx, mi_col + x_idx, 0,
1460                   split_subsize);
1461
1462       split_rate += rt;
1463       split_dist += dt;
1464       set_partition_seg_context(cm, xd, mi_row + y_idx, mi_col + x_idx);
1465       pl = partition_plane_context(xd, bsize);
1466       split_rate += x->partition_cost[pl][PARTITION_NONE];
1467     }
1468     set_partition_seg_context(cm, xd, mi_row, mi_col);
1469     pl = partition_plane_context(xd, bsize);
1470     if (split_rate < INT_MAX) {
1471       split_rate += x->partition_cost[pl][PARTITION_SPLIT];
1472
1473       chosen_rate = split_rate;
1474       chosen_dist = split_dist;
1475     }
1476   }
1477
1478   // If last_part is better set the partitioning to that...
1479   if (RDCOST(x->rdmult, x->rddiv, last_part_rate, last_part_dist)
1480       < RDCOST(x->rdmult, x->rddiv, chosen_rate, chosen_dist)) {
1481     m->mbmi.sb_type = bsize;
1482     if (bsize >= BLOCK_8X8)
1483       *(get_sb_partitioning(x, bsize)) = subsize;
1484     chosen_rate = last_part_rate;
1485     chosen_dist = last_part_dist;
1486   }
1487   // If none was better set the partitioning to that...
1488   if (RDCOST(x->rdmult, x->rddiv, chosen_rate, chosen_dist)
1489       > RDCOST(x->rdmult, x->rddiv, none_rate, none_dist)) {
1490     if (bsize >= BLOCK_8X8)
1491       *(get_sb_partitioning(x, bsize)) = bsize;
1492     chosen_rate = none_rate;
1493     chosen_dist = none_dist;
1494   }
1495
1496   restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1497
1498   // We must have chosen a partitioning and encoding or we'll fail later on.
1499   // No other opportunities for success.
1500   if ( bsize == BLOCK_64X64)
1501     assert(chosen_rate < INT_MAX && chosen_dist < INT_MAX);
1502
1503   if (do_recon)
1504     encode_sb(cpi, tp, mi_row, mi_col, bsize == BLOCK_64X64, bsize);
1505
1506   *rate = chosen_rate;
1507   *dist = chosen_dist;
1508 }
1509
1510 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
1511   BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
1512   BLOCK_4X4, BLOCK_4X4, BLOCK_8X8, BLOCK_8X8,
1513   BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
1514 };
1515
1516 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
1517   BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
1518   BLOCK_32X32, BLOCK_32X32, BLOCK_32X32, BLOCK_64X64,
1519   BLOCK_64X64, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
1520 };
1521
1522 // Look at all the mode_info entries for blocks that are part of this
1523 // partition and find the min and max values for sb_type.
1524 // At the moment this is designed to work on a 64x64 SB but could be
1525 // adjusted to use a size parameter.
1526 //
1527 // The min and max are assumed to have been initialized prior to calling this
1528 // function so repeat calls can accumulate a min and max of more than one sb64.
1529 static void get_sb_partition_size_range(VP9_COMP *cpi, MODE_INFO * mi,
1530                                         BLOCK_SIZE *min_block_size,
1531                                         BLOCK_SIZE *max_block_size ) {
1532   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1533   int sb_width_in_blocks = MI_BLOCK_SIZE;
1534   int sb_height_in_blocks  = MI_BLOCK_SIZE;
1535   int i, j;
1536   int index = 0;
1537
1538   // Check the sb_type for each block that belongs to this region.
1539   for (i = 0; i < sb_height_in_blocks; ++i) {
1540     for (j = 0; j < sb_width_in_blocks; ++j) {
1541       *min_block_size = MIN(*min_block_size, mi[index + j].mbmi.sb_type);
1542       *max_block_size = MAX(*max_block_size, mi[index + j].mbmi.sb_type);
1543     }
1544     index += xd->mode_info_stride;
1545   }
1546 }
1547
1548 // Look at neighboring blocks and set a min and max partition size based on
1549 // what they chose.
1550 static void rd_auto_partition_range(VP9_COMP *cpi,
1551                                     BLOCK_SIZE *min_block_size,
1552                                     BLOCK_SIZE *max_block_size) {
1553   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1554   MODE_INFO *mi = xd->mode_info_context;
1555   MODE_INFO *above_sb64_mi;
1556   MODE_INFO *left_sb64_mi;
1557   const MB_MODE_INFO *const above_mbmi = &mi[-xd->mode_info_stride].mbmi;
1558   const MB_MODE_INFO *const left_mbmi = &mi[-1].mbmi;
1559   const int left_in_image = xd->left_available && left_mbmi->in_image;
1560   const int above_in_image = xd->up_available && above_mbmi->in_image;
1561
1562   // Frequency check
1563   if (cpi->sf.auto_min_max_partition_count <= 0) {
1564     cpi->sf.auto_min_max_partition_count =
1565       cpi->sf.auto_min_max_partition_interval;
1566     *min_block_size = BLOCK_4X4;
1567     *max_block_size = BLOCK_64X64;
1568     return;
1569   } else {
1570     --cpi->sf.auto_min_max_partition_count;
1571   }
1572
1573   // Set default values if not left or above neighbour
1574   if (!left_in_image && !above_in_image) {
1575     *min_block_size = BLOCK_4X4;
1576     *max_block_size = BLOCK_64X64;
1577   } else {
1578     // Default "min to max" and "max to min"
1579     *min_block_size = BLOCK_64X64;
1580     *max_block_size = BLOCK_4X4;
1581
1582     // Find the min and max partition sizes used in the left SB64
1583     if (left_in_image) {
1584       left_sb64_mi = &mi[-MI_BLOCK_SIZE];
1585       get_sb_partition_size_range(cpi, left_sb64_mi,
1586                                   min_block_size, max_block_size);
1587     }
1588
1589     // Find the min and max partition sizes used in the above SB64 taking
1590     // the values found for left as a starting point.
1591     if (above_in_image) {
1592       above_sb64_mi = &mi[-xd->mode_info_stride * MI_BLOCK_SIZE];
1593       get_sb_partition_size_range(cpi, above_sb64_mi,
1594                                   min_block_size, max_block_size);
1595     }
1596
1597     // give a bit of leaway either side of the observed min and max
1598     *min_block_size = min_partition_size[*min_block_size];
1599     *max_block_size = max_partition_size[*max_block_size];
1600   }
1601 }
1602
1603 static void compute_fast_motion_search_level(VP9_COMP *cpi, BLOCK_SIZE bsize) {
1604   VP9_COMMON *const cm = &cpi->common;
1605   MACROBLOCK *const x = &cpi->mb;
1606   MACROBLOCKD *const xd = &x->e_mbd;
1607
1608   // Only use 8x8 result for non HD videos.
1609   // int use_8x8 = (MIN(cpi->common.width, cpi->common.height) < 720) ? 1 : 0;
1610   int use_8x8 = 1;
1611
1612   if (cm->frame_type && !cpi->is_src_frame_alt_ref &&
1613       ((use_8x8 && bsize == BLOCK_16X16) ||
1614       bsize == BLOCK_32X32 || bsize == BLOCK_64X64)) {
1615     int ref0 = 0, ref1 = 0, ref2 = 0, ref3 = 0;
1616     PICK_MODE_CONTEXT *block_context = NULL;
1617
1618     if (bsize == BLOCK_16X16) {
1619       block_context = x->sb8x8_context[xd->sb_index][xd->mb_index];
1620     } else if (bsize == BLOCK_32X32) {
1621       block_context = x->mb_context[xd->sb_index];
1622     } else if (bsize == BLOCK_64X64) {
1623       block_context = x->sb32_context;
1624     }
1625
1626     if (block_context) {
1627       ref0 = block_context[0].mic.mbmi.ref_frame[0];
1628       ref1 = block_context[1].mic.mbmi.ref_frame[0];
1629       ref2 = block_context[2].mic.mbmi.ref_frame[0];
1630       ref3 = block_context[3].mic.mbmi.ref_frame[0];
1631     }
1632
1633     // Currently, only consider 4 inter reference frames.
1634     if (ref0 && ref1 && ref2 && ref3) {
1635       int d01, d23, d02, d13;
1636
1637       // Motion vectors for the four subblocks.
1638       int16_t mvr0 = block_context[0].mic.mbmi.mv[0].as_mv.row;
1639       int16_t mvc0 = block_context[0].mic.mbmi.mv[0].as_mv.col;
1640       int16_t mvr1 = block_context[1].mic.mbmi.mv[0].as_mv.row;
1641       int16_t mvc1 = block_context[1].mic.mbmi.mv[0].as_mv.col;
1642       int16_t mvr2 = block_context[2].mic.mbmi.mv[0].as_mv.row;
1643       int16_t mvc2 = block_context[2].mic.mbmi.mv[0].as_mv.col;
1644       int16_t mvr3 = block_context[3].mic.mbmi.mv[0].as_mv.row;
1645       int16_t mvc3 = block_context[3].mic.mbmi.mv[0].as_mv.col;
1646
1647       // Adjust sign if ref is alt_ref.
1648       if (cm->ref_frame_sign_bias[ref0]) {
1649         mvr0 *= -1;
1650         mvc0 *= -1;
1651       }
1652
1653       if (cm->ref_frame_sign_bias[ref1]) {
1654         mvr1 *= -1;
1655         mvc1 *= -1;
1656       }
1657
1658       if (cm->ref_frame_sign_bias[ref2]) {
1659         mvr2 *= -1;
1660         mvc2 *= -1;
1661       }
1662
1663       if (cm->ref_frame_sign_bias[ref3]) {
1664         mvr3 *= -1;
1665         mvc3 *= -1;
1666       }
1667
1668       // Calculate mv distances.
1669       d01 = MAX(abs(mvr0 - mvr1), abs(mvc0 - mvc1));
1670       d23 = MAX(abs(mvr2 - mvr3), abs(mvc2 - mvc3));
1671       d02 = MAX(abs(mvr0 - mvr2), abs(mvc0 - mvc2));
1672       d13 = MAX(abs(mvr1 - mvr3), abs(mvc1 - mvc3));
1673
1674       if (d01 < FAST_MOTION_MV_THRESH && d23 < FAST_MOTION_MV_THRESH &&
1675           d02 < FAST_MOTION_MV_THRESH && d13 < FAST_MOTION_MV_THRESH) {
1676         // Set fast motion search level.
1677         x->fast_ms = 1;
1678
1679         // Calculate prediction MV.
1680         x->pred_mv.as_mv.row = (mvr0 + mvr1 + mvr2 + mvr3) >> 2;
1681         x->pred_mv.as_mv.col = (mvc0 + mvc1 + mvc2 + mvc3) >> 2;
1682
1683         if (ref0 == ref1 && ref1 == ref2 && ref2 == ref3 &&
1684             d01 < 2 && d23 < 2 && d02 < 2 && d13 < 2) {
1685           // Set fast motion search level.
1686           x->fast_ms = 2;
1687
1688           if (!d01 && !d23 && !d02 && !d13) {
1689             x->fast_ms = 3;
1690             x->subblock_ref = ref0;
1691           }
1692         }
1693       }
1694     }
1695   }
1696 }
1697
1698 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
1699 // unlikely to be selected depending on previous rate-distortion optimization
1700 // results, for encoding speed-up.
1701 static void rd_pick_partition(VP9_COMP *cpi, TOKENEXTRA **tp, int mi_row,
1702                               int mi_col, BLOCK_SIZE bsize, int *rate,
1703                               int64_t *dist, int do_recon, int64_t best_rd) {
1704   VP9_COMMON * const cm = &cpi->common;
1705   MACROBLOCK * const x = &cpi->mb;
1706   MACROBLOCKD * const xd = &x->e_mbd;
1707   const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
1708   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1709   PARTITION_CONTEXT sl[8], sa[8];
1710   TOKENEXTRA *tp_orig = *tp;
1711   int i, pl;
1712   BLOCK_SIZE subsize;
1713   int this_rate, sum_rate = 0, best_rate = INT_MAX;
1714   int64_t this_dist, sum_dist = 0, best_dist = INT64_MAX;
1715   int64_t sum_rd = 0;
1716   int do_split = bsize >= BLOCK_8X8;
1717   int do_rect = 1;
1718   // Override skipping rectangular partition operations for edge blocks
1719   const int force_horz_split = (mi_row + ms >= cm->mi_rows);
1720   const int force_vert_split = (mi_col + ms >= cm->mi_cols);
1721
1722   int partition_none_allowed = !force_horz_split && !force_vert_split;
1723   int partition_horz_allowed = !force_vert_split && bsize >= BLOCK_8X8;
1724   int partition_vert_allowed = !force_horz_split && bsize >= BLOCK_8X8;
1725
1726   int partition_split_done = 0;
1727   (void) *tp_orig;
1728
1729   if (bsize < BLOCK_8X8) {
1730     // When ab_index = 0 all sub-blocks are handled, so for ab_index != 0
1731     // there is nothing to be done.
1732     if (xd->ab_index != 0) {
1733       *rate = 0;
1734       *dist = 0;
1735       return;
1736     }
1737   }
1738   assert(mi_height_log2(bsize) == mi_width_log2(bsize));
1739
1740   // Determine partition types in search according to the speed features.
1741   // The threshold set here has to be of square block size.
1742   if (cpi->sf.auto_min_max_partition_size) {
1743     partition_none_allowed &= (bsize <= cpi->sf.max_partition_size &&
1744                                bsize >= cpi->sf.min_partition_size);
1745     partition_horz_allowed &= ((bsize <= cpi->sf.max_partition_size &&
1746                                 bsize >  cpi->sf.min_partition_size) ||
1747                                 force_horz_split);
1748     partition_vert_allowed &= ((bsize <= cpi->sf.max_partition_size &&
1749                                 bsize >  cpi->sf.min_partition_size) ||
1750                                 force_vert_split);
1751     do_split &= bsize > cpi->sf.min_partition_size;
1752   }
1753   if (cpi->sf.use_square_partition_only) {
1754     partition_horz_allowed &= force_horz_split;
1755     partition_vert_allowed &= force_vert_split;
1756   }
1757
1758   save_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1759
1760   if (cpi->sf.disable_split_var_thresh && partition_none_allowed) {
1761     unsigned int source_variancey;
1762     vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
1763     source_variancey = get_sby_perpixel_variance(cpi, x, bsize);
1764     if (source_variancey < cpi->sf.disable_split_var_thresh) {
1765       do_split = 0;
1766       if (source_variancey < cpi->sf.disable_split_var_thresh / 2)
1767         do_rect = 0;
1768     }
1769   }
1770
1771   // PARTITION_NONE
1772   if (partition_none_allowed) {
1773     pick_sb_modes(cpi, mi_row, mi_col, &this_rate, &this_dist, bsize,
1774                   get_block_context(x, bsize), best_rd);
1775     if (this_rate != INT_MAX) {
1776       if (bsize >= BLOCK_8X8) {
1777         set_partition_seg_context(cm, xd, mi_row, mi_col);
1778         pl = partition_plane_context(xd, bsize);
1779         this_rate += x->partition_cost[pl][PARTITION_NONE];
1780       }
1781       sum_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_dist);
1782       if (sum_rd < best_rd) {
1783         best_rate = this_rate;
1784         best_dist = this_dist;
1785         best_rd = sum_rd;
1786         if (bsize >= BLOCK_8X8)
1787           *(get_sb_partitioning(x, bsize)) = bsize;
1788       }
1789     }
1790     restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1791   }
1792
1793   // PARTITION_SPLIT
1794   sum_rd = 0;
1795   // TODO(jingning): use the motion vectors given by the above search as
1796   // the starting point of motion search in the following partition type check.
1797   if (do_split) {
1798     subsize = get_subsize(bsize, PARTITION_SPLIT);
1799     for (i = 0; i < 4 && sum_rd < best_rd; ++i) {
1800       const int x_idx = (i & 1) * ms;
1801       const int y_idx = (i >> 1) * ms;
1802
1803       if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
1804         continue;
1805
1806       *get_sb_index(xd, subsize) = i;
1807
1808       rd_pick_partition(cpi, tp, mi_row + y_idx, mi_col + x_idx, subsize,
1809                         &this_rate, &this_dist, i != 3, best_rd - sum_rd);
1810
1811       if (this_rate == INT_MAX) {
1812         sum_rd = INT64_MAX;
1813       } else {
1814         sum_rate += this_rate;
1815         sum_dist += this_dist;
1816         sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1817       }
1818     }
1819     if (sum_rd < best_rd && i == 4) {
1820       set_partition_seg_context(cm, xd, mi_row, mi_col);
1821       pl = partition_plane_context(xd, bsize);
1822       sum_rate += x->partition_cost[pl][PARTITION_SPLIT];
1823       sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1824       if (sum_rd < best_rd) {
1825         best_rate = sum_rate;
1826         best_dist = sum_dist;
1827         best_rd = sum_rd;
1828         *(get_sb_partitioning(x, bsize)) = subsize;
1829       } else {
1830         // skip rectangular partition test when larger block size
1831         // gives better rd cost
1832         if (cpi->sf.less_rectangular_check)
1833           do_rect &= !partition_none_allowed;
1834       }
1835     }
1836     partition_split_done = 1;
1837     restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1838   }
1839
1840   x->fast_ms = 0;
1841   x->pred_mv.as_int = 0;
1842   x->subblock_ref = 0;
1843
1844   if (partition_split_done &&
1845       cpi->sf.using_small_partition_info) {
1846     compute_fast_motion_search_level(cpi, bsize);
1847   }
1848
1849   // PARTITION_HORZ
1850   if (partition_horz_allowed && do_rect) {
1851     subsize = get_subsize(bsize, PARTITION_HORZ);
1852     *get_sb_index(xd, subsize) = 0;
1853     pick_sb_modes(cpi, mi_row, mi_col, &sum_rate, &sum_dist, subsize,
1854                   get_block_context(x, subsize), best_rd);
1855     sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1856
1857     if (sum_rd < best_rd && mi_row + ms < cm->mi_rows) {
1858       update_state(cpi, get_block_context(x, subsize), subsize, 0);
1859       encode_superblock(cpi, tp, 0, mi_row, mi_col, subsize);
1860
1861       *get_sb_index(xd, subsize) = 1;
1862       pick_sb_modes(cpi, mi_row + ms, mi_col, &this_rate,
1863                     &this_dist, subsize, get_block_context(x, subsize),
1864                     best_rd - sum_rd);
1865       if (this_rate == INT_MAX) {
1866         sum_rd = INT64_MAX;
1867       } else {
1868         sum_rate += this_rate;
1869         sum_dist += this_dist;
1870         sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1871       }
1872     }
1873     if (sum_rd < best_rd) {
1874       set_partition_seg_context(cm, xd, mi_row, mi_col);
1875       pl = partition_plane_context(xd, bsize);
1876       sum_rate += x->partition_cost[pl][PARTITION_HORZ];
1877       sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1878       if (sum_rd < best_rd) {
1879         best_rd = sum_rd;
1880         best_rate = sum_rate;
1881         best_dist = sum_dist;
1882         *(get_sb_partitioning(x, bsize)) = subsize;
1883       }
1884     }
1885     restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1886   }
1887
1888   // PARTITION_VERT
1889   if (partition_vert_allowed && do_rect) {
1890     subsize = get_subsize(bsize, PARTITION_VERT);
1891
1892     *get_sb_index(xd, subsize) = 0;
1893     pick_sb_modes(cpi, mi_row, mi_col, &sum_rate, &sum_dist, subsize,
1894                   get_block_context(x, subsize), best_rd);
1895     sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1896     if (sum_rd < best_rd && mi_col + ms < cm->mi_cols) {
1897       update_state(cpi, get_block_context(x, subsize), subsize, 0);
1898       encode_superblock(cpi, tp, 0, mi_row, mi_col, subsize);
1899
1900       *get_sb_index(xd, subsize) = 1;
1901       pick_sb_modes(cpi, mi_row, mi_col + ms, &this_rate,
1902                     &this_dist, subsize, get_block_context(x, subsize),
1903                     best_rd - sum_rd);
1904       if (this_rate == INT_MAX) {
1905         sum_rd = INT64_MAX;
1906       } else {
1907         sum_rate += this_rate;
1908         sum_dist += this_dist;
1909         sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1910       }
1911     }
1912     if (sum_rd < best_rd) {
1913       set_partition_seg_context(cm, xd, mi_row, mi_col);
1914       pl = partition_plane_context(xd, bsize);
1915       sum_rate += x->partition_cost[pl][PARTITION_VERT];
1916       sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1917       if (sum_rd < best_rd) {
1918         best_rate = sum_rate;
1919         best_dist = sum_dist;
1920         best_rd = sum_rd;
1921         *(get_sb_partitioning(x, bsize)) = subsize;
1922       }
1923     }
1924     restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1925   }
1926
1927
1928   *rate = best_rate;
1929   *dist = best_dist;
1930
1931   if (best_rate < INT_MAX && best_dist < INT64_MAX && do_recon)
1932     encode_sb(cpi, tp, mi_row, mi_col, bsize == BLOCK_64X64, bsize);
1933   if (bsize == BLOCK_64X64) {
1934     assert(tp_orig < *tp);
1935     assert(best_rate < INT_MAX);
1936     assert(best_dist < INT_MAX);
1937   } else {
1938     assert(tp_orig == *tp);
1939   }
1940 }
1941
1942 // Examines 64x64 block and chooses a best reference frame
1943 static void rd_pick_reference_frame(VP9_COMP *cpi, int mi_row, int mi_col) {
1944   VP9_COMMON * const cm = &cpi->common;
1945   MACROBLOCK * const x = &cpi->mb;
1946   MACROBLOCKD * const xd = &x->e_mbd;
1947   int bsl = b_width_log2(BLOCK_64X64), bs = 1 << bsl;
1948   int ms = bs / 2;
1949   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1950   PARTITION_CONTEXT sl[8], sa[8];
1951   int pl;
1952   int r;
1953   int64_t d;
1954
1955   save_context(cpi, mi_row, mi_col, a, l, sa, sl, BLOCK_64X64);
1956
1957   // Default is non mask (all reference frames allowed.
1958   cpi->ref_frame_mask = 0;
1959
1960   // Do RD search for 64x64.
1961   if ((mi_row + (ms >> 1) < cm->mi_rows) &&
1962       (mi_col + (ms >> 1) < cm->mi_cols)) {
1963     cpi->set_ref_frame_mask = 1;
1964     pick_sb_modes(cpi, mi_row, mi_col, &r, &d, BLOCK_64X64,
1965                   get_block_context(x, BLOCK_64X64), INT64_MAX);
1966     set_partition_seg_context(cm, xd, mi_row, mi_col);
1967     pl = partition_plane_context(xd, BLOCK_64X64);
1968     r += x->partition_cost[pl][PARTITION_NONE];
1969
1970     *(get_sb_partitioning(x, BLOCK_64X64)) = BLOCK_64X64;
1971     cpi->set_ref_frame_mask = 0;
1972   }
1973
1974   restore_context(cpi, mi_row, mi_col, a, l, sa, sl, BLOCK_64X64);
1975 }
1976
1977 static void encode_sb_row(VP9_COMP *cpi, int mi_row, TOKENEXTRA **tp,
1978                           int *totalrate) {
1979   VP9_COMMON * const cm = &cpi->common;
1980   int mi_col;
1981
1982   // Initialize the left context for the new SB row
1983   vpx_memset(&cm->left_context, 0, sizeof(cm->left_context));
1984   vpx_memset(cm->left_seg_context, 0, sizeof(cm->left_seg_context));
1985
1986   // Code each SB in the row
1987   for (mi_col = cm->cur_tile_mi_col_start; mi_col < cm->cur_tile_mi_col_end;
1988        mi_col += MI_BLOCK_SIZE) {
1989     int dummy_rate;
1990     int64_t dummy_dist;
1991
1992     // Initialize a mask of modes that we will not consider;
1993     // cpi->unused_mode_skip_mask = 0x0000000AAE17F800 (test no golden)
1994     if (cpi->common.frame_type == KEY_FRAME)
1995       cpi->unused_mode_skip_mask = 0;
1996     else
1997       cpi->unused_mode_skip_mask = 0xFFFFFFFFFFFFFE00;
1998
1999     if (cpi->sf.reference_masking)
2000       rd_pick_reference_frame(cpi, mi_row, mi_col);
2001
2002     if (cpi->sf.partition_by_variance || cpi->sf.use_lastframe_partitioning ||
2003         cpi->sf.use_one_partition_size_always ) {
2004       const int idx_str = cm->mode_info_stride * mi_row + mi_col;
2005       MODE_INFO *m = cm->mi + idx_str;
2006       MODE_INFO *p = cm->prev_mi + idx_str;
2007
2008       cpi->mb.source_variance = UINT_MAX;
2009       if (cpi->sf.use_one_partition_size_always) {
2010         set_offsets(cpi, mi_row, mi_col, BLOCK_64X64);
2011         set_partitioning(cpi, m, mi_row, mi_col);
2012         rd_use_partition(cpi, m, tp, mi_row, mi_col, BLOCK_64X64,
2013                          &dummy_rate, &dummy_dist, 1);
2014       } else if (cpi->sf.partition_by_variance) {
2015         choose_partitioning(cpi, cm->mi, mi_row, mi_col);
2016         rd_use_partition(cpi, m, tp, mi_row, mi_col, BLOCK_64X64,
2017                          &dummy_rate, &dummy_dist, 1);
2018       } else {
2019         if ((cpi->common.current_video_frame
2020             % cpi->sf.last_partitioning_redo_frequency) == 0
2021             || cm->prev_mi == 0
2022             || cpi->common.show_frame == 0
2023             || cpi->common.frame_type == KEY_FRAME
2024             || cpi->is_src_frame_alt_ref) {
2025           // If required set upper and lower partition size limits
2026           if (cpi->sf.auto_min_max_partition_size) {
2027             set_offsets(cpi, mi_row, mi_col, BLOCK_64X64);
2028             rd_auto_partition_range(cpi,
2029                                     &cpi->sf.min_partition_size,
2030                                     &cpi->sf.max_partition_size);
2031           }
2032           rd_pick_partition(cpi, tp, mi_row, mi_col, BLOCK_64X64,
2033                             &dummy_rate, &dummy_dist, 1, INT64_MAX);
2034         } else {
2035           copy_partitioning(cpi, m, p);
2036           rd_use_partition(cpi, m, tp, mi_row, mi_col, BLOCK_64X64,
2037                            &dummy_rate, &dummy_dist, 1);
2038         }
2039       }
2040     } else {
2041       // If required set upper and lower partition size limits
2042       if (cpi->sf.auto_min_max_partition_size) {
2043         set_offsets(cpi, mi_row, mi_col, BLOCK_64X64);
2044         rd_auto_partition_range(cpi, &cpi->sf.min_partition_size,
2045                                 &cpi->sf.max_partition_size);
2046       }
2047
2048       rd_pick_partition(cpi, tp, mi_row, mi_col, BLOCK_64X64,
2049                         &dummy_rate, &dummy_dist, 1, INT64_MAX);
2050     }
2051   }
2052 }
2053
2054 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
2055   MACROBLOCK *const x = &cpi->mb;
2056   VP9_COMMON *const cm = &cpi->common;
2057   MACROBLOCKD *const xd = &x->e_mbd;
2058   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2059
2060   x->act_zbin_adj = 0;
2061   cpi->seg0_idx = 0;
2062
2063   xd->mode_info_stride = cm->mode_info_stride;
2064
2065   // reset intra mode contexts
2066   if (cm->frame_type == KEY_FRAME)
2067     vp9_init_mbmode_probs(cm);
2068
2069   // Copy data over into macro block data structures.
2070   vp9_setup_src_planes(x, cpi->Source, 0, 0);
2071
2072   // TODO(jkoleszar): are these initializations required?
2073   setup_pre_planes(xd, 0, &cm->yv12_fb[cm->ref_frame_map[cpi->lst_fb_idx]],
2074                    0, 0, NULL);
2075   setup_dst_planes(xd, &cm->yv12_fb[cm->new_fb_idx], 0, 0);
2076
2077   setup_block_dptrs(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
2078
2079   xd->mode_info_context->mbmi.mode = DC_PRED;
2080   xd->mode_info_context->mbmi.uv_mode = DC_PRED;
2081
2082   vp9_zero(cpi->y_mode_count)
2083   vp9_zero(cpi->y_uv_mode_count)
2084   vp9_zero(cm->counts.inter_mode)
2085   vp9_zero(cpi->partition_count);
2086   vp9_zero(cpi->intra_inter_count);
2087   vp9_zero(cpi->comp_inter_count);
2088   vp9_zero(cpi->single_ref_count);
2089   vp9_zero(cpi->comp_ref_count);
2090   vp9_zero(cm->counts.tx);
2091   vp9_zero(cm->counts.mbskip);
2092
2093   // Note: this memset assumes above_context[0], [1] and [2]
2094   // are allocated as part of the same buffer.
2095   vpx_memset(cm->above_context[0], 0,
2096              sizeof(ENTROPY_CONTEXT) * 2 * MAX_MB_PLANE * aligned_mi_cols);
2097   vpx_memset(cm->above_seg_context, 0,
2098              sizeof(PARTITION_CONTEXT) * aligned_mi_cols);
2099 }
2100
2101 static void switch_lossless_mode(VP9_COMP *cpi, int lossless) {
2102   if (lossless) {
2103     // printf("Switching to lossless\n");
2104     cpi->mb.fwd_txm8x4 = vp9_short_walsh8x4;
2105     cpi->mb.fwd_txm4x4 = vp9_short_walsh4x4;
2106     cpi->mb.e_mbd.inv_txm4x4_1_add = vp9_short_iwalsh4x4_1_add;
2107     cpi->mb.e_mbd.inv_txm4x4_add = vp9_short_iwalsh4x4_add;
2108     cpi->mb.optimize = 0;
2109     cpi->common.lf.filter_level = 0;
2110     cpi->zbin_mode_boost_enabled = 0;
2111     cpi->common.tx_mode = ONLY_4X4;
2112   } else {
2113     // printf("Not lossless\n");
2114     cpi->mb.fwd_txm8x4 = vp9_short_fdct8x4;
2115     cpi->mb.fwd_txm4x4 = vp9_short_fdct4x4;
2116     cpi->mb.e_mbd.inv_txm4x4_1_add = vp9_short_idct4x4_1_add;
2117     cpi->mb.e_mbd.inv_txm4x4_add = vp9_short_idct4x4_add;
2118   }
2119 }
2120
2121 static void switch_tx_mode(VP9_COMP *cpi) {
2122   if (cpi->sf.tx_size_search_method == USE_LARGESTALL &&
2123       cpi->common.tx_mode >= ALLOW_32X32)
2124     cpi->common.tx_mode = ALLOW_32X32;
2125 }
2126
2127 static void encode_frame_internal(VP9_COMP *cpi) {
2128   int mi_row;
2129   MACROBLOCK * const x = &cpi->mb;
2130   VP9_COMMON * const cm = &cpi->common;
2131   MACROBLOCKD * const xd = &x->e_mbd;
2132   int totalrate;
2133
2134 //  fprintf(stderr, "encode_frame_internal frame %d (%d) type %d\n",
2135 //           cpi->common.current_video_frame, cpi->common.show_frame,
2136 //           cm->frame_type);
2137
2138 // debug output
2139 #if DBG_PRNT_SEGMAP
2140   {
2141     FILE *statsfile;
2142     statsfile = fopen("segmap2.stt", "a");
2143     fprintf(statsfile, "\n");
2144     fclose(statsfile);
2145   }
2146 #endif
2147
2148   totalrate = 0;
2149
2150   // Reset frame count of inter 0,0 motion vector usage.
2151   cpi->inter_zz_count = 0;
2152
2153   vp9_zero(cm->counts.switchable_interp);
2154   vp9_zero(cpi->txfm_stepdown_count);
2155
2156   xd->mode_info_context = cm->mi;
2157   xd->prev_mode_info_context = cm->prev_mi;
2158
2159   vp9_zero(cpi->NMVcount);
2160   vp9_zero(cpi->coef_counts);
2161   vp9_zero(cm->counts.eob_branch);
2162
2163   cpi->mb.e_mbd.lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0
2164       && cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
2165   switch_lossless_mode(cpi, cpi->mb.e_mbd.lossless);
2166
2167   vp9_frame_init_quantizer(cpi);
2168
2169   vp9_initialize_rd_consts(cpi, cm->base_qindex + cm->y_dc_delta_q);
2170   vp9_initialize_me_consts(cpi, cm->base_qindex);
2171   switch_tx_mode(cpi);
2172
2173   if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
2174     // Initialize encode frame context.
2175     init_encode_frame_mb_context(cpi);
2176
2177     // Build a frame level activity map
2178     build_activity_map(cpi);
2179   }
2180
2181   // Re-initialize encode frame context.
2182   init_encode_frame_mb_context(cpi);
2183
2184   vp9_zero(cpi->rd_comp_pred_diff);
2185   vp9_zero(cpi->rd_filter_diff);
2186   vp9_zero(cpi->rd_tx_select_diff);
2187   vp9_zero(cpi->rd_tx_select_threshes);
2188
2189   set_prev_mi(cm);
2190
2191   {
2192     struct vpx_usec_timer emr_timer;
2193     vpx_usec_timer_start(&emr_timer);
2194
2195     {
2196       // Take tiles into account and give start/end MB
2197       int tile_col, tile_row;
2198       TOKENEXTRA *tp = cpi->tok;
2199       const int tile_cols = 1 << cm->log2_tile_cols;
2200       const int tile_rows = 1 << cm->log2_tile_rows;
2201
2202       for (tile_row = 0; tile_row < tile_rows; tile_row++) {
2203         vp9_get_tile_row_offsets(cm, tile_row);
2204
2205         for (tile_col = 0; tile_col < tile_cols; tile_col++) {
2206           TOKENEXTRA *tp_old = tp;
2207
2208           // For each row of SBs in the frame
2209           vp9_get_tile_col_offsets(cm, tile_col);
2210           for (mi_row = cm->cur_tile_mi_row_start;
2211                mi_row < cm->cur_tile_mi_row_end; mi_row += 8)
2212             encode_sb_row(cpi, mi_row, &tp, &totalrate);
2213
2214           cpi->tok_count[tile_row][tile_col] = (unsigned int)(tp - tp_old);
2215           assert(tp - cpi->tok <= get_token_alloc(cm->mb_rows, cm->mb_cols));
2216         }
2217       }
2218     }
2219
2220     vpx_usec_timer_mark(&emr_timer);
2221     cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
2222   }
2223
2224   if (cpi->sf.skip_encode_sb) {
2225     int j;
2226     unsigned int intra_count = 0, inter_count = 0;
2227     for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
2228       intra_count += cpi->intra_inter_count[j][0];
2229       inter_count += cpi->intra_inter_count[j][1];
2230     }
2231     cpi->sf.skip_encode_frame = ((intra_count << 2) < inter_count);
2232     cpi->sf.skip_encode_frame &= (cm->frame_type != KEY_FRAME);
2233     cpi->sf.skip_encode_frame &= cm->show_frame;
2234   } else {
2235     cpi->sf.skip_encode_frame = 0;
2236   }
2237
2238   // 256 rate units to the bit,
2239   // projected_frame_size in units of BYTES
2240   cpi->projected_frame_size = totalrate >> 8;
2241
2242 #if 0
2243   // Keep record of the total distortion this time around for future use
2244   cpi->last_frame_distortion = cpi->frame_distortion;
2245 #endif
2246
2247 }
2248
2249 static int check_dual_ref_flags(VP9_COMP *cpi) {
2250   const int ref_flags = cpi->ref_frame_flags;
2251
2252   if (vp9_segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
2253     return 0;
2254   } else {
2255     return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG)
2256         + !!(ref_flags & VP9_ALT_FLAG)) >= 2;
2257   }
2258 }
2259
2260 static int get_skip_flag(MODE_INFO *mi, int mis, int ymbs, int xmbs) {
2261   int x, y;
2262
2263   for (y = 0; y < ymbs; y++) {
2264     for (x = 0; x < xmbs; x++) {
2265       if (!mi[y * mis + x].mbmi.skip_coeff)
2266         return 0;
2267     }
2268   }
2269
2270   return 1;
2271 }
2272
2273 static void set_txfm_flag(MODE_INFO *mi, int mis, int ymbs, int xmbs,
2274                           TX_SIZE tx_size) {
2275   int x, y;
2276
2277   for (y = 0; y < ymbs; y++) {
2278     for (x = 0; x < xmbs; x++)
2279       mi[y * mis + x].mbmi.tx_size = tx_size;
2280   }
2281 }
2282
2283 static void reset_skip_txfm_size_b(VP9_COMP *cpi, MODE_INFO *mi, int mis,
2284                                    TX_SIZE max_tx_size, int bw, int bh,
2285                                    int mi_row, int mi_col, BLOCK_SIZE bsize) {
2286   VP9_COMMON *const cm = &cpi->common;
2287   MB_MODE_INFO *const mbmi = &mi->mbmi;
2288
2289   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
2290     return;
2291
2292   if (mbmi->tx_size > max_tx_size) {
2293     MACROBLOCK * const x = &cpi->mb;
2294     MACROBLOCKD * const xd = &x->e_mbd;
2295     const int ymbs = MIN(bh, cm->mi_rows - mi_row);
2296     const int xmbs = MIN(bw, cm->mi_cols - mi_col);
2297
2298     xd->mode_info_context = mi;
2299     assert(vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP) ||
2300            get_skip_flag(mi, mis, ymbs, xmbs));
2301     set_txfm_flag(mi, mis, ymbs, xmbs, max_tx_size);
2302   }
2303 }
2304
2305 static void reset_skip_txfm_size_sb(VP9_COMP *cpi, MODE_INFO *mi,
2306                                     TX_SIZE max_tx_size, int mi_row, int mi_col,
2307                                     BLOCK_SIZE bsize) {
2308   const VP9_COMMON *const cm = &cpi->common;
2309   const int mis = cm->mode_info_stride;
2310   int bw, bh;
2311   const int bs = num_8x8_blocks_wide_lookup[bsize], hbs = bs / 2;
2312
2313   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
2314     return;
2315
2316   bw = num_8x8_blocks_wide_lookup[mi->mbmi.sb_type];
2317   bh = num_8x8_blocks_high_lookup[mi->mbmi.sb_type];
2318
2319   if (bw == bs && bh == bs) {
2320     reset_skip_txfm_size_b(cpi, mi, mis, max_tx_size, bs, bs, mi_row,
2321                            mi_col, bsize);
2322   } else if (bw == bs && bh < bs) {
2323     reset_skip_txfm_size_b(cpi, mi, mis, max_tx_size, bs, hbs, mi_row, mi_col,
2324                            bsize);
2325     reset_skip_txfm_size_b(cpi, mi + hbs * mis, mis, max_tx_size, bs, hbs,
2326                            mi_row + hbs, mi_col, bsize);
2327   } else if (bw < bs && bh == bs) {
2328     reset_skip_txfm_size_b(cpi, mi, mis, max_tx_size, hbs, bs, mi_row, mi_col,
2329                            bsize);
2330     reset_skip_txfm_size_b(cpi, mi + hbs, mis, max_tx_size, hbs, bs, mi_row,
2331                            mi_col + hbs, bsize);
2332   } else {
2333     const BLOCK_SIZE subsize = subsize_lookup[PARTITION_SPLIT][bsize];
2334     int n;
2335
2336     assert(bw < bs && bh < bs);
2337
2338     for (n = 0; n < 4; n++) {
2339       const int mi_dc = hbs * (n & 1);
2340       const int mi_dr = hbs * (n >> 1);
2341
2342       reset_skip_txfm_size_sb(cpi, &mi[mi_dr * mis + mi_dc], max_tx_size,
2343                               mi_row + mi_dr, mi_col + mi_dc, subsize);
2344     }
2345   }
2346 }
2347
2348 static void reset_skip_txfm_size(VP9_COMP *cpi, TX_SIZE txfm_max) {
2349   VP9_COMMON * const cm = &cpi->common;
2350   int mi_row, mi_col;
2351   const int mis = cm->mode_info_stride;
2352   MODE_INFO *mi, *mi_ptr = cm->mi;
2353
2354   for (mi_row = 0; mi_row < cm->mi_rows; mi_row += 8, mi_ptr += 8 * mis) {
2355     mi = mi_ptr;
2356     for (mi_col = 0; mi_col < cm->mi_cols; mi_col += 8, mi += 8)
2357       reset_skip_txfm_size_sb(cpi, mi, txfm_max, mi_row, mi_col, BLOCK_64X64);
2358   }
2359 }
2360
2361 static int get_frame_type(VP9_COMP *cpi) {
2362   int frame_type;
2363   if (cpi->common.frame_type == KEY_FRAME)
2364     frame_type = 0;
2365   else if (cpi->is_src_frame_alt_ref && cpi->refresh_golden_frame)
2366     frame_type = 3;
2367   else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
2368     frame_type = 1;
2369   else
2370     frame_type = 2;
2371   return frame_type;
2372 }
2373
2374 static void select_tx_mode(VP9_COMP *cpi) {
2375   if (cpi->oxcf.lossless) {
2376     cpi->common.tx_mode = ONLY_4X4;
2377   } else if (cpi->common.current_video_frame == 0) {
2378     cpi->common.tx_mode = TX_MODE_SELECT;
2379   } else {
2380     if (cpi->sf.tx_size_search_method == USE_LARGESTALL) {
2381       cpi->common.tx_mode = ALLOW_32X32;
2382     } else if (cpi->sf.tx_size_search_method == USE_FULL_RD) {
2383       int frame_type = get_frame_type(cpi);
2384       cpi->common.tx_mode =
2385           cpi->rd_tx_select_threshes[frame_type][ALLOW_32X32]
2386           > cpi->rd_tx_select_threshes[frame_type][TX_MODE_SELECT] ?
2387           ALLOW_32X32 : TX_MODE_SELECT;
2388     } else {
2389       unsigned int total = 0;
2390       int i;
2391       for (i = 0; i < TX_SIZES; ++i)
2392         total += cpi->txfm_stepdown_count[i];
2393       if (total) {
2394         double fraction = (double)cpi->txfm_stepdown_count[0] / total;
2395         cpi->common.tx_mode = fraction > 0.90 ? ALLOW_32X32 : TX_MODE_SELECT;
2396         // printf("fraction = %f\n", fraction);
2397       }  // else keep unchanged
2398     }
2399   }
2400 }
2401
2402 void vp9_encode_frame(VP9_COMP *cpi) {
2403   VP9_COMMON * const cm = &cpi->common;
2404
2405   // In the longer term the encoder should be generalized to match the
2406   // decoder such that we allow compound where one of the 3 buffers has a
2407   // different sign bias and that buffer is then the fixed ref. However, this
2408   // requires further work in the rd loop. For now the only supported encoder
2409   // side behavior is where the ALT ref buffer has opposite sign bias to
2410   // the other two.
2411   if ((cm->ref_frame_sign_bias[ALTREF_FRAME]
2412        == cm->ref_frame_sign_bias[GOLDEN_FRAME])
2413       || (cm->ref_frame_sign_bias[ALTREF_FRAME]
2414           == cm->ref_frame_sign_bias[LAST_FRAME])) {
2415     cm->allow_comp_inter_inter = 0;
2416   } else {
2417     cm->allow_comp_inter_inter = 1;
2418     cm->comp_fixed_ref = ALTREF_FRAME;
2419     cm->comp_var_ref[0] = LAST_FRAME;
2420     cm->comp_var_ref[1] = GOLDEN_FRAME;
2421   }
2422
2423   if (cpi->sf.RD) {
2424     int i, pred_type;
2425     INTERPOLATIONFILTERTYPE filter_type;
2426     /*
2427      * This code does a single RD pass over the whole frame assuming
2428      * either compound, single or hybrid prediction as per whatever has
2429      * worked best for that type of frame in the past.
2430      * It also predicts whether another coding mode would have worked
2431      * better that this coding mode. If that is the case, it remembers
2432      * that for subsequent frames.
2433      * It does the same analysis for transform size selection also.
2434      */
2435     int frame_type = get_frame_type(cpi);
2436
2437     /* prediction (compound, single or hybrid) mode selection */
2438     if (frame_type == 3 || !cm->allow_comp_inter_inter)
2439       pred_type = SINGLE_PREDICTION_ONLY;
2440     else if (cpi->rd_prediction_type_threshes[frame_type][1]
2441              > cpi->rd_prediction_type_threshes[frame_type][0]
2442              && cpi->rd_prediction_type_threshes[frame_type][1]
2443              > cpi->rd_prediction_type_threshes[frame_type][2]
2444              && check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
2445       pred_type = COMP_PREDICTION_ONLY;
2446     else if (cpi->rd_prediction_type_threshes[frame_type][0]
2447              > cpi->rd_prediction_type_threshes[frame_type][2])
2448       pred_type = SINGLE_PREDICTION_ONLY;
2449     else
2450       pred_type = HYBRID_PREDICTION;
2451
2452     /* filter type selection */
2453     // FIXME(rbultje) for some odd reason, we often select smooth_filter
2454     // as default filter for ARF overlay frames. This is a REALLY BAD
2455     // IDEA so we explicitly disable it here.
2456     if (frame_type != 3 &&
2457         cpi->rd_filter_threshes[frame_type][1] >
2458             cpi->rd_filter_threshes[frame_type][0] &&
2459         cpi->rd_filter_threshes[frame_type][1] >
2460             cpi->rd_filter_threshes[frame_type][2] &&
2461         cpi->rd_filter_threshes[frame_type][1] >
2462             cpi->rd_filter_threshes[frame_type][SWITCHABLE_FILTERS]) {
2463       filter_type = EIGHTTAP_SMOOTH;
2464     } else if (cpi->rd_filter_threshes[frame_type][2] >
2465             cpi->rd_filter_threshes[frame_type][0] &&
2466         cpi->rd_filter_threshes[frame_type][2] >
2467             cpi->rd_filter_threshes[frame_type][SWITCHABLE_FILTERS]) {
2468       filter_type = EIGHTTAP_SHARP;
2469     } else if (cpi->rd_filter_threshes[frame_type][0] >
2470                   cpi->rd_filter_threshes[frame_type][SWITCHABLE_FILTERS]) {
2471       filter_type = EIGHTTAP;
2472     } else {
2473       filter_type = SWITCHABLE;
2474     }
2475
2476     cpi->mb.e_mbd.lossless = 0;
2477     if (cpi->oxcf.lossless) {
2478       cpi->mb.e_mbd.lossless = 1;
2479     }
2480
2481     /* transform size selection (4x4, 8x8, 16x16 or select-per-mb) */
2482     select_tx_mode(cpi);
2483     cpi->common.comp_pred_mode = pred_type;
2484     cpi->common.mcomp_filter_type = filter_type;
2485     encode_frame_internal(cpi);
2486
2487     for (i = 0; i < NB_PREDICTION_TYPES; ++i) {
2488       const int diff = (int) (cpi->rd_comp_pred_diff[i] / cpi->common.MBs);
2489       cpi->rd_prediction_type_threshes[frame_type][i] += diff;
2490       cpi->rd_prediction_type_threshes[frame_type][i] >>= 1;
2491     }
2492
2493     for (i = 0; i <= SWITCHABLE_FILTERS; i++) {
2494       const int64_t diff = cpi->rd_filter_diff[i] / cpi->common.MBs;
2495       cpi->rd_filter_threshes[frame_type][i] =
2496           (cpi->rd_filter_threshes[frame_type][i] + diff) / 2;
2497     }
2498
2499     for (i = 0; i < TX_MODES; ++i) {
2500       int64_t pd = cpi->rd_tx_select_diff[i];
2501       int diff;
2502       if (i == TX_MODE_SELECT)
2503         pd -= RDCOST(cpi->mb.rdmult, cpi->mb.rddiv,
2504                      2048 * (TX_SIZES - 1), 0);
2505       diff = (int) (pd / cpi->common.MBs);
2506       cpi->rd_tx_select_threshes[frame_type][i] += diff;
2507       cpi->rd_tx_select_threshes[frame_type][i] /= 2;
2508     }
2509
2510     if (cpi->common.comp_pred_mode == HYBRID_PREDICTION) {
2511       int single_count_zero = 0;
2512       int comp_count_zero = 0;
2513
2514       for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
2515         single_count_zero += cpi->comp_inter_count[i][0];
2516         comp_count_zero += cpi->comp_inter_count[i][1];
2517       }
2518
2519       if (comp_count_zero == 0) {
2520         cpi->common.comp_pred_mode = SINGLE_PREDICTION_ONLY;
2521         vp9_zero(cpi->comp_inter_count);
2522       } else if (single_count_zero == 0) {
2523         cpi->common.comp_pred_mode = COMP_PREDICTION_ONLY;
2524         vp9_zero(cpi->comp_inter_count);
2525       }
2526     }
2527
2528     if (cpi->common.tx_mode == TX_MODE_SELECT) {
2529       int count4x4 = 0;
2530       int count8x8_lp = 0, count8x8_8x8p = 0;
2531       int count16x16_16x16p = 0, count16x16_lp = 0;
2532       int count32x32 = 0;
2533
2534       for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
2535         count4x4 += cm->counts.tx.p32x32[i][TX_4X4];
2536         count4x4 += cm->counts.tx.p16x16[i][TX_4X4];
2537         count4x4 += cm->counts.tx.p8x8[i][TX_4X4];
2538
2539         count8x8_lp += cm->counts.tx.p32x32[i][TX_8X8];
2540         count8x8_lp += cm->counts.tx.p16x16[i][TX_8X8];
2541         count8x8_8x8p += cm->counts.tx.p8x8[i][TX_8X8];
2542
2543         count16x16_16x16p += cm->counts.tx.p16x16[i][TX_16X16];
2544         count16x16_lp += cm->counts.tx.p32x32[i][TX_16X16];
2545         count32x32 += cm->counts.tx.p32x32[i][TX_32X32];
2546       }
2547
2548       if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0
2549           && count32x32 == 0) {
2550         cpi->common.tx_mode = ALLOW_8X8;
2551         reset_skip_txfm_size(cpi, TX_8X8);
2552       } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0
2553                  && count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
2554         cpi->common.tx_mode = ONLY_4X4;
2555         reset_skip_txfm_size(cpi, TX_4X4);
2556       } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
2557         cpi->common.tx_mode = ALLOW_32X32;
2558       } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
2559         cpi->common.tx_mode = ALLOW_16X16;
2560         reset_skip_txfm_size(cpi, TX_16X16);
2561       }
2562     }
2563   } else {
2564     encode_frame_internal(cpi);
2565   }
2566
2567 }
2568
2569 static void sum_intra_stats(VP9_COMP *cpi, const MODE_INFO *mi) {
2570   const MB_PREDICTION_MODE y_mode = mi->mbmi.mode;
2571   const MB_PREDICTION_MODE uv_mode = mi->mbmi.uv_mode;
2572   const BLOCK_SIZE bsize = mi->mbmi.sb_type;
2573
2574   ++cpi->y_uv_mode_count[y_mode][uv_mode];
2575
2576   if (bsize < BLOCK_8X8) {
2577     int idx, idy;
2578     const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2579     const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2580     for (idy = 0; idy < 2; idy += num_4x4_blocks_high)
2581       for (idx = 0; idx < 2; idx += num_4x4_blocks_wide)
2582         ++cpi->y_mode_count[0][mi->bmi[idy * 2 + idx].as_mode];
2583   } else {
2584     ++cpi->y_mode_count[size_group_lookup[bsize]][y_mode];
2585   }
2586 }
2587
2588 // Experimental stub function to create a per MB zbin adjustment based on
2589 // some previously calculated measure of MB activity.
2590 static void adjust_act_zbin(VP9_COMP *cpi, MACROBLOCK *x) {
2591 #if USE_ACT_INDEX
2592   x->act_zbin_adj = *(x->mb_activity_ptr);
2593 #else
2594   int64_t a;
2595   int64_t b;
2596   int64_t act = *(x->mb_activity_ptr);
2597
2598   // Apply the masking to the RD multiplier.
2599   a = act + 4 * cpi->activity_avg;
2600   b = 4 * act + cpi->activity_avg;
2601
2602   if (act > cpi->activity_avg)
2603     x->act_zbin_adj = (int) (((int64_t) b + (a >> 1)) / a) - 1;
2604   else
2605     x->act_zbin_adj = 1 - (int) (((int64_t) a + (b >> 1)) / b);
2606 #endif
2607 }
2608
2609 static void encode_superblock(VP9_COMP *cpi, TOKENEXTRA **t, int output_enabled,
2610                               int mi_row, int mi_col, BLOCK_SIZE bsize) {
2611   VP9_COMMON * const cm = &cpi->common;
2612   MACROBLOCK * const x = &cpi->mb;
2613   MACROBLOCKD * const xd = &x->e_mbd;
2614   MODE_INFO *mi = xd->mode_info_context;
2615   MB_MODE_INFO *mbmi = &mi->mbmi;
2616   unsigned int segment_id = mbmi->segment_id;
2617   const int mis = cm->mode_info_stride;
2618   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
2619   const int mi_height = num_8x8_blocks_high_lookup[bsize];
2620   x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
2621   x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
2622                     xd->q_index < QIDX_SKIP_THRESH);
2623   if (x->skip_encode)
2624     return;
2625
2626   if (cm->frame_type == KEY_FRAME) {
2627     if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
2628       adjust_act_zbin(cpi, x);
2629       vp9_update_zbin_extra(cpi, x);
2630     }
2631   } else {
2632     vp9_setup_interp_filters(xd, mbmi->interp_filter, cm);
2633
2634     if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
2635       // Adjust the zbin based on this MB rate.
2636       adjust_act_zbin(cpi, x);
2637     }
2638
2639     // Experimental code. Special case for gf and arf zeromv modes.
2640     // Increase zbin size to suppress noise
2641     cpi->zbin_mode_boost = 0;
2642     if (cpi->zbin_mode_boost_enabled) {
2643       if (is_inter_block(mbmi)) {
2644         if (mbmi->mode == ZEROMV) {
2645           if (mbmi->ref_frame[0] != LAST_FRAME)
2646             cpi->zbin_mode_boost = GF_ZEROMV_ZBIN_BOOST;
2647           else
2648             cpi->zbin_mode_boost = LF_ZEROMV_ZBIN_BOOST;
2649         } else if (mbmi->sb_type < BLOCK_8X8) {
2650           cpi->zbin_mode_boost = SPLIT_MV_ZBIN_BOOST;
2651         } else {
2652           cpi->zbin_mode_boost = MV_ZBIN_BOOST;
2653         }
2654       } else {
2655         cpi->zbin_mode_boost = INTRA_ZBIN_BOOST;
2656       }
2657     }
2658
2659     vp9_update_zbin_extra(cpi, x);
2660   }
2661
2662   if (!is_inter_block(mbmi)) {
2663     vp9_encode_intra_block_y(x, MAX(bsize, BLOCK_8X8));
2664     vp9_encode_intra_block_uv(x, MAX(bsize, BLOCK_8X8));
2665     if (output_enabled)
2666       sum_intra_stats(cpi, mi);
2667   } else {
2668     int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, mbmi->ref_frame[0])];
2669     YV12_BUFFER_CONFIG *ref_fb = &cm->yv12_fb[idx];
2670     YV12_BUFFER_CONFIG *second_ref_fb = NULL;
2671     if (mbmi->ref_frame[1] > 0) {
2672       idx = cm->ref_frame_map[get_ref_frame_idx(cpi, mbmi->ref_frame[1])];
2673       second_ref_fb = &cm->yv12_fb[idx];
2674     }
2675
2676     assert(cm->frame_type != KEY_FRAME);
2677
2678     setup_pre_planes(xd, 0, ref_fb, mi_row, mi_col,
2679                      &xd->scale_factor[0]);
2680     setup_pre_planes(xd, 1, second_ref_fb, mi_row, mi_col,
2681                      &xd->scale_factor[1]);
2682
2683
2684     vp9_build_inter_predictors_sb(xd, mi_row, mi_col, MAX(bsize, BLOCK_8X8));
2685   }
2686
2687   if (!is_inter_block(mbmi)) {
2688     vp9_tokenize_sb(cpi, t, !output_enabled, MAX(bsize, BLOCK_8X8));
2689   } else if (!x->skip) {
2690     vp9_encode_sb(x, MAX(bsize, BLOCK_8X8));
2691     vp9_tokenize_sb(cpi, t, !output_enabled, MAX(bsize, BLOCK_8X8));
2692   } else {
2693     int mb_skip_context = xd->left_available ? (mi - 1)->mbmi.skip_coeff : 0;
2694     mb_skip_context += (mi - mis)->mbmi.skip_coeff;
2695
2696     mbmi->skip_coeff = 1;
2697     if (output_enabled)
2698       cm->counts.mbskip[mb_skip_context][1]++;
2699     reset_skip_context(xd, MAX(bsize, BLOCK_8X8));
2700   }
2701
2702   // copy skip flag on all mb_mode_info contexts in this SB
2703   // if this was a skip at this txfm size
2704   vp9_set_pred_flag_mbskip(cm, bsize, mi_row, mi_col, mi->mbmi.skip_coeff);
2705
2706   if (output_enabled) {
2707     if (cm->tx_mode == TX_MODE_SELECT &&
2708         mbmi->sb_type >= BLOCK_8X8  &&
2709         !(is_inter_block(mbmi) &&
2710             (mbmi->skip_coeff ||
2711              vp9_segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP)))) {
2712       const uint8_t context = vp9_get_pred_context_tx_size(xd);
2713       update_tx_counts(bsize, context, mbmi->tx_size, &cm->counts.tx);
2714     } else {
2715       int x, y;
2716       TX_SIZE sz = (cm->tx_mode == TX_MODE_SELECT) ? TX_32X32 : cm->tx_mode;
2717       // The new intra coding scheme requires no change of transform size
2718       if (is_inter_block(&mi->mbmi)) {
2719         if (sz == TX_32X32 && bsize < BLOCK_32X32)
2720           sz = TX_16X16;
2721         if (sz == TX_16X16 && bsize < BLOCK_16X16)
2722           sz = TX_8X8;
2723         if (sz == TX_8X8 && bsize < BLOCK_8X8)
2724           sz = TX_4X4;
2725       } else if (bsize >= BLOCK_8X8) {
2726         sz = mbmi->tx_size;
2727       } else {
2728         sz = TX_4X4;
2729       }
2730
2731       for (y = 0; y < mi_height; y++)
2732         for (x = 0; x < mi_width; x++)
2733           if (mi_col + x < cm->mi_cols && mi_row + y < cm->mi_rows)
2734             mi[mis * y + x].mbmi.tx_size = sz;
2735     }
2736   }
2737 }