Initial WebM release
[platform/upstream/libvpx.git] / vp8 / encoder / rdopt.c
1 /*
2  *  Copyright (c) 2010 The VP8 project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license and patent
5  *  grant that can be found in the LICENSE file in the root of the source
6  *  tree. All contributing project authors may be found in the AUTHORS
7  *  file in the root of the source tree.
8  */
9
10
11 #include <stdio.h>
12 #include <math.h>
13 #include <limits.h>
14 #include <assert.h>
15 #include "pragmas.h"
16
17 #include "tokenize.h"
18 #include "treewriter.h"
19 #include "onyx_int.h"
20 #include "modecosts.h"
21 #include "encodeintra.h"
22 #include "entropymode.h"
23 #include "reconinter.h"
24 #include "reconintra.h"
25 #include "reconintra4x4.h"
26 #include "findnearmv.h"
27 #include "encodemb.h"
28 #include "quantize.h"
29 #include "idct.h"
30 #include "g_common.h"
31 #include "variance.h"
32 #include "mcomp.h"
33
34 #include "vpx_mem/vpx_mem.h"
35 #include "dct.h"
36 #include "systemdependent.h"
37
38 #define DIAMONDSEARCH 1
39 #if CONFIG_RUNTIME_CPU_DETECT
40 #define IF_RTCD(x)  (x)
41 #else
42 #define IF_RTCD(x)  NULL
43 #endif
44
45
46 void vp8cx_mb_init_quantizer(VP8_COMP *cpi, MACROBLOCK *x);
47
48
49 #define RDFUNC(RM,DM,R,D,target_rd) ( ((128+(R)*(RM)) >> 8) + (DM)*(D) )
50 /*int  RDFUNC( int RM,int DM, int R, int D, int target_r )
51 {
52     int rd_value;
53
54     rd_value =  ( ((128+(R)*(RM)) >> 8) + (DM)*(D) );
55
56     return rd_value;
57 }*/
58
59 #define UVRDFUNC(RM,DM,R,D,target_r)  RDFUNC(RM,DM,R,D,target_r)
60
61 #define RDCOST(RM,DM,R,D) ( ((128+(R)*(RM)) >> 8) + (DM)*(D) )
62
63 #define MAXF(a,b)            (((a) > (b)) ? (a) : (b))
64
65
66 extern const TOKENEXTRA vp8_dct_value_tokens[DCT_MAX_VALUE*2];
67 extern const TOKENEXTRA *vp8_dct_value_tokens_ptr;
68 extern int vp8_dct_value_cost[DCT_MAX_VALUE*2];
69 extern int *vp8_dct_value_cost_ptr;
70
71
72 const int vp8_auto_speed_thresh[17] =
73 {
74     1000,
75     200,
76     150,
77     130,
78     150,
79     125,
80     120,
81     115,
82     115,
83     115,
84     115,
85     115,
86     115,
87     115,
88     115,
89     115,
90     105
91 };
92
93 const MB_PREDICTION_MODE vp8_mode_order[MAX_MODES] =
94 {
95     ZEROMV,
96     DC_PRED,
97
98     NEARESTMV,
99     NEARMV,
100
101     ZEROMV,
102     NEARESTMV,
103
104     ZEROMV,
105     NEARESTMV,
106
107     NEARMV,
108     NEARMV,
109
110     V_PRED,
111     H_PRED,
112     TM_PRED,
113
114     NEWMV,
115     NEWMV,
116     NEWMV,
117
118     SPLITMV,
119     SPLITMV,
120     SPLITMV,
121
122     B_PRED,
123 };
124
125 const MV_REFERENCE_FRAME vp8_ref_frame_order[MAX_MODES] =
126 {
127     LAST_FRAME,
128     INTRA_FRAME,
129
130     LAST_FRAME,
131     LAST_FRAME,
132
133     GOLDEN_FRAME,
134     GOLDEN_FRAME,
135
136     ALTREF_FRAME,
137     ALTREF_FRAME,
138
139     GOLDEN_FRAME,
140     ALTREF_FRAME,
141
142     INTRA_FRAME,
143     INTRA_FRAME,
144     INTRA_FRAME,
145
146     LAST_FRAME,
147     GOLDEN_FRAME,
148     ALTREF_FRAME,
149
150     LAST_FRAME,
151     GOLDEN_FRAME,
152     ALTREF_FRAME,
153
154     INTRA_FRAME,
155 };
156
157 static void fill_token_costs(
158     unsigned int c      [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens],
159     const vp8_prob p    [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens-1]
160 )
161 {
162     int i, j, k;
163
164
165     for (i = 0; i < BLOCK_TYPES; i++)
166         for (j = 0; j < COEF_BANDS; j++)
167             for (k = 0; k < PREV_COEF_CONTEXTS; k++)
168
169                 vp8_cost_tokens((int *)(c [i][j][k]), p [i][j][k], vp8_coef_tree);
170
171 }
172
173 static int rd_iifactor [ 32 ] =  {    16,  16,  16,  12,   8,   4,   2,   0,
174                                       0,   0,   0,   0,   0,   0,   0,   0,
175                                       0,   0,   0,   0,   0,   0,   0,   0,
176                                       0,   0,   0,   0,   0,   0,   0,   0,
177                                  };
178
179
180
181
182 // The values in this table should be reviewed
183 static int sad_per_bit16lut[128] =
184 {
185     4,  4, 4, 4,  4, 4, 4, 4,   // 4
186     4,  4, 4, 4,  4, 4, 4, 4,   // 1
187     4,  4, 4, 4,  4, 4, 4, 4,   // 2
188     4,  4, 4, 4,  4, 4, 4, 4,   // 3
189     4,  4, 4, 4,  4, 4, 4, 4,   // 4
190     4,  4, 12, 12, 13, 13, 14, 14, // 5
191     14, 14, 14, 15, 15, 15, 15, 15, // 6
192     15, 15, 15, 15, 15, 15, 15, 15, // 7
193     15, 15, 15, 15, 15, 16, 16, 16, // 8
194     16, 16, 18, 18, 18, 18, 19, 19, // 9
195     19, 19, 19, 19, 19, 19, 19, 19, // 10
196     20, 20, 22, 22, 22, 22, 21, 21, // 11
197     22, 22, 22, 22, 22, 22, 22, 22, // 12
198     22, 22, 22, 22, 22, 22, 22, 22, // 13
199     22, 22, 22, 22, 22, 22, 22, 22, // 14
200     22, 22, 22, 22, 22, 22, 22, 22, // 15
201 };
202
203 static int sad_per_bit4lut[128] =
204 {
205     4,  4, 4, 4,  4, 4, 4, 4,   // 4
206     4,  4, 4, 4,  4, 4, 4, 4,   // 1
207     4,  4, 4, 4,  4, 4, 4, 4,   // 2
208     4,  4, 4, 4,  4, 4, 4, 4,   // 3
209     4,  4, 4, 4,  4, 4, 4, 4,   // 4
210     4,  4, 15, 15, 15, 15, 16, 16, // 5
211     16, 17, 17, 17, 17, 17, 17, 17, // 6
212     17, 17, 19, 19, 22, 22, 21, 21, // 7
213     23, 23, 23, 23, 23, 24, 24, 24, // 8
214     25, 25, 27, 27, 27, 27, 28, 28, // 9
215     28, 28, 29, 29, 29, 29, 29, 29, // 10
216     30, 30, 31, 31, 31, 31, 32, 32, // 11
217     34, 34, 34, 34, 34, 34, 34, 34, // 12
218     34, 34, 34, 34, 34, 34, 34, 34, // 13
219     34, 34, 34, 34, 34, 34, 34, 34, // 14
220     34, 34, 34, 34, 34, 34, 34, 34, // 15
221 };
222
223 void vp8cx_initialize_me_consts(VP8_COMP *cpi, int QIndex)
224 {
225     cpi->mb.sadperbit16 =  sad_per_bit16lut[QIndex];
226     cpi->mb.sadperbit4  =  sad_per_bit4lut[QIndex];
227 }
228
229 void vp8_initialize_rd_consts(VP8_COMP *cpi, int Qvalue)
230 {
231     int q;
232     int i;
233     int *thresh;
234     int threshmult;
235
236     int capped_q = (Qvalue < 160) ? Qvalue : 160;
237
238     vp8_clear_system_state();  //__asm emms;
239
240     cpi->RDMULT = (int)((0.00007 * (capped_q * capped_q * capped_q * capped_q)) - (0.0125 * (capped_q * capped_q * capped_q)) +
241                         (2.25 * (capped_q * capped_q)) - (12.5 * capped_q) + 25.0);
242
243     if (cpi->RDMULT < 25)
244         cpi->RDMULT = 25;
245
246     if (cpi->pass == 2)
247     {
248         if (cpi->common.frame_type == KEY_FRAME)
249             cpi->RDMULT += (cpi->RDMULT * rd_iifactor[0]) / 16;
250         else if (cpi->next_iiratio > 31)
251             cpi->RDMULT += (cpi->RDMULT * rd_iifactor[31]) / 16;
252         else
253             cpi->RDMULT += (cpi->RDMULT * rd_iifactor[cpi->next_iiratio]) / 16;
254     }
255
256
257     // Extend rate multiplier along side quantizer zbin increases
258     if (cpi->zbin_over_quant  > 0)
259     {
260         // Extend rate multiplier along side quantizer zbin increases
261         if (cpi->zbin_over_quant  > 0)
262         {
263             double oq_factor = pow(1.006,  cpi->zbin_over_quant);
264
265             if (oq_factor > (1.0 + ((double)cpi->zbin_over_quant / 64.0)))
266                 oq_factor = (1.0 + (double)cpi->zbin_over_quant / 64.0);
267
268             cpi->RDMULT *= (int)oq_factor;
269         }
270     }
271
272     cpi->mb.errorperbit = (cpi->RDMULT / 100);
273
274     if (cpi->mb.errorperbit < 1)
275         cpi->mb.errorperbit = 1;
276
277     vp8_set_speed_features(cpi);
278
279     if (cpi->common.simpler_lpf)
280         cpi->common.filter_type = SIMPLE_LOOPFILTER;
281
282     q = (int)pow(Qvalue, 1.25);
283
284     if (q < 8)
285         q = 8;
286
287     if (cpi->ref_frame_flags == VP8_ALT_FLAG)
288     {
289         thresh      = &cpi->rd_threshes[THR_NEWA];
290         threshmult  = cpi->sf.thresh_mult[THR_NEWA];
291     }
292     else if (cpi->ref_frame_flags == VP8_GOLD_FLAG)
293     {
294         thresh      = &cpi->rd_threshes[THR_NEWG];
295         threshmult  = cpi->sf.thresh_mult[THR_NEWG];
296     }
297     else
298     {
299         thresh      = &cpi->rd_threshes[THR_NEWMV];
300         threshmult  = cpi->sf.thresh_mult[THR_NEWMV];
301     }
302
303     if (cpi->RDMULT > 1000)
304     {
305         cpi->RDDIV = 1;
306         cpi->RDMULT /= 100;
307
308         for (i = 0; i < MAX_MODES; i++)
309         {
310             if (cpi->sf.thresh_mult[i] < INT_MAX)
311             {
312                 cpi->rd_threshes[i] = cpi->sf.thresh_mult[i] * q / 100;
313             }
314             else
315             {
316                 cpi->rd_threshes[i] = INT_MAX;
317             }
318
319             cpi->rd_baseline_thresh[i] = cpi->rd_threshes[i];
320         }
321     }
322     else
323     {
324         cpi->RDDIV = 100;
325
326         for (i = 0; i < MAX_MODES; i++)
327         {
328             if (cpi->sf.thresh_mult[i] < (INT_MAX / q))
329             {
330                 cpi->rd_threshes[i] = cpi->sf.thresh_mult[i] * q;
331             }
332             else
333             {
334                 cpi->rd_threshes[i] = INT_MAX;
335             }
336
337             cpi->rd_baseline_thresh[i] = cpi->rd_threshes[i];
338         }
339     }
340
341     fill_token_costs(
342         cpi->mb.token_costs,
343         (const vp8_prob( *)[8][3][11]) cpi->common.fc.coef_probs
344     );
345
346     vp8_init_mode_costs(cpi);
347
348 }
349
350 void vp8_auto_select_speed(VP8_COMP *cpi)
351 {
352     int used = cpi->oxcf.cpu_used;
353
354     int milliseconds_for_compress = (int)(1000000 / cpi->oxcf.frame_rate);
355
356     milliseconds_for_compress = milliseconds_for_compress * (16 - cpi->oxcf.cpu_used) / 16;
357
358 #if 0
359
360     if (0)
361     {
362         FILE *f;
363
364         f = fopen("speed.stt", "a");
365         fprintf(f, " %8ld %10ld %10ld %10ld\n",
366                 cpi->common.current_video_frame, cpi->Speed, milliseconds_for_compress, cpi->avg_pick_mode_time);
367         fclose(f);
368     }
369
370 #endif
371
372     /*
373     // this is done during parameter valid check
374     if( used > 16)
375         used = 16;
376     if( used < -16)
377         used = -16;
378     */
379
380     if (cpi->avg_pick_mode_time < milliseconds_for_compress && (cpi->avg_encode_time - cpi->avg_pick_mode_time) < milliseconds_for_compress)
381     {
382         if (cpi->avg_pick_mode_time == 0)
383         {
384             cpi->Speed = 4;
385         }
386         else
387         {
388             if (milliseconds_for_compress * 100 < cpi->avg_encode_time * 95)
389             {
390                 cpi->Speed          += 2;
391                 cpi->avg_pick_mode_time = 0;
392                 cpi->avg_encode_time = 0;
393
394                 if (cpi->Speed > 16)
395                 {
396                     cpi->Speed = 16;
397                 }
398             }
399
400             if (milliseconds_for_compress * 100 > cpi->avg_encode_time * vp8_auto_speed_thresh[cpi->Speed])
401             {
402                 cpi->Speed          -= 1;
403                 cpi->avg_pick_mode_time = 0;
404                 cpi->avg_encode_time = 0;
405
406                 // In real-time mode, cpi->speed is in [4, 16].
407                 if (cpi->Speed < 4)        //if ( cpi->Speed < 0 )
408                 {
409                     cpi->Speed = 4;        //cpi->Speed = 0;
410                 }
411             }
412         }
413     }
414     else
415     {
416         cpi->Speed += 4;
417
418         if (cpi->Speed > 16)
419             cpi->Speed = 16;
420
421
422         cpi->avg_pick_mode_time = 0;
423         cpi->avg_encode_time = 0;
424     }
425 }
426
427 int vp8_block_error_c(short *coeff, short *dqcoeff)
428 {
429     int i;
430     int error = 0;
431
432     for (i = 0; i < 16; i++)
433     {
434         int this_diff = coeff[i] - dqcoeff[i];
435         error += this_diff * this_diff;
436     }
437
438     return error;
439 }
440
441 int vp8_mbblock_error_c(MACROBLOCK *mb, int dc)
442 {
443     BLOCK  *be;
444     BLOCKD *bd;
445     int i, j;
446     int berror, error = 0;
447
448     for (i = 0; i < 16; i++)
449     {
450         be = &mb->block[i];
451         bd = &mb->e_mbd.block[i];
452
453         berror = 0;
454
455         for (j = dc; j < 16; j++)
456         {
457             int this_diff = be->coeff[j] - bd->dqcoeff[j];
458             berror += this_diff * this_diff;
459         }
460
461         error += berror;
462     }
463
464     return error;
465 }
466
467 int vp8_mbuverror_c(MACROBLOCK *mb)
468 {
469
470     BLOCK  *be;
471     BLOCKD *bd;
472
473
474     int i;
475     int error = 0;
476
477     for (i = 16; i < 24; i++)
478     {
479         be = &mb->block[i];
480         bd = &mb->e_mbd.block[i];
481
482         error += vp8_block_error_c(be->coeff, bd->dqcoeff);
483     }
484
485     return error;
486 }
487
488 #if !(CONFIG_REALTIME_ONLY)
489 static int macro_block_max_error(MACROBLOCK *mb)
490 {
491     int error = 0;
492     int dc = 0;
493     BLOCK  *be;
494     int i, j;
495     int berror;
496
497     dc = !(mb->e_mbd.mbmi.mode == B_PRED || mb->e_mbd.mbmi.mode == SPLITMV);
498
499     for (i = 0; i < 16; i++)
500     {
501         be = &mb->block[i];
502
503         berror = 0;
504
505         for (j = dc; j < 16; j++)
506         {
507             int this_diff = be->coeff[j];
508             berror += this_diff * this_diff;
509         }
510
511         error += berror;
512     }
513
514     for (i = 16; i < 24; i++)
515     {
516         be = &mb->block[i];
517         berror = 0;
518
519         for (j = 0; j < 16; j++)
520         {
521             int this_diff = be->coeff[j];
522             berror += this_diff * this_diff;
523         }
524
525         error += berror;
526     }
527
528     error <<= 2;
529
530     if (dc)
531     {
532         be = &mb->block[24];
533         berror = 0;
534
535         for (j = 0; j < 16; j++)
536         {
537             int this_diff = be->coeff[j];
538             berror += this_diff * this_diff;
539         }
540
541         error += berror;
542     }
543
544     error >>= 4;
545     return error;
546 }
547 #endif
548
549 int VP8_UVSSE(MACROBLOCK *x, const vp8_variance_rtcd_vtable_t *rtcd)
550 {
551     unsigned char *uptr, *vptr;
552     unsigned char *upred_ptr = (*(x->block[16].base_src) + x->block[16].src);
553     unsigned char *vpred_ptr = (*(x->block[20].base_src) + x->block[20].src);
554     int uv_stride = x->block[16].src_stride;
555
556     unsigned int sse1 = 0;
557     unsigned int sse2 = 0;
558     int mv_row;
559     int mv_col;
560     int offset;
561     int pre_stride = x->e_mbd.block[16].pre_stride;
562
563     vp8_build_uvmvs(&x->e_mbd, 0);
564     mv_row = x->e_mbd.block[16].bmi.mv.as_mv.row;
565     mv_col = x->e_mbd.block[16].bmi.mv.as_mv.col;
566
567     offset = (mv_row >> 3) * pre_stride + (mv_col >> 3);
568     uptr = x->e_mbd.pre.u_buffer + offset;
569     vptr = x->e_mbd.pre.v_buffer + offset;
570
571     if ((mv_row | mv_col) & 7)
572     {
573         VARIANCE_INVOKE(rtcd, subpixvar8x8)(uptr, pre_stride, mv_col & 7, mv_row & 7, upred_ptr, uv_stride, &sse2);
574         VARIANCE_INVOKE(rtcd, subpixvar8x8)(vptr, pre_stride, mv_col & 7, mv_row & 7, vpred_ptr, uv_stride, &sse1);
575         sse2 += sse1;
576     }
577     else
578     {
579         VARIANCE_INVOKE(rtcd, subpixvar8x8)(uptr, pre_stride, mv_col & 7, mv_row & 7, upred_ptr, uv_stride, &sse2);
580         VARIANCE_INVOKE(rtcd, subpixvar8x8)(vptr, pre_stride, mv_col & 7, mv_row & 7, vpred_ptr, uv_stride, &sse1);
581         sse2 += sse1;
582     }
583
584     return sse2;
585
586 }
587
588 #if !(CONFIG_REALTIME_ONLY)
589 static int cost_coeffs(MACROBLOCK *mb, BLOCKD *b, int type, ENTROPY_CONTEXT *a, ENTROPY_CONTEXT *l)
590 {
591     int c = !type;              /* start at coef 0, unless Y with Y2 */
592     int eob = b->eob;
593     int pt ;    /* surrounding block/prev coef predictor */
594     int cost = 0;
595     short *qcoeff_ptr = b->qcoeff;
596
597     VP8_COMBINEENTROPYCONTEXTS(pt, *a, *l);
598
599 # define QC( I)  ( qcoeff_ptr [vp8_default_zig_zag1d[I]] )
600
601     for (; c < eob; c++)
602     {
603         int v = QC(c);
604         int t = vp8_dct_value_tokens_ptr[v].Token;
605         cost += mb->token_costs [type] [vp8_coef_bands[c]] [pt] [t];
606         cost += vp8_dct_value_cost_ptr[v];
607         pt = vp8_prev_token_class[t];
608     }
609
610 # undef QC
611
612     if (c < 16)
613         cost += mb->token_costs [type] [vp8_coef_bands[c]] [pt] [DCT_EOB_TOKEN];
614
615     pt = (c != !type); // is eob first coefficient;
616     *a = *l = pt;
617
618     return cost;
619 }
620
621 int vp8_rdcost_mby(MACROBLOCK *mb)
622 {
623     int cost = 0;
624     int b;
625     TEMP_CONTEXT t, t2;
626     int type = 0;
627
628     MACROBLOCKD *x = &mb->e_mbd;
629
630     vp8_setup_temp_context(&t, x->above_context[Y1CONTEXT], x->left_context[Y1CONTEXT], 4);
631     vp8_setup_temp_context(&t2, x->above_context[Y2CONTEXT], x->left_context[Y2CONTEXT], 1);
632
633     if (x->mbmi.mode == SPLITMV)
634         type = 3;
635
636     for (b = 0; b < 16; b++)
637         cost += cost_coeffs(mb, x->block + b, type,
638                             t.a + vp8_block2above[b], t.l + vp8_block2left[b]);
639
640     if (x->mbmi.mode != SPLITMV)
641         cost += cost_coeffs(mb, x->block + 24, 1,
642                             t2.a + vp8_block2above[24], t2.l + vp8_block2left[24]);
643
644     return cost;
645 }
646
647
648 static void rd_pick_intra4x4block(
649     VP8_COMP *cpi,
650     MACROBLOCK *x,
651     BLOCK *be,
652     BLOCKD *b,
653     B_PREDICTION_MODE *best_mode,
654     B_PREDICTION_MODE above,
655     B_PREDICTION_MODE left,
656     ENTROPY_CONTEXT *a,
657     ENTROPY_CONTEXT *l,
658
659     int *bestrate,
660     int *bestratey,
661     int *bestdistortion)
662 {
663     B_PREDICTION_MODE mode;
664     int best_rd = INT_MAX;       // 1<<30
665     int rate = 0;
666     int distortion;
667     unsigned int *mode_costs;
668
669     ENTROPY_CONTEXT ta = *a, tempa = *a;
670     ENTROPY_CONTEXT tl = *l, templ = *l;
671
672
673     if (x->e_mbd.frame_type == KEY_FRAME)
674     {
675         mode_costs  = x->bmode_costs[above][left];
676     }
677     else
678     {
679         mode_costs = x->inter_bmode_costs;
680     }
681
682     for (mode = B_DC_PRED; mode <= B_HU_PRED; mode++)
683     {
684         int this_rd;
685         int ratey;
686
687         rate = mode_costs[mode];
688         vp8_encode_intra4x4block_rd(IF_RTCD(&cpi->rtcd), x, be, b, mode);
689
690         tempa = ta;
691         templ = tl;
692
693         ratey = cost_coeffs(x, b, 3, &tempa, &templ);
694         rate += ratey;
695         distortion = ENCODEMB_INVOKE(IF_RTCD(&cpi->rtcd.encodemb), berr)(be->coeff, b->dqcoeff) >> 2;
696
697         this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
698
699         if (this_rd < best_rd)
700         {
701             *bestrate = rate;
702             *bestratey = ratey;
703             *bestdistortion = distortion;
704             best_rd = this_rd;
705             *best_mode = mode;
706             *a = tempa;
707             *l = templ;
708         }
709     }
710
711     b->bmi.mode = (B_PREDICTION_MODE)(*best_mode);
712     vp8_encode_intra4x4block_rd(IF_RTCD(&cpi->rtcd), x, be, b, b->bmi.mode);
713
714 }
715
716
717 int vp8_rd_pick_intra4x4mby_modes(VP8_COMP *cpi, MACROBLOCK *mb, int *Rate, int *rate_y, int *Distortion)
718 {
719     MACROBLOCKD *const xd = &mb->e_mbd;
720     int i;
721     TEMP_CONTEXT t;
722     int cost = mb->mbmode_cost [xd->frame_type] [B_PRED];
723     int distortion = 0;
724     int tot_rate_y = 0;
725
726     vp8_intra_prediction_down_copy(xd);
727     vp8_setup_temp_context(&t, xd->above_context[Y1CONTEXT], xd->left_context[Y1CONTEXT], 4);
728
729     for (i = 0; i < 16; i++)
730     {
731         MODE_INFO *const mic = xd->mode_info_context;
732         const int mis = xd->mode_info_stride;
733         const B_PREDICTION_MODE A = vp8_above_bmi(mic, i, mis)->mode;
734         const B_PREDICTION_MODE L = vp8_left_bmi(mic, i)->mode;
735         B_PREDICTION_MODE UNINITIALIZED_IS_SAFE(best_mode);
736         int UNINITIALIZED_IS_SAFE(r), UNINITIALIZED_IS_SAFE(ry), UNINITIALIZED_IS_SAFE(d);
737
738         rd_pick_intra4x4block(
739             cpi, mb, mb->block + i, xd->block + i, &best_mode, A, L,
740             t.a + vp8_block2above[i],
741             t.l + vp8_block2left[i], &r, &ry, &d);
742
743         cost += r;
744         distortion += d;
745         tot_rate_y += ry;
746         mic->bmi[i].mode = xd->block[i].bmi.mode = best_mode;
747     }
748
749     *Rate = cost;
750     *rate_y += tot_rate_y;
751     *Distortion = distortion;
752
753     return RDCOST(mb->rdmult, mb->rddiv, cost, distortion);
754 }
755
756 int vp8_rd_pick_intra16x16mby_mode(VP8_COMP *cpi, MACROBLOCK *x, int *Rate, int *rate_y, int *Distortion)
757 {
758
759     MB_PREDICTION_MODE mode;
760     MB_PREDICTION_MODE UNINITIALIZED_IS_SAFE(mode_selected);
761     int rate, ratey;
762     unsigned int distortion;
763     int best_rd = INT_MAX;
764
765     //Y Search for 16x16 intra prediction mode
766     for (mode = DC_PRED; mode <= TM_PRED; mode++)
767     {
768         int this_rd;
769         int dummy;
770         rate = 0;
771
772         x->e_mbd.mbmi.mode = mode;
773
774         rate += x->mbmode_cost[x->e_mbd.frame_type][x->e_mbd.mbmi.mode];
775
776         vp8_encode_intra16x16mbyrd(IF_RTCD(&cpi->rtcd), x);
777
778         ratey = vp8_rdcost_mby(x);
779
780         rate += ratey;
781
782         VARIANCE_INVOKE(&cpi->rtcd.variance, get16x16var)(x->src.y_buffer, x->src.y_stride, x->e_mbd.dst.y_buffer, x->e_mbd.dst.y_stride, &distortion, &dummy);
783
784         this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
785
786         if (this_rd < best_rd)
787         {
788             mode_selected = mode;
789             best_rd = this_rd;
790             *Rate = rate;
791             *rate_y = ratey;
792             *Distortion = (int)distortion;
793         }
794     }
795
796     x->e_mbd.mbmi.mode = mode_selected;
797     return best_rd;
798 }
799
800
801 static int rd_cost_mbuv(MACROBLOCK *mb)
802 {
803     TEMP_CONTEXT t, t2;
804     int b;
805     int cost = 0;
806     MACROBLOCKD *x = &mb->e_mbd;
807
808     vp8_setup_temp_context(&t, x->above_context[UCONTEXT], x->left_context[UCONTEXT], 2);
809     vp8_setup_temp_context(&t2, x->above_context[VCONTEXT], x->left_context[VCONTEXT], 2);
810
811     for (b = 16; b < 20; b++)
812         cost += cost_coeffs(mb, x->block + b, vp8_block2type[b],
813                             t.a + vp8_block2above[b], t.l + vp8_block2left[b]);
814
815     for (b = 20; b < 24; b++)
816         cost += cost_coeffs(mb, x->block + b, vp8_block2type[b],
817                             t2.a + vp8_block2above[b], t2.l + vp8_block2left[b]);
818
819     return cost;
820 }
821
822
823 unsigned int vp8_get_mbuvrecon_error(const vp8_variance_rtcd_vtable_t *rtcd, const MACROBLOCK *x) // sum of squares
824 {
825     unsigned int sse0, sse1;
826     int sum0, sum1;
827     VARIANCE_INVOKE(rtcd, get8x8var)(x->src.u_buffer, x->src.uv_stride, x->e_mbd.dst.u_buffer, x->e_mbd.dst.uv_stride, &sse0, &sum0);
828     VARIANCE_INVOKE(rtcd, get8x8var)(x->src.v_buffer, x->src.uv_stride, x->e_mbd.dst.v_buffer, x->e_mbd.dst.uv_stride, &sse1, &sum1);
829     return (sse0 + sse1);
830 }
831
832 static int vp8_rd_inter_uv(VP8_COMP *cpi, MACROBLOCK *x, int *rate, int *distortion, int fullpixel)
833 {
834     vp8_build_uvmvs(&x->e_mbd, fullpixel);
835     vp8_encode_inter16x16uvrd(IF_RTCD(&cpi->rtcd), x);
836
837
838     *rate       = rd_cost_mbuv(x);
839     *distortion = ENCODEMB_INVOKE(&cpi->rtcd.encodemb, mbuverr)(x) / 4;
840
841     return UVRDFUNC(x->rdmult, x->rddiv, *rate, *distortion, cpi->target_bits_per_mb);
842 }
843
844 int vp8_rd_pick_intra_mbuv_mode(VP8_COMP *cpi, MACROBLOCK *x, int *rate, int *rate_tokenonly, int *distortion)
845 {
846     MB_PREDICTION_MODE mode;
847     MB_PREDICTION_MODE UNINITIALIZED_IS_SAFE(mode_selected);
848     int best_rd = INT_MAX;
849     int UNINITIALIZED_IS_SAFE(d), UNINITIALIZED_IS_SAFE(r);
850     int rate_to;
851
852     for (mode = DC_PRED; mode <= TM_PRED; mode++)
853     {
854         int rate;
855         int distortion;
856         int this_rd;
857
858         x->e_mbd.mbmi.uv_mode = mode;
859         vp8_encode_intra16x16mbuvrd(IF_RTCD(&cpi->rtcd), x);
860
861         rate_to = rd_cost_mbuv(x);
862         rate = rate_to + x->intra_uv_mode_cost[x->e_mbd.frame_type][x->e_mbd.mbmi.uv_mode];
863
864         distortion = vp8_get_mbuvrecon_error(IF_RTCD(&cpi->rtcd.variance), x);
865
866         this_rd = UVRDFUNC(x->rdmult, x->rddiv, rate, distortion, cpi->target_bits_per_mb);
867
868         if (this_rd < best_rd)
869         {
870             best_rd = this_rd;
871             d = distortion;
872             r = rate;
873             *rate_tokenonly = rate_to;
874             mode_selected = mode;
875         }
876     }
877
878     *rate = r;
879     *distortion = d;
880
881     x->e_mbd.mbmi.uv_mode = mode_selected;
882     return best_rd;
883 }
884 #endif
885
886 int vp8_cost_mv_ref(MB_PREDICTION_MODE m, const int near_mv_ref_ct[4])
887 {
888     vp8_prob p [VP8_MVREFS-1];
889     assert(NEARESTMV <= m  &&  m <= SPLITMV);
890     vp8_mv_ref_probs(p, near_mv_ref_ct);
891     return vp8_cost_token(vp8_mv_ref_tree, p, VP8_MVREFENCODINGS + m);
892 }
893
894 void vp8_set_mbmode_and_mvs(MACROBLOCK *x, MB_PREDICTION_MODE mb, MV *mv)
895 {
896     int i;
897
898     x->e_mbd.mbmi.mode = mb;
899     x->e_mbd.mbmi.mv.as_mv.row = mv->row;
900     x->e_mbd.mbmi.mv.as_mv.col = mv->col;
901
902     for (i = 0; i < 16; i++)
903     {
904         B_MODE_INFO *bmi = &x->e_mbd.block[i].bmi;
905         bmi->mode = (B_PREDICTION_MODE) mb;
906         bmi->mv.as_mv.row = mv->row;
907         bmi->mv.as_mv.col = mv->col;
908     }
909 }
910
911 #if !(CONFIG_REALTIME_ONLY)
912 int vp8_count_labels(int const *labelings)
913 {
914     int i;
915     int count = 0;
916
917     for (i = 0; i < 16; i++)
918     {
919         if (labelings[i] > count)
920             count = labelings[i];
921     }
922
923     return count + 1;
924 }
925
926
927 static int labels2mode(
928     MACROBLOCK *x,
929     int const *labelings, int which_label,
930     B_PREDICTION_MODE this_mode,
931     MV *this_mv, MV *best_ref_mv,
932     int *mvcost[2]
933 )
934 {
935     MACROBLOCKD *const xd = & x->e_mbd;
936     MODE_INFO *const mic = xd->mode_info_context;
937     const int mis = xd->mode_info_stride;
938
939     int cost = 0;
940     int thismvcost = 0;
941
942     /* We have to be careful retrieving previously-encoded motion vectors.
943        Ones from this macroblock have to be pulled from the BLOCKD array
944        as they have not yet made it to the bmi array in our MB_MODE_INFO. */
945
946     int i = 0;
947
948     do
949     {
950         BLOCKD *const d = xd->block + i;
951         const int row = i >> 2,  col = i & 3;
952
953         B_PREDICTION_MODE m;
954
955         if (labelings[i] != which_label)
956             continue;
957
958         if (col  &&  labelings[i] == labelings[i-1])
959             m = LEFT4X4;
960         else if (row  &&  labelings[i] == labelings[i-4])
961             m = ABOVE4X4;
962         else
963         {
964             // the only time we should do costing for new motion vector or mode
965             // is when we are on a new label  (jbb May 08, 2007)
966             switch (m = this_mode)
967             {
968             case NEW4X4 :
969                 thismvcost  = vp8_mv_bit_cost(this_mv, best_ref_mv, mvcost, 102);
970                 break;
971             case LEFT4X4:
972                 *this_mv = col ? d[-1].bmi.mv.as_mv : vp8_left_bmi(mic, i)->mv.as_mv;
973                 break;
974             case ABOVE4X4:
975                 *this_mv = row ? d[-4].bmi.mv.as_mv : vp8_above_bmi(mic, i, mis)->mv.as_mv;
976                 break;
977             case ZERO4X4:
978                 this_mv->row = this_mv->col = 0;
979                 break;
980             default:
981                 break;
982             }
983
984             if (m == ABOVE4X4)  // replace above with left if same
985             {
986                 const MV mv = col ? d[-1].bmi.mv.as_mv : vp8_left_bmi(mic, i)->mv.as_mv;
987
988                 if (mv.row == this_mv->row  &&  mv.col == this_mv->col)
989                     m = LEFT4X4;
990             }
991
992             cost = x->inter_bmode_costs[ m];
993         }
994
995         d->bmi.mode = m;
996         d->bmi.mv.as_mv = *this_mv;
997
998     }
999     while (++i < 16);
1000
1001     cost += thismvcost ;
1002     return cost;
1003 }
1004
1005 static int rdcost_mbsegment_y(MACROBLOCK *mb, const int *labels, int which_label, TEMP_CONTEXT *t)
1006 {
1007     int cost = 0;
1008     int b;
1009     MACROBLOCKD *x = &mb->e_mbd;
1010
1011
1012     for (b = 0; b < 16; b++)
1013         if (labels[ b] == which_label)
1014             cost += cost_coeffs(mb, x->block + b, 3,
1015                                 t->a + vp8_block2above[b],
1016                                 t->l + vp8_block2left[b]);
1017
1018     return cost;
1019
1020 }
1021 static unsigned int vp8_encode_inter_mb_segment(MACROBLOCK *x, int const *labels, int which_label, const vp8_encodemb_rtcd_vtable_t *rtcd)
1022 {
1023     int i;
1024     unsigned int distortion = 0;
1025
1026     for (i = 0; i < 16; i++)
1027     {
1028         if (labels[i] == which_label)
1029         {
1030             BLOCKD *bd = &x->e_mbd.block[i];
1031             BLOCK *be = &x->block[i];
1032
1033
1034             vp8_build_inter_predictors_b(bd, 16, x->e_mbd.subpixel_predict);
1035             ENCODEMB_INVOKE(rtcd, subb)(be, bd, 16);
1036             x->short_fdct4x4rd(be->src_diff, be->coeff, 32);
1037
1038             // set to 0 no way to account for 2nd order DC so discount
1039             //be->coeff[0] = 0;
1040             x->quantize_brd(be, bd);
1041
1042             distortion += ENCODEMB_INVOKE(rtcd, berr)(be->coeff, bd->dqcoeff);
1043         }
1044     }
1045
1046     return distortion;
1047 }
1048
1049 static void macro_block_yrd(MACROBLOCK *mb, int *Rate, int *Distortion, const vp8_encodemb_rtcd_vtable_t *rtcd)
1050 {
1051     int b;
1052     MACROBLOCKD *const x = &mb->e_mbd;
1053     BLOCK   *const mb_y2 = mb->block + 24;
1054     BLOCKD *const x_y2  = x->block + 24;
1055     short *Y2DCPtr = mb_y2->src_diff;
1056     BLOCK *beptr;
1057     int d;
1058
1059     ENCODEMB_INVOKE(rtcd, submby)(mb->src_diff, mb->src.y_buffer, mb->e_mbd.predictor, mb->src.y_stride);
1060
1061     // Fdct and building the 2nd order block
1062     for (beptr = mb->block; beptr < mb->block + 16; beptr += 2)
1063     {
1064         mb->short_fdct8x4rd(beptr->src_diff, beptr->coeff, 32);
1065         *Y2DCPtr++ = beptr->coeff[0];
1066         *Y2DCPtr++ = beptr->coeff[16];
1067     }
1068
1069     // 2nd order fdct
1070     if (x->mbmi.mode != SPLITMV)
1071     {
1072         mb->short_walsh4x4(mb_y2->src_diff, mb_y2->coeff, 8);
1073     }
1074
1075     // Quantization
1076     for (b = 0; b < 16; b++)
1077     {
1078         mb->quantize_brd(&mb->block[b], &mb->e_mbd.block[b]);
1079     }
1080
1081     // DC predication and Quantization of 2nd Order block
1082     if (x->mbmi.mode != SPLITMV)
1083     {
1084
1085         {
1086             mb->quantize_brd(mb_y2, x_y2);
1087         }
1088     }
1089
1090     // Distortion
1091     if (x->mbmi.mode == SPLITMV)
1092         d = ENCODEMB_INVOKE(rtcd, mberr)(mb, 0) << 2;
1093     else
1094     {
1095         d = ENCODEMB_INVOKE(rtcd, mberr)(mb, 1) << 2;
1096         d += ENCODEMB_INVOKE(rtcd, berr)(mb_y2->coeff, x_y2->dqcoeff);
1097     }
1098
1099     *Distortion = (d >> 4);
1100
1101     // rate
1102     *Rate = vp8_rdcost_mby(mb);
1103 }
1104
1105 static int vp8_rd_pick_best_mbsegmentation(VP8_COMP *cpi, MACROBLOCK *x, MV *best_ref_mv, int best_rd, int *mdcounts, int *returntotrate, int *returnyrate, int *returndistortion, int compressor_speed, int *mvcost[2], int mvthresh, int fullpixel)
1106 {
1107     int i, segmentation;
1108     B_PREDICTION_MODE this_mode;
1109     MACROBLOCKD *xc = &x->e_mbd;
1110     BLOCK *b = &x->block[0];
1111     BLOCKD *d = &x->e_mbd.block[0];
1112     BLOCK *c = &x->block[0];
1113     BLOCKD *e = &x->e_mbd.block[0];
1114     int const *labels;
1115     int best_segment_rd = INT_MAX;
1116     int best_seg = 0;
1117     int br = 0;
1118     int bd = 0;
1119     int bsr = 0;
1120     int bsd = 0;
1121     int bestsegmentyrate = 0;
1122
1123     // FIX TO Rd error outrange bug PGW 9 june 2004
1124     B_PREDICTION_MODE bmodes[16] = {ZERO4X4, ZERO4X4, ZERO4X4, ZERO4X4,
1125                                     ZERO4X4, ZERO4X4, ZERO4X4, ZERO4X4,
1126                                     ZERO4X4, ZERO4X4, ZERO4X4, ZERO4X4,
1127                                     ZERO4X4, ZERO4X4, ZERO4X4, ZERO4X4
1128                                    };
1129
1130     MV bmvs[16];
1131     int beobs[16];
1132
1133     for (segmentation = 0; segmentation < VP8_NUMMBSPLITS; segmentation++)
1134     {
1135         int label_count;
1136         int this_segment_rd = 0;
1137         int label_mv_thresh;
1138         int rate = 0;
1139         int sbr = 0;
1140         int sbd = 0;
1141         int UNINITIALIZED_IS_SAFE(sseshift);
1142         int segmentyrate = 0;
1143
1144         vp8_variance_fn_ptr_t v_fn_ptr;
1145
1146         TEMP_CONTEXT t;
1147         TEMP_CONTEXT tb;
1148         vp8_setup_temp_context(&t, xc->above_context[Y1CONTEXT], xc->left_context[Y1CONTEXT], 4);
1149
1150         br = 0;
1151         bd = 0;
1152
1153         switch (segmentation)
1154         {
1155         case 0:
1156             v_fn_ptr.vf    = VARIANCE_INVOKE(&cpi->rtcd.variance, var16x8);
1157             v_fn_ptr.svf   = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar16x8);
1158             v_fn_ptr.sdf   = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8);
1159             v_fn_ptr.sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x3);
1160             v_fn_ptr.sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad16x8x4d);
1161             sseshift = 3;
1162             break;
1163         case 1:
1164             v_fn_ptr.vf    = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x16);
1165             v_fn_ptr.svf   = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x16);
1166             v_fn_ptr.sdf   = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16);
1167             v_fn_ptr.sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x3);
1168             v_fn_ptr.sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x16x4d);
1169             sseshift = 3;
1170             break;
1171         case 2:
1172             v_fn_ptr.vf    = VARIANCE_INVOKE(&cpi->rtcd.variance, var8x8);
1173             v_fn_ptr.svf   = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar8x8);
1174             v_fn_ptr.sdf   = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8);
1175             v_fn_ptr.sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x3);
1176             v_fn_ptr.sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad8x8x4d);
1177             sseshift = 2;
1178             break;
1179         case 3:
1180             v_fn_ptr.vf    = VARIANCE_INVOKE(&cpi->rtcd.variance, var4x4);
1181             v_fn_ptr.svf   = VARIANCE_INVOKE(&cpi->rtcd.variance, subpixvar4x4);
1182             v_fn_ptr.sdf   = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4);
1183             v_fn_ptr.sdx3f = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x3);
1184             v_fn_ptr.sdx4df = VARIANCE_INVOKE(&cpi->rtcd.variance, sad4x4x4d);
1185             sseshift = 0;
1186             break;
1187         }
1188
1189         labels = vp8_mbsplits[segmentation];
1190         label_count = vp8_count_labels(labels);
1191
1192         // 64 makes this threshold really big effectively
1193         // making it so that we very rarely check mvs on
1194         // segments.   setting this to 1 would make mv thresh
1195         // roughly equal to what it is for macroblocks
1196         label_mv_thresh = 1 * mvthresh / label_count ;
1197
1198         // Segmentation method overheads
1199         rate = vp8_cost_token(vp8_mbsplit_tree, vp8_mbsplit_probs, vp8_mbsplit_encodings + segmentation);
1200
1201         rate += vp8_cost_mv_ref(SPLITMV, mdcounts);
1202
1203         this_segment_rd += RDFUNC(x->rdmult, x->rddiv, rate, 0, cpi->target_bits_per_mb);
1204         br += rate;
1205
1206         for (i = 0; i < label_count; i++)
1207         {
1208             MV mode_mv[B_MODE_COUNT];
1209             int best_label_rd = INT_MAX;
1210             B_PREDICTION_MODE mode_selected = ZERO4X4;
1211             int j;
1212             int bestlabelyrate = 0;
1213
1214             b = &x->block[0];
1215             d = &x->e_mbd.block[0];
1216
1217
1218             // find first label
1219             for (j = 0; j < 16; j++)
1220                 if (labels[j] == i)
1221                     break;
1222
1223             c = &x->block[j];
1224             e = &x->e_mbd.block[j];
1225
1226             // search for the best motion vector on this segment
1227             for (this_mode = LEFT4X4; this_mode <= NEW4X4 ; this_mode ++)
1228             {
1229                 int distortion;
1230                 int this_rd;
1231                 int num00;
1232                 int labelyrate;
1233
1234                 TEMP_CONTEXT ts;
1235                 vp8_setup_temp_context(&ts, &t.a[0], &t.l[0], 4);
1236
1237                 if (this_mode == NEW4X4)
1238                 {
1239                     int step_param = 0;
1240                     int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
1241                     int n;
1242                     int thissme;
1243                     int bestsme = INT_MAX;
1244                     MV  temp_mv;
1245
1246                     // Is the best so far sufficiently good that we cant justify doing and new motion search.
1247                     if (best_label_rd < label_mv_thresh)
1248                         break;
1249
1250                     {
1251                         int sadpb = x->sadperbit4;
1252
1253                         if (cpi->sf.search_method == HEX)
1254                             bestsme = vp8_hex_search(x, c, e, best_ref_mv, &mode_mv[NEW4X4], step_param, sadpb/*x->errorperbit*/, &num00, v_fn_ptr.vf, v_fn_ptr.sdf, x->mvsadcost, mvcost);
1255                         else
1256                         {
1257                             bestsme = cpi->diamond_search_sad(x, c, e, best_ref_mv, &mode_mv[NEW4X4], step_param, sadpb / 2/*x->errorperbit*/, &num00, &v_fn_ptr, x->mvsadcost, mvcost);
1258
1259                             n = num00;
1260                             num00 = 0;
1261
1262                             while (n < further_steps)
1263                             {
1264                                 n++;
1265
1266                                 if (num00)
1267                                     num00--;
1268                                 else
1269                                 {
1270                                     thissme = cpi->diamond_search_sad(x, c, e, best_ref_mv, &temp_mv, step_param + n, sadpb / 2/*x->errorperbit*/, &num00, &v_fn_ptr, x->mvsadcost, mvcost);
1271
1272                                     if (thissme < bestsme)
1273                                     {
1274                                         bestsme = thissme;
1275                                         mode_mv[NEW4X4].row = temp_mv.row;
1276                                         mode_mv[NEW4X4].col = temp_mv.col;
1277                                     }
1278                                 }
1279                             }
1280                         }
1281
1282                         // Should we do a full search (best quality only)
1283                         if ((compressor_speed == 0) && (bestsme >> sseshift) > 4000)
1284                         {
1285                             thissme = cpi->full_search_sad(x, c, e, best_ref_mv, sadpb / 4, 16, &v_fn_ptr, x->mvcost, x->mvsadcost);
1286
1287                             if (thissme < bestsme)
1288                             {
1289                                 bestsme = thissme;
1290                                 mode_mv[NEW4X4] = e->bmi.mv.as_mv;
1291                             }
1292                             else
1293                             {
1294                                 // The full search result is actually worse so re-instate the previous best vector
1295                                 e->bmi.mv.as_mv = mode_mv[NEW4X4];
1296                             }
1297                         }
1298                     }
1299
1300                     if (bestsme < INT_MAX)
1301                     {
1302                         if (!fullpixel)
1303                             cpi->find_fractional_mv_step(x, c, e, &mode_mv[NEW4X4], best_ref_mv, x->errorperbit / 2, v_fn_ptr.svf, v_fn_ptr.vf, mvcost);
1304                         else
1305                             vp8_skip_fractional_mv_step(x, c, e, &mode_mv[NEW4X4], best_ref_mv, x->errorperbit, v_fn_ptr.svf, v_fn_ptr.vf, mvcost);
1306                     }
1307                 }
1308
1309                 rate = labels2mode(x, labels, i, this_mode, &mode_mv[this_mode], best_ref_mv, mvcost);
1310
1311                 // Trap vectors that reach beyond the UMV borders
1312                 if (((mode_mv[this_mode].row >> 3) < x->mv_row_min) || ((mode_mv[this_mode].row >> 3) > x->mv_row_max) ||
1313                     ((mode_mv[this_mode].col >> 3) < x->mv_col_min) || ((mode_mv[this_mode].col >> 3) > x->mv_col_max))
1314                 {
1315                     continue;
1316                 }
1317
1318                 distortion = vp8_encode_inter_mb_segment(x, labels, i, IF_RTCD(&cpi->rtcd.encodemb)) / 4;
1319
1320                 labelyrate = rdcost_mbsegment_y(x, labels, i, &ts);
1321                 rate += labelyrate;
1322
1323                 this_rd = RDFUNC(x->rdmult, x->rddiv, rate, distortion, cpi->target_bits_per_mb);
1324
1325                 if (this_rd < best_label_rd)
1326                 {
1327                     sbr = rate;
1328                     sbd = distortion;
1329                     bestlabelyrate = labelyrate;
1330                     mode_selected = this_mode;
1331                     best_label_rd = this_rd;
1332                     vp8_setup_temp_context(&tb, &ts.a[0], &ts.l[0], 4);
1333
1334                 }
1335             }
1336
1337             vp8_setup_temp_context(&t, &tb.a[0], &tb.l[0], 4);
1338
1339             labels2mode(x, labels, i, mode_selected, &mode_mv[mode_selected], best_ref_mv, mvcost);
1340
1341             br += sbr;
1342             bd += sbd;
1343             segmentyrate += bestlabelyrate;
1344             this_segment_rd += best_label_rd;
1345
1346             if ((this_segment_rd > best_rd) || (this_segment_rd > best_segment_rd))
1347                 break;
1348         }
1349
1350         if ((this_segment_rd <= best_rd) && (this_segment_rd < best_segment_rd))
1351         {
1352             bsr = br;
1353             bsd = bd;
1354             bestsegmentyrate = segmentyrate;
1355             best_segment_rd = this_segment_rd;
1356             best_seg = segmentation;
1357
1358             // store everything needed to come back to this!!
1359             for (i = 0; i < 16; i++)
1360             {
1361                 BLOCKD *bd = &x->e_mbd.block[i];
1362
1363                 bmvs[i] = bd->bmi.mv.as_mv;
1364                 bmodes[i] = bd->bmi.mode;
1365                 beobs[i] = bd->eob;
1366             }
1367         }
1368     }
1369
1370     // set it to the best
1371     for (i = 0; i < 16; i++)
1372     {
1373         BLOCKD *bd = &x->e_mbd.block[i];
1374
1375         bd->bmi.mv.as_mv = bmvs[i];
1376         bd->bmi.mode = bmodes[i];
1377         bd->eob = beobs[i];
1378     }
1379
1380     // Trap cases where the best split mode has all vectors coded 0,0 (or all the same)
1381     if (FALSE)
1382     {
1383         int allsame = 1;
1384
1385         for (i = 1; i < 16; i++)
1386         {
1387             if ((bmvs[i].col != bmvs[i-1].col) || (bmvs[i].row != bmvs[i-1].row))
1388             {
1389                 allsame = 0;
1390                 break;
1391             }
1392         }
1393
1394         if (allsame)
1395         {
1396             best_segment_rd = INT_MAX;
1397         }
1398     }
1399
1400     *returntotrate = bsr;
1401     *returndistortion = bsd;
1402     *returnyrate = bestsegmentyrate;
1403
1404
1405
1406     // save partitions
1407     labels = vp8_mbsplits[best_seg];
1408     x->e_mbd.mbmi.partitioning = best_seg;
1409     x->e_mbd.mbmi.partition_count = vp8_count_labels(labels);
1410
1411     for (i = 0; i < x->e_mbd.mbmi.partition_count; i++)
1412     {
1413         int j;
1414
1415         for (j = 0; j < 16; j++)
1416         {
1417             if (labels[j] == i)
1418                 break;
1419         }
1420
1421         x->e_mbd.mbmi.partition_bmi[i].mode = x->e_mbd.block[j].bmi.mode;
1422         x->e_mbd.mbmi.partition_bmi[i].mv.as_mv = x->e_mbd.block[j].bmi.mv.as_mv;
1423     }
1424
1425     return best_segment_rd;
1426 }
1427
1428
1429 int vp8_rd_pick_inter_mode(VP8_COMP *cpi, MACROBLOCK *x, int recon_yoffset, int recon_uvoffset, int *returnrate, int *returndistortion, int *returnintra)
1430 {
1431     BLOCK *b = &x->block[0];
1432     BLOCKD *d = &x->e_mbd.block[0];
1433     MACROBLOCKD *xd = &x->e_mbd;
1434     B_MODE_INFO best_bmodes[16];
1435     MB_MODE_INFO best_mbmode;
1436     MV best_ref_mv;
1437     MV mode_mv[MB_MODE_COUNT];
1438     MB_PREDICTION_MODE this_mode;
1439     int num00;
1440     int best_mode_index = 0;
1441
1442     int i;
1443     int mode_index;
1444     int mdcounts[4];
1445     int rate;
1446     int distortion;
1447     int best_rd = INT_MAX; // 1 << 30;
1448     int ref_frame_cost[MAX_REF_FRAMES];
1449     int rate2, distortion2;
1450     int uv_intra_rate, uv_intra_distortion, uv_intra_rate_tokenonly;
1451     int rate_y, UNINITIALIZED_IS_SAFE(rate_uv);
1452
1453     //int all_rds[MAX_MODES];        // Experimental debug code.
1454     //int all_rates[MAX_MODES];
1455     //int all_dist[MAX_MODES];
1456     //int intermodecost[MAX_MODES];
1457
1458     MB_PREDICTION_MODE uv_intra_mode;
1459     int sse;
1460     int sum;
1461     int uvintra_eob = 0;
1462     int tteob = 0;
1463     int force_no_skip = 0;
1464
1465     *returnintra = INT_MAX;
1466
1467     cpi->mbs_tested_so_far++;          // Count of the number of MBs tested so far this frame
1468
1469     x->skip = 0;
1470
1471     ref_frame_cost[INTRA_FRAME]   = vp8_cost_zero(cpi->prob_intra_coded);
1472
1473     // Experimental code
1474     // Adjust the RD multiplier based on the best case distortion we saw in the most recently coded mb
1475     //if ( (cpi->last_mb_distortion) > 0 && (cpi->target_bits_per_mb > 0) )
1476     /*{
1477         int tmprdmult;
1478
1479         //tmprdmult = (cpi->last_mb_distortion * 256) / ((cpi->av_per_frame_bandwidth*256)/cpi->common.MBs);
1480         tmprdmult = (cpi->last_mb_distortion * 256) / cpi->target_bits_per_mb;
1481         //tmprdmult = tmprdmult;
1482
1483         //if ( tmprdmult > cpi->RDMULT * 2 )
1484         //  tmprdmult = cpi->RDMULT * 2;
1485         //else if ( tmprdmult < cpi->RDMULT / 2 )
1486         //  tmprdmult = cpi->RDMULT / 2;
1487
1488         //tmprdmult = (tmprdmult < 25) ? 25 : tmprdmult;
1489
1490         //x->rdmult = tmprdmult;
1491
1492     }*/
1493
1494     // Special case treatment when GF and ARF are not sensible options for reference
1495     if (cpi->ref_frame_flags == VP8_LAST_FLAG)
1496     {
1497         ref_frame_cost[LAST_FRAME]    = vp8_cost_one(cpi->prob_intra_coded)
1498                                         + vp8_cost_zero(255);
1499         ref_frame_cost[GOLDEN_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
1500                                         + vp8_cost_one(255)
1501                                         + vp8_cost_zero(128);
1502         ref_frame_cost[ALTREF_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
1503                                         + vp8_cost_one(255)
1504                                         + vp8_cost_one(128);
1505     }
1506     else
1507     {
1508         ref_frame_cost[LAST_FRAME]    = vp8_cost_one(cpi->prob_intra_coded)
1509                                         + vp8_cost_zero(cpi->prob_last_coded);
1510         ref_frame_cost[GOLDEN_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
1511                                         + vp8_cost_one(cpi->prob_last_coded)
1512                                         + vp8_cost_zero(cpi->prob_gf_coded);
1513         ref_frame_cost[ALTREF_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
1514                                         + vp8_cost_one(cpi->prob_last_coded)
1515                                         + vp8_cost_one(cpi->prob_gf_coded);
1516     }
1517
1518     vpx_memset(mode_mv, 0, sizeof(mode_mv));
1519
1520     x->e_mbd.mbmi.ref_frame = INTRA_FRAME;
1521     vp8_rd_pick_intra_mbuv_mode(cpi, x, &uv_intra_rate, &uv_intra_rate_tokenonly, &uv_intra_distortion);
1522     uv_intra_mode = x->e_mbd.mbmi.uv_mode;
1523     {
1524         uvintra_eob = 0;
1525
1526         for (i = 16; i < 24; i++)
1527             uvintra_eob += x->e_mbd.block[i].eob;
1528     }
1529
1530     for (mode_index = 0; mode_index < MAX_MODES; mode_index++)
1531     {
1532         int frame_cost;
1533         int this_rd = INT_MAX;
1534         int lf_or_gf = 0;           // Lat Frame (01) or gf/arf (1)
1535         int disable_skip = 0;
1536
1537         force_no_skip = 0;
1538
1539         // Experimental debug code.
1540         // Record of rd values recorded for this MB. -1 indicates not measured
1541         //all_rds[mode_index] = -1;
1542         //all_rates[mode_index] = -1;
1543         //all_dist[mode_index] = -1;
1544         //intermodecost[mode_index] = -1;  
1545
1546         // Test best rd so far against threshold for trying this mode.
1547         if (best_rd <= cpi->rd_threshes[mode_index])
1548             continue;
1549
1550
1551
1552         // These variables hold are rolling total cost and distortion for this mode
1553         rate2 = 0;
1554         distortion2 = 0;
1555
1556         // Where skip is allowable add in the default per mb cost for the no skip case.
1557         // where we then decide to skip we have to delete this and replace it with the
1558         // cost of signallying a skip
1559         if (cpi->common.mb_no_coeff_skip)
1560         {
1561             rate2 += vp8_cost_bit(cpi->prob_skip_false, 0);
1562         }
1563
1564         this_mode = vp8_mode_order[mode_index];
1565
1566         x->e_mbd.mbmi.mode = this_mode;
1567         x->e_mbd.mbmi.uv_mode = DC_PRED;
1568         x->e_mbd.mbmi.ref_frame = vp8_ref_frame_order[mode_index];
1569
1570         //Only consider ZEROMV/ALTREF_FRAME for alt ref frame.
1571         if (cpi->is_src_frame_alt_ref)
1572         {
1573             if (this_mode != ZEROMV || x->e_mbd.mbmi.ref_frame != ALTREF_FRAME)
1574                 continue;
1575         }
1576
1577         if (x->e_mbd.mbmi.ref_frame == LAST_FRAME)
1578         {
1579             if (!(cpi->ref_frame_flags & VP8_LAST_FLAG))
1580                 continue;
1581
1582             lf_or_gf = 0;  // Local last frame vs Golden frame flag
1583
1584             // Set up pointers for this macro block into the previous frame recon buffer
1585             x->e_mbd.pre.y_buffer = cpi->common.last_frame.y_buffer + recon_yoffset;
1586             x->e_mbd.pre.u_buffer = cpi->common.last_frame.u_buffer + recon_uvoffset;
1587             x->e_mbd.pre.v_buffer = cpi->common.last_frame.v_buffer + recon_uvoffset;
1588         }
1589         else if (x->e_mbd.mbmi.ref_frame == GOLDEN_FRAME)
1590         {
1591
1592             // not supposed to reference gold frame
1593             if (!(cpi->ref_frame_flags & VP8_GOLD_FLAG))
1594                 continue;
1595
1596             lf_or_gf = 1;  // Local last frame vs Golden frame flag
1597
1598             // Set up pointers for this macro block into the previous frame recon buffer
1599             x->e_mbd.pre.y_buffer = cpi->common.golden_frame.y_buffer + recon_yoffset;
1600             x->e_mbd.pre.u_buffer = cpi->common.golden_frame.u_buffer + recon_uvoffset;
1601             x->e_mbd.pre.v_buffer = cpi->common.golden_frame.v_buffer + recon_uvoffset;
1602         }
1603         else if (x->e_mbd.mbmi.ref_frame == ALTREF_FRAME)
1604         {
1605             // not supposed to reference alt ref frame
1606             if (!(cpi->ref_frame_flags & VP8_ALT_FLAG))
1607                 continue;
1608
1609             //if ( !cpi->source_alt_ref_active )
1610             //  continue;
1611
1612             lf_or_gf = 1;  // Local last frame vs Golden frame flag
1613
1614             // Set up pointers for this macro block into the previous frame recon buffer
1615             x->e_mbd.pre.y_buffer = cpi->common.alt_ref_frame.y_buffer + recon_yoffset;
1616             x->e_mbd.pre.u_buffer = cpi->common.alt_ref_frame.u_buffer + recon_uvoffset;
1617             x->e_mbd.pre.v_buffer = cpi->common.alt_ref_frame.v_buffer + recon_uvoffset;
1618         }
1619
1620         vp8_find_near_mvs(&x->e_mbd,
1621                           x->e_mbd.mode_info_context,
1622                           &mode_mv[NEARESTMV], &mode_mv[NEARMV], &best_ref_mv,
1623                           mdcounts, x->e_mbd.mbmi.ref_frame, cpi->common.ref_frame_sign_bias);
1624
1625
1626         // Estimate the reference frame signaling cost and add it to the rolling cost variable.
1627         frame_cost = ref_frame_cost[x->e_mbd.mbmi.ref_frame];
1628         rate2 += frame_cost;
1629
1630         if (this_mode <= B_PRED)
1631         {
1632             for (i = 0; i < 16; i++)
1633             {
1634                 vpx_memset(&x->e_mbd.block[i].bmi, 0, sizeof(B_MODE_INFO));
1635             }
1636         }
1637
1638         // Check to see if the testing frequency for this mode is at its max
1639         // If so then prevent it from being tested and increase the threshold for its testing
1640         if (cpi->mode_test_hit_counts[mode_index] && (cpi->mode_check_freq[mode_index] > 1))
1641         {
1642             if (cpi->mbs_tested_so_far  <= cpi->mode_check_freq[mode_index] * cpi->mode_test_hit_counts[mode_index])
1643             {
1644                 // Increase the threshold for coding this mode to make it less likely to be chosen
1645                 cpi->rd_thresh_mult[mode_index] += 4;
1646
1647                 if (cpi->rd_thresh_mult[mode_index] > MAX_THRESHMULT)
1648                     cpi->rd_thresh_mult[mode_index] = MAX_THRESHMULT;
1649
1650                 cpi->rd_threshes[mode_index] = (cpi->rd_baseline_thresh[mode_index] >> 7) * cpi->rd_thresh_mult[mode_index];
1651
1652                 continue;
1653             }
1654         }
1655
1656         // We have now reached the point where we are going to test the current mode so increment the counter for the number of times it has been tested
1657         cpi->mode_test_hit_counts[mode_index] ++;
1658
1659         // Experimental code. Special case for gf and arf zeromv modes. Increase zbin size to supress noise
1660         if (cpi->zbin_mode_boost_enabled)
1661         {
1662             if ((vp8_mode_order[mode_index] == ZEROMV) && (vp8_ref_frame_order[mode_index] != LAST_FRAME))
1663                 cpi->zbin_mode_boost = GF_ZEROMV_ZBIN_BOOST;
1664             else
1665                 cpi->zbin_mode_boost = 0;
1666
1667             vp8cx_mb_init_quantizer(cpi, x);
1668         }
1669
1670         switch (this_mode)
1671         {
1672         case B_PRED:
1673
1674             // Note the rate value returned here includes the cost of coding the BPRED mode : x->mbmode_cost[x->e_mbd.frame_type][BPRED];
1675             vp8_rd_pick_intra4x4mby_modes(cpi, x, &rate, &rate_y, &distortion);
1676             rate2 += rate;
1677             //rate_y = rate;
1678             distortion2 += distortion;
1679             rate2 += uv_intra_rate;
1680             rate_uv = uv_intra_rate_tokenonly;
1681             distortion2 += uv_intra_distortion;
1682             break;
1683
1684         case SPLITMV:
1685         {
1686             int frame_cost_rd = RDFUNC(x->rdmult, x->rddiv, frame_cost, 0, cpi->target_bits_per_mb);
1687             int saved_rate = rate2;
1688
1689             // vp8_rd_pick_best_mbsegmentation looks only at Y and does not account for frame_cost.
1690             // (best_rd - frame_cost_rd) is thus a conservative breakout number.
1691             int breakout_rd = best_rd - frame_cost_rd;
1692             int tmp_rd;
1693
1694             if (x->e_mbd.mbmi.ref_frame == LAST_FRAME)
1695                 tmp_rd = vp8_rd_pick_best_mbsegmentation(cpi, x, &best_ref_mv, breakout_rd, mdcounts, &rate, &rate_y, &distortion, cpi->compressor_speed, x->mvcost, cpi->rd_threshes[THR_NEWMV], cpi->common.full_pixel) ;
1696             else if (x->e_mbd.mbmi.ref_frame == GOLDEN_FRAME)
1697                 tmp_rd = vp8_rd_pick_best_mbsegmentation(cpi, x, &best_ref_mv, breakout_rd, mdcounts, &rate, &rate_y, &distortion, cpi->compressor_speed, x->mvcost, cpi->rd_threshes[THR_NEWG], cpi->common.full_pixel) ;
1698             else
1699                 tmp_rd = vp8_rd_pick_best_mbsegmentation(cpi, x, &best_ref_mv, breakout_rd, mdcounts, &rate, &rate_y, &distortion, cpi->compressor_speed, x->mvcost, cpi->rd_threshes[THR_NEWA], cpi->common.full_pixel) ;
1700
1701             rate2 += rate;
1702             distortion2 += distortion;
1703
1704             // If even the 'Y' rd value of split is higher than best so far then dont bother looking at UV
1705             if (tmp_rd < breakout_rd)
1706             {
1707                 // Now work out UV cost and add it in
1708                 vp8_rd_inter_uv(cpi, x, &rate, &distortion, cpi->common.full_pixel);
1709                 rate2 += rate;
1710                 rate_uv = rate;
1711                 distortion2 += distortion;
1712
1713             }
1714             else
1715             {
1716                 this_rd = INT_MAX;
1717                 disable_skip = 1;
1718             }
1719
1720             // Trap cases where the best split mode has all vectors coded 0,0 (or all the same)
1721             if (0)
1722             {
1723                 int allsame = 1;
1724
1725                 for (i = 1; i < 16; i++)
1726                 {
1727                     BLOCKD *bd = &x->e_mbd.block[i];
1728
1729                     if (bd->bmi.mv.as_int != x->e_mbd.block[0].bmi.mv.as_int)   //(bmvs[i].col != bmvs[i-1].col) || (bmvs[i].row != bmvs[i-1].row ) )
1730                     {
1731                         allsame = 0;
1732                         break;
1733                     }
1734                 }
1735
1736                 if (allsame)
1737                 {
1738                     // reset mode and mv and jump to newmv
1739                     this_mode = NEWMV;
1740                     distortion2 = 0;
1741                     rate2 = saved_rate;
1742                     mode_mv[NEWMV].row = x->e_mbd.block[0].bmi.mv.as_mv.row;
1743                     mode_mv[NEWMV].col = x->e_mbd.block[0].bmi.mv.as_mv.col;
1744                     rate2 += vp8_mv_bit_cost(&mode_mv[NEWMV], &best_ref_mv, x->mvcost, 96);
1745                     goto mv_selected;
1746                 }
1747             }
1748
1749             // trap cases where the 8x8s can be promoted to 8x16s or 16x8s
1750             if (0)//x->e_mbd.mbmi.partition_count == 4)
1751             {
1752
1753                 if (x->e_mbd.mbmi.partition_bmi[0].mv.as_int == x->e_mbd.mbmi.partition_bmi[1].mv.as_int
1754                     && x->e_mbd.mbmi.partition_bmi[2].mv.as_int == x->e_mbd.mbmi.partition_bmi[3].mv.as_int)
1755                 {
1756                     const int *labels = vp8_mbsplits[2];
1757                     x->e_mbd.mbmi.partitioning = 0;
1758                     rate -= vp8_cost_token(vp8_mbsplit_tree, vp8_mbsplit_probs, vp8_mbsplit_encodings + 2);
1759                     rate += vp8_cost_token(vp8_mbsplit_tree, vp8_mbsplit_probs, vp8_mbsplit_encodings);
1760                     //rate -=  x->inter_bmode_costs[  x->e_mbd.mbmi.partition_bmi[1]];
1761                     //rate -=  x->inter_bmode_costs[  x->e_mbd.mbmi.partition_bmi[3]];
1762                     x->e_mbd.mbmi.partition_bmi[1] = x->e_mbd.mbmi.partition_bmi[2];
1763                 }
1764             }
1765
1766         }
1767         break;
1768         case DC_PRED:
1769         case V_PRED:
1770         case H_PRED:
1771         case TM_PRED:
1772             x->e_mbd.mbmi.ref_frame = INTRA_FRAME;
1773             vp8_build_intra_predictors_mby_ptr(&x->e_mbd);
1774             {
1775                 macro_block_yrd(x, &rate, &distortion, IF_RTCD(&cpi->rtcd.encodemb)) ;
1776                 rate2 += rate;
1777                 rate_y = rate;
1778                 distortion2 += distortion;
1779                 rate2 += x->mbmode_cost[x->e_mbd.frame_type][x->e_mbd.mbmi.mode];
1780                 rate2 += uv_intra_rate;
1781                 rate_uv = uv_intra_rate_tokenonly;
1782                 distortion2 += uv_intra_distortion;
1783             }
1784             break;
1785
1786         case NEWMV:
1787
1788             // Decrement full search counter
1789             if (cpi->check_freq[lf_or_gf] > 0)
1790                 cpi->check_freq[lf_or_gf] --;
1791
1792             {
1793                 int thissme;
1794                 int bestsme = INT_MAX;
1795                 int step_param = cpi->sf.first_step;
1796                 int search_range;
1797                 int further_steps;
1798                 int n;
1799
1800                 // Work out how long a search we should do
1801                 search_range = MAXF(abs(best_ref_mv.col), abs(best_ref_mv.row)) >> 3;
1802
1803                 if (search_range >= x->vector_range)
1804                     x->vector_range = search_range;
1805                 else if (x->vector_range > cpi->sf.min_fs_radius)
1806                     x->vector_range--;
1807
1808                 // Initial step/diamond search
1809                 {
1810                     int sadpb = x->sadperbit16;
1811
1812                     if (cpi->sf.search_method == HEX)
1813                     {
1814                         bestsme = vp8_hex_search(x, b, d, &best_ref_mv, &d->bmi.mv.as_mv, step_param, sadpb/*x->errorperbit*/, &num00, cpi->fn_ptr.vf, cpi->fn_ptr.sdf, x->mvsadcost, x->mvcost);
1815                         mode_mv[NEWMV].row = d->bmi.mv.as_mv.row;
1816                         mode_mv[NEWMV].col = d->bmi.mv.as_mv.col;
1817                     }
1818                     else
1819                     {
1820                         bestsme = cpi->diamond_search_sad(x, b, d, &best_ref_mv, &d->bmi.mv.as_mv, step_param, sadpb / 2/*x->errorperbit*/, &num00, &cpi->fn_ptr, x->mvsadcost, x->mvcost); //sadpb < 9
1821                         mode_mv[NEWMV].row = d->bmi.mv.as_mv.row;
1822                         mode_mv[NEWMV].col = d->bmi.mv.as_mv.col;
1823
1824                         // Further step/diamond searches as necessary
1825                         n = 0;
1826                         further_steps = (cpi->sf.max_step_search_steps - 1) - step_param;
1827
1828                         n = num00;
1829                         num00 = 0;
1830
1831                         while (n < further_steps)
1832                         {
1833                             n++;
1834
1835                             if (num00)
1836                                 num00--;
1837                             else
1838                             {
1839                                 thissme = cpi->diamond_search_sad(x, b, d, &best_ref_mv, &d->bmi.mv.as_mv, step_param + n, sadpb / 4/*x->errorperbit*/, &num00, &cpi->fn_ptr, x->mvsadcost, x->mvcost); //sadpb = 9
1840
1841                                 if (thissme < bestsme)
1842                                 {
1843                                     bestsme = thissme;
1844                                     mode_mv[NEWMV].row = d->bmi.mv.as_mv.row;
1845                                     mode_mv[NEWMV].col = d->bmi.mv.as_mv.col;
1846                                 }
1847                                 else
1848                                 {
1849                                     d->bmi.mv.as_mv.row = mode_mv[NEWMV].row;
1850                                     d->bmi.mv.as_mv.col = mode_mv[NEWMV].col;
1851                                 }
1852                             }
1853                         }
1854                     }
1855
1856                 }
1857
1858                 // Should we do a full search
1859                 if (!cpi->check_freq[lf_or_gf] || cpi->do_full[lf_or_gf])
1860                 {
1861                     int thissme;
1862                     int full_flag_thresh = 0;
1863
1864                     // Update x->vector_range based on best vector found in step search
1865                     search_range = MAXF(abs(d->bmi.mv.as_mv.row), abs(d->bmi.mv.as_mv.col));
1866
1867                     if (search_range > x->vector_range)
1868                         x->vector_range = search_range;
1869                     else
1870                         search_range = x->vector_range;
1871
1872                     // Apply limits
1873                     search_range = (search_range > cpi->sf.max_fs_radius) ? cpi->sf.max_fs_radius : search_range;
1874                     {
1875                         int sadpb = x->sadperbit16 >> 2;
1876                         thissme = cpi->full_search_sad(x, b, d, &best_ref_mv, sadpb, search_range, &cpi->fn_ptr, x->mvcost, x->mvsadcost);
1877                     }
1878
1879                     // Barrier threshold to initiating full search
1880                     // full_flag_thresh = 10 + (thissme >> 7);
1881                     if ((thissme + full_flag_thresh) < bestsme)
1882                     {
1883                         cpi->do_full[lf_or_gf] ++;
1884                         bestsme = thissme;
1885                     }
1886                     else if (thissme < bestsme)
1887                         bestsme = thissme;
1888                     else
1889                     {
1890                         cpi->do_full[lf_or_gf] = cpi->do_full[lf_or_gf] >> 1;
1891                         cpi->check_freq[lf_or_gf] = cpi->sf.full_freq[lf_or_gf];
1892
1893                         // The full search result is actually worse so re-instate the previous best vector
1894                         d->bmi.mv.as_mv.row = mode_mv[NEWMV].row;
1895                         d->bmi.mv.as_mv.col = mode_mv[NEWMV].col;
1896                     }
1897                 }
1898
1899                 if (bestsme < INT_MAX)
1900                     // cpi->find_fractional_mv_step(x,b,d,&d->bmi.mv.as_mv,&best_ref_mv,x->errorperbit/2,cpi->fn_ptr.svf,cpi->fn_ptr.vf,x->mvcost);  // normal mvc=11
1901                     cpi->find_fractional_mv_step(x, b, d, &d->bmi.mv.as_mv, &best_ref_mv, x->errorperbit / 4, cpi->fn_ptr.svf, cpi->fn_ptr.vf, x->mvcost);
1902
1903                 mode_mv[NEWMV].row = d->bmi.mv.as_mv.row;
1904                 mode_mv[NEWMV].col = d->bmi.mv.as_mv.col;
1905
1906                 // Add the new motion vector cost to our rolling cost variable
1907                 rate2 += vp8_mv_bit_cost(&mode_mv[NEWMV], &best_ref_mv, x->mvcost, 96);
1908
1909             }
1910
1911         case NEARESTMV:
1912         case NEARMV:
1913
1914             // Clip "next_nearest" so that it does not extend to far out of image
1915             if (mode_mv[this_mode].col < (xd->mb_to_left_edge - LEFT_TOP_MARGIN))
1916                 mode_mv[this_mode].col = xd->mb_to_left_edge - LEFT_TOP_MARGIN;
1917             else if (mode_mv[this_mode].col > xd->mb_to_right_edge + RIGHT_BOTTOM_MARGIN)
1918                 mode_mv[this_mode].col = xd->mb_to_right_edge + RIGHT_BOTTOM_MARGIN;
1919
1920             if (mode_mv[this_mode].row < (xd->mb_to_top_edge - LEFT_TOP_MARGIN))
1921                 mode_mv[this_mode].row = xd->mb_to_top_edge - LEFT_TOP_MARGIN;
1922             else if (mode_mv[this_mode].row > xd->mb_to_bottom_edge + RIGHT_BOTTOM_MARGIN)
1923                 mode_mv[this_mode].row = xd->mb_to_bottom_edge + RIGHT_BOTTOM_MARGIN;
1924
1925             // Do not bother proceeding if the vector (from newmv,nearest or near) is 0,0 as this should then be coded using the zeromv mode.
1926             if (((this_mode == NEARMV) || (this_mode == NEARESTMV)) &&
1927                 ((mode_mv[this_mode].row == 0) && (mode_mv[this_mode].col == 0)))
1928                 continue;
1929
1930         case ZEROMV:
1931
1932         mv_selected:
1933
1934             // Trap vectors that reach beyond the UMV borders
1935             // Note that ALL New MV, Nearest MV Near MV and Zero MV code drops through to this point
1936             // because of the lack of break statements in the previous two cases.
1937             if (((mode_mv[this_mode].row >> 3) < x->mv_row_min) || ((mode_mv[this_mode].row >> 3) > x->mv_row_max) ||
1938                 ((mode_mv[this_mode].col >> 3) < x->mv_col_min) || ((mode_mv[this_mode].col >> 3) > x->mv_col_max))
1939                 continue;
1940
1941             vp8_set_mbmode_and_mvs(x, this_mode, &mode_mv[this_mode]);
1942             vp8_build_inter_predictors_mby(&x->e_mbd);
1943             VARIANCE_INVOKE(&cpi->rtcd.variance, get16x16var)(x->src.y_buffer, x->src.y_stride, x->e_mbd.predictor, 16, (unsigned int *)(&sse), &sum);
1944
1945             if (cpi->active_map_enabled && x->active_ptr[0] == 0)
1946             {
1947                 x->skip = 1;
1948             }
1949             else if (sse < x->encode_breakout)
1950             {
1951                 // Check u and v to make sure skip is ok
1952                 int sse2 = 0;
1953
1954                 sse2 = VP8_UVSSE(x, IF_RTCD(&cpi->rtcd.variance));
1955
1956                 if (sse2 * 2 < x->encode_breakout)
1957                 {
1958                     x->skip = 1;
1959                     distortion2 = sse;
1960                     rate2 = 500;
1961
1962                     disable_skip = 1;    // We have no real rate data so trying to adjust for rate_y and rate_uv below will cause problems.
1963                     this_rd = RDFUNC(x->rdmult, x->rddiv, rate2, distortion2, cpi->target_bits_per_mb);
1964
1965                     break;              // (PGW) Move break here from below - for now at least
1966                 }
1967                 else
1968                     x->skip = 0;
1969             }
1970
1971             //intermodecost[mode_index] = vp8_cost_mv_ref(this_mode, mdcounts);   // Experimental debug code
1972
1973             // Add in the Mv/mode cost
1974             rate2 += vp8_cost_mv_ref(this_mode, mdcounts);
1975
1976             // Y cost and distortion
1977             macro_block_yrd(x, &rate, &distortion, IF_RTCD(&cpi->rtcd.encodemb));
1978             rate2 += rate;
1979             rate_y = rate;
1980             distortion2 += distortion;
1981
1982             // UV cost and distortion
1983             vp8_rd_inter_uv(cpi, x, &rate, &distortion, cpi->common.full_pixel);
1984             rate2 += rate;
1985             rate_uv = rate;
1986             distortion2 += distortion;
1987             break;
1988
1989         default:
1990             break;
1991         }
1992
1993         if (!disable_skip)
1994         {
1995             // Test for the condition where skip block will be activated because there are no non zero coefficients and make any necessary adjustment for rate
1996             if (cpi->common.mb_no_coeff_skip)
1997             {
1998                 tteob = 0;
1999
2000                 for (i = 0; i <= 24; i++)
2001                 {
2002                     tteob += x->e_mbd.block[i].eob;
2003                 }
2004
2005                 if (tteob == 0)
2006                 {
2007 #if 1
2008                     rate2 -= (rate_y + rate_uv);
2009
2010                     // Back out no skip flag costing and add in skip flag costing
2011                     if (cpi->prob_skip_false)
2012                     {
2013                         rate2 += vp8_cost_bit(cpi->prob_skip_false, 1);
2014                         rate2 -= vp8_cost_bit(cpi->prob_skip_false, 0);
2015                     }
2016
2017 #else
2018                     int rateuseskip;
2019                     int ratenotuseskip;
2020
2021
2022
2023                     ratenotuseskip = rate_y + rate_uv + vp8_cost_bit(cpi->prob_skip_false, 0);
2024                     rateuseskip    = vp8_cost_bit(cpi->prob_skip_false, 1);
2025
2026                     if (1) // rateuseskip<ratenotuseskip)
2027                     {
2028                         rate2 -= ratenotuseskip;
2029                         rate2 += rateuseskip;
2030                         force_no_skip = 0;
2031                     }
2032                     else
2033                     {
2034                         force_no_skip = 1;
2035                     }
2036
2037 #endif
2038                 }
2039
2040 #if             0
2041                 else
2042                 {
2043                     int rateuseskip;
2044                     int ratenotuseskip;
2045                     int maxdistortion;
2046                     int minrate;
2047                     int skip_rd;
2048
2049                     // distortion when no coeff is encoded
2050                     maxdistortion = macro_block_max_error(x);
2051
2052                     ratenotuseskip = rate_y + rate_uv + vp8_cost_bit(cpi->prob_skip_false, 0);
2053                     rateuseskip    = vp8_cost_bit(cpi->prob_skip_false, 1);
2054
2055                     minrate         = rateuseskip - ratenotuseskip;
2056
2057                     skip_rd = RDFUNC(x->rdmult, x->rddiv, minrate, maxdistortion - distortion2, cpi->target_bits_per_mb);
2058
2059                     if (skip_rd + 50 < 0 && x->e_mbd.mbmi.ref_frame != INTRA_FRAME && rate_y + rate_uv < 4000)
2060                     {
2061                         force_no_skip = 1;
2062                         rate2       = rate2 + rateuseskip - ratenotuseskip;
2063                         distortion2 =  maxdistortion;
2064                     }
2065                     else
2066                     {
2067                         force_no_skip = 0;
2068                     }
2069
2070                 }
2071
2072 #endif
2073
2074             }
2075
2076             // Calculate the final RD estimate for this mode
2077             this_rd = RDFUNC(x->rdmult, x->rddiv, rate2, distortion2, cpi->target_bits_per_mb);
2078         }
2079
2080         // Experimental debug code.
2081         //all_rds[mode_index] = this_rd;
2082         //all_rates[mode_index] = rate2;
2083         //all_dist[mode_index] = distortion2;
2084
2085         if ((x->e_mbd.mbmi.ref_frame == INTRA_FRAME)  && (this_rd < *returnintra))
2086         {
2087             *returnintra = this_rd ;
2088         }
2089
2090         // Did this mode help.. i.i is it the new best mode
2091         if (this_rd < best_rd || x->skip)
2092         {
2093             // Note index of best mode so far
2094             best_mode_index = mode_index;
2095             x->e_mbd.mbmi.force_no_skip = force_no_skip;
2096
2097             if (this_mode <= B_PRED)
2098             {
2099                 x->e_mbd.mbmi.uv_mode = uv_intra_mode;
2100             }
2101
2102             *returnrate = rate2;
2103             *returndistortion = distortion2;
2104             best_rd = this_rd;
2105             vpx_memcpy(&best_mbmode, &x->e_mbd.mbmi, sizeof(MB_MODE_INFO));
2106
2107             for (i = 0; i < 16; i++)
2108             {
2109                 vpx_memcpy(&best_bmodes[i], &x->e_mbd.block[i].bmi, sizeof(B_MODE_INFO));
2110             }
2111
2112             // Testing this mode gave rise to an improvement in best error score. Lower threshold a bit for next time
2113             cpi->rd_thresh_mult[mode_index] = (cpi->rd_thresh_mult[mode_index] >= (MIN_THRESHMULT + 2)) ? cpi->rd_thresh_mult[mode_index] - 2 : MIN_THRESHMULT;
2114             cpi->rd_threshes[mode_index] = (cpi->rd_baseline_thresh[mode_index] >> 7) * cpi->rd_thresh_mult[mode_index];
2115         }
2116
2117         // If the mode did not help improve the best error case then raise the threshold for testing that mode next time around.
2118         else
2119         {
2120             cpi->rd_thresh_mult[mode_index] += 4;
2121
2122             if (cpi->rd_thresh_mult[mode_index] > MAX_THRESHMULT)
2123                 cpi->rd_thresh_mult[mode_index] = MAX_THRESHMULT;
2124
2125             cpi->rd_threshes[mode_index] = (cpi->rd_baseline_thresh[mode_index] >> 7) * cpi->rd_thresh_mult[mode_index];
2126         }
2127
2128         if (x->skip)
2129             break;
2130     }
2131
2132     // Reduce the activation RD thresholds for the best choice mode
2133     if ((cpi->rd_baseline_thresh[best_mode_index] > 0) && (cpi->rd_baseline_thresh[best_mode_index] < (INT_MAX >> 2)))
2134     {
2135         int best_adjustment = (cpi->rd_thresh_mult[best_mode_index] >> 2);
2136
2137         cpi->rd_thresh_mult[best_mode_index] = (cpi->rd_thresh_mult[best_mode_index] >= (MIN_THRESHMULT + best_adjustment)) ? cpi->rd_thresh_mult[best_mode_index] - best_adjustment : MIN_THRESHMULT;
2138         cpi->rd_threshes[best_mode_index] = (cpi->rd_baseline_thresh[best_mode_index] >> 7) * cpi->rd_thresh_mult[best_mode_index];
2139
2140         // If we chose a split mode then reset the new MV thresholds as well
2141         /*if ( vp8_mode_order[best_mode_index] == SPLITMV )
2142         {
2143             best_adjustment = 4; //(cpi->rd_thresh_mult[THR_NEWMV] >> 4);
2144             cpi->rd_thresh_mult[THR_NEWMV] = (cpi->rd_thresh_mult[THR_NEWMV] >= (MIN_THRESHMULT+best_adjustment)) ? cpi->rd_thresh_mult[THR_NEWMV]-best_adjustment: MIN_THRESHMULT;
2145             cpi->rd_threshes[THR_NEWMV] = (cpi->rd_baseline_thresh[THR_NEWMV] >> 7) * cpi->rd_thresh_mult[THR_NEWMV];
2146
2147             best_adjustment = 4; //(cpi->rd_thresh_mult[THR_NEWG] >> 4);
2148             cpi->rd_thresh_mult[THR_NEWG] = (cpi->rd_thresh_mult[THR_NEWG] >= (MIN_THRESHMULT+best_adjustment)) ? cpi->rd_thresh_mult[THR_NEWG]-best_adjustment: MIN_THRESHMULT;
2149             cpi->rd_threshes[THR_NEWG] = (cpi->rd_baseline_thresh[THR_NEWG] >> 7) * cpi->rd_thresh_mult[THR_NEWG];
2150
2151             best_adjustment = 4; //(cpi->rd_thresh_mult[THR_NEWA] >> 4);
2152             cpi->rd_thresh_mult[THR_NEWA] = (cpi->rd_thresh_mult[THR_NEWA] >= (MIN_THRESHMULT+best_adjustment)) ? cpi->rd_thresh_mult[THR_NEWA]-best_adjustment: MIN_THRESHMULT;
2153             cpi->rd_threshes[THR_NEWA] = (cpi->rd_baseline_thresh[THR_NEWA] >> 7) * cpi->rd_thresh_mult[THR_NEWA];
2154         }*/
2155
2156     }
2157
2158     // If we have chosen new mv or split then decay the full search check count more quickly.
2159     if ((vp8_mode_order[best_mode_index] == NEWMV) || (vp8_mode_order[best_mode_index] == SPLITMV))
2160     {
2161         int lf_or_gf = (vp8_ref_frame_order[best_mode_index] == LAST_FRAME) ? 0 : 1;
2162
2163         if (cpi->check_freq[lf_or_gf] && !cpi->do_full[lf_or_gf])
2164         {
2165             cpi->check_freq[lf_or_gf] --;
2166         }
2167     }
2168
2169     // Keep a record of best mode index that we chose
2170     cpi->last_best_mode_index = best_mode_index;
2171
2172     // Note how often each mode chosen as best
2173     cpi->mode_chosen_counts[best_mode_index] ++;
2174
2175
2176     if (cpi->is_src_frame_alt_ref && (best_mbmode.mode != ZEROMV || best_mbmode.ref_frame != ALTREF_FRAME))
2177     {
2178         best_mbmode.mode = ZEROMV;
2179         best_mbmode.ref_frame = ALTREF_FRAME;
2180         best_mbmode.mv.as_int = 0;
2181         best_mbmode.uv_mode = 0;
2182         best_mbmode.mb_skip_coeff = (cpi->common.mb_no_coeff_skip) ? 1 : 0;
2183         best_mbmode.partitioning = 0;
2184         best_mbmode.dc_diff = 0;
2185
2186         vpx_memcpy(&x->e_mbd.mbmi, &best_mbmode, sizeof(MB_MODE_INFO));
2187
2188         for (i = 0; i < 16; i++)
2189         {
2190             vpx_memset(&x->e_mbd.block[i].bmi, 0, sizeof(B_MODE_INFO));
2191         }
2192
2193         x->e_mbd.mbmi.mv.as_int = 0;
2194
2195         return best_rd;
2196     }
2197
2198
2199     // macroblock modes
2200     vpx_memcpy(&x->e_mbd.mbmi, &best_mbmode, sizeof(MB_MODE_INFO));
2201
2202     for (i = 0; i < 16; i++)
2203     {
2204         vpx_memcpy(&x->e_mbd.block[i].bmi, &best_bmodes[i], sizeof(B_MODE_INFO));
2205     }
2206
2207     x->e_mbd.mbmi.mv.as_mv = x->e_mbd.block[15].bmi.mv.as_mv;
2208
2209     return best_rd;
2210 }
2211 #endif
2212