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