2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
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.
15 #include "./vp9_rtcd.h"
16 #include "./vpx_config.h"
18 #include "vpx_ports/vpx_timer.h"
20 #include "vp9/common/vp9_common.h"
21 #include "vp9/common/vp9_entropy.h"
22 #include "vp9/common/vp9_entropymode.h"
23 #include "vp9/common/vp9_extend.h"
24 #include "vp9/common/vp9_findnearmv.h"
25 #include "vp9/common/vp9_mvref_common.h"
26 #include "vp9/common/vp9_pred_common.h"
27 #include "vp9/common/vp9_quant_common.h"
28 #include "vp9/common/vp9_reconintra.h"
29 #include "vp9/common/vp9_reconinter.h"
30 #include "vp9/common/vp9_seg_common.h"
31 #include "vp9/common/vp9_tile_common.h"
33 #include "vp9/encoder/vp9_encodeframe.h"
34 #include "vp9/encoder/vp9_encodeintra.h"
35 #include "vp9/encoder/vp9_encodemb.h"
36 #include "vp9/encoder/vp9_encodemv.h"
37 #include "vp9/encoder/vp9_onyx_int.h"
38 #include "vp9/encoder/vp9_rdopt.h"
39 #include "vp9/encoder/vp9_segmentation.h"
40 #include "vp9/encoder/vp9_tokenize.h"
42 #define DBG_PRNT_SEGMAP 0
49 static void encode_superblock(VP9_COMP *cpi, TOKENEXTRA **t, int output_enabled,
50 int mi_row, int mi_col, BLOCK_SIZE bsize);
52 static void adjust_act_zbin(VP9_COMP *cpi, MACROBLOCK *x);
54 /* activity_avg must be positive, or flat regions could get a zero weight
55 * (infinite lambda), which confounds analysis.
56 * This also avoids the need for divide by zero checks in
57 * vp9_activity_masking().
59 #define ACTIVITY_AVG_MIN (64)
61 /* Motion vector component magnitude threshold for defining fast motion. */
62 #define FAST_MOTION_MV_THRESH (24)
64 /* This is used as a reference when computing the source variance for the
65 * purposes of activity masking.
66 * Eventually this should be replaced by custom no-reference routines,
67 * which will be faster.
69 static const uint8_t VP9_VAR_OFFS[64] = {
70 128, 128, 128, 128, 128, 128, 128, 128,
71 128, 128, 128, 128, 128, 128, 128, 128,
72 128, 128, 128, 128, 128, 128, 128, 128,
73 128, 128, 128, 128, 128, 128, 128, 128,
74 128, 128, 128, 128, 128, 128, 128, 128,
75 128, 128, 128, 128, 128, 128, 128, 128,
76 128, 128, 128, 128, 128, 128, 128, 128,
77 128, 128, 128, 128, 128, 128, 128, 128
80 static unsigned int get_sby_perpixel_variance(VP9_COMP *cpi, MACROBLOCK *x,
82 unsigned int var, sse;
83 var = cpi->fn_ptr[bs].vf(x->plane[0].src.buf,
84 x->plane[0].src.stride,
85 VP9_VAR_OFFS, 0, &sse);
86 return (var + (1 << (num_pels_log2_lookup[bs] - 1))) >>
87 num_pels_log2_lookup[bs];
90 // Original activity measure from Tim T's code.
91 static unsigned int tt_activity_measure(MACROBLOCK *x) {
94 /* TODO: This could also be done over smaller areas (8x8), but that would
95 * require extensive changes elsewhere, as lambda is assumed to be fixed
96 * over an entire MB in most of the code.
97 * Another option is to compute four 8x8 variances, and pick a single
98 * lambda using a non-linear combination (e.g., the smallest, or second
101 act = vp9_variance16x16(x->plane[0].src.buf, x->plane[0].src.stride,
102 VP9_VAR_OFFS, 0, &sse);
105 /* If the region is flat, lower the activity some more. */
107 act = act < 5 << 12 ? act : 5 << 12;
112 // Stub for alternative experimental activity measures.
113 static unsigned int alt_activity_measure(MACROBLOCK *x, int use_dc_pred) {
114 return vp9_encode_intra(x, use_dc_pred);
116 DECLARE_ALIGNED(16, static const uint8_t, vp9_64x64_zeros[64*64]) = {0};
118 // Measure the activity of the current macroblock
119 // What we measure here is TBD so abstracted to this function
120 #define ALT_ACT_MEASURE 1
121 static unsigned int mb_activity_measure(MACROBLOCK *x, int mb_row, int mb_col) {
122 unsigned int mb_activity;
124 if (ALT_ACT_MEASURE) {
125 int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
127 // Or use and alternative.
128 mb_activity = alt_activity_measure(x, use_dc_pred);
130 // Original activity measure from Tim T's code.
131 mb_activity = tt_activity_measure(x);
134 if (mb_activity < ACTIVITY_AVG_MIN)
135 mb_activity = ACTIVITY_AVG_MIN;
140 // Calculate an "average" mb activity value for the frame
142 static void calc_av_activity(VP9_COMP *cpi, int64_t activity_sum) {
144 // Find median: Simple n^2 algorithm for experimentation
148 unsigned int *sortlist;
151 // Create a list to sort to
152 CHECK_MEM_ERROR(&cpi->common, sortlist, vpx_calloc(sizeof(unsigned int),
155 // Copy map to sort list
156 vpx_memcpy(sortlist, cpi->mb_activity_map,
157 sizeof(unsigned int) * cpi->common.MBs);
159 // Ripple each value down to its correct position
160 for (i = 1; i < cpi->common.MBs; i ++) {
161 for (j = i; j > 0; j --) {
162 if (sortlist[j] < sortlist[j - 1]) {
164 tmp = sortlist[j - 1];
165 sortlist[j - 1] = sortlist[j];
172 // Even number MBs so estimate median as mean of two either side.
173 median = (1 + sortlist[cpi->common.MBs >> 1] +
174 sortlist[(cpi->common.MBs >> 1) + 1]) >> 1;
176 cpi->activity_avg = median;
181 // Simple mean for now
182 cpi->activity_avg = (unsigned int) (activity_sum / cpi->common.MBs);
185 if (cpi->activity_avg < ACTIVITY_AVG_MIN)
186 cpi->activity_avg = ACTIVITY_AVG_MIN;
188 // Experimental code: return fixed value normalized for several clips
190 cpi->activity_avg = 100000;
193 #define USE_ACT_INDEX 0
194 #define OUTPUT_NORM_ACT_STATS 0
197 // Calculate an activity index for each mb
198 static void calc_activity_index(VP9_COMP *cpi, MACROBLOCK *x) {
199 VP9_COMMON *const cm = &cpi->common;
206 #if OUTPUT_NORM_ACT_STATS
207 FILE *f = fopen("norm_act.stt", "a");
208 fprintf(f, "\n%12d\n", cpi->activity_avg);
211 // Reset pointers to start of activity map
212 x->mb_activity_ptr = cpi->mb_activity_map;
214 // Calculate normalized mb activity number.
215 for (mb_row = 0; mb_row < cm->mb_rows; mb_row++) {
216 // for each macroblock col in image
217 for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
218 // Read activity from the map
219 act = *(x->mb_activity_ptr);
221 // Calculate a normalized activity number
222 a = act + 4 * cpi->activity_avg;
223 b = 4 * act + cpi->activity_avg;
226 *(x->activity_ptr) = (int)((b + (a >> 1)) / a) - 1;
228 *(x->activity_ptr) = 1 - (int)((a + (b >> 1)) / b);
230 #if OUTPUT_NORM_ACT_STATS
231 fprintf(f, " %6d", *(x->mb_activity_ptr));
233 // Increment activity map pointers
234 x->mb_activity_ptr++;
237 #if OUTPUT_NORM_ACT_STATS
243 #if OUTPUT_NORM_ACT_STATS
248 #endif // USE_ACT_INDEX
250 // Loop through all MBs. Note activity of each, average activity and
251 // calculate a normalized activity for each
252 static void build_activity_map(VP9_COMP *cpi) {
253 MACROBLOCK * const x = &cpi->mb;
254 MACROBLOCKD *xd = &x->e_mbd;
255 VP9_COMMON * const cm = &cpi->common;
258 YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
260 int recon_y_stride = new_yv12->y_stride;
264 unsigned int mb_activity;
265 int64_t activity_sum = 0;
267 x->mb_activity_ptr = cpi->mb_activity_map;
269 // for each macroblock row in image
270 for (mb_row = 0; mb_row < cm->mb_rows; mb_row++) {
272 // reset above block coeffs
273 xd->up_available = (mb_row != 0);
274 recon_yoffset = (mb_row * recon_y_stride * 16);
276 // for each macroblock col in image
277 for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
279 xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
280 xd->left_available = (mb_col != 0);
285 mb_activity = mb_activity_measure(x, mb_row, mb_col);
288 activity_sum += mb_activity;
290 // Store MB level activity details.
291 *x->mb_activity_ptr = mb_activity;
293 // Increment activity map pointer
294 x->mb_activity_ptr++;
296 // adjust to the next column of source macroblocks
297 x->plane[0].src.buf += 16;
300 // adjust to the next row of mbs
301 x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
304 // Calculate an "average" MB activity
305 calc_av_activity(cpi, activity_sum);
308 // Calculate an activity index number of each mb
309 calc_activity_index(cpi, x);
314 // Macroblock activity masking
315 void vp9_activity_masking(VP9_COMP *cpi, MACROBLOCK *x) {
317 x->rdmult += *(x->mb_activity_ptr) * (x->rdmult >> 2);
318 x->errorperbit = x->rdmult * 100 / (110 * x->rddiv);
319 x->errorperbit += (x->errorperbit == 0);
323 int64_t act = *(x->mb_activity_ptr);
325 // Apply the masking to the RD multiplier.
326 a = act + (2 * cpi->activity_avg);
327 b = (2 * act) + cpi->activity_avg;
329 x->rdmult = (unsigned int) (((int64_t) x->rdmult * b + (a >> 1)) / a);
330 x->errorperbit = x->rdmult * 100 / (110 * x->rddiv);
331 x->errorperbit += (x->errorperbit == 0);
334 // Activity based Zbin adjustment
335 adjust_act_zbin(cpi, x);
338 static void update_state(VP9_COMP *cpi, PICK_MODE_CONTEXT *ctx,
339 BLOCK_SIZE bsize, int output_enabled) {
341 VP9_COMMON *const cm = &cpi->common;
342 MACROBLOCK *const x = &cpi->mb;
343 MACROBLOCKD *const xd = &x->e_mbd;
344 MODE_INFO *mi = &ctx->mic;
345 MB_MODE_INFO *const mbmi = &xd->mode_info_context->mbmi;
347 int mb_mode_index = ctx->best_mode_index;
348 const int mis = cm->mode_info_stride;
349 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
350 const int mi_height = num_8x8_blocks_high_lookup[bsize];
352 assert(mi->mbmi.mode < MB_MODE_COUNT);
353 assert(mb_mode_index < MAX_MODES);
354 assert(mi->mbmi.ref_frame[0] < MAX_REF_FRAMES);
355 assert(mi->mbmi.ref_frame[1] < MAX_REF_FRAMES);
356 assert(mi->mbmi.sb_type == bsize);
358 // Restore the coding context of the MB to that that was in place
359 // when the mode was picked for it
360 for (y = 0; y < mi_height; y++)
361 for (x_idx = 0; x_idx < mi_width; x_idx++)
362 if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx
363 && (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y)
364 xd->mode_info_context[x_idx + y * mis] = *mi;
366 // FIXME(rbultje) I'm pretty sure this should go to the end of this block
367 // (i.e. after the output_enabled)
368 if (bsize < BLOCK_32X32) {
369 if (bsize < BLOCK_16X16)
370 ctx->tx_rd_diff[ALLOW_16X16] = ctx->tx_rd_diff[ALLOW_8X8];
371 ctx->tx_rd_diff[ALLOW_32X32] = ctx->tx_rd_diff[ALLOW_16X16];
374 if (is_inter_block(mbmi) && mbmi->sb_type < BLOCK_8X8) {
375 *x->partition_info = ctx->partition_info;
376 mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
377 mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
384 if (!vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
385 for (i = 0; i < TX_MODES; i++)
386 cpi->rd_tx_select_diff[i] += ctx->tx_rd_diff[i];
389 if (cm->frame_type == KEY_FRAME) {
390 // Restore the coding modes to that held in the coding context
391 // if (mb_mode == I4X4_PRED)
392 // for (i = 0; i < 16; i++)
394 // xd->block[i].bmi.as_mode =
395 // xd->mode_info_context->bmi[i].as_mode;
396 // assert(xd->mode_info_context->bmi[i].as_mode < MB_MODE_COUNT);
398 #if CONFIG_INTERNAL_STATS
399 static const int kf_mode_index[] = {
401 THR_V_PRED /*V_PRED*/,
402 THR_H_PRED /*H_PRED*/,
403 THR_D45_PRED /*D45_PRED*/,
404 THR_D135_PRED /*D135_PRED*/,
405 THR_D117_PRED /*D117_PRED*/,
406 THR_D153_PRED /*D153_PRED*/,
407 THR_D207_PRED /*D207_PRED*/,
408 THR_D63_PRED /*D63_PRED*/,
410 THR_B_PRED /*I4X4_PRED*/,
412 cpi->mode_chosen_counts[kf_mode_index[mi->mbmi.mode]]++;
415 // Note how often each mode chosen as best
416 cpi->mode_chosen_counts[mb_mode_index]++;
417 if (is_inter_block(mbmi)
418 && (mbmi->sb_type < BLOCK_8X8 || mbmi->mode == NEWMV)) {
419 int_mv best_mv, best_second_mv;
420 const MV_REFERENCE_FRAME rf1 = mbmi->ref_frame[0];
421 const MV_REFERENCE_FRAME rf2 = mbmi->ref_frame[1];
422 best_mv.as_int = ctx->best_ref_mv.as_int;
423 best_second_mv.as_int = ctx->second_best_ref_mv.as_int;
424 if (mbmi->mode == NEWMV) {
425 best_mv.as_int = mbmi->ref_mvs[rf1][0].as_int;
426 best_second_mv.as_int = mbmi->ref_mvs[rf2][0].as_int;
428 mbmi->best_mv.as_int = best_mv.as_int;
429 mbmi->best_second_mv.as_int = best_second_mv.as_int;
430 vp9_update_nmv_count(cpi, x, &best_mv, &best_second_mv);
433 if (bsize > BLOCK_8X8 && mbmi->mode == NEWMV) {
435 for (j = 0; j < mi_height; ++j)
436 for (i = 0; i < mi_width; ++i)
437 if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > i
438 && (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > j)
439 xd->mode_info_context[mis * j + i].mbmi = *mbmi;
442 if (cm->mcomp_filter_type == SWITCHABLE && is_inter_mode(mbmi->mode)) {
443 const int ctx = vp9_get_pred_context_switchable_interp(xd);
444 ++cm->counts.switchable_interp[ctx][mbmi->interp_filter];
447 cpi->rd_comp_pred_diff[SINGLE_PREDICTION_ONLY] += ctx->single_pred_diff;
448 cpi->rd_comp_pred_diff[COMP_PREDICTION_ONLY] += ctx->comp_pred_diff;
449 cpi->rd_comp_pred_diff[HYBRID_PREDICTION] += ctx->hybrid_pred_diff;
451 for (i = 0; i <= SWITCHABLE_FILTERS; i++)
452 cpi->rd_filter_diff[i] += ctx->best_filter_diff[i];
456 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
457 int mb_row, int mb_col) {
458 uint8_t *buffers[4] = {src->y_buffer, src->u_buffer, src->v_buffer, src
460 int strides[4] = {src->y_stride, src->uv_stride, src->uv_stride, src
464 for (i = 0; i < MAX_MB_PLANE; i++) {
465 setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mb_row, mb_col,
466 NULL, x->e_mbd.plane[i].subsampling_x,
467 x->e_mbd.plane[i].subsampling_y);
471 static void set_offsets(VP9_COMP *cpi, int mi_row, int mi_col,
473 MACROBLOCK *const x = &cpi->mb;
474 VP9_COMMON *const cm = &cpi->common;
475 MACROBLOCKD *const xd = &x->e_mbd;
477 const int dst_fb_idx = cm->new_fb_idx;
478 const int idx_str = xd->mode_info_stride * mi_row + mi_col;
479 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
480 const int mi_height = num_8x8_blocks_high_lookup[bsize];
481 const int mb_row = mi_row >> 1;
482 const int mb_col = mi_col >> 1;
483 const int idx_map = mb_row * cm->mb_cols + mb_col;
484 const struct segmentation *const seg = &cm->seg;
486 set_skip_context(cm, xd, mi_row, mi_col);
487 set_partition_seg_context(cm, xd, mi_row, mi_col);
489 // Activity map pointer
490 x->mb_activity_ptr = &cpi->mb_activity_map[idx_map];
491 x->active_ptr = cpi->active_map + idx_map;
493 /* pointers to mode info contexts */
494 x->partition_info = x->pi + idx_str;
495 xd->mode_info_context = cm->mi + idx_str;
496 mbmi = &xd->mode_info_context->mbmi;
497 // Special case: if prev_mi is NULL, the previous mode info context
499 xd->prev_mode_info_context = cm->prev_mi ? cm->prev_mi + idx_str : NULL;
501 // Set up destination pointers
502 setup_dst_planes(xd, &cm->yv12_fb[dst_fb_idx], mi_row, mi_col);
504 // Set up limit values for MV components
505 // mv beyond the range do not produce new/different prediction block
506 x->mv_row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
507 x->mv_col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
508 x->mv_row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
509 x->mv_col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
511 // Set up distance of MB to edge of frame in 1/8th pel units
512 assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
513 set_mi_row_col(cm, xd, mi_row, mi_height, mi_col, mi_width);
515 /* set up source buffers */
516 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
519 x->rddiv = cpi->RDDIV;
520 x->rdmult = cpi->RDMULT;
524 uint8_t *map = seg->update_map ? cpi->segmentation_map
525 : cm->last_frame_seg_map;
526 mbmi->segment_id = vp9_get_segment_id(cm, map, bsize, mi_row, mi_col);
528 vp9_mb_init_quantizer(cpi, x);
530 if (seg->enabled && cpi->seg0_cnt > 0
531 && !vp9_segfeature_active(seg, 0, SEG_LVL_REF_FRAME)
532 && vp9_segfeature_active(seg, 1, SEG_LVL_REF_FRAME)) {
533 cpi->seg0_progress = (cpi->seg0_idx << 16) / cpi->seg0_cnt;
535 const int y = mb_row & ~3;
536 const int x = mb_col & ~3;
537 const int p16 = ((mb_row & 1) << 1) + (mb_col & 1);
538 const int p32 = ((mb_row & 2) << 2) + ((mb_col & 2) << 1);
539 const int tile_progress = cm->cur_tile_mi_col_start * cm->mb_rows >> 1;
540 const int mb_cols = (cm->cur_tile_mi_col_end - cm->cur_tile_mi_col_start)
543 cpi->seg0_progress = ((y * mb_cols + x * 4 + p32 + p16 + tile_progress)
547 x->encode_breakout = cpi->segment_encode_breakout[mbmi->segment_id];
549 mbmi->segment_id = 0;
550 x->encode_breakout = cpi->oxcf.encode_breakout;
554 static void pick_sb_modes(VP9_COMP *cpi, int mi_row, int mi_col,
555 int *totalrate, int64_t *totaldist,
556 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
558 VP9_COMMON *const cm = &cpi->common;
559 MACROBLOCK *const x = &cpi->mb;
560 MACROBLOCKD *const xd = &x->e_mbd;
562 // Use the lower precision, but faster, 32x32 fdct for mode selection.
563 x->use_lp32x32fdct = 1;
565 if (bsize < BLOCK_8X8) {
566 // When ab_index = 0 all sub-blocks are handled, so for ab_index != 0
567 // there is nothing to be done.
568 if (xd->ab_index != 0) {
575 set_offsets(cpi, mi_row, mi_col, bsize);
576 xd->mode_info_context->mbmi.sb_type = bsize;
578 // Set to zero to make sure we do not use the previous encoded frame stats
579 xd->mode_info_context->mbmi.skip_coeff = 0;
581 x->source_variance = get_sby_perpixel_variance(cpi, x, bsize);
583 if (cpi->oxcf.tuning == VP8_TUNE_SSIM)
584 vp9_activity_masking(cpi, x);
586 // Find best coding mode & reconstruct the MB so it is available
587 // as a predictor for MBs that follow in the SB
588 if (cm->frame_type == KEY_FRAME)
589 vp9_rd_pick_intra_mode_sb(cpi, x, totalrate, totaldist, bsize, ctx,
592 vp9_rd_pick_inter_mode_sb(cpi, x, mi_row, mi_col, totalrate, totaldist,
593 bsize, ctx, best_rd);
596 static void update_stats(VP9_COMP *cpi) {
597 VP9_COMMON *const cm = &cpi->common;
598 MACROBLOCK *const x = &cpi->mb;
599 MACROBLOCKD *const xd = &x->e_mbd;
600 MODE_INFO *mi = xd->mode_info_context;
601 MB_MODE_INFO *const mbmi = &mi->mbmi;
603 if (cm->frame_type != KEY_FRAME) {
604 const int seg_ref_active = vp9_segfeature_active(&cm->seg, mbmi->segment_id,
608 cpi->intra_inter_count[vp9_get_pred_context_intra_inter(xd)]
609 [is_inter_block(mbmi)]++;
611 // If the segment reference feature is enabled we have only a single
612 // reference frame allowed for the segment so exclude it from
613 // the reference frame counts used to work out probabilities.
614 if (is_inter_block(mbmi) && !seg_ref_active) {
615 if (cm->comp_pred_mode == HYBRID_PREDICTION)
616 cpi->comp_inter_count[vp9_get_pred_context_comp_inter_inter(cm, xd)]
617 [has_second_ref(mbmi)]++;
619 if (has_second_ref(mbmi)) {
620 cpi->comp_ref_count[vp9_get_pred_context_comp_ref_p(cm, xd)]
621 [mbmi->ref_frame[0] == GOLDEN_FRAME]++;
623 cpi->single_ref_count[vp9_get_pred_context_single_ref_p1(xd)][0]
624 [mbmi->ref_frame[0] != LAST_FRAME]++;
625 if (mbmi->ref_frame[0] != LAST_FRAME)
626 cpi->single_ref_count[vp9_get_pred_context_single_ref_p2(xd)][1]
627 [mbmi->ref_frame[0] != GOLDEN_FRAME]++;
631 // Count of last ref frame 0,0 usage
632 if (mbmi->mode == ZEROMV && mbmi->ref_frame[0] == LAST_FRAME)
633 cpi->inter_zz_count++;
637 // TODO(jingning): the variables used here are little complicated. need further
638 // refactoring on organizing the temporary buffers, when recursive
639 // partition down to 4x4 block size is enabled.
640 static PICK_MODE_CONTEXT *get_block_context(MACROBLOCK *x, BLOCK_SIZE bsize) {
641 MACROBLOCKD *const xd = &x->e_mbd;
645 return &x->sb64_context;
647 return &x->sb64x32_context[xd->sb_index];
649 return &x->sb32x64_context[xd->sb_index];
651 return &x->sb32_context[xd->sb_index];
653 return &x->sb32x16_context[xd->sb_index][xd->mb_index];
655 return &x->sb16x32_context[xd->sb_index][xd->mb_index];
657 return &x->mb_context[xd->sb_index][xd->mb_index];
659 return &x->sb16x8_context[xd->sb_index][xd->mb_index][xd->b_index];
661 return &x->sb8x16_context[xd->sb_index][xd->mb_index][xd->b_index];
663 return &x->sb8x8_context[xd->sb_index][xd->mb_index][xd->b_index];
665 return &x->sb8x4_context[xd->sb_index][xd->mb_index][xd->b_index];
667 return &x->sb4x8_context[xd->sb_index][xd->mb_index][xd->b_index];
669 return &x->ab4x4_context[xd->sb_index][xd->mb_index][xd->b_index];
676 static BLOCK_SIZE *get_sb_partitioning(MACROBLOCK *x, BLOCK_SIZE bsize) {
677 MACROBLOCKD *const xd = &x->e_mbd;
680 return &x->sb64_partitioning;
682 return &x->sb_partitioning[xd->sb_index];
684 return &x->mb_partitioning[xd->sb_index][xd->mb_index];
686 return &x->b_partitioning[xd->sb_index][xd->mb_index][xd->b_index];
693 static void restore_context(VP9_COMP *cpi, int mi_row, int mi_col,
694 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
695 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
696 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
698 VP9_COMMON *const cm = &cpi->common;
699 MACROBLOCK *const x = &cpi->mb;
700 MACROBLOCKD *const xd = &x->e_mbd;
702 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
703 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
704 int mi_width = num_8x8_blocks_wide_lookup[bsize];
705 int mi_height = num_8x8_blocks_high_lookup[bsize];
706 for (p = 0; p < MAX_MB_PLANE; p++) {
708 cm->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
709 a + num_4x4_blocks_wide * p,
710 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
711 xd->plane[p].subsampling_x);
714 + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
715 l + num_4x4_blocks_high * p,
716 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
717 xd->plane[p].subsampling_y);
719 vpx_memcpy(cm->above_seg_context + mi_col, sa,
720 sizeof(PARTITION_CONTEXT) * mi_width);
721 vpx_memcpy(cm->left_seg_context + (mi_row & MI_MASK), sl,
722 sizeof(PARTITION_CONTEXT) * mi_height);
724 static void save_context(VP9_COMP *cpi, int mi_row, int mi_col,
725 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
726 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
727 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
729 const VP9_COMMON *const cm = &cpi->common;
730 const MACROBLOCK *const x = &cpi->mb;
731 const MACROBLOCKD *const xd = &x->e_mbd;
733 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
734 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
735 int mi_width = num_8x8_blocks_wide_lookup[bsize];
736 int mi_height = num_8x8_blocks_high_lookup[bsize];
738 // buffer the above/left context information of the block in search.
739 for (p = 0; p < MAX_MB_PLANE; ++p) {
741 a + num_4x4_blocks_wide * p,
742 cm->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
743 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
744 xd->plane[p].subsampling_x);
746 l + num_4x4_blocks_high * p,
748 + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
749 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
750 xd->plane[p].subsampling_y);
752 vpx_memcpy(sa, cm->above_seg_context + mi_col,
753 sizeof(PARTITION_CONTEXT) * mi_width);
754 vpx_memcpy(sl, cm->left_seg_context + (mi_row & MI_MASK),
755 sizeof(PARTITION_CONTEXT) * mi_height);
758 static void encode_b(VP9_COMP *cpi, TOKENEXTRA **tp, int mi_row, int mi_col,
759 int output_enabled, BLOCK_SIZE bsize, int sub_index) {
760 VP9_COMMON * const cm = &cpi->common;
761 MACROBLOCK * const x = &cpi->mb;
762 MACROBLOCKD * const xd = &x->e_mbd;
764 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
768 *get_sb_index(xd, bsize) = sub_index;
770 if (bsize < BLOCK_8X8) {
771 // When ab_index = 0 all sub-blocks are handled, so for ab_index != 0
772 // there is nothing to be done.
773 if (xd->ab_index > 0)
776 set_offsets(cpi, mi_row, mi_col, bsize);
777 update_state(cpi, get_block_context(x, bsize), bsize, output_enabled);
778 encode_superblock(cpi, tp, output_enabled, mi_row, mi_col, bsize);
780 if (output_enabled) {
783 (*tp)->token = EOSB_TOKEN;
788 static void encode_sb(VP9_COMP *cpi, TOKENEXTRA **tp, int mi_row, int mi_col,
789 int output_enabled, BLOCK_SIZE bsize) {
790 VP9_COMMON * const cm = &cpi->common;
791 MACROBLOCK * const x = &cpi->mb;
792 MACROBLOCKD * const xd = &x->e_mbd;
793 BLOCK_SIZE c1 = BLOCK_8X8;
794 const int bsl = b_width_log2(bsize), bs = (1 << bsl) / 4;
795 int UNINITIALIZED_IS_SAFE(pl);
796 PARTITION_TYPE partition;
800 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
804 if (bsize >= BLOCK_8X8) {
805 set_partition_seg_context(cm, xd, mi_row, mi_col);
806 pl = partition_plane_context(xd, bsize);
807 c1 = *(get_sb_partitioning(x, bsize));
809 partition = partition_lookup[bsl][c1];
813 if (output_enabled && bsize >= BLOCK_8X8)
814 cpi->partition_count[pl][PARTITION_NONE]++;
815 encode_b(cpi, tp, mi_row, mi_col, output_enabled, c1, -1);
819 cpi->partition_count[pl][PARTITION_VERT]++;
820 encode_b(cpi, tp, mi_row, mi_col, output_enabled, c1, 0);
821 encode_b(cpi, tp, mi_row, mi_col + bs, output_enabled, c1, 1);
825 cpi->partition_count[pl][PARTITION_HORZ]++;
826 encode_b(cpi, tp, mi_row, mi_col, output_enabled, c1, 0);
827 encode_b(cpi, tp, mi_row + bs, mi_col, output_enabled, c1, 1);
829 case PARTITION_SPLIT:
830 subsize = get_subsize(bsize, PARTITION_SPLIT);
833 cpi->partition_count[pl][PARTITION_SPLIT]++;
835 for (i = 0; i < 4; i++) {
836 const int x_idx = i & 1, y_idx = i >> 1;
838 *get_sb_index(xd, subsize) = i;
839 encode_sb(cpi, tp, mi_row + y_idx * bs, mi_col + x_idx * bs,
840 output_enabled, subsize);
848 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8) {
849 set_partition_seg_context(cm, xd, mi_row, mi_col);
850 update_partition_context(xd, c1, bsize);
854 // Check to see if the given partition size is allowed for a specified number
855 // of 8x8 block rows and columns remaining in the image.
856 // If not then return the largest allowed partition size
857 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize,
858 int rows_left, int cols_left,
860 if ((rows_left <= 0) || (cols_left <= 0)) {
861 return MIN(bsize, BLOCK_8X8);
863 for (; bsize > 0; --bsize) {
864 *bh = num_8x8_blocks_high_lookup[bsize];
865 *bw = num_8x8_blocks_wide_lookup[bsize];
866 if ((*bh <= rows_left) && (*bw <= cols_left)) {
874 // This function attempts to set all mode info entries in a given SB64
875 // to the same block partition size.
876 // However, at the bottom and right borders of the image the requested size
877 // may not be allowed in which case this code attempts to choose the largest
878 // allowable partition.
879 static void set_partitioning(VP9_COMP *cpi, MODE_INFO *m,
880 int mi_row, int mi_col) {
881 VP9_COMMON *const cm = &cpi->common;
882 BLOCK_SIZE bsize = cpi->sf.always_this_block_size;
883 const int mis = cm->mode_info_stride;
884 int row8x8_remaining = cm->cur_tile_mi_row_end - mi_row;
885 int col8x8_remaining = cm->cur_tile_mi_col_end - mi_col;
886 int block_row, block_col;
888 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
890 // Apply the requested partition size to the SB64 if it is all "in image"
891 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
892 (row8x8_remaining >= MI_BLOCK_SIZE)) {
893 for (block_row = 0; block_row < MI_BLOCK_SIZE; ++block_row) {
894 for (block_col = 0; block_col < MI_BLOCK_SIZE; ++block_col) {
895 m[block_row * mis + block_col].mbmi.sb_type = bsize;
899 // Else this is a partial SB64.
900 int bh = num_8x8_blocks_high_lookup[bsize];
901 int bw = num_8x8_blocks_wide_lookup[bsize];
907 for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
908 for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
909 // Find a partition size that fits
910 bsize = find_partition_size(cpi->sf.always_this_block_size,
911 (row8x8_remaining - block_row),
912 (col8x8_remaining - block_col), &bh, &bw);
914 // Set the mi entries for all 8x8 blocks within the selected size
915 for (sub_block_row = 0; sub_block_row < bh; ++sub_block_row) {
916 for (sub_block_col = 0; sub_block_col < bw; ++sub_block_col) {
917 row_index = block_row + sub_block_row;
918 col_index = block_col + sub_block_col;
919 m[row_index * mis + col_index].mbmi.sb_type = bsize;
926 static void copy_partitioning(VP9_COMP *cpi, MODE_INFO *m, MODE_INFO *p) {
927 VP9_COMMON *const cm = &cpi->common;
928 const int mis = cm->mode_info_stride;
929 int block_row, block_col;
930 for (block_row = 0; block_row < 8; ++block_row) {
931 for (block_col = 0; block_col < 8; ++block_col) {
932 m[block_row * mis + block_col].mbmi.sb_type =
933 p[block_row * mis + block_col].mbmi.sb_type;
938 static void set_block_size(VP9_COMMON * const cm, MODE_INFO *mi,
939 BLOCK_SIZE bsize, int mis, int mi_row,
942 const int bs = MAX(num_8x8_blocks_wide_lookup[bsize],
943 num_8x8_blocks_high_lookup[bsize]);
944 MODE_INFO *const mi2 = &mi[mi_row * mis + mi_col];
945 for (r = 0; r < bs; r++)
946 for (c = 0; c < bs; c++)
947 if (mi_row + r < cm->mi_rows && mi_col + c < cm->mi_cols)
948 mi2[r * mis + c].mbmi.sb_type = bsize;
952 int64_t sum_square_error;
962 } partition_variance;
964 #define VT(TYPE, BLOCKSIZE) \
966 partition_variance vt; \
967 BLOCKSIZE split[4]; } TYPE;
975 partition_variance *vt;
985 static void tree_to_node(void *data, BLOCK_SIZE bsize, vt_node *node) {
989 v64x64 *vt = (v64x64 *) data;
991 for (i = 0; i < 4; i++)
992 node->split[i] = &vt->split[i].vt.none;
996 v32x32 *vt = (v32x32 *) data;
998 for (i = 0; i < 4; i++)
999 node->split[i] = &vt->split[i].vt.none;
1003 v16x16 *vt = (v16x16 *) data;
1005 for (i = 0; i < 4; i++)
1006 node->split[i] = &vt->split[i].vt.none;
1010 v8x8 *vt = (v8x8 *) data;
1012 for (i = 0; i < 4; i++)
1013 node->split[i] = &vt->split[i];
1018 for (i = 0; i < 4; i++)
1024 // Set variance values given sum square error, sum error, count.
1025 static void fill_variance(var *v, int64_t s2, int64_t s, int c) {
1026 v->sum_square_error = s2;
1031 * (v->sum_square_error - v->sum_error * v->sum_error / v->count)
1037 // Combine 2 variance structures by summing the sum_error, sum_square_error,
1038 // and counts and then calculating the new variance.
1039 void sum_2_variances(var *r, var *a, var*b) {
1040 fill_variance(r, a->sum_square_error + b->sum_square_error,
1041 a->sum_error + b->sum_error, a->count + b->count);
1044 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
1046 tree_to_node(data, bsize, &node);
1047 sum_2_variances(&node.vt->horz[0], node.split[0], node.split[1]);
1048 sum_2_variances(&node.vt->horz[1], node.split[2], node.split[3]);
1049 sum_2_variances(&node.vt->vert[0], node.split[0], node.split[2]);
1050 sum_2_variances(&node.vt->vert[1], node.split[1], node.split[3]);
1051 sum_2_variances(&node.vt->none, &node.vt->vert[0], &node.vt->vert[1]);
1054 #if PERFORM_RANDOM_PARTITIONING
1055 static int set_vt_partitioning(VP9_COMP *cpi, void *data, MODE_INFO *m,
1056 BLOCK_SIZE block_size, int mi_row,
1057 int mi_col, int mi_size) {
1058 VP9_COMMON * const cm = &cpi->common;
1060 const int mis = cm->mode_info_stride;
1061 int64_t threshold = 4 * cpi->common.base_qindex * cpi->common.base_qindex;
1063 tree_to_node(data, block_size, &vt);
1065 // split none is available only if we have more than half a block size
1066 // in width and height inside the visible image
1067 if (mi_col + mi_size < cm->mi_cols && mi_row + mi_size < cm->mi_rows &&
1069 set_block_size(cm, m, block_size, mis, mi_row, mi_col);
1073 // vertical split is available on all but the bottom border
1074 if (mi_row + mi_size < cm->mi_rows && vt.vt->vert[0].variance < threshold
1075 && (rand() & 3) < 1) {
1076 set_block_size(cm, m, get_subsize(block_size, PARTITION_VERT), mis, mi_row,
1081 // horizontal split is available on all but the right border
1082 if (mi_col + mi_size < cm->mi_cols && vt.vt->horz[0].variance < threshold
1083 && (rand() & 3) < 1) {
1084 set_block_size(cm, m, get_subsize(block_size, PARTITION_HORZ), mis, mi_row,
1092 #else // !PERFORM_RANDOM_PARTITIONING
1094 static int set_vt_partitioning(VP9_COMP *cpi, void *data, MODE_INFO *m,
1095 BLOCK_SIZE bsize, int mi_row,
1096 int mi_col, int mi_size) {
1097 VP9_COMMON * const cm = &cpi->common;
1099 const int mis = cm->mode_info_stride;
1100 int64_t threshold = 50 * cpi->common.base_qindex;
1102 tree_to_node(data, bsize, &vt);
1104 // split none is available only if we have more than half a block size
1105 // in width and height inside the visible image
1106 if (mi_col + mi_size < cm->mi_cols && mi_row + mi_size < cm->mi_rows
1107 && vt.vt->none.variance < threshold) {
1108 set_block_size(cm, m, bsize, mis, mi_row, mi_col);
1112 // vertical split is available on all but the bottom border
1113 if (mi_row + mi_size < cm->mi_rows && vt.vt->vert[0].variance < threshold
1114 && vt.vt->vert[1].variance < threshold) {
1115 set_block_size(cm, m, get_subsize(bsize, PARTITION_VERT), mis, mi_row,
1120 // horizontal split is available on all but the right border
1121 if (mi_col + mi_size < cm->mi_cols && vt.vt->horz[0].variance < threshold
1122 && vt.vt->horz[1].variance < threshold) {
1123 set_block_size(cm, m, get_subsize(bsize, PARTITION_HORZ), mis, mi_row,
1130 #endif // PERFORM_RANDOM_PARTITIONING
1132 static void choose_partitioning(VP9_COMP *cpi, MODE_INFO *m, int mi_row,
1134 VP9_COMMON * const cm = &cpi->common;
1135 MACROBLOCK *x = &cpi->mb;
1136 MACROBLOCKD *xd = &cpi->mb.e_mbd;
1137 const int mis = cm->mode_info_stride;
1138 // TODO(JBB): More experimentation or testing of this threshold;
1139 int64_t threshold = 4;
1144 const unsigned char * d;
1146 int pixels_wide = 64, pixels_high = 64;
1149 set_offsets(cpi, mi_row, mi_col, BLOCK_64X64);
1151 if (xd->mb_to_right_edge < 0)
1152 pixels_wide += (xd->mb_to_right_edge >> 3);
1154 if (xd->mb_to_bottom_edge < 0)
1155 pixels_high += (xd->mb_to_bottom_edge >> 3);
1157 s = x->plane[0].src.buf;
1158 sp = x->plane[0].src.stride;
1160 // TODO(JBB): Clearly the higher the quantizer the fewer partitions we want
1161 // but this needs more experimentation.
1162 threshold = threshold * cpi->common.base_qindex * cpi->common.base_qindex;
1164 d = vp9_64x64_zeros;
1166 if (cm->frame_type != KEY_FRAME) {
1167 int_mv nearest_mv, near_mv;
1168 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, LAST_FRAME)];
1169 YV12_BUFFER_CONFIG *ref_fb = &cm->yv12_fb[idx];
1170 YV12_BUFFER_CONFIG *second_ref_fb = NULL;
1172 setup_pre_planes(xd, 0, ref_fb, mi_row, mi_col,
1173 &xd->scale_factor[0]);
1174 setup_pre_planes(xd, 1, second_ref_fb, mi_row, mi_col,
1175 &xd->scale_factor[1]);
1176 xd->mode_info_context->mbmi.ref_frame[0] = LAST_FRAME;
1177 xd->mode_info_context->mbmi.sb_type = BLOCK_64X64;
1178 vp9_find_best_ref_mvs(xd, m->mbmi.ref_mvs[m->mbmi.ref_frame[0]],
1179 &nearest_mv, &near_mv);
1181 xd->mode_info_context->mbmi.mv[0] = nearest_mv;
1182 vp9_build_inter_predictors_sby(xd, mi_row, mi_col, BLOCK_64X64);
1183 d = xd->plane[0].dst.buf;
1184 dp = xd->plane[0].dst.stride;
1187 // Fill in the entire tree of 8x8 variances for splits.
1188 for (i = 0; i < 4; i++) {
1189 const int x32_idx = ((i & 1) << 5);
1190 const int y32_idx = ((i >> 1) << 5);
1191 for (j = 0; j < 4; j++) {
1192 const int x16_idx = x32_idx + ((j & 1) << 4);
1193 const int y16_idx = y32_idx + ((j >> 1) << 4);
1194 v16x16 *vst = &vt.split[i].split[j];
1195 for (k = 0; k < 4; k++) {
1196 int x_idx = x16_idx + ((k & 1) << 3);
1197 int y_idx = y16_idx + ((k >> 1) << 3);
1198 unsigned int sse = 0;
1200 if (x_idx < pixels_wide && y_idx < pixels_high)
1201 vp9_get_sse_sum_8x8(s + y_idx * sp + x_idx, sp,
1202 d + y_idx * dp + x_idx, dp, &sse, &sum);
1203 fill_variance(&vst->split[k].vt.none, sse, sum, 64);
1207 // Fill the rest of the variance tree by summing the split partition
1209 for (i = 0; i < 4; i++) {
1210 for (j = 0; j < 4; j++) {
1211 fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1213 fill_variance_tree(&vt.split[i], BLOCK_32X32);
1215 fill_variance_tree(&vt, BLOCK_64X64);
1216 // Now go through the entire structure, splitting every block size until
1217 // we get to one that's got a variance lower than our threshold, or we
1219 if (!set_vt_partitioning(cpi, &vt, m, BLOCK_64X64, mi_row, mi_col,
1221 for (i = 0; i < 4; ++i) {
1222 const int x32_idx = ((i & 1) << 2);
1223 const int y32_idx = ((i >> 1) << 2);
1224 if (!set_vt_partitioning(cpi, &vt.split[i], m, BLOCK_32X32,
1225 (mi_row + y32_idx), (mi_col + x32_idx), 2)) {
1226 for (j = 0; j < 4; ++j) {
1227 const int x16_idx = ((j & 1) << 1);
1228 const int y16_idx = ((j >> 1) << 1);
1229 if (!set_vt_partitioning(cpi, &vt.split[i].split[j], m,
1231 (mi_row + y32_idx + y16_idx),
1232 (mi_col + x32_idx + x16_idx), 1)) {
1233 for (k = 0; k < 4; ++k) {
1234 const int x8_idx = (k & 1);
1235 const int y8_idx = (k >> 1);
1236 set_block_size(cm, m, BLOCK_8X8, mis,
1237 (mi_row + y32_idx + y16_idx + y8_idx),
1238 (mi_col + x32_idx + x16_idx + x8_idx));
1247 static void rd_use_partition(VP9_COMP *cpi, MODE_INFO *m, TOKENEXTRA **tp,
1248 int mi_row, int mi_col, BLOCK_SIZE bsize,
1249 int *rate, int64_t *dist, int do_recon) {
1250 VP9_COMMON * const cm = &cpi->common;
1251 MACROBLOCK * const x = &cpi->mb;
1252 MACROBLOCKD *xd = &cpi->mb.e_mbd;
1253 const int mis = cm->mode_info_stride;
1254 int bsl = b_width_log2(bsize);
1255 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1256 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1257 int ms = num_4x4_blocks_wide / 2;
1258 int mh = num_4x4_blocks_high / 2;
1259 int bss = (1 << bsl) / 4;
1261 PARTITION_TYPE partition = PARTITION_NONE;
1263 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1264 PARTITION_CONTEXT sl[8], sa[8];
1265 int last_part_rate = INT_MAX;
1266 int64_t last_part_dist = INT_MAX;
1267 int split_rate = INT_MAX;
1268 int64_t split_dist = INT_MAX;
1269 int none_rate = INT_MAX;
1270 int64_t none_dist = INT_MAX;
1271 int chosen_rate = INT_MAX;
1272 int64_t chosen_dist = INT_MAX;
1273 BLOCK_SIZE sub_subsize = BLOCK_4X4;
1274 int splits_below = 0;
1275 BLOCK_SIZE bs_type = m->mbmi.sb_type;
1277 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1280 partition = partition_lookup[bsl][bs_type];
1282 subsize = get_subsize(bsize, partition);
1284 if (bsize < BLOCK_8X8) {
1285 // When ab_index = 0 all sub-blocks are handled, so for ab_index != 0
1286 // there is nothing to be done.
1287 if (xd->ab_index != 0) {
1293 *(get_sb_partitioning(x, bsize)) = subsize;
1295 save_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1298 x->pred_mv.as_int = 0;
1299 x->subblock_ref = 0;
1301 if (cpi->sf.adjust_partitioning_from_last_frame) {
1302 // Check if any of the sub blocks are further split.
1303 if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
1304 sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
1306 for (i = 0; i < 4; i++) {
1307 int jj = i >> 1, ii = i & 0x01;
1308 if (m[jj * bss * mis + ii * bss].mbmi.sb_type >= sub_subsize) {
1314 // If partition is not none try none unless each of the 4 splits are split
1316 if (partition != PARTITION_NONE && !splits_below &&
1317 mi_row + (ms >> 1) < cm->mi_rows &&
1318 mi_col + (ms >> 1) < cm->mi_cols) {
1319 *(get_sb_partitioning(x, bsize)) = bsize;
1320 pick_sb_modes(cpi, mi_row, mi_col, &none_rate, &none_dist, bsize,
1321 get_block_context(x, bsize), INT64_MAX);
1323 set_partition_seg_context(cm, xd, mi_row, mi_col);
1324 pl = partition_plane_context(xd, bsize);
1325 none_rate += x->partition_cost[pl][PARTITION_NONE];
1327 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1328 m->mbmi.sb_type = bs_type;
1329 *(get_sb_partitioning(x, bsize)) = subsize;
1333 switch (partition) {
1334 case PARTITION_NONE:
1335 pick_sb_modes(cpi, mi_row, mi_col, &last_part_rate, &last_part_dist,
1336 bsize, get_block_context(x, bsize), INT64_MAX);
1338 case PARTITION_HORZ:
1339 *get_sb_index(xd, subsize) = 0;
1340 pick_sb_modes(cpi, mi_row, mi_col, &last_part_rate, &last_part_dist,
1341 subsize, get_block_context(x, subsize), INT64_MAX);
1342 if (last_part_rate != INT_MAX &&
1343 bsize >= BLOCK_8X8 && mi_row + (mh >> 1) < cm->mi_rows) {
1346 update_state(cpi, get_block_context(x, subsize), subsize, 0);
1347 encode_superblock(cpi, tp, 0, mi_row, mi_col, subsize);
1348 *get_sb_index(xd, subsize) = 1;
1349 pick_sb_modes(cpi, mi_row + (ms >> 1), mi_col, &rt, &dt, subsize,
1350 get_block_context(x, subsize), INT64_MAX);
1351 if (rt == INT_MAX || dt == INT_MAX) {
1352 last_part_rate = INT_MAX;
1353 last_part_dist = INT_MAX;
1357 last_part_rate += rt;
1358 last_part_dist += dt;
1361 case PARTITION_VERT:
1362 *get_sb_index(xd, subsize) = 0;
1363 pick_sb_modes(cpi, mi_row, mi_col, &last_part_rate, &last_part_dist,
1364 subsize, get_block_context(x, subsize), INT64_MAX);
1365 if (last_part_rate != INT_MAX &&
1366 bsize >= BLOCK_8X8 && mi_col + (ms >> 1) < cm->mi_cols) {
1369 update_state(cpi, get_block_context(x, subsize), subsize, 0);
1370 encode_superblock(cpi, tp, 0, mi_row, mi_col, subsize);
1371 *get_sb_index(xd, subsize) = 1;
1372 pick_sb_modes(cpi, mi_row, mi_col + (ms >> 1), &rt, &dt, subsize,
1373 get_block_context(x, subsize), INT64_MAX);
1374 if (rt == INT_MAX || dt == INT_MAX) {
1375 last_part_rate = INT_MAX;
1376 last_part_dist = INT_MAX;
1379 last_part_rate += rt;
1380 last_part_dist += dt;
1383 case PARTITION_SPLIT:
1387 for (i = 0; i < 4; i++) {
1388 int x_idx = (i & 1) * (ms >> 1);
1389 int y_idx = (i >> 1) * (ms >> 1);
1390 int jj = i >> 1, ii = i & 0x01;
1394 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
1397 *get_sb_index(xd, subsize) = i;
1399 rd_use_partition(cpi, m + jj * bss * mis + ii * bss, tp, mi_row + y_idx,
1400 mi_col + x_idx, subsize, &rt, &dt, i != 3);
1401 if (rt == INT_MAX || dt == INT_MAX) {
1402 last_part_rate = INT_MAX;
1403 last_part_dist = INT_MAX;
1406 last_part_rate += rt;
1407 last_part_dist += dt;
1413 set_partition_seg_context(cm, xd, mi_row, mi_col);
1414 pl = partition_plane_context(xd, bsize);
1415 if (last_part_rate < INT_MAX)
1416 last_part_rate += x->partition_cost[pl][partition];
1418 if (cpi->sf.adjust_partitioning_from_last_frame
1419 && partition != PARTITION_SPLIT && bsize > BLOCK_8X8
1420 && (mi_row + ms < cm->mi_rows || mi_row + (ms >> 1) == cm->mi_rows)
1421 && (mi_col + ms < cm->mi_cols || mi_col + (ms >> 1) == cm->mi_cols)) {
1422 BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
1425 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1428 for (i = 0; i < 4; i++) {
1429 int x_idx = (i & 1) * (num_4x4_blocks_wide >> 2);
1430 int y_idx = (i >> 1) * (num_4x4_blocks_wide >> 2);
1433 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1434 PARTITION_CONTEXT sl[8], sa[8];
1436 if ((mi_row + y_idx >= cm->mi_rows)
1437 || (mi_col + x_idx >= cm->mi_cols))
1440 *get_sb_index(xd, split_subsize) = i;
1441 *get_sb_partitioning(x, bsize) = split_subsize;
1442 *get_sb_partitioning(x, split_subsize) = split_subsize;
1444 save_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1446 pick_sb_modes(cpi, mi_row + y_idx, mi_col + x_idx, &rt, &dt,
1447 split_subsize, get_block_context(x, split_subsize),
1450 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1452 if (rt == INT_MAX || dt == INT_MAX) {
1453 split_rate = INT_MAX;
1454 split_dist = INT_MAX;
1459 encode_sb(cpi, tp, mi_row + y_idx, mi_col + x_idx, 0,
1464 set_partition_seg_context(cm, xd, mi_row + y_idx, mi_col + x_idx);
1465 pl = partition_plane_context(xd, bsize);
1466 split_rate += x->partition_cost[pl][PARTITION_NONE];
1468 set_partition_seg_context(cm, xd, mi_row, mi_col);
1469 pl = partition_plane_context(xd, bsize);
1470 if (split_rate < INT_MAX) {
1471 split_rate += x->partition_cost[pl][PARTITION_SPLIT];
1473 chosen_rate = split_rate;
1474 chosen_dist = split_dist;
1478 // If last_part is better set the partitioning to that...
1479 if (RDCOST(x->rdmult, x->rddiv, last_part_rate, last_part_dist)
1480 < RDCOST(x->rdmult, x->rddiv, chosen_rate, chosen_dist)) {
1481 m->mbmi.sb_type = bsize;
1482 if (bsize >= BLOCK_8X8)
1483 *(get_sb_partitioning(x, bsize)) = subsize;
1484 chosen_rate = last_part_rate;
1485 chosen_dist = last_part_dist;
1487 // If none was better set the partitioning to that...
1488 if (RDCOST(x->rdmult, x->rddiv, chosen_rate, chosen_dist)
1489 > RDCOST(x->rdmult, x->rddiv, none_rate, none_dist)) {
1490 if (bsize >= BLOCK_8X8)
1491 *(get_sb_partitioning(x, bsize)) = bsize;
1492 chosen_rate = none_rate;
1493 chosen_dist = none_dist;
1496 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1498 // We must have chosen a partitioning and encoding or we'll fail later on.
1499 // No other opportunities for success.
1500 if ( bsize == BLOCK_64X64)
1501 assert(chosen_rate < INT_MAX && chosen_dist < INT_MAX);
1504 encode_sb(cpi, tp, mi_row, mi_col, bsize == BLOCK_64X64, bsize);
1506 *rate = chosen_rate;
1507 *dist = chosen_dist;
1510 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
1511 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
1512 BLOCK_4X4, BLOCK_4X4, BLOCK_8X8, BLOCK_8X8,
1513 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
1516 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
1517 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
1518 BLOCK_32X32, BLOCK_32X32, BLOCK_32X32, BLOCK_64X64,
1519 BLOCK_64X64, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
1522 // Look at all the mode_info entries for blocks that are part of this
1523 // partition and find the min and max values for sb_type.
1524 // At the moment this is designed to work on a 64x64 SB but could be
1525 // adjusted to use a size parameter.
1527 // The min and max are assumed to have been initialized prior to calling this
1528 // function so repeat calls can accumulate a min and max of more than one sb64.
1529 static void get_sb_partition_size_range(VP9_COMP *cpi, MODE_INFO * mi,
1530 BLOCK_SIZE *min_block_size,
1531 BLOCK_SIZE *max_block_size ) {
1532 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1533 int sb_width_in_blocks = MI_BLOCK_SIZE;
1534 int sb_height_in_blocks = MI_BLOCK_SIZE;
1538 // Check the sb_type for each block that belongs to this region.
1539 for (i = 0; i < sb_height_in_blocks; ++i) {
1540 for (j = 0; j < sb_width_in_blocks; ++j) {
1541 *min_block_size = MIN(*min_block_size, mi[index + j].mbmi.sb_type);
1542 *max_block_size = MAX(*max_block_size, mi[index + j].mbmi.sb_type);
1544 index += xd->mode_info_stride;
1548 // Look at neighboring blocks and set a min and max partition size based on
1550 static void rd_auto_partition_range(VP9_COMP *cpi,
1551 BLOCK_SIZE *min_block_size,
1552 BLOCK_SIZE *max_block_size) {
1553 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1554 MODE_INFO *mi = xd->mode_info_context;
1555 MODE_INFO *above_sb64_mi;
1556 MODE_INFO *left_sb64_mi;
1557 const MB_MODE_INFO *const above_mbmi = &mi[-xd->mode_info_stride].mbmi;
1558 const MB_MODE_INFO *const left_mbmi = &mi[-1].mbmi;
1559 const int left_in_image = xd->left_available && left_mbmi->in_image;
1560 const int above_in_image = xd->up_available && above_mbmi->in_image;
1563 if (cpi->sf.auto_min_max_partition_count <= 0) {
1564 cpi->sf.auto_min_max_partition_count =
1565 cpi->sf.auto_min_max_partition_interval;
1566 *min_block_size = BLOCK_4X4;
1567 *max_block_size = BLOCK_64X64;
1570 --cpi->sf.auto_min_max_partition_count;
1573 // Set default values if not left or above neighbour
1574 if (!left_in_image && !above_in_image) {
1575 *min_block_size = BLOCK_4X4;
1576 *max_block_size = BLOCK_64X64;
1578 // Default "min to max" and "max to min"
1579 *min_block_size = BLOCK_64X64;
1580 *max_block_size = BLOCK_4X4;
1582 // Find the min and max partition sizes used in the left SB64
1583 if (left_in_image) {
1584 left_sb64_mi = &mi[-MI_BLOCK_SIZE];
1585 get_sb_partition_size_range(cpi, left_sb64_mi,
1586 min_block_size, max_block_size);
1589 // Find the min and max partition sizes used in the above SB64 taking
1590 // the values found for left as a starting point.
1591 if (above_in_image) {
1592 above_sb64_mi = &mi[-xd->mode_info_stride * MI_BLOCK_SIZE];
1593 get_sb_partition_size_range(cpi, above_sb64_mi,
1594 min_block_size, max_block_size);
1597 // give a bit of leaway either side of the observed min and max
1598 *min_block_size = min_partition_size[*min_block_size];
1599 *max_block_size = max_partition_size[*max_block_size];
1603 static void compute_fast_motion_search_level(VP9_COMP *cpi, BLOCK_SIZE bsize) {
1604 VP9_COMMON *const cm = &cpi->common;
1605 MACROBLOCK *const x = &cpi->mb;
1606 MACROBLOCKD *const xd = &x->e_mbd;
1608 // Only use 8x8 result for non HD videos.
1609 // int use_8x8 = (MIN(cpi->common.width, cpi->common.height) < 720) ? 1 : 0;
1612 if (cm->frame_type && !cpi->is_src_frame_alt_ref &&
1613 ((use_8x8 && bsize == BLOCK_16X16) ||
1614 bsize == BLOCK_32X32 || bsize == BLOCK_64X64)) {
1615 int ref0 = 0, ref1 = 0, ref2 = 0, ref3 = 0;
1616 PICK_MODE_CONTEXT *block_context = NULL;
1618 if (bsize == BLOCK_16X16) {
1619 block_context = x->sb8x8_context[xd->sb_index][xd->mb_index];
1620 } else if (bsize == BLOCK_32X32) {
1621 block_context = x->mb_context[xd->sb_index];
1622 } else if (bsize == BLOCK_64X64) {
1623 block_context = x->sb32_context;
1626 if (block_context) {
1627 ref0 = block_context[0].mic.mbmi.ref_frame[0];
1628 ref1 = block_context[1].mic.mbmi.ref_frame[0];
1629 ref2 = block_context[2].mic.mbmi.ref_frame[0];
1630 ref3 = block_context[3].mic.mbmi.ref_frame[0];
1633 // Currently, only consider 4 inter reference frames.
1634 if (ref0 && ref1 && ref2 && ref3) {
1635 int d01, d23, d02, d13;
1637 // Motion vectors for the four subblocks.
1638 int16_t mvr0 = block_context[0].mic.mbmi.mv[0].as_mv.row;
1639 int16_t mvc0 = block_context[0].mic.mbmi.mv[0].as_mv.col;
1640 int16_t mvr1 = block_context[1].mic.mbmi.mv[0].as_mv.row;
1641 int16_t mvc1 = block_context[1].mic.mbmi.mv[0].as_mv.col;
1642 int16_t mvr2 = block_context[2].mic.mbmi.mv[0].as_mv.row;
1643 int16_t mvc2 = block_context[2].mic.mbmi.mv[0].as_mv.col;
1644 int16_t mvr3 = block_context[3].mic.mbmi.mv[0].as_mv.row;
1645 int16_t mvc3 = block_context[3].mic.mbmi.mv[0].as_mv.col;
1647 // Adjust sign if ref is alt_ref.
1648 if (cm->ref_frame_sign_bias[ref0]) {
1653 if (cm->ref_frame_sign_bias[ref1]) {
1658 if (cm->ref_frame_sign_bias[ref2]) {
1663 if (cm->ref_frame_sign_bias[ref3]) {
1668 // Calculate mv distances.
1669 d01 = MAX(abs(mvr0 - mvr1), abs(mvc0 - mvc1));
1670 d23 = MAX(abs(mvr2 - mvr3), abs(mvc2 - mvc3));
1671 d02 = MAX(abs(mvr0 - mvr2), abs(mvc0 - mvc2));
1672 d13 = MAX(abs(mvr1 - mvr3), abs(mvc1 - mvc3));
1674 if (d01 < FAST_MOTION_MV_THRESH && d23 < FAST_MOTION_MV_THRESH &&
1675 d02 < FAST_MOTION_MV_THRESH && d13 < FAST_MOTION_MV_THRESH) {
1676 // Set fast motion search level.
1679 // Calculate prediction MV.
1680 x->pred_mv.as_mv.row = (mvr0 + mvr1 + mvr2 + mvr3) >> 2;
1681 x->pred_mv.as_mv.col = (mvc0 + mvc1 + mvc2 + mvc3) >> 2;
1683 if (ref0 == ref1 && ref1 == ref2 && ref2 == ref3 &&
1684 d01 < 2 && d23 < 2 && d02 < 2 && d13 < 2) {
1685 // Set fast motion search level.
1688 if (!d01 && !d23 && !d02 && !d13) {
1690 x->subblock_ref = ref0;
1698 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
1699 // unlikely to be selected depending on previous rate-distortion optimization
1700 // results, for encoding speed-up.
1701 static void rd_pick_partition(VP9_COMP *cpi, TOKENEXTRA **tp, int mi_row,
1702 int mi_col, BLOCK_SIZE bsize, int *rate,
1703 int64_t *dist, int do_recon, int64_t best_rd) {
1704 VP9_COMMON * const cm = &cpi->common;
1705 MACROBLOCK * const x = &cpi->mb;
1706 MACROBLOCKD * const xd = &x->e_mbd;
1707 const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
1708 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1709 PARTITION_CONTEXT sl[8], sa[8];
1710 TOKENEXTRA *tp_orig = *tp;
1713 int this_rate, sum_rate = 0, best_rate = INT_MAX;
1714 int64_t this_dist, sum_dist = 0, best_dist = INT64_MAX;
1716 int do_split = bsize >= BLOCK_8X8;
1718 // Override skipping rectangular partition operations for edge blocks
1719 const int force_horz_split = (mi_row + ms >= cm->mi_rows);
1720 const int force_vert_split = (mi_col + ms >= cm->mi_cols);
1722 int partition_none_allowed = !force_horz_split && !force_vert_split;
1723 int partition_horz_allowed = !force_vert_split && bsize >= BLOCK_8X8;
1724 int partition_vert_allowed = !force_horz_split && bsize >= BLOCK_8X8;
1726 int partition_split_done = 0;
1729 if (bsize < BLOCK_8X8) {
1730 // When ab_index = 0 all sub-blocks are handled, so for ab_index != 0
1731 // there is nothing to be done.
1732 if (xd->ab_index != 0) {
1738 assert(mi_height_log2(bsize) == mi_width_log2(bsize));
1740 // Determine partition types in search according to the speed features.
1741 // The threshold set here has to be of square block size.
1742 if (cpi->sf.auto_min_max_partition_size) {
1743 partition_none_allowed &= (bsize <= cpi->sf.max_partition_size &&
1744 bsize >= cpi->sf.min_partition_size);
1745 partition_horz_allowed &= ((bsize <= cpi->sf.max_partition_size &&
1746 bsize > cpi->sf.min_partition_size) ||
1748 partition_vert_allowed &= ((bsize <= cpi->sf.max_partition_size &&
1749 bsize > cpi->sf.min_partition_size) ||
1751 do_split &= bsize > cpi->sf.min_partition_size;
1753 if (cpi->sf.use_square_partition_only) {
1754 partition_horz_allowed &= force_horz_split;
1755 partition_vert_allowed &= force_vert_split;
1758 save_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1760 if (cpi->sf.disable_split_var_thresh && partition_none_allowed) {
1761 unsigned int source_variancey;
1762 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
1763 source_variancey = get_sby_perpixel_variance(cpi, x, bsize);
1764 if (source_variancey < cpi->sf.disable_split_var_thresh) {
1766 if (source_variancey < cpi->sf.disable_split_var_thresh / 2)
1772 if (partition_none_allowed) {
1773 pick_sb_modes(cpi, mi_row, mi_col, &this_rate, &this_dist, bsize,
1774 get_block_context(x, bsize), best_rd);
1775 if (this_rate != INT_MAX) {
1776 if (bsize >= BLOCK_8X8) {
1777 set_partition_seg_context(cm, xd, mi_row, mi_col);
1778 pl = partition_plane_context(xd, bsize);
1779 this_rate += x->partition_cost[pl][PARTITION_NONE];
1781 sum_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_dist);
1782 if (sum_rd < best_rd) {
1783 best_rate = this_rate;
1784 best_dist = this_dist;
1786 if (bsize >= BLOCK_8X8)
1787 *(get_sb_partitioning(x, bsize)) = bsize;
1790 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1795 // TODO(jingning): use the motion vectors given by the above search as
1796 // the starting point of motion search in the following partition type check.
1798 subsize = get_subsize(bsize, PARTITION_SPLIT);
1799 for (i = 0; i < 4 && sum_rd < best_rd; ++i) {
1800 const int x_idx = (i & 1) * ms;
1801 const int y_idx = (i >> 1) * ms;
1803 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
1806 *get_sb_index(xd, subsize) = i;
1808 rd_pick_partition(cpi, tp, mi_row + y_idx, mi_col + x_idx, subsize,
1809 &this_rate, &this_dist, i != 3, best_rd - sum_rd);
1811 if (this_rate == INT_MAX) {
1814 sum_rate += this_rate;
1815 sum_dist += this_dist;
1816 sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1819 if (sum_rd < best_rd && i == 4) {
1820 set_partition_seg_context(cm, xd, mi_row, mi_col);
1821 pl = partition_plane_context(xd, bsize);
1822 sum_rate += x->partition_cost[pl][PARTITION_SPLIT];
1823 sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1824 if (sum_rd < best_rd) {
1825 best_rate = sum_rate;
1826 best_dist = sum_dist;
1828 *(get_sb_partitioning(x, bsize)) = subsize;
1830 // skip rectangular partition test when larger block size
1831 // gives better rd cost
1832 if (cpi->sf.less_rectangular_check)
1833 do_rect &= !partition_none_allowed;
1836 partition_split_done = 1;
1837 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1841 x->pred_mv.as_int = 0;
1842 x->subblock_ref = 0;
1844 if (partition_split_done &&
1845 cpi->sf.using_small_partition_info) {
1846 compute_fast_motion_search_level(cpi, bsize);
1850 if (partition_horz_allowed && do_rect) {
1851 subsize = get_subsize(bsize, PARTITION_HORZ);
1852 *get_sb_index(xd, subsize) = 0;
1853 pick_sb_modes(cpi, mi_row, mi_col, &sum_rate, &sum_dist, subsize,
1854 get_block_context(x, subsize), best_rd);
1855 sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1857 if (sum_rd < best_rd && mi_row + ms < cm->mi_rows) {
1858 update_state(cpi, get_block_context(x, subsize), subsize, 0);
1859 encode_superblock(cpi, tp, 0, mi_row, mi_col, subsize);
1861 *get_sb_index(xd, subsize) = 1;
1862 pick_sb_modes(cpi, mi_row + ms, mi_col, &this_rate,
1863 &this_dist, subsize, get_block_context(x, subsize),
1865 if (this_rate == INT_MAX) {
1868 sum_rate += this_rate;
1869 sum_dist += this_dist;
1870 sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1873 if (sum_rd < best_rd) {
1874 set_partition_seg_context(cm, xd, mi_row, mi_col);
1875 pl = partition_plane_context(xd, bsize);
1876 sum_rate += x->partition_cost[pl][PARTITION_HORZ];
1877 sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1878 if (sum_rd < best_rd) {
1880 best_rate = sum_rate;
1881 best_dist = sum_dist;
1882 *(get_sb_partitioning(x, bsize)) = subsize;
1885 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1889 if (partition_vert_allowed && do_rect) {
1890 subsize = get_subsize(bsize, PARTITION_VERT);
1892 *get_sb_index(xd, subsize) = 0;
1893 pick_sb_modes(cpi, mi_row, mi_col, &sum_rate, &sum_dist, subsize,
1894 get_block_context(x, subsize), best_rd);
1895 sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1896 if (sum_rd < best_rd && mi_col + ms < cm->mi_cols) {
1897 update_state(cpi, get_block_context(x, subsize), subsize, 0);
1898 encode_superblock(cpi, tp, 0, mi_row, mi_col, subsize);
1900 *get_sb_index(xd, subsize) = 1;
1901 pick_sb_modes(cpi, mi_row, mi_col + ms, &this_rate,
1902 &this_dist, subsize, get_block_context(x, subsize),
1904 if (this_rate == INT_MAX) {
1907 sum_rate += this_rate;
1908 sum_dist += this_dist;
1909 sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1912 if (sum_rd < best_rd) {
1913 set_partition_seg_context(cm, xd, mi_row, mi_col);
1914 pl = partition_plane_context(xd, bsize);
1915 sum_rate += x->partition_cost[pl][PARTITION_VERT];
1916 sum_rd = RDCOST(x->rdmult, x->rddiv, sum_rate, sum_dist);
1917 if (sum_rd < best_rd) {
1918 best_rate = sum_rate;
1919 best_dist = sum_dist;
1921 *(get_sb_partitioning(x, bsize)) = subsize;
1924 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, bsize);
1931 if (best_rate < INT_MAX && best_dist < INT64_MAX && do_recon)
1932 encode_sb(cpi, tp, mi_row, mi_col, bsize == BLOCK_64X64, bsize);
1933 if (bsize == BLOCK_64X64) {
1934 assert(tp_orig < *tp);
1935 assert(best_rate < INT_MAX);
1936 assert(best_dist < INT_MAX);
1938 assert(tp_orig == *tp);
1942 // Examines 64x64 block and chooses a best reference frame
1943 static void rd_pick_reference_frame(VP9_COMP *cpi, int mi_row, int mi_col) {
1944 VP9_COMMON * const cm = &cpi->common;
1945 MACROBLOCK * const x = &cpi->mb;
1946 MACROBLOCKD * const xd = &x->e_mbd;
1947 int bsl = b_width_log2(BLOCK_64X64), bs = 1 << bsl;
1949 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1950 PARTITION_CONTEXT sl[8], sa[8];
1955 save_context(cpi, mi_row, mi_col, a, l, sa, sl, BLOCK_64X64);
1957 // Default is non mask (all reference frames allowed.
1958 cpi->ref_frame_mask = 0;
1960 // Do RD search for 64x64.
1961 if ((mi_row + (ms >> 1) < cm->mi_rows) &&
1962 (mi_col + (ms >> 1) < cm->mi_cols)) {
1963 cpi->set_ref_frame_mask = 1;
1964 pick_sb_modes(cpi, mi_row, mi_col, &r, &d, BLOCK_64X64,
1965 get_block_context(x, BLOCK_64X64), INT64_MAX);
1966 set_partition_seg_context(cm, xd, mi_row, mi_col);
1967 pl = partition_plane_context(xd, BLOCK_64X64);
1968 r += x->partition_cost[pl][PARTITION_NONE];
1970 *(get_sb_partitioning(x, BLOCK_64X64)) = BLOCK_64X64;
1971 cpi->set_ref_frame_mask = 0;
1974 restore_context(cpi, mi_row, mi_col, a, l, sa, sl, BLOCK_64X64);
1977 static void encode_sb_row(VP9_COMP *cpi, int mi_row, TOKENEXTRA **tp,
1979 VP9_COMMON * const cm = &cpi->common;
1982 // Initialize the left context for the new SB row
1983 vpx_memset(&cm->left_context, 0, sizeof(cm->left_context));
1984 vpx_memset(cm->left_seg_context, 0, sizeof(cm->left_seg_context));
1986 // Code each SB in the row
1987 for (mi_col = cm->cur_tile_mi_col_start; mi_col < cm->cur_tile_mi_col_end;
1988 mi_col += MI_BLOCK_SIZE) {
1992 // Initialize a mask of modes that we will not consider;
1993 // cpi->unused_mode_skip_mask = 0x0000000AAE17F800 (test no golden)
1994 if (cpi->common.frame_type == KEY_FRAME)
1995 cpi->unused_mode_skip_mask = 0;
1997 cpi->unused_mode_skip_mask = 0xFFFFFFFFFFFFFE00;
1999 if (cpi->sf.reference_masking)
2000 rd_pick_reference_frame(cpi, mi_row, mi_col);
2002 if (cpi->sf.partition_by_variance || cpi->sf.use_lastframe_partitioning ||
2003 cpi->sf.use_one_partition_size_always ) {
2004 const int idx_str = cm->mode_info_stride * mi_row + mi_col;
2005 MODE_INFO *m = cm->mi + idx_str;
2006 MODE_INFO *p = cm->prev_mi + idx_str;
2008 cpi->mb.source_variance = UINT_MAX;
2009 if (cpi->sf.use_one_partition_size_always) {
2010 set_offsets(cpi, mi_row, mi_col, BLOCK_64X64);
2011 set_partitioning(cpi, m, mi_row, mi_col);
2012 rd_use_partition(cpi, m, tp, mi_row, mi_col, BLOCK_64X64,
2013 &dummy_rate, &dummy_dist, 1);
2014 } else if (cpi->sf.partition_by_variance) {
2015 choose_partitioning(cpi, cm->mi, mi_row, mi_col);
2016 rd_use_partition(cpi, m, tp, mi_row, mi_col, BLOCK_64X64,
2017 &dummy_rate, &dummy_dist, 1);
2019 if ((cpi->common.current_video_frame
2020 % cpi->sf.last_partitioning_redo_frequency) == 0
2022 || cpi->common.show_frame == 0
2023 || cpi->common.frame_type == KEY_FRAME
2024 || cpi->is_src_frame_alt_ref) {
2025 // If required set upper and lower partition size limits
2026 if (cpi->sf.auto_min_max_partition_size) {
2027 set_offsets(cpi, mi_row, mi_col, BLOCK_64X64);
2028 rd_auto_partition_range(cpi,
2029 &cpi->sf.min_partition_size,
2030 &cpi->sf.max_partition_size);
2032 rd_pick_partition(cpi, tp, mi_row, mi_col, BLOCK_64X64,
2033 &dummy_rate, &dummy_dist, 1, INT64_MAX);
2035 copy_partitioning(cpi, m, p);
2036 rd_use_partition(cpi, m, tp, mi_row, mi_col, BLOCK_64X64,
2037 &dummy_rate, &dummy_dist, 1);
2041 // If required set upper and lower partition size limits
2042 if (cpi->sf.auto_min_max_partition_size) {
2043 set_offsets(cpi, mi_row, mi_col, BLOCK_64X64);
2044 rd_auto_partition_range(cpi, &cpi->sf.min_partition_size,
2045 &cpi->sf.max_partition_size);
2048 rd_pick_partition(cpi, tp, mi_row, mi_col, BLOCK_64X64,
2049 &dummy_rate, &dummy_dist, 1, INT64_MAX);
2054 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
2055 MACROBLOCK *const x = &cpi->mb;
2056 VP9_COMMON *const cm = &cpi->common;
2057 MACROBLOCKD *const xd = &x->e_mbd;
2058 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2060 x->act_zbin_adj = 0;
2063 xd->mode_info_stride = cm->mode_info_stride;
2065 // reset intra mode contexts
2066 if (cm->frame_type == KEY_FRAME)
2067 vp9_init_mbmode_probs(cm);
2069 // Copy data over into macro block data structures.
2070 vp9_setup_src_planes(x, cpi->Source, 0, 0);
2072 // TODO(jkoleszar): are these initializations required?
2073 setup_pre_planes(xd, 0, &cm->yv12_fb[cm->ref_frame_map[cpi->lst_fb_idx]],
2075 setup_dst_planes(xd, &cm->yv12_fb[cm->new_fb_idx], 0, 0);
2077 setup_block_dptrs(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
2079 xd->mode_info_context->mbmi.mode = DC_PRED;
2080 xd->mode_info_context->mbmi.uv_mode = DC_PRED;
2082 vp9_zero(cpi->y_mode_count)
2083 vp9_zero(cpi->y_uv_mode_count)
2084 vp9_zero(cm->counts.inter_mode)
2085 vp9_zero(cpi->partition_count);
2086 vp9_zero(cpi->intra_inter_count);
2087 vp9_zero(cpi->comp_inter_count);
2088 vp9_zero(cpi->single_ref_count);
2089 vp9_zero(cpi->comp_ref_count);
2090 vp9_zero(cm->counts.tx);
2091 vp9_zero(cm->counts.mbskip);
2093 // Note: this memset assumes above_context[0], [1] and [2]
2094 // are allocated as part of the same buffer.
2095 vpx_memset(cm->above_context[0], 0,
2096 sizeof(ENTROPY_CONTEXT) * 2 * MAX_MB_PLANE * aligned_mi_cols);
2097 vpx_memset(cm->above_seg_context, 0,
2098 sizeof(PARTITION_CONTEXT) * aligned_mi_cols);
2101 static void switch_lossless_mode(VP9_COMP *cpi, int lossless) {
2103 // printf("Switching to lossless\n");
2104 cpi->mb.fwd_txm8x4 = vp9_short_walsh8x4;
2105 cpi->mb.fwd_txm4x4 = vp9_short_walsh4x4;
2106 cpi->mb.e_mbd.inv_txm4x4_1_add = vp9_short_iwalsh4x4_1_add;
2107 cpi->mb.e_mbd.inv_txm4x4_add = vp9_short_iwalsh4x4_add;
2108 cpi->mb.optimize = 0;
2109 cpi->common.lf.filter_level = 0;
2110 cpi->zbin_mode_boost_enabled = 0;
2111 cpi->common.tx_mode = ONLY_4X4;
2113 // printf("Not lossless\n");
2114 cpi->mb.fwd_txm8x4 = vp9_short_fdct8x4;
2115 cpi->mb.fwd_txm4x4 = vp9_short_fdct4x4;
2116 cpi->mb.e_mbd.inv_txm4x4_1_add = vp9_short_idct4x4_1_add;
2117 cpi->mb.e_mbd.inv_txm4x4_add = vp9_short_idct4x4_add;
2121 static void switch_tx_mode(VP9_COMP *cpi) {
2122 if (cpi->sf.tx_size_search_method == USE_LARGESTALL &&
2123 cpi->common.tx_mode >= ALLOW_32X32)
2124 cpi->common.tx_mode = ALLOW_32X32;
2127 static void encode_frame_internal(VP9_COMP *cpi) {
2129 MACROBLOCK * const x = &cpi->mb;
2130 VP9_COMMON * const cm = &cpi->common;
2131 MACROBLOCKD * const xd = &x->e_mbd;
2134 // fprintf(stderr, "encode_frame_internal frame %d (%d) type %d\n",
2135 // cpi->common.current_video_frame, cpi->common.show_frame,
2142 statsfile = fopen("segmap2.stt", "a");
2143 fprintf(statsfile, "\n");
2150 // Reset frame count of inter 0,0 motion vector usage.
2151 cpi->inter_zz_count = 0;
2153 vp9_zero(cm->counts.switchable_interp);
2154 vp9_zero(cpi->txfm_stepdown_count);
2156 xd->mode_info_context = cm->mi;
2157 xd->prev_mode_info_context = cm->prev_mi;
2159 vp9_zero(cpi->NMVcount);
2160 vp9_zero(cpi->coef_counts);
2161 vp9_zero(cm->counts.eob_branch);
2163 cpi->mb.e_mbd.lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0
2164 && cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
2165 switch_lossless_mode(cpi, cpi->mb.e_mbd.lossless);
2167 vp9_frame_init_quantizer(cpi);
2169 vp9_initialize_rd_consts(cpi, cm->base_qindex + cm->y_dc_delta_q);
2170 vp9_initialize_me_consts(cpi, cm->base_qindex);
2171 switch_tx_mode(cpi);
2173 if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
2174 // Initialize encode frame context.
2175 init_encode_frame_mb_context(cpi);
2177 // Build a frame level activity map
2178 build_activity_map(cpi);
2181 // Re-initialize encode frame context.
2182 init_encode_frame_mb_context(cpi);
2184 vp9_zero(cpi->rd_comp_pred_diff);
2185 vp9_zero(cpi->rd_filter_diff);
2186 vp9_zero(cpi->rd_tx_select_diff);
2187 vp9_zero(cpi->rd_tx_select_threshes);
2192 struct vpx_usec_timer emr_timer;
2193 vpx_usec_timer_start(&emr_timer);
2196 // Take tiles into account and give start/end MB
2197 int tile_col, tile_row;
2198 TOKENEXTRA *tp = cpi->tok;
2199 const int tile_cols = 1 << cm->log2_tile_cols;
2200 const int tile_rows = 1 << cm->log2_tile_rows;
2202 for (tile_row = 0; tile_row < tile_rows; tile_row++) {
2203 vp9_get_tile_row_offsets(cm, tile_row);
2205 for (tile_col = 0; tile_col < tile_cols; tile_col++) {
2206 TOKENEXTRA *tp_old = tp;
2208 // For each row of SBs in the frame
2209 vp9_get_tile_col_offsets(cm, tile_col);
2210 for (mi_row = cm->cur_tile_mi_row_start;
2211 mi_row < cm->cur_tile_mi_row_end; mi_row += 8)
2212 encode_sb_row(cpi, mi_row, &tp, &totalrate);
2214 cpi->tok_count[tile_row][tile_col] = (unsigned int)(tp - tp_old);
2215 assert(tp - cpi->tok <= get_token_alloc(cm->mb_rows, cm->mb_cols));
2220 vpx_usec_timer_mark(&emr_timer);
2221 cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
2224 if (cpi->sf.skip_encode_sb) {
2226 unsigned int intra_count = 0, inter_count = 0;
2227 for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
2228 intra_count += cpi->intra_inter_count[j][0];
2229 inter_count += cpi->intra_inter_count[j][1];
2231 cpi->sf.skip_encode_frame = ((intra_count << 2) < inter_count);
2232 cpi->sf.skip_encode_frame &= (cm->frame_type != KEY_FRAME);
2233 cpi->sf.skip_encode_frame &= cm->show_frame;
2235 cpi->sf.skip_encode_frame = 0;
2238 // 256 rate units to the bit,
2239 // projected_frame_size in units of BYTES
2240 cpi->projected_frame_size = totalrate >> 8;
2243 // Keep record of the total distortion this time around for future use
2244 cpi->last_frame_distortion = cpi->frame_distortion;
2249 static int check_dual_ref_flags(VP9_COMP *cpi) {
2250 const int ref_flags = cpi->ref_frame_flags;
2252 if (vp9_segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
2255 return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG)
2256 + !!(ref_flags & VP9_ALT_FLAG)) >= 2;
2260 static int get_skip_flag(MODE_INFO *mi, int mis, int ymbs, int xmbs) {
2263 for (y = 0; y < ymbs; y++) {
2264 for (x = 0; x < xmbs; x++) {
2265 if (!mi[y * mis + x].mbmi.skip_coeff)
2273 static void set_txfm_flag(MODE_INFO *mi, int mis, int ymbs, int xmbs,
2277 for (y = 0; y < ymbs; y++) {
2278 for (x = 0; x < xmbs; x++)
2279 mi[y * mis + x].mbmi.tx_size = tx_size;
2283 static void reset_skip_txfm_size_b(VP9_COMP *cpi, MODE_INFO *mi, int mis,
2284 TX_SIZE max_tx_size, int bw, int bh,
2285 int mi_row, int mi_col, BLOCK_SIZE bsize) {
2286 VP9_COMMON *const cm = &cpi->common;
2287 MB_MODE_INFO *const mbmi = &mi->mbmi;
2289 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
2292 if (mbmi->tx_size > max_tx_size) {
2293 MACROBLOCK * const x = &cpi->mb;
2294 MACROBLOCKD * const xd = &x->e_mbd;
2295 const int ymbs = MIN(bh, cm->mi_rows - mi_row);
2296 const int xmbs = MIN(bw, cm->mi_cols - mi_col);
2298 xd->mode_info_context = mi;
2299 assert(vp9_segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP) ||
2300 get_skip_flag(mi, mis, ymbs, xmbs));
2301 set_txfm_flag(mi, mis, ymbs, xmbs, max_tx_size);
2305 static void reset_skip_txfm_size_sb(VP9_COMP *cpi, MODE_INFO *mi,
2306 TX_SIZE max_tx_size, int mi_row, int mi_col,
2308 const VP9_COMMON *const cm = &cpi->common;
2309 const int mis = cm->mode_info_stride;
2311 const int bs = num_8x8_blocks_wide_lookup[bsize], hbs = bs / 2;
2313 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
2316 bw = num_8x8_blocks_wide_lookup[mi->mbmi.sb_type];
2317 bh = num_8x8_blocks_high_lookup[mi->mbmi.sb_type];
2319 if (bw == bs && bh == bs) {
2320 reset_skip_txfm_size_b(cpi, mi, mis, max_tx_size, bs, bs, mi_row,
2322 } else if (bw == bs && bh < bs) {
2323 reset_skip_txfm_size_b(cpi, mi, mis, max_tx_size, bs, hbs, mi_row, mi_col,
2325 reset_skip_txfm_size_b(cpi, mi + hbs * mis, mis, max_tx_size, bs, hbs,
2326 mi_row + hbs, mi_col, bsize);
2327 } else if (bw < bs && bh == bs) {
2328 reset_skip_txfm_size_b(cpi, mi, mis, max_tx_size, hbs, bs, mi_row, mi_col,
2330 reset_skip_txfm_size_b(cpi, mi + hbs, mis, max_tx_size, hbs, bs, mi_row,
2331 mi_col + hbs, bsize);
2333 const BLOCK_SIZE subsize = subsize_lookup[PARTITION_SPLIT][bsize];
2336 assert(bw < bs && bh < bs);
2338 for (n = 0; n < 4; n++) {
2339 const int mi_dc = hbs * (n & 1);
2340 const int mi_dr = hbs * (n >> 1);
2342 reset_skip_txfm_size_sb(cpi, &mi[mi_dr * mis + mi_dc], max_tx_size,
2343 mi_row + mi_dr, mi_col + mi_dc, subsize);
2348 static void reset_skip_txfm_size(VP9_COMP *cpi, TX_SIZE txfm_max) {
2349 VP9_COMMON * const cm = &cpi->common;
2351 const int mis = cm->mode_info_stride;
2352 MODE_INFO *mi, *mi_ptr = cm->mi;
2354 for (mi_row = 0; mi_row < cm->mi_rows; mi_row += 8, mi_ptr += 8 * mis) {
2356 for (mi_col = 0; mi_col < cm->mi_cols; mi_col += 8, mi += 8)
2357 reset_skip_txfm_size_sb(cpi, mi, txfm_max, mi_row, mi_col, BLOCK_64X64);
2361 static int get_frame_type(VP9_COMP *cpi) {
2363 if (cpi->common.frame_type == KEY_FRAME)
2365 else if (cpi->is_src_frame_alt_ref && cpi->refresh_golden_frame)
2367 else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
2374 static void select_tx_mode(VP9_COMP *cpi) {
2375 if (cpi->oxcf.lossless) {
2376 cpi->common.tx_mode = ONLY_4X4;
2377 } else if (cpi->common.current_video_frame == 0) {
2378 cpi->common.tx_mode = TX_MODE_SELECT;
2380 if (cpi->sf.tx_size_search_method == USE_LARGESTALL) {
2381 cpi->common.tx_mode = ALLOW_32X32;
2382 } else if (cpi->sf.tx_size_search_method == USE_FULL_RD) {
2383 int frame_type = get_frame_type(cpi);
2384 cpi->common.tx_mode =
2385 cpi->rd_tx_select_threshes[frame_type][ALLOW_32X32]
2386 > cpi->rd_tx_select_threshes[frame_type][TX_MODE_SELECT] ?
2387 ALLOW_32X32 : TX_MODE_SELECT;
2389 unsigned int total = 0;
2391 for (i = 0; i < TX_SIZES; ++i)
2392 total += cpi->txfm_stepdown_count[i];
2394 double fraction = (double)cpi->txfm_stepdown_count[0] / total;
2395 cpi->common.tx_mode = fraction > 0.90 ? ALLOW_32X32 : TX_MODE_SELECT;
2396 // printf("fraction = %f\n", fraction);
2397 } // else keep unchanged
2402 void vp9_encode_frame(VP9_COMP *cpi) {
2403 VP9_COMMON * const cm = &cpi->common;
2405 // In the longer term the encoder should be generalized to match the
2406 // decoder such that we allow compound where one of the 3 buffers has a
2407 // different sign bias and that buffer is then the fixed ref. However, this
2408 // requires further work in the rd loop. For now the only supported encoder
2409 // side behavior is where the ALT ref buffer has opposite sign bias to
2411 if ((cm->ref_frame_sign_bias[ALTREF_FRAME]
2412 == cm->ref_frame_sign_bias[GOLDEN_FRAME])
2413 || (cm->ref_frame_sign_bias[ALTREF_FRAME]
2414 == cm->ref_frame_sign_bias[LAST_FRAME])) {
2415 cm->allow_comp_inter_inter = 0;
2417 cm->allow_comp_inter_inter = 1;
2418 cm->comp_fixed_ref = ALTREF_FRAME;
2419 cm->comp_var_ref[0] = LAST_FRAME;
2420 cm->comp_var_ref[1] = GOLDEN_FRAME;
2425 INTERPOLATIONFILTERTYPE filter_type;
2427 * This code does a single RD pass over the whole frame assuming
2428 * either compound, single or hybrid prediction as per whatever has
2429 * worked best for that type of frame in the past.
2430 * It also predicts whether another coding mode would have worked
2431 * better that this coding mode. If that is the case, it remembers
2432 * that for subsequent frames.
2433 * It does the same analysis for transform size selection also.
2435 int frame_type = get_frame_type(cpi);
2437 /* prediction (compound, single or hybrid) mode selection */
2438 if (frame_type == 3 || !cm->allow_comp_inter_inter)
2439 pred_type = SINGLE_PREDICTION_ONLY;
2440 else if (cpi->rd_prediction_type_threshes[frame_type][1]
2441 > cpi->rd_prediction_type_threshes[frame_type][0]
2442 && cpi->rd_prediction_type_threshes[frame_type][1]
2443 > cpi->rd_prediction_type_threshes[frame_type][2]
2444 && check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
2445 pred_type = COMP_PREDICTION_ONLY;
2446 else if (cpi->rd_prediction_type_threshes[frame_type][0]
2447 > cpi->rd_prediction_type_threshes[frame_type][2])
2448 pred_type = SINGLE_PREDICTION_ONLY;
2450 pred_type = HYBRID_PREDICTION;
2452 /* filter type selection */
2453 // FIXME(rbultje) for some odd reason, we often select smooth_filter
2454 // as default filter for ARF overlay frames. This is a REALLY BAD
2455 // IDEA so we explicitly disable it here.
2456 if (frame_type != 3 &&
2457 cpi->rd_filter_threshes[frame_type][1] >
2458 cpi->rd_filter_threshes[frame_type][0] &&
2459 cpi->rd_filter_threshes[frame_type][1] >
2460 cpi->rd_filter_threshes[frame_type][2] &&
2461 cpi->rd_filter_threshes[frame_type][1] >
2462 cpi->rd_filter_threshes[frame_type][SWITCHABLE_FILTERS]) {
2463 filter_type = EIGHTTAP_SMOOTH;
2464 } else if (cpi->rd_filter_threshes[frame_type][2] >
2465 cpi->rd_filter_threshes[frame_type][0] &&
2466 cpi->rd_filter_threshes[frame_type][2] >
2467 cpi->rd_filter_threshes[frame_type][SWITCHABLE_FILTERS]) {
2468 filter_type = EIGHTTAP_SHARP;
2469 } else if (cpi->rd_filter_threshes[frame_type][0] >
2470 cpi->rd_filter_threshes[frame_type][SWITCHABLE_FILTERS]) {
2471 filter_type = EIGHTTAP;
2473 filter_type = SWITCHABLE;
2476 cpi->mb.e_mbd.lossless = 0;
2477 if (cpi->oxcf.lossless) {
2478 cpi->mb.e_mbd.lossless = 1;
2481 /* transform size selection (4x4, 8x8, 16x16 or select-per-mb) */
2482 select_tx_mode(cpi);
2483 cpi->common.comp_pred_mode = pred_type;
2484 cpi->common.mcomp_filter_type = filter_type;
2485 encode_frame_internal(cpi);
2487 for (i = 0; i < NB_PREDICTION_TYPES; ++i) {
2488 const int diff = (int) (cpi->rd_comp_pred_diff[i] / cpi->common.MBs);
2489 cpi->rd_prediction_type_threshes[frame_type][i] += diff;
2490 cpi->rd_prediction_type_threshes[frame_type][i] >>= 1;
2493 for (i = 0; i <= SWITCHABLE_FILTERS; i++) {
2494 const int64_t diff = cpi->rd_filter_diff[i] / cpi->common.MBs;
2495 cpi->rd_filter_threshes[frame_type][i] =
2496 (cpi->rd_filter_threshes[frame_type][i] + diff) / 2;
2499 for (i = 0; i < TX_MODES; ++i) {
2500 int64_t pd = cpi->rd_tx_select_diff[i];
2502 if (i == TX_MODE_SELECT)
2503 pd -= RDCOST(cpi->mb.rdmult, cpi->mb.rddiv,
2504 2048 * (TX_SIZES - 1), 0);
2505 diff = (int) (pd / cpi->common.MBs);
2506 cpi->rd_tx_select_threshes[frame_type][i] += diff;
2507 cpi->rd_tx_select_threshes[frame_type][i] /= 2;
2510 if (cpi->common.comp_pred_mode == HYBRID_PREDICTION) {
2511 int single_count_zero = 0;
2512 int comp_count_zero = 0;
2514 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
2515 single_count_zero += cpi->comp_inter_count[i][0];
2516 comp_count_zero += cpi->comp_inter_count[i][1];
2519 if (comp_count_zero == 0) {
2520 cpi->common.comp_pred_mode = SINGLE_PREDICTION_ONLY;
2521 vp9_zero(cpi->comp_inter_count);
2522 } else if (single_count_zero == 0) {
2523 cpi->common.comp_pred_mode = COMP_PREDICTION_ONLY;
2524 vp9_zero(cpi->comp_inter_count);
2528 if (cpi->common.tx_mode == TX_MODE_SELECT) {
2530 int count8x8_lp = 0, count8x8_8x8p = 0;
2531 int count16x16_16x16p = 0, count16x16_lp = 0;
2534 for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
2535 count4x4 += cm->counts.tx.p32x32[i][TX_4X4];
2536 count4x4 += cm->counts.tx.p16x16[i][TX_4X4];
2537 count4x4 += cm->counts.tx.p8x8[i][TX_4X4];
2539 count8x8_lp += cm->counts.tx.p32x32[i][TX_8X8];
2540 count8x8_lp += cm->counts.tx.p16x16[i][TX_8X8];
2541 count8x8_8x8p += cm->counts.tx.p8x8[i][TX_8X8];
2543 count16x16_16x16p += cm->counts.tx.p16x16[i][TX_16X16];
2544 count16x16_lp += cm->counts.tx.p32x32[i][TX_16X16];
2545 count32x32 += cm->counts.tx.p32x32[i][TX_32X32];
2548 if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0
2549 && count32x32 == 0) {
2550 cpi->common.tx_mode = ALLOW_8X8;
2551 reset_skip_txfm_size(cpi, TX_8X8);
2552 } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0
2553 && count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
2554 cpi->common.tx_mode = ONLY_4X4;
2555 reset_skip_txfm_size(cpi, TX_4X4);
2556 } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
2557 cpi->common.tx_mode = ALLOW_32X32;
2558 } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
2559 cpi->common.tx_mode = ALLOW_16X16;
2560 reset_skip_txfm_size(cpi, TX_16X16);
2564 encode_frame_internal(cpi);
2569 static void sum_intra_stats(VP9_COMP *cpi, const MODE_INFO *mi) {
2570 const MB_PREDICTION_MODE y_mode = mi->mbmi.mode;
2571 const MB_PREDICTION_MODE uv_mode = mi->mbmi.uv_mode;
2572 const BLOCK_SIZE bsize = mi->mbmi.sb_type;
2574 ++cpi->y_uv_mode_count[y_mode][uv_mode];
2576 if (bsize < BLOCK_8X8) {
2578 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2579 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2580 for (idy = 0; idy < 2; idy += num_4x4_blocks_high)
2581 for (idx = 0; idx < 2; idx += num_4x4_blocks_wide)
2582 ++cpi->y_mode_count[0][mi->bmi[idy * 2 + idx].as_mode];
2584 ++cpi->y_mode_count[size_group_lookup[bsize]][y_mode];
2588 // Experimental stub function to create a per MB zbin adjustment based on
2589 // some previously calculated measure of MB activity.
2590 static void adjust_act_zbin(VP9_COMP *cpi, MACROBLOCK *x) {
2592 x->act_zbin_adj = *(x->mb_activity_ptr);
2596 int64_t act = *(x->mb_activity_ptr);
2598 // Apply the masking to the RD multiplier.
2599 a = act + 4 * cpi->activity_avg;
2600 b = 4 * act + cpi->activity_avg;
2602 if (act > cpi->activity_avg)
2603 x->act_zbin_adj = (int) (((int64_t) b + (a >> 1)) / a) - 1;
2605 x->act_zbin_adj = 1 - (int) (((int64_t) a + (b >> 1)) / b);
2609 static void encode_superblock(VP9_COMP *cpi, TOKENEXTRA **t, int output_enabled,
2610 int mi_row, int mi_col, BLOCK_SIZE bsize) {
2611 VP9_COMMON * const cm = &cpi->common;
2612 MACROBLOCK * const x = &cpi->mb;
2613 MACROBLOCKD * const xd = &x->e_mbd;
2614 MODE_INFO *mi = xd->mode_info_context;
2615 MB_MODE_INFO *mbmi = &mi->mbmi;
2616 unsigned int segment_id = mbmi->segment_id;
2617 const int mis = cm->mode_info_stride;
2618 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
2619 const int mi_height = num_8x8_blocks_high_lookup[bsize];
2620 x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
2621 x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
2622 xd->q_index < QIDX_SKIP_THRESH);
2626 if (cm->frame_type == KEY_FRAME) {
2627 if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
2628 adjust_act_zbin(cpi, x);
2629 vp9_update_zbin_extra(cpi, x);
2632 vp9_setup_interp_filters(xd, mbmi->interp_filter, cm);
2634 if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
2635 // Adjust the zbin based on this MB rate.
2636 adjust_act_zbin(cpi, x);
2639 // Experimental code. Special case for gf and arf zeromv modes.
2640 // Increase zbin size to suppress noise
2641 cpi->zbin_mode_boost = 0;
2642 if (cpi->zbin_mode_boost_enabled) {
2643 if (is_inter_block(mbmi)) {
2644 if (mbmi->mode == ZEROMV) {
2645 if (mbmi->ref_frame[0] != LAST_FRAME)
2646 cpi->zbin_mode_boost = GF_ZEROMV_ZBIN_BOOST;
2648 cpi->zbin_mode_boost = LF_ZEROMV_ZBIN_BOOST;
2649 } else if (mbmi->sb_type < BLOCK_8X8) {
2650 cpi->zbin_mode_boost = SPLIT_MV_ZBIN_BOOST;
2652 cpi->zbin_mode_boost = MV_ZBIN_BOOST;
2655 cpi->zbin_mode_boost = INTRA_ZBIN_BOOST;
2659 vp9_update_zbin_extra(cpi, x);
2662 if (!is_inter_block(mbmi)) {
2663 vp9_encode_intra_block_y(x, MAX(bsize, BLOCK_8X8));
2664 vp9_encode_intra_block_uv(x, MAX(bsize, BLOCK_8X8));
2666 sum_intra_stats(cpi, mi);
2668 int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, mbmi->ref_frame[0])];
2669 YV12_BUFFER_CONFIG *ref_fb = &cm->yv12_fb[idx];
2670 YV12_BUFFER_CONFIG *second_ref_fb = NULL;
2671 if (mbmi->ref_frame[1] > 0) {
2672 idx = cm->ref_frame_map[get_ref_frame_idx(cpi, mbmi->ref_frame[1])];
2673 second_ref_fb = &cm->yv12_fb[idx];
2676 assert(cm->frame_type != KEY_FRAME);
2678 setup_pre_planes(xd, 0, ref_fb, mi_row, mi_col,
2679 &xd->scale_factor[0]);
2680 setup_pre_planes(xd, 1, second_ref_fb, mi_row, mi_col,
2681 &xd->scale_factor[1]);
2684 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, MAX(bsize, BLOCK_8X8));
2687 if (!is_inter_block(mbmi)) {
2688 vp9_tokenize_sb(cpi, t, !output_enabled, MAX(bsize, BLOCK_8X8));
2689 } else if (!x->skip) {
2690 vp9_encode_sb(x, MAX(bsize, BLOCK_8X8));
2691 vp9_tokenize_sb(cpi, t, !output_enabled, MAX(bsize, BLOCK_8X8));
2693 int mb_skip_context = xd->left_available ? (mi - 1)->mbmi.skip_coeff : 0;
2694 mb_skip_context += (mi - mis)->mbmi.skip_coeff;
2696 mbmi->skip_coeff = 1;
2698 cm->counts.mbskip[mb_skip_context][1]++;
2699 reset_skip_context(xd, MAX(bsize, BLOCK_8X8));
2702 // copy skip flag on all mb_mode_info contexts in this SB
2703 // if this was a skip at this txfm size
2704 vp9_set_pred_flag_mbskip(cm, bsize, mi_row, mi_col, mi->mbmi.skip_coeff);
2706 if (output_enabled) {
2707 if (cm->tx_mode == TX_MODE_SELECT &&
2708 mbmi->sb_type >= BLOCK_8X8 &&
2709 !(is_inter_block(mbmi) &&
2710 (mbmi->skip_coeff ||
2711 vp9_segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP)))) {
2712 const uint8_t context = vp9_get_pred_context_tx_size(xd);
2713 update_tx_counts(bsize, context, mbmi->tx_size, &cm->counts.tx);
2716 TX_SIZE sz = (cm->tx_mode == TX_MODE_SELECT) ? TX_32X32 : cm->tx_mode;
2717 // The new intra coding scheme requires no change of transform size
2718 if (is_inter_block(&mi->mbmi)) {
2719 if (sz == TX_32X32 && bsize < BLOCK_32X32)
2721 if (sz == TX_16X16 && bsize < BLOCK_16X16)
2723 if (sz == TX_8X8 && bsize < BLOCK_8X8)
2725 } else if (bsize >= BLOCK_8X8) {
2731 for (y = 0; y < mi_height; y++)
2732 for (x = 0; x < mi_width; x++)
2733 if (mi_col + x < cm->mi_cols && mi_row + y < cm->mi_rows)
2734 mi[mis * y + x].mbmi.tx_size = sz;