666948060f962b3287aa6dd1d5f754db1b8a8119
[profile/ivi/libvpx.git] / vp8 / encoder / pickinter.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 <limits.h>
13 #include "vpx_ports/config.h"
14 #include "onyx_int.h"
15 #include "modecosts.h"
16 #include "encodeintra.h"
17 #include "vp8/common/entropymode.h"
18 #include "pickinter.h"
19 #include "vp8/common/findnearmv.h"
20 #include "encodemb.h"
21 #include "vp8/common/reconinter.h"
22 #include "vp8/common/reconintra.h"
23 #include "vp8/common/reconintra4x4.h"
24 #include "vp8/common/g_common.h"
25 #include "variance.h"
26 #include "mcomp.h"
27 #include "rdopt.h"
28 #include "vpx_mem/vpx_mem.h"
29
30 #if CONFIG_RUNTIME_CPU_DETECT
31 #define IF_RTCD(x) (x)
32 #else
33 #define IF_RTCD(x)  NULL
34 #endif
35
36 extern int VP8_UVSSE(MACROBLOCK *x, const vp8_variance_rtcd_vtable_t *rtcd);
37
38 #ifdef SPEEDSTATS
39 extern unsigned int cnt_pm;
40 #endif
41
42 extern const MV_REFERENCE_FRAME vp8_ref_frame_order[MAX_MODES];
43 extern const MB_PREDICTION_MODE vp8_mode_order[MAX_MODES];
44
45
46 extern unsigned int (*vp8_get16x16pred_error)(unsigned char *src_ptr, int src_stride, unsigned char *ref_ptr, int ref_stride);
47 extern unsigned int (*vp8_get4x4sse_cs)(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride);
48 extern int vp8_rd_pick_best_mbsegmentation(VP8_COMP *cpi, MACROBLOCK *x, MV *best_ref_mv, int best_rd, int *, int *, int *, int, int *mvcost[2], int, int fullpixel);
49 extern int vp8_cost_mv_ref(MB_PREDICTION_MODE m, const int near_mv_ref_ct[4]);
50 extern void vp8_set_mbmode_and_mvs(MACROBLOCK *x, MB_PREDICTION_MODE mb, int_mv *mv);
51
52
53 int vp8_skip_fractional_mv_step(MACROBLOCK *mb, BLOCK *b, BLOCKD *d,
54                                 int_mv *bestmv, int_mv *ref_mv,
55                                 int error_per_bit,
56                                 const vp8_variance_fn_ptr_t *vfp,
57                                 int *mvcost[2], int *distortion,
58                                 unsigned int *sse)
59 {
60     (void) b;
61     (void) d;
62     (void) ref_mv;
63     (void) error_per_bit;
64     (void) vfp;
65     (void) mvcost;
66     (void) distortion;
67     (void) sse;
68     bestmv->as_mv.row <<= 3;
69     bestmv->as_mv.col <<= 3;
70     return 0;
71 }
72
73
74 static int get_inter_mbpred_error(MACROBLOCK *mb, const vp8_variance_fn_ptr_t *vfp, unsigned int *sse)
75 {
76
77     BLOCK *b = &mb->block[0];
78     BLOCKD *d = &mb->e_mbd.block[0];
79     unsigned char *what = (*(b->base_src) + b->src);
80     int what_stride = b->src_stride;
81     unsigned char *in_what = *(d->base_pre) + d->pre ;
82     int in_what_stride = d->pre_stride;
83     int xoffset = d->bmi.mv.as_mv.col & 7;
84     int yoffset = d->bmi.mv.as_mv.row & 7;
85
86     in_what += (d->bmi.mv.as_mv.row >> 3) * d->pre_stride + (d->bmi.mv.as_mv.col >> 3);
87
88     if (xoffset | yoffset)
89     {
90         return vfp->svf(in_what, in_what_stride, xoffset, yoffset, what, what_stride, sse);
91     }
92     else
93     {
94         return vfp->vf(what, what_stride, in_what, in_what_stride, sse);
95     }
96
97 }
98
99 unsigned int vp8_get16x16pred_error_c
100 (
101     const unsigned char *src_ptr,
102     int src_stride,
103     const unsigned char *ref_ptr,
104     int ref_stride,
105     int max_sad
106 )
107 {
108     unsigned pred_error = 0;
109     int i, j;
110     int sum = 0;
111
112     for (i = 0; i < 16; i++)
113     {
114         int diff;
115
116         for (j = 0; j < 16; j++)
117         {
118             diff = src_ptr[j] - ref_ptr[j];
119             sum += diff;
120             pred_error += diff * diff;
121         }
122
123         src_ptr += src_stride;
124         ref_ptr += ref_stride;
125     }
126
127     pred_error -= sum * sum / 256;
128     return pred_error;
129 }
130
131
132 unsigned int vp8_get4x4sse_cs_c
133 (
134     const unsigned char *src_ptr,
135     int  source_stride,
136     const unsigned char *ref_ptr,
137     int  recon_stride,
138     int max_sad
139 )
140 {
141     int distortion = 0;
142     int r, c;
143
144     for (r = 0; r < 4; r++)
145     {
146         for (c = 0; c < 4; c++)
147         {
148             int diff = src_ptr[c] - ref_ptr[c];
149             distortion += diff * diff;
150         }
151
152         src_ptr += source_stride;
153         ref_ptr += recon_stride;
154     }
155
156     return distortion;
157 }
158
159 static int get_prediction_error(BLOCK *be, BLOCKD *b, const vp8_variance_rtcd_vtable_t *rtcd)
160 {
161     unsigned char *sptr;
162     unsigned char *dptr;
163     sptr = (*(be->base_src) + be->src);
164     dptr = b->predictor;
165
166     return VARIANCE_INVOKE(rtcd, get4x4sse_cs)(sptr, be->src_stride, dptr, 16, 0x7fffffff);
167
168 }
169
170 static int pick_intra4x4block(
171     const VP8_ENCODER_RTCD *rtcd,
172     MACROBLOCK *x,
173     int ib,
174     B_PREDICTION_MODE *best_mode,
175     B_PREDICTION_MODE above,
176     B_PREDICTION_MODE left,
177
178     int *bestrate,
179     int *bestdistortion)
180 {
181
182     BLOCKD *b = &x->e_mbd.block[ib];
183     BLOCK *be = &x->block[ib];
184     B_PREDICTION_MODE mode;
185     int best_rd = INT_MAX;       // 1<<30
186     int rate;
187     int distortion;
188     unsigned int *mode_costs;
189
190     if (x->e_mbd.frame_type == KEY_FRAME)
191     {
192         mode_costs = x->bmode_costs[above][left];
193     }
194     else
195     {
196         mode_costs = x->inter_bmode_costs;
197     }
198
199     for (mode = B_DC_PRED; mode <= B_HE_PRED /*B_HU_PRED*/; mode++)
200     {
201         int this_rd;
202
203         rate = mode_costs[mode];
204         RECON_INVOKE(&rtcd->common->recon, intra4x4_predict)
205                      (b, mode, b->predictor);
206         distortion = get_prediction_error(be, b, &rtcd->variance);
207         this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
208
209         if (this_rd < best_rd)
210         {
211             *bestrate = rate;
212             *bestdistortion = distortion;
213             best_rd = this_rd;
214             *best_mode = mode;
215         }
216     }
217     b->bmi.mode = (B_PREDICTION_MODE)(*best_mode);
218     vp8_encode_intra4x4block(rtcd, x, ib);
219     return best_rd;
220 }
221
222
223 int vp8_pick_intra4x4mby_modes
224 (
225     const VP8_ENCODER_RTCD *rtcd,
226     MACROBLOCK *mb,
227     int *Rate,
228     int *best_dist
229 )
230 {
231     MACROBLOCKD *const xd = &mb->e_mbd;
232     int i;
233     int cost = mb->mbmode_cost [xd->frame_type] [B_PRED];
234     int error;
235     int distortion = 0;
236
237     vp8_intra_prediction_down_copy(xd);
238
239     for (i = 0; i < 16; i++)
240     {
241         MODE_INFO *const mic = xd->mode_info_context;
242         const int mis = xd->mode_info_stride;
243         const B_PREDICTION_MODE A = above_block_mode(mic, i, mis);
244         const B_PREDICTION_MODE L = left_block_mode(mic, i);
245
246         B_PREDICTION_MODE UNINITIALIZED_IS_SAFE(best_mode);
247         int UNINITIALIZED_IS_SAFE(r), UNINITIALIZED_IS_SAFE(d);
248
249         pick_intra4x4block(rtcd, mb, i, &best_mode, A, L, &r, &d);
250
251         cost += r;
252         distortion += d;
253         mic->bmi[i].as_mode = xd->block[i].bmi.mode = best_mode;
254
255         // Break out case where we have already exceeded best so far value
256         // that was passed in
257         if (distortion > *best_dist)
258             break;
259     }
260
261     *Rate = cost;
262
263     if (i == 16)
264     {
265         *best_dist = distortion;
266         error = RDCOST(mb->rdmult, mb->rddiv, cost, distortion);
267     }
268     else
269     {
270         *best_dist = INT_MAX;
271         error = INT_MAX;
272     }
273
274     return error;
275 }
276
277 void vp8_pick_intra_mbuv_mode(MACROBLOCK *mb)
278 {
279
280     MACROBLOCKD *x = &mb->e_mbd;
281     unsigned char *uabove_row = x->dst.u_buffer - x->dst.uv_stride;
282     unsigned char *vabove_row = x->dst.v_buffer - x->dst.uv_stride;
283     unsigned char *usrc_ptr = (mb->block[16].src + *mb->block[16].base_src);
284     unsigned char *vsrc_ptr = (mb->block[20].src + *mb->block[20].base_src);
285     int uvsrc_stride = mb->block[16].src_stride;
286     unsigned char uleft_col[8];
287     unsigned char vleft_col[8];
288     unsigned char utop_left = uabove_row[-1];
289     unsigned char vtop_left = vabove_row[-1];
290     int i, j;
291     int expected_udc;
292     int expected_vdc;
293     int shift;
294     int Uaverage = 0;
295     int Vaverage = 0;
296     int diff;
297     int pred_error[4] = {0, 0, 0, 0}, best_error = INT_MAX;
298     MB_PREDICTION_MODE UNINITIALIZED_IS_SAFE(best_mode);
299
300
301     for (i = 0; i < 8; i++)
302     {
303         uleft_col[i] = x->dst.u_buffer [i* x->dst.uv_stride -1];
304         vleft_col[i] = x->dst.v_buffer [i* x->dst.uv_stride -1];
305     }
306
307     if (!x->up_available && !x->left_available)
308     {
309         expected_udc = 128;
310         expected_vdc = 128;
311     }
312     else
313     {
314         shift = 2;
315
316         if (x->up_available)
317         {
318
319             for (i = 0; i < 8; i++)
320             {
321                 Uaverage += uabove_row[i];
322                 Vaverage += vabove_row[i];
323             }
324
325             shift ++;
326
327         }
328
329         if (x->left_available)
330         {
331             for (i = 0; i < 8; i++)
332             {
333                 Uaverage += uleft_col[i];
334                 Vaverage += vleft_col[i];
335             }
336
337             shift ++;
338
339         }
340
341         expected_udc = (Uaverage + (1 << (shift - 1))) >> shift;
342         expected_vdc = (Vaverage + (1 << (shift - 1))) >> shift;
343     }
344
345
346     for (i = 0; i < 8; i++)
347     {
348         for (j = 0; j < 8; j++)
349         {
350
351             int predu = uleft_col[i] + uabove_row[j] - utop_left;
352             int predv = vleft_col[i] + vabove_row[j] - vtop_left;
353             int u_p, v_p;
354
355             u_p = usrc_ptr[j];
356             v_p = vsrc_ptr[j];
357
358             if (predu < 0)
359                 predu = 0;
360
361             if (predu > 255)
362                 predu = 255;
363
364             if (predv < 0)
365                 predv = 0;
366
367             if (predv > 255)
368                 predv = 255;
369
370
371             diff = u_p - expected_udc;
372             pred_error[DC_PRED] += diff * diff;
373             diff = v_p - expected_vdc;
374             pred_error[DC_PRED] += diff * diff;
375
376
377             diff = u_p - uabove_row[j];
378             pred_error[V_PRED] += diff * diff;
379             diff = v_p - vabove_row[j];
380             pred_error[V_PRED] += diff * diff;
381
382
383             diff = u_p - uleft_col[i];
384             pred_error[H_PRED] += diff * diff;
385             diff = v_p - vleft_col[i];
386             pred_error[H_PRED] += diff * diff;
387
388
389             diff = u_p - predu;
390             pred_error[TM_PRED] += diff * diff;
391             diff = v_p - predv;
392             pred_error[TM_PRED] += diff * diff;
393
394
395         }
396
397         usrc_ptr += uvsrc_stride;
398         vsrc_ptr += uvsrc_stride;
399
400         if (i == 3)
401         {
402             usrc_ptr = (mb->block[18].src + *mb->block[18].base_src);
403             vsrc_ptr = (mb->block[22].src + *mb->block[22].base_src);
404         }
405
406
407
408     }
409
410
411     for (i = DC_PRED; i <= TM_PRED; i++)
412     {
413         if (best_error > pred_error[i])
414         {
415             best_error = pred_error[i];
416             best_mode = (MB_PREDICTION_MODE)i;
417         }
418     }
419
420
421     mb->e_mbd.mode_info_context->mbmi.uv_mode = best_mode;
422
423 }
424
425 static void update_mvcount(VP8_COMP *cpi, MACROBLOCKD *xd, int_mv *best_ref_mv)
426 {
427     /* Split MV modes currently not supported when RD is nopt enabled,
428      * therefore, only need to modify MVcount in NEWMV mode. */
429     if (xd->mode_info_context->mbmi.mode == NEWMV)
430     {
431         cpi->MVcount[0][mv_max+((xd->mode_info_context->mbmi.mv.as_mv.row -
432                                       best_ref_mv->as_mv.row) >> 1)]++;
433         cpi->MVcount[1][mv_max+((xd->mode_info_context->mbmi.mv.as_mv.col -
434                                       best_ref_mv->as_mv.col) >> 1)]++;
435     }
436 }
437
438 void vp8_pick_inter_mode(VP8_COMP *cpi, MACROBLOCK *x, int recon_yoffset,
439                          int recon_uvoffset, int *returnrate,
440                          int *returndistortion, int *returnintra)
441 {
442     BLOCK *b = &x->block[0];
443     BLOCKD *d = &x->e_mbd.block[0];
444     MACROBLOCKD *xd = &x->e_mbd;
445     B_MODE_INFO best_bmodes[16];
446     MB_MODE_INFO best_mbmode;
447
448     int_mv best_ref_mv;
449     int_mv mode_mv[MB_MODE_COUNT];
450     MB_PREDICTION_MODE this_mode;
451     int num00;
452     int i;
453     int mdcounts[4];
454     int best_rd = INT_MAX; // 1 << 30;
455     int best_intra_rd = INT_MAX;
456     int mode_index;
457     int ref_frame_cost[MAX_REF_FRAMES];
458     int rate;
459     int rate2;
460     int distortion2;
461     int bestsme;
462     //int all_rds[MAX_MODES];         // Experimental debug code.
463     int best_mode_index = 0;
464     unsigned int sse = INT_MAX;
465
466     int_mv mvp;
467     int near_sadidx[8] = {0, 1, 2, 3, 4, 5, 6, 7};
468     int saddone=0;
469     int sr=0;    //search range got from mv_pred(). It uses step_param levels. (0-7)
470
471     int_mv nearest_mv[4];
472     int_mv near_mv[4];
473     int_mv frame_best_ref_mv[4];
474     int MDCounts[4][4];
475     unsigned char *y_buffer[4];
476     unsigned char *u_buffer[4];
477     unsigned char *v_buffer[4];
478
479     int skip_mode[4] = {0, 0, 0, 0};
480
481     int have_subp_search = cpi->sf.half_pixel_search;  /* In real-time mode, when Speed >= 15, no sub-pixel search. */
482
483     vpx_memset(mode_mv, 0, sizeof(mode_mv));
484     vpx_memset(nearest_mv, 0, sizeof(nearest_mv));
485     vpx_memset(near_mv, 0, sizeof(near_mv));
486     vpx_memset(&best_mbmode, 0, sizeof(best_mbmode));
487
488
489     // set up all the refframe dependent pointers.
490     if (cpi->ref_frame_flags & VP8_LAST_FLAG)
491     {
492         YV12_BUFFER_CONFIG *lst_yv12 = &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
493
494         vp8_find_near_mvs(&x->e_mbd, x->e_mbd.mode_info_context, &nearest_mv[LAST_FRAME], &near_mv[LAST_FRAME],
495                           &frame_best_ref_mv[LAST_FRAME], MDCounts[LAST_FRAME], LAST_FRAME, cpi->common.ref_frame_sign_bias);
496
497         y_buffer[LAST_FRAME] = lst_yv12->y_buffer + recon_yoffset;
498         u_buffer[LAST_FRAME] = lst_yv12->u_buffer + recon_uvoffset;
499         v_buffer[LAST_FRAME] = lst_yv12->v_buffer + recon_uvoffset;
500     }
501     else
502         skip_mode[LAST_FRAME] = 1;
503
504     if (cpi->ref_frame_flags & VP8_GOLD_FLAG)
505     {
506         YV12_BUFFER_CONFIG *gld_yv12 = &cpi->common.yv12_fb[cpi->common.gld_fb_idx];
507
508         vp8_find_near_mvs(&x->e_mbd, x->e_mbd.mode_info_context, &nearest_mv[GOLDEN_FRAME], &near_mv[GOLDEN_FRAME],
509                           &frame_best_ref_mv[GOLDEN_FRAME], MDCounts[GOLDEN_FRAME], GOLDEN_FRAME, cpi->common.ref_frame_sign_bias);
510
511         y_buffer[GOLDEN_FRAME] = gld_yv12->y_buffer + recon_yoffset;
512         u_buffer[GOLDEN_FRAME] = gld_yv12->u_buffer + recon_uvoffset;
513         v_buffer[GOLDEN_FRAME] = gld_yv12->v_buffer + recon_uvoffset;
514     }
515     else
516         skip_mode[GOLDEN_FRAME] = 1;
517
518     if (cpi->ref_frame_flags & VP8_ALT_FLAG && cpi->source_alt_ref_active)
519     {
520         YV12_BUFFER_CONFIG *alt_yv12 = &cpi->common.yv12_fb[cpi->common.alt_fb_idx];
521
522         vp8_find_near_mvs(&x->e_mbd, x->e_mbd.mode_info_context, &nearest_mv[ALTREF_FRAME], &near_mv[ALTREF_FRAME],
523                           &frame_best_ref_mv[ALTREF_FRAME], MDCounts[ALTREF_FRAME], ALTREF_FRAME, cpi->common.ref_frame_sign_bias);
524
525         y_buffer[ALTREF_FRAME] = alt_yv12->y_buffer + recon_yoffset;
526         u_buffer[ALTREF_FRAME] = alt_yv12->u_buffer + recon_uvoffset;
527         v_buffer[ALTREF_FRAME] = alt_yv12->v_buffer + recon_uvoffset;
528     }
529     else
530         skip_mode[ALTREF_FRAME] = 1;
531
532     cpi->mbs_tested_so_far++;          // Count of the number of MBs tested so far this frame
533
534     *returnintra = INT_MAX;
535     x->skip = 0;
536
537     ref_frame_cost[INTRA_FRAME]   = vp8_cost_zero(cpi->prob_intra_coded);
538
539     // Special case treatment when GF and ARF are not sensible options for reference
540     if (cpi->ref_frame_flags == VP8_LAST_FLAG)
541     {
542         ref_frame_cost[LAST_FRAME]    = vp8_cost_one(cpi->prob_intra_coded)
543                                         + vp8_cost_zero(255);
544         ref_frame_cost[GOLDEN_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
545                                         + vp8_cost_one(255)
546                                         + vp8_cost_zero(128);
547         ref_frame_cost[ALTREF_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
548                                         + vp8_cost_one(255)
549                                         + vp8_cost_one(128);
550     }
551     else
552     {
553         ref_frame_cost[LAST_FRAME]    = vp8_cost_one(cpi->prob_intra_coded)
554                                         + vp8_cost_zero(cpi->prob_last_coded);
555         ref_frame_cost[GOLDEN_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
556                                         + vp8_cost_one(cpi->prob_last_coded)
557                                         + vp8_cost_zero(cpi->prob_gf_coded);
558         ref_frame_cost[ALTREF_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
559                                         + vp8_cost_one(cpi->prob_last_coded)
560                                         + vp8_cost_one(cpi->prob_gf_coded);
561     }
562
563     x->e_mbd.mode_info_context->mbmi.ref_frame = INTRA_FRAME;
564
565     // if we encode a new mv this is important
566     // find the best new motion vector
567     for (mode_index = 0; mode_index < MAX_MODES; mode_index++)
568     {
569         int frame_cost;
570         int this_rd = INT_MAX;
571
572         if (best_rd <= cpi->rd_threshes[mode_index])
573             continue;
574
575         x->e_mbd.mode_info_context->mbmi.ref_frame = vp8_ref_frame_order[mode_index];
576
577         if (skip_mode[x->e_mbd.mode_info_context->mbmi.ref_frame])
578             continue;
579
580         // Check to see if the testing frequency for this mode is at its max
581         // If so then prevent it from being tested and increase the threshold for its testing
582         if (cpi->mode_test_hit_counts[mode_index] && (cpi->mode_check_freq[mode_index] > 1))
583         {
584             //if ( (cpi->mbs_tested_so_far / cpi->mode_test_hit_counts[mode_index]) <= cpi->mode_check_freq[mode_index] )
585             if (cpi->mbs_tested_so_far <= (cpi->mode_check_freq[mode_index] * cpi->mode_test_hit_counts[mode_index]))
586             {
587                 // Increase the threshold for coding this mode to make it less likely to be chosen
588                 cpi->rd_thresh_mult[mode_index] += 4;
589
590                 if (cpi->rd_thresh_mult[mode_index] > MAX_THRESHMULT)
591                     cpi->rd_thresh_mult[mode_index] = MAX_THRESHMULT;
592
593                 cpi->rd_threshes[mode_index] = (cpi->rd_baseline_thresh[mode_index] >> 7) * cpi->rd_thresh_mult[mode_index];
594
595                 continue;
596             }
597         }
598
599         // 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
600         cpi->mode_test_hit_counts[mode_index] ++;
601
602         rate2 = 0;
603         distortion2 = 0;
604
605         this_mode = vp8_mode_order[mode_index];
606
607         // Experimental debug code.
608         //all_rds[mode_index] = -1;
609
610         x->e_mbd.mode_info_context->mbmi.mode = this_mode;
611         x->e_mbd.mode_info_context->mbmi.uv_mode = DC_PRED;
612
613         // Work out the cost assosciated with selecting the reference frame
614         frame_cost = ref_frame_cost[x->e_mbd.mode_info_context->mbmi.ref_frame];
615         rate2 += frame_cost;
616
617         // everything but intra
618         if (x->e_mbd.mode_info_context->mbmi.ref_frame)
619         {
620             x->e_mbd.pre.y_buffer = y_buffer[x->e_mbd.mode_info_context->mbmi.ref_frame];
621             x->e_mbd.pre.u_buffer = u_buffer[x->e_mbd.mode_info_context->mbmi.ref_frame];
622             x->e_mbd.pre.v_buffer = v_buffer[x->e_mbd.mode_info_context->mbmi.ref_frame];
623             mode_mv[NEARESTMV] = nearest_mv[x->e_mbd.mode_info_context->mbmi.ref_frame];
624             mode_mv[NEARMV] = near_mv[x->e_mbd.mode_info_context->mbmi.ref_frame];
625             best_ref_mv = frame_best_ref_mv[x->e_mbd.mode_info_context->mbmi.ref_frame];
626             memcpy(mdcounts, MDCounts[x->e_mbd.mode_info_context->mbmi.ref_frame], sizeof(mdcounts));
627         }
628
629         // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
630         // unless ARNR filtering is enabled in which case we want
631         // an unfiltered alternative
632         if (cpi->is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
633         {
634             if (this_mode != ZEROMV || x->e_mbd.mode_info_context->mbmi.ref_frame != ALTREF_FRAME)
635                 continue;
636         }
637
638         if(cpi->sf.improved_mv_pred && x->e_mbd.mode_info_context->mbmi.mode == NEWMV)
639         {
640             if(!saddone)
641             {
642                 vp8_cal_sad(cpi,xd,x, recon_yoffset ,&near_sadidx[0] );
643                 saddone = 1;
644             }
645
646             vp8_mv_pred(cpi, &x->e_mbd, x->e_mbd.mode_info_context, &mvp,
647                         x->e_mbd.mode_info_context->mbmi.ref_frame, cpi->common.ref_frame_sign_bias, &sr, &near_sadidx[0]);
648
649             /* adjust mvp to make sure it is within MV range */
650             vp8_clamp_mv(&mvp,
651                          best_ref_mv.as_mv.col - MAX_FULL_PEL_VAL,
652                          best_ref_mv.as_mv.col + MAX_FULL_PEL_VAL,
653                          best_ref_mv.as_mv.row - MAX_FULL_PEL_VAL,
654                          best_ref_mv.as_mv.row + MAX_FULL_PEL_VAL);
655         }
656
657         switch (this_mode)
658         {
659         case B_PRED:
660             // Pass best so far to vp8_pick_intra4x4mby_modes to use as breakout
661             distortion2 = *returndistortion;
662             vp8_pick_intra4x4mby_modes(IF_RTCD(&cpi->rtcd), x,
663                                          &rate, &distortion2);
664
665             if (distortion2 == INT_MAX)
666             {
667                 this_rd = INT_MAX;
668             }
669             else
670             {
671                 rate2 += rate;
672                 distortion2 = VARIANCE_INVOKE
673                                 (&cpi->rtcd.variance, get16x16prederror)(
674                                     x->src.y_buffer, x->src.y_stride,
675                                     x->e_mbd.predictor, 16, 0x7fffffff);
676                 this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
677
678                 if (this_rd < best_intra_rd)
679                 {
680                     best_intra_rd = this_rd;
681                     *returnintra = distortion2;
682                 }
683             }
684
685             break;
686
687         case SPLITMV:
688
689             // Split MV modes currently not supported when RD is nopt enabled.
690             break;
691
692         case DC_PRED:
693         case V_PRED:
694         case H_PRED:
695         case TM_PRED:
696             RECON_INVOKE(&cpi->common.rtcd.recon, build_intra_predictors_mby)
697                 (&x->e_mbd);
698             distortion2 = VARIANCE_INVOKE(&cpi->rtcd.variance, get16x16prederror)(x->src.y_buffer, x->src.y_stride, x->e_mbd.predictor, 16, 0x7fffffff);
699             rate2 += x->mbmode_cost[x->e_mbd.frame_type][x->e_mbd.mode_info_context->mbmi.mode];
700             this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
701
702             if (this_rd < best_intra_rd)
703             {
704                 best_intra_rd = this_rd;
705                 *returnintra = distortion2;
706             }
707             break;
708
709         case NEWMV:
710         {
711             int thissme;
712             int step_param;
713             int further_steps;
714             int n = 0;
715             int sadpb = x->sadperbit16;
716
717             int col_min;
718             int col_max;
719             int row_min;
720             int row_max;
721
722             int tmp_col_min = x->mv_col_min;
723             int tmp_col_max = x->mv_col_max;
724             int tmp_row_min = x->mv_row_min;
725             int tmp_row_max = x->mv_row_max;
726
727             int speed_adjust = (cpi->Speed > 5) ? ((cpi->Speed >= 8)? 3 : 2) : 1;
728
729             // Further step/diamond searches as necessary
730             step_param = cpi->sf.first_step + speed_adjust;
731
732             if(cpi->sf.improved_mv_pred)
733             {
734                 sr += speed_adjust;
735                 //adjust search range according to sr from mv prediction
736                 if(sr > step_param)
737                     step_param = sr;
738
739                 col_min = (best_ref_mv.as_mv.col - MAX_FULL_PEL_VAL) >>3;
740                 col_max = (best_ref_mv.as_mv.col + MAX_FULL_PEL_VAL) >>3;
741                 row_min = (best_ref_mv.as_mv.row - MAX_FULL_PEL_VAL) >>3;
742                 row_max = (best_ref_mv.as_mv.row + MAX_FULL_PEL_VAL) >>3;
743
744                 // Get intersection of UMV window and valid MV window to reduce # of checks in diamond search.
745                 if (x->mv_col_min < col_min )
746                     x->mv_col_min = col_min;
747                 if (x->mv_col_max > col_max )
748                     x->mv_col_max = col_max;
749                 if (x->mv_row_min < row_min )
750                     x->mv_row_min = row_min;
751                 if (x->mv_row_max > row_max )
752                     x->mv_row_max = row_max;
753             }else
754             {
755                 mvp.as_int = best_ref_mv.as_int;
756             }
757
758             further_steps = (cpi->Speed >= 8)? 0: (cpi->sf.max_step_search_steps - 1 - step_param);
759
760             if (cpi->sf.search_method == HEX)
761             {
762                 bestsme = vp8_hex_search(x, b, d, &mvp, &d->bmi.mv, step_param, sadpb/*x->errorperbit*/, &num00, &cpi->fn_ptr[BLOCK_16X16], x->mvsadcost, x->mvcost, &best_ref_mv);
763                 mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
764             }
765             else
766             {
767                 bestsme = cpi->diamond_search_sad(x, b, d, &mvp, &d->bmi.mv, step_param, sadpb / 2/*x->errorperbit*/, &num00, &cpi->fn_ptr[BLOCK_16X16], x->mvcost, &best_ref_mv); //sadpb < 9
768                 mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
769
770                 // Further step/diamond searches as necessary
771                 n = 0;
772                 //further_steps = (cpi->sf.max_step_search_steps - 1) - step_param;
773
774                 n = num00;
775                 num00 = 0;
776
777                 while (n < further_steps)
778                 {
779                     n++;
780
781                     if (num00)
782                         num00--;
783                     else
784                     {
785                         thissme =
786                         cpi->diamond_search_sad(x, b, d, &mvp,
787                                                 &d->bmi.mv,
788                                                 step_param + n,
789                                                 sadpb / 4, &num00,
790                                                 &cpi->fn_ptr[BLOCK_16X16],
791                                                 x->mvcost, &best_ref_mv);
792                         if (thissme < bestsme)
793                         {
794                             bestsme = thissme;
795                             mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
796                         }
797                         else
798                         {
799                             d->bmi.mv.as_int = mode_mv[NEWMV].as_int;
800                         }
801                     }
802                 }
803             }
804
805             if(cpi->sf.improved_mv_pred)
806             {
807                 x->mv_col_min = tmp_col_min;
808                 x->mv_col_max = tmp_col_max;
809                 x->mv_row_min = tmp_row_min;
810                 x->mv_row_max = tmp_row_max;
811             }
812
813             if (bestsme < INT_MAX)
814                 cpi->find_fractional_mv_step(x, b, d, &d->bmi.mv, &best_ref_mv, x->errorperbit, &cpi->fn_ptr[BLOCK_16X16], cpi->mb.mvcost, &distortion2, &sse);
815
816             mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
817
818             // mv cost;
819             rate2 += vp8_mv_bit_cost(&mode_mv[NEWMV], &best_ref_mv, cpi->mb.mvcost, 128);
820         }
821
822         case NEARESTMV:
823         case NEARMV:
824
825             if (mode_mv[this_mode].as_int == 0)
826                 continue;
827
828         case ZEROMV:
829
830             // Trap vectors that reach beyond the UMV borders
831             // Note that ALL New MV, Nearest MV Near MV and Zero MV code drops through to this point
832             // because of the lack of break statements in the previous two cases.
833             if (((mode_mv[this_mode].as_mv.row >> 3) < x->mv_row_min) || ((mode_mv[this_mode].as_mv.row >> 3) > x->mv_row_max) ||
834                 ((mode_mv[this_mode].as_mv.col >> 3) < x->mv_col_min) || ((mode_mv[this_mode].as_mv.col >> 3) > x->mv_col_max))
835                 continue;
836
837             rate2 += vp8_cost_mv_ref(this_mode, mdcounts);
838             x->e_mbd.mode_info_context->mbmi.mode = this_mode;
839             x->e_mbd.mode_info_context->mbmi.mv.as_mv = mode_mv[this_mode].as_mv;
840             x->e_mbd.block[0].bmi.mode = this_mode;
841             x->e_mbd.block[0].bmi.mv.as_int = x->e_mbd.mode_info_context->mbmi.mv.as_int;
842
843             if((this_mode != NEWMV) || !(have_subp_search) || cpi->common.full_pixel==1)
844                 distortion2 = get_inter_mbpred_error(x, &cpi->fn_ptr[BLOCK_16X16], &sse);
845
846             this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
847
848             if (cpi->active_map_enabled && x->active_ptr[0] == 0)
849             {
850                 x->skip = 1;
851             }
852             else if (sse < x->encode_breakout)
853             {
854                 // Check u and v to make sure skip is ok
855                 int sse2 = 0;
856
857                 sse2 = VP8_UVSSE(x, IF_RTCD(&cpi->rtcd.variance));
858
859                 if (sse2 * 2 < x->encode_breakout)
860                     x->skip = 1;
861                 else
862                     x->skip = 0;
863             }
864
865             break;
866         default:
867             break;
868         }
869
870         // Experimental debug code.
871         //all_rds[mode_index] = this_rd;
872
873         if (this_rd < best_rd || x->skip)
874         {
875             // Note index of best mode
876             best_mode_index = mode_index;
877
878             *returnrate = rate2;
879             *returndistortion = distortion2;
880             best_rd = this_rd;
881             vpx_memcpy(&best_mbmode, &x->e_mbd.mode_info_context->mbmi, sizeof(MB_MODE_INFO));
882
883             if (this_mode == B_PRED)
884                 for (i = 0; i < 16; i++)
885                 {
886                     vpx_memcpy(&best_bmodes[i], &x->e_mbd.block[i].bmi, sizeof(B_MODE_INFO));
887                 }
888             else
889             {
890                 best_bmodes[0].mv = x->e_mbd.block[0].bmi.mv;
891             }
892
893             // Testing this mode gave rise to an improvement in best error score. Lower threshold a bit for next time
894             cpi->rd_thresh_mult[mode_index] = (cpi->rd_thresh_mult[mode_index] >= (MIN_THRESHMULT + 2)) ? cpi->rd_thresh_mult[mode_index] - 2 : MIN_THRESHMULT;
895             cpi->rd_threshes[mode_index] = (cpi->rd_baseline_thresh[mode_index] >> 7) * cpi->rd_thresh_mult[mode_index];
896         }
897
898         // If the mode did not help improve the best error case then raise the threshold for testing that mode next time around.
899         else
900         {
901             cpi->rd_thresh_mult[mode_index] += 4;
902
903             if (cpi->rd_thresh_mult[mode_index] > MAX_THRESHMULT)
904                 cpi->rd_thresh_mult[mode_index] = MAX_THRESHMULT;
905
906             cpi->rd_threshes[mode_index] = (cpi->rd_baseline_thresh[mode_index] >> 7) * cpi->rd_thresh_mult[mode_index];
907         }
908
909         if (x->skip)
910             break;
911     }
912
913     // Reduce the activation RD thresholds for the best choice mode
914     if ((cpi->rd_baseline_thresh[best_mode_index] > 0) && (cpi->rd_baseline_thresh[best_mode_index] < (INT_MAX >> 2)))
915     {
916         int best_adjustment = (cpi->rd_thresh_mult[best_mode_index] >> 3);
917
918         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;
919         cpi->rd_threshes[best_mode_index] = (cpi->rd_baseline_thresh[best_mode_index] >> 7) * cpi->rd_thresh_mult[best_mode_index];
920     }
921
922     if (best_mbmode.mode <= B_PRED)
923     {
924         x->e_mbd.mode_info_context->mbmi.ref_frame = INTRA_FRAME;
925         vp8_pick_intra_mbuv_mode(x);
926         best_mbmode.uv_mode = x->e_mbd.mode_info_context->mbmi.uv_mode;
927     }
928
929
930     {
931         int this_rdbin = (*returndistortion >> 7);
932
933         if (this_rdbin >= 1024)
934         {
935             this_rdbin = 1023;
936         }
937
938         cpi->error_bins[this_rdbin] ++;
939     }
940
941
942     if (cpi->is_src_frame_alt_ref && (best_mbmode.mode != ZEROMV || best_mbmode.ref_frame != ALTREF_FRAME))
943     {
944         best_mbmode.mode = ZEROMV;
945         best_mbmode.ref_frame = ALTREF_FRAME;
946         best_mbmode.mv.as_int = 0;
947         best_mbmode.uv_mode = 0;
948         best_mbmode.mb_skip_coeff = (cpi->common.mb_no_coeff_skip) ? 1 : 0;
949         best_mbmode.partitioning = 0;
950
951         vpx_memcpy(&x->e_mbd.mode_info_context->mbmi, &best_mbmode, sizeof(MB_MODE_INFO));
952
953         for (i = 0; i < 16; i++)
954         {
955             vpx_memset(&x->e_mbd.block[i].bmi, 0, sizeof(B_MODE_INFO));
956         }
957
958         x->e_mbd.mode_info_context->mbmi.mv.as_int = 0;
959         return;
960     }
961
962     // macroblock modes
963     vpx_memcpy(&x->e_mbd.mode_info_context->mbmi, &best_mbmode, sizeof(MB_MODE_INFO));
964
965
966     if (x->e_mbd.mode_info_context->mbmi.mode <= B_PRED)
967         for (i = 0; i < 16; i++)
968         {
969             x->e_mbd.block[i].bmi.mode = best_bmodes[i].mode;
970         }
971     else
972     {
973         vp8_set_mbmode_and_mvs(x, x->e_mbd.mode_info_context->mbmi.mode, &best_bmodes[0].mv);
974     }
975
976     update_mvcount(cpi, &x->e_mbd, &frame_best_ref_mv[xd->mode_info_context->mbmi.ref_frame]);
977 }