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