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