PageRenderTime 90ms CodeModel.GetById 13ms app.highlight 67ms RepoModel.GetById 1ms app.codeStats 1ms

/media/libvpx/vp8/encoder/encodeframe.c

http://github.com/zpao/v8monkey
C | 1332 lines | 931 code | 255 blank | 146 comment | 175 complexity | 175ad2814536cc68f2b1f328abcecc10 MD5 | raw file
   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
  12#include "vpx_ports/config.h"
  13#include "encodemb.h"
  14#include "encodemv.h"
  15#include "vp8/common/common.h"
  16#include "onyx_int.h"
  17#include "vp8/common/extend.h"
  18#include "vp8/common/entropymode.h"
  19#include "vp8/common/quant_common.h"
  20#include "segmentation.h"
  21#include "vp8/common/setupintrarecon.h"
  22#include "encodeintra.h"
  23#include "vp8/common/reconinter.h"
  24#include "rdopt.h"
  25#include "pickinter.h"
  26#include "vp8/common/findnearmv.h"
  27#include "vp8/common/reconintra.h"
  28#include <stdio.h>
  29#include <limits.h>
  30#include "vp8/common/subpixel.h"
  31#include "vpx_ports/vpx_timer.h"
  32
  33#if CONFIG_RUNTIME_CPU_DETECT
  34#define RTCD(x)     &cpi->common.rtcd.x
  35#define IF_RTCD(x)  (x)
  36#else
  37#define RTCD(x)     NULL
  38#define IF_RTCD(x)  NULL
  39#endif
  40extern void vp8_stuff_mb(VP8_COMP *cpi, MACROBLOCKD *x, TOKENEXTRA **t) ;
  41
  42extern void vp8cx_initialize_me_consts(VP8_COMP *cpi, int QIndex);
  43extern void vp8_auto_select_speed(VP8_COMP *cpi);
  44extern void vp8cx_init_mbrthread_data(VP8_COMP *cpi,
  45                                      MACROBLOCK *x,
  46                                      MB_ROW_COMP *mbr_ei,
  47                                      int mb_row,
  48                                      int count);
  49void vp8_build_block_offsets(MACROBLOCK *x);
  50void vp8_setup_block_ptrs(MACROBLOCK *x);
  51int vp8cx_encode_inter_macroblock(VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t, int recon_yoffset, int recon_uvoffset);
  52int vp8cx_encode_intra_macro_block(VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t);
  53static void adjust_act_zbin( VP8_COMP *cpi, MACROBLOCK *x );
  54
  55#ifdef MODE_STATS
  56unsigned int inter_y_modes[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  57unsigned int inter_uv_modes[4] = {0, 0, 0, 0};
  58unsigned int inter_b_modes[15]  = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  59unsigned int y_modes[5]   = {0, 0, 0, 0, 0};
  60unsigned int uv_modes[4]  = {0, 0, 0, 0};
  61unsigned int b_modes[14]  = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  62#endif
  63
  64
  65/* activity_avg must be positive, or flat regions could get a zero weight
  66 *  (infinite lambda), which confounds analysis.
  67 * This also avoids the need for divide by zero checks in
  68 *  vp8_activity_masking().
  69 */
  70#define VP8_ACTIVITY_AVG_MIN (64)
  71
  72/* This is used as a reference when computing the source variance for the
  73 *  purposes of activity masking.
  74 * Eventually this should be replaced by custom no-reference routines,
  75 *  which will be faster.
  76 */
  77static const unsigned char VP8_VAR_OFFS[16]=
  78{
  79    128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128
  80};
  81
  82
  83// Original activity measure from Tim T's code.
  84static unsigned int tt_activity_measure( VP8_COMP *cpi, MACROBLOCK *x )
  85{
  86    unsigned int act;
  87    unsigned int sse;
  88    /* TODO: This could also be done over smaller areas (8x8), but that would
  89     *  require extensive changes elsewhere, as lambda is assumed to be fixed
  90     *  over an entire MB in most of the code.
  91     * Another option is to compute four 8x8 variances, and pick a single
  92     *  lambda using a non-linear combination (e.g., the smallest, or second
  93     *  smallest, etc.).
  94     */
  95    act =     VARIANCE_INVOKE(&cpi->rtcd.variance, var16x16)(x->src.y_buffer,
  96                    x->src.y_stride, VP8_VAR_OFFS, 0, &sse);
  97    act = act<<4;
  98
  99    /* If the region is flat, lower the activity some more. */
 100    if (act < 8<<12)
 101        act = act < 5<<12 ? act : 5<<12;
 102
 103    return act;
 104}
 105
 106// Stub for alternative experimental activity measures.
 107static unsigned int alt_activity_measure( VP8_COMP *cpi,
 108                                          MACROBLOCK *x, int use_dc_pred )
 109{
 110    return vp8_encode_intra(cpi,x, use_dc_pred);
 111}
 112
 113
 114// Measure the activity of the current macroblock
 115// What we measure here is TBD so abstracted to this function
 116#define ALT_ACT_MEASURE 1
 117static unsigned int mb_activity_measure( VP8_COMP *cpi, MACROBLOCK *x,
 118                                  int mb_row, int mb_col)
 119{
 120    unsigned int mb_activity;
 121
 122    if  ( ALT_ACT_MEASURE )
 123    {
 124        int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
 125
 126        // Or use and alternative.
 127        mb_activity = alt_activity_measure( cpi, x, use_dc_pred );
 128    }
 129    else
 130    {
 131        // Original activity measure from Tim T's code.
 132        mb_activity = tt_activity_measure( cpi, x );
 133    }
 134
 135    if ( mb_activity < VP8_ACTIVITY_AVG_MIN )
 136        mb_activity = VP8_ACTIVITY_AVG_MIN;
 137
 138    return mb_activity;
 139}
 140
 141// Calculate an "average" mb activity value for the frame
 142#define ACT_MEDIAN 0
 143static void calc_av_activity( VP8_COMP *cpi, int64_t activity_sum )
 144{
 145#if ACT_MEDIAN
 146    // Find median: Simple n^2 algorithm for experimentation
 147    {
 148        unsigned int median;
 149        unsigned int i,j;
 150        unsigned int * sortlist;
 151        unsigned int tmp;
 152
 153        // Create a list to sort to
 154        CHECK_MEM_ERROR(sortlist,
 155                        vpx_calloc(sizeof(unsigned int),
 156                        cpi->common.MBs));
 157
 158        // Copy map to sort list
 159        vpx_memcpy( sortlist, cpi->mb_activity_map,
 160                    sizeof(unsigned int) * cpi->common.MBs );
 161
 162
 163        // Ripple each value down to its correct position
 164        for ( i = 1; i < cpi->common.MBs; i ++ )
 165        {
 166            for ( j = i; j > 0; j -- )
 167            {
 168                if ( sortlist[j] < sortlist[j-1] )
 169                {
 170                    // Swap values
 171                    tmp = sortlist[j-1];
 172                    sortlist[j-1] = sortlist[j];
 173                    sortlist[j] = tmp;
 174                }
 175                else
 176                    break;
 177            }
 178        }
 179
 180        // Even number MBs so estimate median as mean of two either side.
 181        median = ( 1 + sortlist[cpi->common.MBs >> 1] +
 182                   sortlist[(cpi->common.MBs >> 1) + 1] ) >> 1;
 183
 184        cpi->activity_avg = median;
 185
 186        vpx_free(sortlist);
 187    }
 188#else
 189    // Simple mean for now
 190    cpi->activity_avg = (unsigned int)(activity_sum/cpi->common.MBs);
 191#endif
 192
 193    if (cpi->activity_avg < VP8_ACTIVITY_AVG_MIN)
 194        cpi->activity_avg = VP8_ACTIVITY_AVG_MIN;
 195
 196    // Experimental code: return fixed value normalized for several clips
 197    if  ( ALT_ACT_MEASURE )
 198        cpi->activity_avg = 100000;
 199}
 200
 201#define USE_ACT_INDEX   0
 202#define OUTPUT_NORM_ACT_STATS   0
 203
 204#if USE_ACT_INDEX
 205// Calculate and activity index for each mb
 206static void calc_activity_index( VP8_COMP *cpi, MACROBLOCK *x )
 207{
 208    VP8_COMMON *const cm = & cpi->common;
 209    int mb_row, mb_col;
 210
 211    int64_t act;
 212    int64_t a;
 213    int64_t b;
 214
 215#if OUTPUT_NORM_ACT_STATS
 216    FILE *f = fopen("norm_act.stt", "a");
 217    fprintf(f, "\n%12d\n", cpi->activity_avg );
 218#endif
 219
 220    // Reset pointers to start of activity map
 221    x->mb_activity_ptr = cpi->mb_activity_map;
 222
 223    // Calculate normalized mb activity number.
 224    for (mb_row = 0; mb_row < cm->mb_rows; mb_row++)
 225    {
 226        // for each macroblock col in image
 227        for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
 228        {
 229            // Read activity from the map
 230            act = *(x->mb_activity_ptr);
 231
 232            // Calculate a normalized activity number
 233            a = act + 4*cpi->activity_avg;
 234            b = 4*act + cpi->activity_avg;
 235
 236            if ( b >= a )
 237                *(x->activity_ptr) = (int)((b + (a>>1))/a) - 1;
 238            else
 239                *(x->activity_ptr) = 1 - (int)((a + (b>>1))/b);
 240
 241#if OUTPUT_NORM_ACT_STATS
 242            fprintf(f, " %6d", *(x->mb_activity_ptr));
 243#endif
 244            // Increment activity map pointers
 245            x->mb_activity_ptr++;
 246        }
 247
 248#if OUTPUT_NORM_ACT_STATS
 249        fprintf(f, "\n");
 250#endif
 251
 252    }
 253
 254#if OUTPUT_NORM_ACT_STATS
 255    fclose(f);
 256#endif
 257
 258}
 259#endif
 260
 261// Loop through all MBs. Note activity of each, average activity and
 262// calculate a normalized activity for each
 263static void build_activity_map( VP8_COMP *cpi )
 264{
 265    MACROBLOCK *const x = & cpi->mb;
 266    MACROBLOCKD *xd = &x->e_mbd;
 267    VP8_COMMON *const cm = & cpi->common;
 268
 269#if ALT_ACT_MEASURE
 270    YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
 271    int recon_yoffset;
 272    int recon_y_stride = new_yv12->y_stride;
 273#endif
 274
 275    int mb_row, mb_col;
 276    unsigned int mb_activity;
 277    int64_t activity_sum = 0;
 278
 279    // for each macroblock row in image
 280    for (mb_row = 0; mb_row < cm->mb_rows; mb_row++)
 281    {
 282#if ALT_ACT_MEASURE
 283        // reset above block coeffs
 284        xd->up_available = (mb_row != 0);
 285        recon_yoffset = (mb_row * recon_y_stride * 16);
 286#endif
 287        // for each macroblock col in image
 288        for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
 289        {
 290#if ALT_ACT_MEASURE
 291            xd->dst.y_buffer = new_yv12->y_buffer + recon_yoffset;
 292            xd->left_available = (mb_col != 0);
 293            recon_yoffset += 16;
 294#endif
 295            //Copy current mb to a buffer
 296            RECON_INVOKE(&xd->rtcd->recon, copy16x16)(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
 297
 298            // measure activity
 299            mb_activity = mb_activity_measure( cpi, x, mb_row, mb_col );
 300
 301            // Keep frame sum
 302            activity_sum += mb_activity;
 303
 304            // Store MB level activity details.
 305            *x->mb_activity_ptr = mb_activity;
 306
 307            // Increment activity map pointer
 308            x->mb_activity_ptr++;
 309
 310            // adjust to the next column of source macroblocks
 311            x->src.y_buffer += 16;
 312        }
 313
 314
 315        // adjust to the next row of mbs
 316        x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
 317
 318#if ALT_ACT_MEASURE
 319        //extend the recon for intra prediction
 320        vp8_extend_mb_row(new_yv12, xd->dst.y_buffer + 16,
 321                          xd->dst.u_buffer + 8, xd->dst.v_buffer + 8);
 322#endif
 323
 324    }
 325
 326    // Calculate an "average" MB activity
 327    calc_av_activity(cpi, activity_sum);
 328
 329#if USE_ACT_INDEX
 330    // Calculate an activity index number of each mb
 331    calc_activity_index( cpi, x );
 332#endif
 333
 334}
 335
 336// Macroblock activity masking
 337void vp8_activity_masking(VP8_COMP *cpi, MACROBLOCK *x)
 338{
 339#if USE_ACT_INDEX
 340    x->rdmult += *(x->mb_activity_ptr) * (x->rdmult >> 2);
 341    x->errorperbit = x->rdmult * 100 /(110 * x->rddiv);
 342    x->errorperbit += (x->errorperbit==0);
 343#else
 344    int64_t a;
 345    int64_t b;
 346    int64_t act = *(x->mb_activity_ptr);
 347
 348    // Apply the masking to the RD multiplier.
 349    a = act + (2*cpi->activity_avg);
 350    b = (2*act) + cpi->activity_avg;
 351
 352    x->rdmult = (unsigned int)(((int64_t)x->rdmult*b + (a>>1))/a);
 353    x->errorperbit = x->rdmult * 100 /(110 * x->rddiv);
 354    x->errorperbit += (x->errorperbit==0);
 355#endif
 356
 357    // Activity based Zbin adjustment
 358    adjust_act_zbin(cpi, x);
 359}
 360
 361static
 362void encode_mb_row(VP8_COMP *cpi,
 363                   VP8_COMMON *cm,
 364                   int mb_row,
 365                   MACROBLOCK  *x,
 366                   MACROBLOCKD *xd,
 367                   TOKENEXTRA **tp,
 368                   int *segment_counts,
 369                   int *totalrate)
 370{
 371    int i;
 372    int recon_yoffset, recon_uvoffset;
 373    int mb_col;
 374    int ref_fb_idx = cm->lst_fb_idx;
 375    int dst_fb_idx = cm->new_fb_idx;
 376    int recon_y_stride = cm->yv12_fb[ref_fb_idx].y_stride;
 377    int recon_uv_stride = cm->yv12_fb[ref_fb_idx].uv_stride;
 378    int map_index = (mb_row * cpi->common.mb_cols);
 379
 380#if CONFIG_MULTITHREAD
 381    const int nsync = cpi->mt_sync_range;
 382    const int rightmost_col = cm->mb_cols - 1;
 383    volatile const int *last_row_current_mb_col;
 384
 385    if ((cpi->b_multi_threaded != 0) && (mb_row != 0))
 386        last_row_current_mb_col = &cpi->mt_current_mb_col[mb_row - 1];
 387    else
 388        last_row_current_mb_col = &rightmost_col;
 389#endif
 390
 391    // reset above block coeffs
 392    xd->above_context = cm->above_context;
 393
 394    xd->up_available = (mb_row != 0);
 395    recon_yoffset = (mb_row * recon_y_stride * 16);
 396    recon_uvoffset = (mb_row * recon_uv_stride * 8);
 397
 398    cpi->tplist[mb_row].start = *tp;
 399    //printf("Main mb_row = %d\n", mb_row);
 400
 401    // Distance of Mb to the top & bottom edges, specified in 1/8th pel
 402    // units as they are always compared to values that are in 1/8th pel units
 403    xd->mb_to_top_edge = -((mb_row * 16) << 3);
 404    xd->mb_to_bottom_edge = ((cm->mb_rows - 1 - mb_row) * 16) << 3;
 405
 406    // Set up limit values for vertical motion vector components
 407    // to prevent them extending beyond the UMV borders
 408    x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16));
 409    x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16)
 410                        + (VP8BORDERINPIXELS - 16);
 411
 412    // Set the mb activity pointer to the start of the row.
 413    x->mb_activity_ptr = &cpi->mb_activity_map[map_index];
 414
 415    // for each macroblock col in image
 416    for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
 417    {
 418        // Distance of Mb to the left & right edges, specified in
 419        // 1/8th pel units as they are always compared to values
 420        // that are in 1/8th pel units
 421        xd->mb_to_left_edge = -((mb_col * 16) << 3);
 422        xd->mb_to_right_edge = ((cm->mb_cols - 1 - mb_col) * 16) << 3;
 423
 424        // Set up limit values for horizontal motion vector components
 425        // to prevent them extending beyond the UMV borders
 426        x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16));
 427        x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16)
 428                            + (VP8BORDERINPIXELS - 16);
 429
 430        xd->dst.y_buffer = cm->yv12_fb[dst_fb_idx].y_buffer + recon_yoffset;
 431        xd->dst.u_buffer = cm->yv12_fb[dst_fb_idx].u_buffer + recon_uvoffset;
 432        xd->dst.v_buffer = cm->yv12_fb[dst_fb_idx].v_buffer + recon_uvoffset;
 433        xd->left_available = (mb_col != 0);
 434
 435        x->rddiv = cpi->RDDIV;
 436        x->rdmult = cpi->RDMULT;
 437
 438        //Copy current mb to a buffer
 439        RECON_INVOKE(&xd->rtcd->recon, copy16x16)(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
 440
 441#if CONFIG_MULTITHREAD
 442        if ((cpi->b_multi_threaded != 0) && (mb_row != 0))
 443        {
 444            if ((mb_col & (nsync - 1)) == 0)
 445            {
 446                while (mb_col > (*last_row_current_mb_col - nsync)
 447                        && (*last_row_current_mb_col) != (cm->mb_cols - 1))
 448                {
 449                    x86_pause_hint();
 450                    thread_sleep(0);
 451                }
 452            }
 453        }
 454#endif
 455
 456        if(cpi->oxcf.tuning == VP8_TUNE_SSIM)
 457            vp8_activity_masking(cpi, x);
 458
 459        // Is segmentation enabled
 460        // MB level adjutment to quantizer
 461        if (xd->segmentation_enabled)
 462        {
 463            // Code to set segment id in xd->mbmi.segment_id for current MB (with range checking)
 464            if (cpi->segmentation_map[map_index+mb_col] <= 3)
 465                xd->mode_info_context->mbmi.segment_id = cpi->segmentation_map[map_index+mb_col];
 466            else
 467                xd->mode_info_context->mbmi.segment_id = 0;
 468
 469            vp8cx_mb_init_quantizer(cpi, x);
 470        }
 471        else
 472            xd->mode_info_context->mbmi.segment_id = 0;         // Set to Segment 0 by default
 473
 474        x->active_ptr = cpi->active_map + map_index + mb_col;
 475
 476        if (cm->frame_type == KEY_FRAME)
 477        {
 478            *totalrate += vp8cx_encode_intra_macro_block(cpi, x, tp);
 479#ifdef MODE_STATS
 480            y_modes[xd->mbmi.mode] ++;
 481#endif
 482        }
 483        else
 484        {
 485            *totalrate += vp8cx_encode_inter_macroblock(cpi, x, tp, recon_yoffset, recon_uvoffset);
 486
 487#ifdef MODE_STATS
 488            inter_y_modes[xd->mbmi.mode] ++;
 489
 490            if (xd->mbmi.mode == SPLITMV)
 491            {
 492                int b;
 493
 494                for (b = 0; b < xd->mbmi.partition_count; b++)
 495                {
 496                    inter_b_modes[x->partition->bmi[b].mode] ++;
 497                }
 498            }
 499
 500#endif
 501
 502            // Count of last ref frame 0,0 useage
 503            if ((xd->mode_info_context->mbmi.mode == ZEROMV) && (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME))
 504                cpi->inter_zz_count ++;
 505
 506            // Special case code for cyclic refresh
 507            // If cyclic update enabled then copy xd->mbmi.segment_id; (which may have been updated based on mode
 508            // during vp8cx_encode_inter_macroblock()) back into the global sgmentation map
 509            if (cpi->cyclic_refresh_mode_enabled && xd->segmentation_enabled)
 510            {
 511                cpi->segmentation_map[map_index+mb_col] = xd->mode_info_context->mbmi.segment_id;
 512
 513                // If the block has been refreshed mark it as clean (the magnitude of the -ve influences how long it will be before we consider another refresh):
 514                // Else if it was coded (last frame 0,0) and has not already been refreshed then mark it as a candidate for cleanup next time (marked 0)
 515                // else mark it as dirty (1).
 516                if (xd->mode_info_context->mbmi.segment_id)
 517                    cpi->cyclic_refresh_map[map_index+mb_col] = -1;
 518                else if ((xd->mode_info_context->mbmi.mode == ZEROMV) && (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME))
 519                {
 520                    if (cpi->cyclic_refresh_map[map_index+mb_col] == 1)
 521                        cpi->cyclic_refresh_map[map_index+mb_col] = 0;
 522                }
 523                else
 524                    cpi->cyclic_refresh_map[map_index+mb_col] = 1;
 525
 526            }
 527        }
 528
 529        cpi->tplist[mb_row].stop = *tp;
 530
 531        // Increment pointer into gf useage flags structure.
 532        x->gf_active_ptr++;
 533
 534        // Increment the activity mask pointers.
 535        x->mb_activity_ptr++;
 536
 537        /* save the block info */
 538        for (i = 0; i < 16; i++)
 539            xd->mode_info_context->bmi[i] = xd->block[i].bmi;
 540
 541        // adjust to the next column of macroblocks
 542        x->src.y_buffer += 16;
 543        x->src.u_buffer += 8;
 544        x->src.v_buffer += 8;
 545
 546        recon_yoffset += 16;
 547        recon_uvoffset += 8;
 548
 549        // Keep track of segment useage
 550        segment_counts[xd->mode_info_context->mbmi.segment_id] ++;
 551
 552        // skip to next mb
 553        xd->mode_info_context++;
 554        x->partition_info++;
 555
 556        xd->above_context++;
 557#if CONFIG_MULTITHREAD
 558        if (cpi->b_multi_threaded != 0)
 559        {
 560            cpi->mt_current_mb_col[mb_row] = mb_col;
 561        }
 562#endif
 563    }
 564
 565    //extend the recon for intra prediction
 566    vp8_extend_mb_row(
 567        &cm->yv12_fb[dst_fb_idx],
 568        xd->dst.y_buffer + 16,
 569        xd->dst.u_buffer + 8,
 570        xd->dst.v_buffer + 8);
 571
 572    // this is to account for the border
 573    xd->mode_info_context++;
 574    x->partition_info++;
 575
 576#if CONFIG_MULTITHREAD
 577    if ((cpi->b_multi_threaded != 0) && (mb_row == cm->mb_rows - 1))
 578    {
 579        sem_post(&cpi->h_event_end_encoding); /* signal frame encoding end */
 580    }
 581#endif
 582}
 583
 584void init_encode_frame_mb_context(VP8_COMP *cpi)
 585{
 586    MACROBLOCK *const x = & cpi->mb;
 587    VP8_COMMON *const cm = & cpi->common;
 588    MACROBLOCKD *const xd = & x->e_mbd;
 589
 590    // GF active flags data structure
 591    x->gf_active_ptr = (signed char *)cpi->gf_active_flags;
 592
 593    // Activity map pointer
 594    x->mb_activity_ptr = cpi->mb_activity_map;
 595
 596    x->vector_range = 32;
 597
 598    x->act_zbin_adj = 0;
 599
 600    x->partition_info = x->pi;
 601
 602    xd->mode_info_context = cm->mi;
 603    xd->mode_info_stride = cm->mode_info_stride;
 604
 605    xd->frame_type = cm->frame_type;
 606
 607    xd->frames_since_golden = cm->frames_since_golden;
 608    xd->frames_till_alt_ref_frame = cm->frames_till_alt_ref_frame;
 609
 610    // reset intra mode contexts
 611    if (cm->frame_type == KEY_FRAME)
 612        vp8_init_mbmode_probs(cm);
 613
 614    // Copy data over into macro block data sturctures.
 615    x->src = * cpi->Source;
 616    xd->pre = cm->yv12_fb[cm->lst_fb_idx];
 617    xd->dst = cm->yv12_fb[cm->new_fb_idx];
 618
 619    // set up frame for intra coded blocks
 620    vp8_setup_intra_recon(&cm->yv12_fb[cm->new_fb_idx]);
 621
 622    vp8_build_block_offsets(x);
 623
 624    vp8_setup_block_dptrs(&x->e_mbd);
 625
 626    vp8_setup_block_ptrs(x);
 627
 628    xd->mode_info_context->mbmi.mode = DC_PRED;
 629    xd->mode_info_context->mbmi.uv_mode = DC_PRED;
 630
 631    xd->left_context = &cm->left_context;
 632
 633    vp8_zero(cpi->count_mb_ref_frame_usage)
 634    vp8_zero(cpi->ymode_count)
 635    vp8_zero(cpi->uv_mode_count)
 636
 637    x->mvc = cm->fc.mvc;
 638
 639    vpx_memset(cm->above_context, 0,
 640               sizeof(ENTROPY_CONTEXT_PLANES) * cm->mb_cols);
 641
 642    xd->ref_frame_cost[INTRA_FRAME]   = vp8_cost_zero(cpi->prob_intra_coded);
 643
 644    // Special case treatment when GF and ARF are not sensible options for reference
 645    if (cpi->ref_frame_flags == VP8_LAST_FLAG)
 646    {
 647        xd->ref_frame_cost[LAST_FRAME]    = vp8_cost_one(cpi->prob_intra_coded)
 648                                        + vp8_cost_zero(255);
 649        xd->ref_frame_cost[GOLDEN_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
 650                                        + vp8_cost_one(255)
 651                                        + vp8_cost_zero(128);
 652        xd->ref_frame_cost[ALTREF_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
 653                                        + vp8_cost_one(255)
 654                                        + vp8_cost_one(128);
 655    }
 656    else
 657    {
 658        xd->ref_frame_cost[LAST_FRAME]    = vp8_cost_one(cpi->prob_intra_coded)
 659                                        + vp8_cost_zero(cpi->prob_last_coded);
 660        xd->ref_frame_cost[GOLDEN_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
 661                                        + vp8_cost_one(cpi->prob_last_coded)
 662                                        + vp8_cost_zero(cpi->prob_gf_coded);
 663        xd->ref_frame_cost[ALTREF_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
 664                                        + vp8_cost_one(cpi->prob_last_coded)
 665                                        + vp8_cost_one(cpi->prob_gf_coded);
 666    }
 667
 668}
 669
 670void vp8_encode_frame(VP8_COMP *cpi)
 671{
 672    int mb_row;
 673    MACROBLOCK *const x = & cpi->mb;
 674    VP8_COMMON *const cm = & cpi->common;
 675    MACROBLOCKD *const xd = & x->e_mbd;
 676
 677    TOKENEXTRA *tp = cpi->tok;
 678    int segment_counts[MAX_MB_SEGMENTS];
 679    int totalrate;
 680
 681    vpx_memset(segment_counts, 0, sizeof(segment_counts));
 682    totalrate = 0;
 683
 684    if (cpi->compressor_speed == 2)
 685    {
 686        if (cpi->oxcf.cpu_used < 0)
 687            cpi->Speed = -(cpi->oxcf.cpu_used);
 688        else
 689            vp8_auto_select_speed(cpi);
 690    }
 691
 692    // Functions setup for all frame types so we can use MC in AltRef
 693    if (cm->mcomp_filter_type == SIXTAP)
 694    {
 695        xd->subpixel_predict        = SUBPIX_INVOKE(
 696                                        &cpi->common.rtcd.subpix, sixtap4x4);
 697        xd->subpixel_predict8x4     = SUBPIX_INVOKE(
 698                                        &cpi->common.rtcd.subpix, sixtap8x4);
 699        xd->subpixel_predict8x8     = SUBPIX_INVOKE(
 700                                        &cpi->common.rtcd.subpix, sixtap8x8);
 701        xd->subpixel_predict16x16   = SUBPIX_INVOKE(
 702                                        &cpi->common.rtcd.subpix, sixtap16x16);
 703    }
 704    else
 705    {
 706        xd->subpixel_predict        = SUBPIX_INVOKE(
 707                                        &cpi->common.rtcd.subpix, bilinear4x4);
 708        xd->subpixel_predict8x4     = SUBPIX_INVOKE(
 709                                        &cpi->common.rtcd.subpix, bilinear8x4);
 710        xd->subpixel_predict8x8     = SUBPIX_INVOKE(
 711                                        &cpi->common.rtcd.subpix, bilinear8x8);
 712        xd->subpixel_predict16x16   = SUBPIX_INVOKE(
 713                                      &cpi->common.rtcd.subpix, bilinear16x16);
 714    }
 715
 716    // Reset frame count of inter 0,0 motion vector useage.
 717    cpi->inter_zz_count = 0;
 718
 719    vpx_memset(segment_counts, 0, sizeof(segment_counts));
 720
 721    cpi->prediction_error = 0;
 722    cpi->intra_error = 0;
 723    cpi->skip_true_count = 0;
 724    cpi->skip_false_count = 0;
 725
 726#if 0
 727    // Experimental code
 728    cpi->frame_distortion = 0;
 729    cpi->last_mb_distortion = 0;
 730#endif
 731
 732    xd->mode_info_context = cm->mi;
 733
 734    vp8_zero(cpi->MVcount);
 735    vp8_zero(cpi->coef_counts);
 736
 737    vp8cx_frame_init_quantizer(cpi);
 738
 739    vp8_initialize_rd_consts(cpi,
 740                             vp8_dc_quant(cm->base_qindex, cm->y1dc_delta_q));
 741
 742    vp8cx_initialize_me_consts(cpi, cm->base_qindex);
 743
 744    if(cpi->oxcf.tuning == VP8_TUNE_SSIM)
 745    {
 746        // Initialize encode frame context.
 747        init_encode_frame_mb_context(cpi);
 748
 749        // Build a frame level activity map
 750        build_activity_map(cpi);
 751    }
 752
 753    // re-initencode frame context.
 754    init_encode_frame_mb_context(cpi);
 755
 756    {
 757        struct vpx_usec_timer  emr_timer;
 758        vpx_usec_timer_start(&emr_timer);
 759
 760#if CONFIG_MULTITHREAD
 761        if (cpi->b_multi_threaded)
 762        {
 763            int i;
 764
 765            vp8cx_init_mbrthread_data(cpi, x, cpi->mb_row_ei, 1,  cpi->encoding_thread_count);
 766
 767            for (i = 0; i < cm->mb_rows; i++)
 768                cpi->mt_current_mb_col[i] = -1;
 769
 770            for (i = 0; i < cpi->encoding_thread_count; i++)
 771            {
 772                sem_post(&cpi->h_event_start_encoding[i]);
 773            }
 774
 775            for (mb_row = 0; mb_row < cm->mb_rows; mb_row += (cpi->encoding_thread_count + 1))
 776            {
 777                vp8_zero(cm->left_context)
 778
 779                tp = cpi->tok + mb_row * (cm->mb_cols * 16 * 24);
 780
 781                encode_mb_row(cpi, cm, mb_row, x, xd, &tp, segment_counts, &totalrate);
 782
 783                // adjust to the next row of mbs
 784                x->src.y_buffer += 16 * x->src.y_stride * (cpi->encoding_thread_count + 1) - 16 * cm->mb_cols;
 785                x->src.u_buffer +=  8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) - 8 * cm->mb_cols;
 786                x->src.v_buffer +=  8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) - 8 * cm->mb_cols;
 787
 788                xd->mode_info_context += xd->mode_info_stride * cpi->encoding_thread_count;
 789                x->partition_info  += xd->mode_info_stride * cpi->encoding_thread_count;
 790                x->gf_active_ptr   += cm->mb_cols * cpi->encoding_thread_count;
 791
 792            }
 793
 794            sem_wait(&cpi->h_event_end_encoding); /* wait for other threads to finish */
 795
 796            cpi->tok_count = 0;
 797
 798            for (mb_row = 0; mb_row < cm->mb_rows; mb_row ++)
 799            {
 800                cpi->tok_count += cpi->tplist[mb_row].stop - cpi->tplist[mb_row].start;
 801            }
 802
 803            if (xd->segmentation_enabled)
 804            {
 805                int i, j;
 806
 807                if (xd->segmentation_enabled)
 808                {
 809
 810                    for (i = 0; i < cpi->encoding_thread_count; i++)
 811                    {
 812                        for (j = 0; j < 4; j++)
 813                            segment_counts[j] += cpi->mb_row_ei[i].segment_counts[j];
 814                    }
 815                }
 816            }
 817
 818            for (i = 0; i < cpi->encoding_thread_count; i++)
 819            {
 820                totalrate += cpi->mb_row_ei[i].totalrate;
 821            }
 822
 823        }
 824        else
 825#endif
 826        {
 827            // for each macroblock row in image
 828            for (mb_row = 0; mb_row < cm->mb_rows; mb_row++)
 829            {
 830
 831                vp8_zero(cm->left_context)
 832
 833                encode_mb_row(cpi, cm, mb_row, x, xd, &tp, segment_counts, &totalrate);
 834
 835                // adjust to the next row of mbs
 836                x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
 837                x->src.u_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
 838                x->src.v_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
 839            }
 840
 841            cpi->tok_count = tp - cpi->tok;
 842
 843        }
 844
 845        vpx_usec_timer_mark(&emr_timer);
 846        cpi->time_encode_mb_row += vpx_usec_timer_elapsed(&emr_timer);
 847
 848    }
 849
 850
 851    // Work out the segment probabilites if segmentation is enabled
 852    if (xd->segmentation_enabled)
 853    {
 854        int tot_count;
 855        int i;
 856
 857        // Set to defaults
 858        vpx_memset(xd->mb_segment_tree_probs, 255 , sizeof(xd->mb_segment_tree_probs));
 859
 860        tot_count = segment_counts[0] + segment_counts[1] + segment_counts[2] + segment_counts[3];
 861
 862        if (tot_count)
 863        {
 864            xd->mb_segment_tree_probs[0] = ((segment_counts[0] + segment_counts[1]) * 255) / tot_count;
 865
 866            tot_count = segment_counts[0] + segment_counts[1];
 867
 868            if (tot_count > 0)
 869            {
 870                xd->mb_segment_tree_probs[1] = (segment_counts[0] * 255) / tot_count;
 871            }
 872
 873            tot_count = segment_counts[2] + segment_counts[3];
 874
 875            if (tot_count > 0)
 876                xd->mb_segment_tree_probs[2] = (segment_counts[2] * 255) / tot_count;
 877
 878            // Zero probabilities not allowed
 879            for (i = 0; i < MB_FEATURE_TREE_PROBS; i ++)
 880            {
 881                if (xd->mb_segment_tree_probs[i] == 0)
 882                    xd->mb_segment_tree_probs[i] = 1;
 883            }
 884        }
 885    }
 886
 887    // 256 rate units to the bit
 888    cpi->projected_frame_size = totalrate >> 8;   // projected_frame_size in units of BYTES
 889
 890    // Make a note of the percentage MBs coded Intra.
 891    if (cm->frame_type == KEY_FRAME)
 892    {
 893        cpi->this_frame_percent_intra = 100;
 894    }
 895    else
 896    {
 897        int tot_modes;
 898
 899        tot_modes = cpi->count_mb_ref_frame_usage[INTRA_FRAME]
 900                    + cpi->count_mb_ref_frame_usage[LAST_FRAME]
 901                    + cpi->count_mb_ref_frame_usage[GOLDEN_FRAME]
 902                    + cpi->count_mb_ref_frame_usage[ALTREF_FRAME];
 903
 904        if (tot_modes)
 905            cpi->this_frame_percent_intra = cpi->count_mb_ref_frame_usage[INTRA_FRAME] * 100 / tot_modes;
 906
 907    }
 908
 909#if 0
 910    {
 911        int cnt = 0;
 912        int flag[2] = {0, 0};
 913
 914        for (cnt = 0; cnt < MVPcount; cnt++)
 915        {
 916            if (cm->fc.pre_mvc[0][cnt] != cm->fc.mvc[0][cnt])
 917            {
 918                flag[0] = 1;
 919                vpx_memcpy(cm->fc.pre_mvc[0], cm->fc.mvc[0], MVPcount);
 920                break;
 921            }
 922        }
 923
 924        for (cnt = 0; cnt < MVPcount; cnt++)
 925        {
 926            if (cm->fc.pre_mvc[1][cnt] != cm->fc.mvc[1][cnt])
 927            {
 928                flag[1] = 1;
 929                vpx_memcpy(cm->fc.pre_mvc[1], cm->fc.mvc[1], MVPcount);
 930                break;
 931            }
 932        }
 933
 934        if (flag[0] || flag[1])
 935            vp8_build_component_cost_table(cpi->mb.mvcost, (const MV_CONTEXT *) cm->fc.mvc, flag);
 936    }
 937#endif
 938
 939    // Adjust the projected reference frame useage probability numbers to reflect
 940    // what we have just seen. This may be usefull when we make multiple itterations
 941    // of the recode loop rather than continuing to use values from the previous frame.
 942    if ((cm->frame_type != KEY_FRAME) && !cm->refresh_alt_ref_frame && !cm->refresh_golden_frame)
 943    {
 944        const int *const rfct = cpi->count_mb_ref_frame_usage;
 945        const int rf_intra = rfct[INTRA_FRAME];
 946        const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
 947
 948        if ((rf_intra + rf_inter) > 0)
 949        {
 950            cpi->prob_intra_coded = (rf_intra * 255) / (rf_intra + rf_inter);
 951
 952            if (cpi->prob_intra_coded < 1)
 953                cpi->prob_intra_coded = 1;
 954
 955            if ((cm->frames_since_golden > 0) || cpi->source_alt_ref_active)
 956            {
 957                cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
 958
 959                if (cpi->prob_last_coded < 1)
 960                    cpi->prob_last_coded = 1;
 961
 962                cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
 963                                     ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
 964
 965                if (cpi->prob_gf_coded < 1)
 966                    cpi->prob_gf_coded = 1;
 967            }
 968        }
 969    }
 970
 971#if 0
 972    // Keep record of the total distortion this time around for future use
 973    cpi->last_frame_distortion = cpi->frame_distortion;
 974#endif
 975
 976}
 977void vp8_setup_block_ptrs(MACROBLOCK *x)
 978{
 979    int r, c;
 980    int i;
 981
 982    for (r = 0; r < 4; r++)
 983    {
 984        for (c = 0; c < 4; c++)
 985        {
 986            x->block[r*4+c].src_diff = x->src_diff + r * 4 * 16 + c * 4;
 987        }
 988    }
 989
 990    for (r = 0; r < 2; r++)
 991    {
 992        for (c = 0; c < 2; c++)
 993        {
 994            x->block[16 + r*2+c].src_diff = x->src_diff + 256 + r * 4 * 8 + c * 4;
 995        }
 996    }
 997
 998
 999    for (r = 0; r < 2; r++)
1000    {
1001        for (c = 0; c < 2; c++)
1002        {
1003            x->block[20 + r*2+c].src_diff = x->src_diff + 320 + r * 4 * 8 + c * 4;
1004        }
1005    }
1006
1007    x->block[24].src_diff = x->src_diff + 384;
1008
1009
1010    for (i = 0; i < 25; i++)
1011    {
1012        x->block[i].coeff = x->coeff + i * 16;
1013    }
1014}
1015
1016void vp8_build_block_offsets(MACROBLOCK *x)
1017{
1018    int block = 0;
1019    int br, bc;
1020
1021    vp8_build_block_doffsets(&x->e_mbd);
1022
1023    // y blocks
1024    x->thismb_ptr = &x->thismb[0];
1025    for (br = 0; br < 4; br++)
1026    {
1027        for (bc = 0; bc < 4; bc++)
1028        {
1029            BLOCK *this_block = &x->block[block];
1030            //this_block->base_src = &x->src.y_buffer;
1031            //this_block->src_stride = x->src.y_stride;
1032            //this_block->src = 4 * br * this_block->src_stride + 4 * bc;
1033            this_block->base_src = &x->thismb_ptr;
1034            this_block->src_stride = 16;
1035            this_block->src = 4 * br * 16 + 4 * bc;
1036            ++block;
1037        }
1038    }
1039
1040    // u blocks
1041    for (br = 0; br < 2; br++)
1042    {
1043        for (bc = 0; bc < 2; bc++)
1044        {
1045            BLOCK *this_block = &x->block[block];
1046            this_block->base_src = &x->src.u_buffer;
1047            this_block->src_stride = x->src.uv_stride;
1048            this_block->src = 4 * br * this_block->src_stride + 4 * bc;
1049            ++block;
1050        }
1051    }
1052
1053    // v blocks
1054    for (br = 0; br < 2; br++)
1055    {
1056        for (bc = 0; bc < 2; bc++)
1057        {
1058            BLOCK *this_block = &x->block[block];
1059            this_block->base_src = &x->src.v_buffer;
1060            this_block->src_stride = x->src.uv_stride;
1061            this_block->src = 4 * br * this_block->src_stride + 4 * bc;
1062            ++block;
1063        }
1064    }
1065}
1066
1067static void sum_intra_stats(VP8_COMP *cpi, MACROBLOCK *x)
1068{
1069    const MACROBLOCKD *xd = & x->e_mbd;
1070    const MB_PREDICTION_MODE m = xd->mode_info_context->mbmi.mode;
1071    const MB_PREDICTION_MODE uvm = xd->mode_info_context->mbmi.uv_mode;
1072
1073#ifdef MODE_STATS
1074    const int is_key = cpi->common.frame_type == KEY_FRAME;
1075
1076    ++ (is_key ? uv_modes : inter_uv_modes)[uvm];
1077
1078    if (m == B_PRED)
1079    {
1080        unsigned int *const bct = is_key ? b_modes : inter_b_modes;
1081
1082        int b = 0;
1083
1084        do
1085        {
1086            ++ bct[xd->block[b].bmi.mode];
1087        }
1088        while (++b < 16);
1089    }
1090
1091#endif
1092
1093    ++cpi->ymode_count[m];
1094    ++cpi->uv_mode_count[uvm];
1095
1096}
1097
1098// Experimental stub function to create a per MB zbin adjustment based on
1099// some previously calculated measure of MB activity.
1100static void adjust_act_zbin( VP8_COMP *cpi, MACROBLOCK *x )
1101{
1102#if USE_ACT_INDEX
1103    x->act_zbin_adj = *(x->mb_activity_ptr);
1104#else
1105    int64_t a;
1106    int64_t b;
1107    int64_t act = *(x->mb_activity_ptr);
1108
1109    // Apply the masking to the RD multiplier.
1110    a = act + 4*cpi->activity_avg;
1111    b = 4*act + cpi->activity_avg;
1112
1113    if ( act > cpi->activity_avg )
1114        x->act_zbin_adj = (int)(((int64_t)b + (a>>1))/a) - 1;
1115    else
1116        x->act_zbin_adj = 1 - (int)(((int64_t)a + (b>>1))/b);
1117#endif
1118}
1119
1120int vp8cx_encode_intra_macro_block(VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t)
1121{
1122    int rate;
1123
1124    if (cpi->sf.RD && cpi->compressor_speed != 2)
1125        vp8_rd_pick_intra_mode(cpi, x, &rate);
1126    else
1127        vp8_pick_intra_mode(cpi, x, &rate);
1128
1129    if(cpi->oxcf.tuning == VP8_TUNE_SSIM)
1130    {
1131        adjust_act_zbin( cpi, x );
1132        vp8_update_zbin_extra(cpi, x);
1133    }
1134
1135    if (x->e_mbd.mode_info_context->mbmi.mode == B_PRED)
1136        vp8_encode_intra4x4mby(IF_RTCD(&cpi->rtcd), x);
1137    else
1138        vp8_encode_intra16x16mby(IF_RTCD(&cpi->rtcd), x);
1139
1140    vp8_encode_intra16x16mbuv(IF_RTCD(&cpi->rtcd), x);
1141    sum_intra_stats(cpi, x);
1142    vp8_tokenize_mb(cpi, &x->e_mbd, t);
1143
1144    return rate;
1145}
1146#ifdef SPEEDSTATS
1147extern int cnt_pm;
1148#endif
1149
1150extern void vp8_fix_contexts(MACROBLOCKD *x);
1151
1152int vp8cx_encode_inter_macroblock
1153(
1154    VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t,
1155    int recon_yoffset, int recon_uvoffset
1156)
1157{
1158    MACROBLOCKD *const xd = &x->e_mbd;
1159    int intra_error = 0;
1160    int rate;
1161    int distortion;
1162
1163    x->skip = 0;
1164
1165    if (xd->segmentation_enabled)
1166        x->encode_breakout = cpi->segment_encode_breakout[xd->mode_info_context->mbmi.segment_id];
1167    else
1168        x->encode_breakout = cpi->oxcf.encode_breakout;
1169
1170    if (cpi->sf.RD)
1171    {
1172        int zbin_mode_boost_enabled = cpi->zbin_mode_boost_enabled;
1173
1174        /* Are we using the fast quantizer for the mode selection? */
1175        if(cpi->sf.use_fastquant_for_pick)
1176        {
1177            cpi->mb.quantize_b      = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1178                                                      fastquantb);
1179            cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1180                                                      fastquantb_pair);
1181
1182            /* the fast quantizer does not use zbin_extra, so
1183             * do not recalculate */
1184            cpi->zbin_mode_boost_enabled = 0;
1185        }
1186        vp8_rd_pick_inter_mode(cpi, x, recon_yoffset, recon_uvoffset, &rate,
1187                               &distortion, &intra_error);
1188
1189        /* switch back to the regular quantizer for the encode */
1190        if (cpi->sf.improved_quant)
1191        {
1192            cpi->mb.quantize_b      = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1193                                                      quantb);
1194            cpi->mb.quantize_b_pair = QUANTIZE_INVOKE(&cpi->rtcd.quantize,
1195                                                      quantb_pair);
1196        }
1197
1198        /* restore cpi->zbin_mode_boost_enabled */
1199        cpi->zbin_mode_boost_enabled = zbin_mode_boost_enabled;
1200
1201    }
1202    else
1203        vp8_pick_inter_mode(cpi, x, recon_yoffset, recon_uvoffset, &rate,
1204                            &distortion, &intra_error);
1205
1206    cpi->prediction_error += distortion;
1207    cpi->intra_error += intra_error;
1208
1209    if(cpi->oxcf.tuning == VP8_TUNE_SSIM)
1210    {
1211        // Adjust the zbin based on this MB rate.
1212        adjust_act_zbin( cpi, x );
1213    }
1214
1215#if 0
1216    // Experimental RD code
1217    cpi->frame_distortion += distortion;
1218    cpi->last_mb_distortion = distortion;
1219#endif
1220
1221    // MB level adjutment to quantizer setup
1222    if (xd->segmentation_enabled)
1223    {
1224        // If cyclic update enabled
1225        if (cpi->cyclic_refresh_mode_enabled)
1226        {
1227            // Clear segment_id back to 0 if not coded (last frame 0,0)
1228            if ((xd->mode_info_context->mbmi.segment_id == 1) &&
1229                ((xd->mode_info_context->mbmi.ref_frame != LAST_FRAME) || (xd->mode_info_context->mbmi.mode != ZEROMV)))
1230            {
1231                xd->mode_info_context->mbmi.segment_id = 0;
1232
1233                /* segment_id changed, so update */
1234                vp8cx_mb_init_quantizer(cpi, x);
1235            }
1236        }
1237    }
1238
1239    {
1240        // Experimental code. Special case for gf and arf zeromv modes.
1241        // Increase zbin size to supress noise
1242        cpi->zbin_mode_boost = 0;
1243        if (cpi->zbin_mode_boost_enabled)
1244        {
1245            if ( xd->mode_info_context->mbmi.ref_frame != INTRA_FRAME )
1246            {
1247                if (xd->mode_info_context->mbmi.mode == ZEROMV)
1248                {
1249                    if (xd->mode_info_context->mbmi.ref_frame != LAST_FRAME)
1250                        cpi->zbin_mode_boost = GF_ZEROMV_ZBIN_BOOST;
1251                    else
1252                        cpi->zbin_mode_boost = LF_ZEROMV_ZBIN_BOOST;
1253                }
1254                else if (xd->mode_info_context->mbmi.mode == SPLITMV)
1255                    cpi->zbin_mode_boost = 0;
1256                else
1257                    cpi->zbin_mode_boost = MV_ZBIN_BOOST;
1258            }
1259        }
1260        vp8_update_zbin_extra(cpi, x);
1261    }
1262
1263    cpi->count_mb_ref_frame_usage[xd->mode_info_context->mbmi.ref_frame] ++;
1264
1265    if (xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME)
1266    {
1267        vp8_encode_intra16x16mbuv(IF_RTCD(&cpi->rtcd), x);
1268
1269        if (xd->mode_info_context->mbmi.mode == B_PRED)
1270        {
1271            vp8_encode_intra4x4mby(IF_RTCD(&cpi->rtcd), x);
1272        }
1273        else
1274        {
1275            vp8_encode_intra16x16mby(IF_RTCD(&cpi->rtcd), x);
1276        }
1277
1278        sum_intra_stats(cpi, x);
1279    }
1280    else
1281    {
1282        int ref_fb_idx;
1283
1284        vp8_build_uvmvs(xd, cpi->common.full_pixel);
1285
1286        if (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME)
1287            ref_fb_idx = cpi->common.lst_fb_idx;
1288        else if (xd->mode_info_context->mbmi.ref_frame == GOLDEN_FRAME)
1289            ref_fb_idx = cpi->common.gld_fb_idx;
1290        else
1291            ref_fb_idx = cpi->common.alt_fb_idx;
1292
1293        xd->pre.y_buffer = cpi->common.yv12_fb[ref_fb_idx].y_buffer + recon_yoffset;
1294        xd->pre.u_buffer = cpi->common.yv12_fb[ref_fb_idx].u_buffer + recon_uvoffset;
1295        xd->pre.v_buffer = cpi->common.yv12_fb[ref_fb_idx].v_buffer + recon_uvoffset;
1296
1297        if (!x->skip)
1298        {
1299            vp8_encode_inter16x16(IF_RTCD(&cpi->rtcd), x);
1300
1301            // Clear mb_skip_coeff if mb_no_coeff_skip is not set
1302            if (!cpi->common.mb_no_coeff_skip)
1303                xd->mode_info_context->mbmi.mb_skip_coeff = 0;
1304
1305        }
1306        else
1307            vp8_build_inter16x16_predictors_mb(xd, xd->dst.y_buffer,
1308                                           xd->dst.u_buffer, xd->dst.v_buffer,
1309                                           xd->dst.y_stride, xd->dst.uv_stride);
1310
1311    }
1312
1313    if (!x->skip)
1314        vp8_tokenize_mb(cpi, xd, t);
1315    else
1316    {
1317        if (cpi->common.mb_no_coeff_skip)
1318        {
1319            xd->mode_info_context->mbmi.mb_skip_coeff = 1;
1320            cpi->skip_true_count ++;
1321            vp8_fix_contexts(xd);
1322        }
1323        else
1324        {
1325            vp8_stuff_mb(cpi, xd, t);
1326            xd->mode_info_context->mbmi.mb_skip_coeff = 0;
1327            cpi->skip_false_count ++;
1328        }
1329    }
1330
1331    return rate;
1332}