4de84fda6b9556e29ff8b566b43a2e4fb5912a05
[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_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/reconintra4x4.h"
23 #include "vp8/common/variance.h"
24 #include "mcomp.h"
25 #include "rdopt.h"
26 #include "vpx_mem/vpx_mem.h"
27 #if CONFIG_TEMPORAL_DENOISING
28 #include "denoising.h"
29 #endif
30
31 extern int VP8_UVSSE(MACROBLOCK *x);
32
33 #ifdef SPEEDSTATS
34 extern unsigned int cnt_pm;
35 #endif
36
37 extern const int vp8_ref_frame_order[MAX_MODES];
38 extern const MB_PREDICTION_MODE vp8_mode_order[MAX_MODES];
39
40 extern int vp8_cost_mv_ref(MB_PREDICTION_MODE m, const int near_mv_ref_ct[4]);
41
42
43 int vp8_skip_fractional_mv_step(MACROBLOCK *mb, BLOCK *b, BLOCKD *d,
44                                 int_mv *bestmv, int_mv *ref_mv,
45                                 int error_per_bit,
46                                 const vp8_variance_fn_ptr_t *vfp,
47                                 int *mvcost[2], int *distortion,
48                                 unsigned int *sse)
49 {
50     (void) b;
51     (void) d;
52     (void) ref_mv;
53     (void) error_per_bit;
54     (void) vfp;
55     (void) mvcost;
56     (void) distortion;
57     (void) sse;
58     bestmv->as_mv.row <<= 3;
59     bestmv->as_mv.col <<= 3;
60     return 0;
61 }
62
63
64 static int get_inter_mbpred_error(MACROBLOCK *mb,
65                                   const vp8_variance_fn_ptr_t *vfp,
66                                   unsigned int *sse,
67                                   int_mv this_mv)
68 {
69
70     BLOCK *b = &mb->block[0];
71     BLOCKD *d = &mb->e_mbd.block[0];
72     unsigned char *what = (*(b->base_src) + b->src);
73     int what_stride = b->src_stride;
74     int pre_stride = mb->e_mbd.pre.y_stride;
75     unsigned char *in_what = mb->e_mbd.pre.y_buffer + d->offset ;
76     int in_what_stride = pre_stride;
77     int xoffset = this_mv.as_mv.col & 7;
78     int yoffset = this_mv.as_mv.row & 7;
79
80     in_what += (this_mv.as_mv.row >> 3) * pre_stride + (this_mv.as_mv.col >> 3);
81
82     if (xoffset | yoffset)
83     {
84         return vfp->svf(in_what, in_what_stride, xoffset, yoffset, what, what_stride, sse);
85     }
86     else
87     {
88         return vfp->vf(what, what_stride, in_what, in_what_stride, sse);
89     }
90
91 }
92
93
94 unsigned int vp8_get4x4sse_cs_c
95 (
96     const unsigned char *src_ptr,
97     int  source_stride,
98     const unsigned char *ref_ptr,
99     int  recon_stride
100 )
101 {
102     int distortion = 0;
103     int r, c;
104
105     for (r = 0; r < 4; r++)
106     {
107         for (c = 0; c < 4; c++)
108         {
109             int diff = src_ptr[c] - ref_ptr[c];
110             distortion += diff * diff;
111         }
112
113         src_ptr += source_stride;
114         ref_ptr += recon_stride;
115     }
116
117     return distortion;
118 }
119
120 static int get_prediction_error(BLOCK *be, BLOCKD *b)
121 {
122     unsigned char *sptr;
123     unsigned char *dptr;
124     sptr = (*(be->base_src) + be->src);
125     dptr = b->predictor;
126
127     return vp8_get4x4sse_cs(sptr, be->src_stride, dptr, 16);
128
129 }
130
131 static int pick_intra4x4block(
132     MACROBLOCK *x,
133     int ib,
134     B_PREDICTION_MODE *best_mode,
135     const int *mode_costs,
136
137     int *bestrate,
138     int *bestdistortion)
139 {
140
141     BLOCKD *b = &x->e_mbd.block[ib];
142     BLOCK *be = &x->block[ib];
143     int dst_stride = x->e_mbd.dst.y_stride;
144     unsigned char *base_dst = x->e_mbd.dst.y_buffer;
145     B_PREDICTION_MODE mode;
146     int best_rd = INT_MAX;       // 1<<30
147     int rate;
148     int distortion;
149
150     for (mode = B_DC_PRED; mode <= B_HE_PRED /*B_HU_PRED*/; mode++)
151     {
152         int this_rd;
153
154         rate = mode_costs[mode];
155         vp8_intra4x4_predict
156                      (base_dst + b->offset, dst_stride,
157                       mode, b->predictor, 16);
158         distortion = get_prediction_error(be, b);
159         this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
160
161         if (this_rd < best_rd)
162         {
163             *bestrate = rate;
164             *bestdistortion = distortion;
165             best_rd = this_rd;
166             *best_mode = mode;
167         }
168     }
169
170     b->bmi.as_mode = (B_PREDICTION_MODE)(*best_mode);
171     vp8_encode_intra4x4block(x, ib);
172     return best_rd;
173 }
174
175
176 static int pick_intra4x4mby_modes
177 (
178     MACROBLOCK *mb,
179     int *Rate,
180     int *best_dist
181 )
182 {
183     MACROBLOCKD *const xd = &mb->e_mbd;
184     int i;
185     int cost = mb->mbmode_cost [xd->frame_type] [B_PRED];
186     int error;
187     int distortion = 0;
188     const int *bmode_costs;
189
190     intra_prediction_down_copy(xd, xd->dst.y_buffer - xd->dst.y_stride + 16);
191
192     bmode_costs = mb->inter_bmode_costs;
193
194     for (i = 0; i < 16; i++)
195     {
196         MODE_INFO *const mic = xd->mode_info_context;
197         const int mis = xd->mode_info_stride;
198
199         B_PREDICTION_MODE UNINITIALIZED_IS_SAFE(best_mode);
200         int UNINITIALIZED_IS_SAFE(r), UNINITIALIZED_IS_SAFE(d);
201
202         if (mb->e_mbd.frame_type == KEY_FRAME)
203         {
204             const B_PREDICTION_MODE A = above_block_mode(mic, i, mis);
205             const B_PREDICTION_MODE L = left_block_mode(mic, i);
206
207             bmode_costs  = mb->bmode_costs[A][L];
208         }
209
210
211         pick_intra4x4block(mb, i, &best_mode, bmode_costs, &r, &d);
212
213         cost += r;
214         distortion += d;
215         mic->bmi[i].as_mode = best_mode;
216
217         // Break out case where we have already exceeded best so far value
218         // that was passed in
219         if (distortion > *best_dist)
220             break;
221     }
222
223     *Rate = cost;
224
225     if (i == 16)
226     {
227         *best_dist = distortion;
228         error = RDCOST(mb->rdmult, mb->rddiv, cost, distortion);
229     }
230     else
231     {
232         *best_dist = INT_MAX;
233         error = INT_MAX;
234     }
235
236     return error;
237 }
238
239 static void pick_intra_mbuv_mode(MACROBLOCK *mb)
240 {
241
242     MACROBLOCKD *x = &mb->e_mbd;
243     unsigned char *uabove_row = x->dst.u_buffer - x->dst.uv_stride;
244     unsigned char *vabove_row = x->dst.v_buffer - x->dst.uv_stride;
245     unsigned char *usrc_ptr = (mb->block[16].src + *mb->block[16].base_src);
246     unsigned char *vsrc_ptr = (mb->block[20].src + *mb->block[20].base_src);
247     int uvsrc_stride = mb->block[16].src_stride;
248     unsigned char uleft_col[8];
249     unsigned char vleft_col[8];
250     unsigned char utop_left = uabove_row[-1];
251     unsigned char vtop_left = vabove_row[-1];
252     int i, j;
253     int expected_udc;
254     int expected_vdc;
255     int shift;
256     int Uaverage = 0;
257     int Vaverage = 0;
258     int diff;
259     int pred_error[4] = {0, 0, 0, 0}, best_error = INT_MAX;
260     MB_PREDICTION_MODE UNINITIALIZED_IS_SAFE(best_mode);
261
262
263     for (i = 0; i < 8; i++)
264     {
265         uleft_col[i] = x->dst.u_buffer [i* x->dst.uv_stride -1];
266         vleft_col[i] = x->dst.v_buffer [i* x->dst.uv_stride -1];
267     }
268
269     if (!x->up_available && !x->left_available)
270     {
271         expected_udc = 128;
272         expected_vdc = 128;
273     }
274     else
275     {
276         shift = 2;
277
278         if (x->up_available)
279         {
280
281             for (i = 0; i < 8; i++)
282             {
283                 Uaverage += uabove_row[i];
284                 Vaverage += vabove_row[i];
285             }
286
287             shift ++;
288
289         }
290
291         if (x->left_available)
292         {
293             for (i = 0; i < 8; i++)
294             {
295                 Uaverage += uleft_col[i];
296                 Vaverage += vleft_col[i];
297             }
298
299             shift ++;
300
301         }
302
303         expected_udc = (Uaverage + (1 << (shift - 1))) >> shift;
304         expected_vdc = (Vaverage + (1 << (shift - 1))) >> shift;
305     }
306
307
308     for (i = 0; i < 8; i++)
309     {
310         for (j = 0; j < 8; j++)
311         {
312
313             int predu = uleft_col[i] + uabove_row[j] - utop_left;
314             int predv = vleft_col[i] + vabove_row[j] - vtop_left;
315             int u_p, v_p;
316
317             u_p = usrc_ptr[j];
318             v_p = vsrc_ptr[j];
319
320             if (predu < 0)
321                 predu = 0;
322
323             if (predu > 255)
324                 predu = 255;
325
326             if (predv < 0)
327                 predv = 0;
328
329             if (predv > 255)
330                 predv = 255;
331
332
333             diff = u_p - expected_udc;
334             pred_error[DC_PRED] += diff * diff;
335             diff = v_p - expected_vdc;
336             pred_error[DC_PRED] += diff * diff;
337
338
339             diff = u_p - uabove_row[j];
340             pred_error[V_PRED] += diff * diff;
341             diff = v_p - vabove_row[j];
342             pred_error[V_PRED] += diff * diff;
343
344
345             diff = u_p - uleft_col[i];
346             pred_error[H_PRED] += diff * diff;
347             diff = v_p - vleft_col[i];
348             pred_error[H_PRED] += diff * diff;
349
350
351             diff = u_p - predu;
352             pred_error[TM_PRED] += diff * diff;
353             diff = v_p - predv;
354             pred_error[TM_PRED] += diff * diff;
355
356
357         }
358
359         usrc_ptr += uvsrc_stride;
360         vsrc_ptr += uvsrc_stride;
361
362         if (i == 3)
363         {
364             usrc_ptr = (mb->block[18].src + *mb->block[18].base_src);
365             vsrc_ptr = (mb->block[22].src + *mb->block[22].base_src);
366         }
367
368
369
370     }
371
372
373     for (i = DC_PRED; i <= TM_PRED; i++)
374     {
375         if (best_error > pred_error[i])
376         {
377             best_error = pred_error[i];
378             best_mode = (MB_PREDICTION_MODE)i;
379         }
380     }
381
382
383     mb->e_mbd.mode_info_context->mbmi.uv_mode = best_mode;
384
385 }
386
387 static void update_mvcount(VP8_COMP *cpi, MACROBLOCKD *xd, int_mv *best_ref_mv)
388 {
389     /* Split MV modes currently not supported when RD is nopt enabled,
390      * therefore, only need to modify MVcount in NEWMV mode. */
391     if (xd->mode_info_context->mbmi.mode == NEWMV)
392     {
393         cpi->MVcount[0][mv_max+((xd->mode_info_context->mbmi.mv.as_mv.row -
394                                       best_ref_mv->as_mv.row) >> 1)]++;
395         cpi->MVcount[1][mv_max+((xd->mode_info_context->mbmi.mv.as_mv.col -
396                                       best_ref_mv->as_mv.col) >> 1)]++;
397     }
398 }
399
400
401 #if CONFIG_MULTI_RES_ENCODING
402 static
403 void get_lower_res_motion_info(VP8_COMP *cpi, MACROBLOCKD *xd, int *dissim,
404                                int *parent_ref_frame,
405                                MB_PREDICTION_MODE *parent_mode,
406                                int_mv *parent_ref_mv, int mb_row, int mb_col)
407 {
408     LOWER_RES_MB_INFO* store_mode_info
409                           = ((LOWER_RES_FRAME_INFO*)cpi->oxcf.mr_low_res_mode_info)->mb_info;
410     unsigned int parent_mb_index;
411     //unsigned int parent_mb_index = map_640x480_to_320x240[mb_row][mb_col];
412
413     /* Consider different down_sampling_factor.  */
414     {
415         /* TODO: Removed the loop that supports special down_sampling_factor
416          * such as 2, 4, 8. Will revisit it if needed.
417          * Should also try using a look-up table to see if it helps
418          * performance. */
419         int parent_mb_row, parent_mb_col;
420
421         parent_mb_row = mb_row*cpi->oxcf.mr_down_sampling_factor.den
422                     /cpi->oxcf.mr_down_sampling_factor.num;
423         parent_mb_col = mb_col*cpi->oxcf.mr_down_sampling_factor.den
424                     /cpi->oxcf.mr_down_sampling_factor.num;
425         parent_mb_index = parent_mb_row*cpi->mr_low_res_mb_cols + parent_mb_col;
426     }
427
428     /* Read lower-resolution mode & motion result from memory.*/
429     *parent_ref_frame = store_mode_info[parent_mb_index].ref_frame;
430     *parent_mode =  store_mode_info[parent_mb_index].mode;
431     *dissim = store_mode_info[parent_mb_index].dissim;
432
433     /* For highest-resolution encoder, adjust dissim value. Lower its quality
434      * for good performance. */
435     if (cpi->oxcf.mr_encoder_id == (cpi->oxcf.mr_total_resolutions - 1))
436         *dissim>>=1;
437
438     if(*parent_ref_frame != INTRA_FRAME)
439     {
440         /* Consider different down_sampling_factor.
441          * The result can be rounded to be more precise, but it takes more time.
442          */
443         //int round = cpi->oxcf.mr_down_sampling_factor.den/2;
444         (*parent_ref_mv).as_mv.row = store_mode_info[parent_mb_index].mv.as_mv.row
445                                   *cpi->oxcf.mr_down_sampling_factor.num
446                                   /cpi->oxcf.mr_down_sampling_factor.den;
447         (*parent_ref_mv).as_mv.col = store_mode_info[parent_mb_index].mv.as_mv.col
448                                   *cpi->oxcf.mr_down_sampling_factor.num
449                                   /cpi->oxcf.mr_down_sampling_factor.den;
450
451         vp8_clamp_mv2(parent_ref_mv, xd);
452     }
453 }
454 #endif
455
456 static void check_for_encode_breakout(unsigned int sse, MACROBLOCK* x)
457 {
458     if (sse < x->encode_breakout)
459     {
460         // Check u and v to make sure skip is ok
461         unsigned int sse2 = 0;
462
463         sse2 = VP8_UVSSE(x);
464
465         if (sse2 * 2 < x->encode_breakout)
466             x->skip = 1;
467         else
468             x->skip = 0;
469     }
470 }
471
472 static int evaluate_inter_mode(unsigned int* sse, int rate2, int* distortion2, VP8_COMP *cpi, MACROBLOCK *x)
473 {
474     MB_PREDICTION_MODE this_mode = x->e_mbd.mode_info_context->mbmi.mode;
475     int_mv mv = x->e_mbd.mode_info_context->mbmi.mv;
476     int this_rd;
477     /* Exit early and don't compute the distortion if this macroblock
478      * is marked inactive. */
479     if (cpi->active_map_enabled && x->active_ptr[0] == 0)
480     {
481         *sse = 0;
482         *distortion2 = 0;
483         x->skip = 1;
484         return INT_MAX;
485     }
486
487     if((this_mode != NEWMV) ||
488         !(cpi->sf.half_pixel_search) || cpi->common.full_pixel==1)
489         *distortion2 = get_inter_mbpred_error(x,
490                                               &cpi->fn_ptr[BLOCK_16X16],
491                                               sse, mv);
492
493     this_rd = RDCOST(x->rdmult, x->rddiv, rate2, *distortion2);
494
495     check_for_encode_breakout(*sse, x);
496     return this_rd;
497 }
498
499 void vp8_pick_inter_mode(VP8_COMP *cpi, MACROBLOCK *x, int recon_yoffset,
500                          int recon_uvoffset, int *returnrate,
501                          int *returndistortion, int *returnintra, int mb_row,
502                          int mb_col)
503 {
504     BLOCK *b = &x->block[0];
505     BLOCKD *d = &x->e_mbd.block[0];
506     MACROBLOCKD *xd = &x->e_mbd;
507     MB_MODE_INFO best_mbmode;
508
509     int_mv best_ref_mv_sb[2];
510     int_mv mode_mv_sb[2][MB_MODE_COUNT];
511     int_mv best_ref_mv;
512     int_mv *mode_mv;
513     MB_PREDICTION_MODE this_mode;
514     int num00;
515     int mdcounts[4];
516     int best_rd = INT_MAX; // 1 << 30;
517     int best_intra_rd = INT_MAX;
518     int mode_index;
519     int rate;
520     int rate2;
521     int distortion2;
522     int bestsme = INT_MAX;
523     int best_mode_index = 0;
524     unsigned int sse = INT_MAX, best_rd_sse = INT_MAX;
525 #if CONFIG_TEMPORAL_DENOISING
526     unsigned int zero_mv_sse = 0, best_sse = INT_MAX;
527 #endif
528
529     int_mv mvp;
530
531     int near_sadidx[8] = {0, 1, 2, 3, 4, 5, 6, 7};
532     int saddone=0;
533     int sr=0;    //search range got from mv_pred(). It uses step_param levels. (0-7)
534
535     unsigned char *plane[4][3];
536     int ref_frame_map[4];
537     int sign_bias = 0;
538
539 #if CONFIG_MULTI_RES_ENCODING
540     int dissim = INT_MAX;
541     int parent_ref_frame = 0;
542     int_mv parent_ref_mv;
543     MB_PREDICTION_MODE parent_mode = 0;
544
545     if (cpi->oxcf.mr_encoder_id)
546         get_lower_res_motion_info(cpi, xd, &dissim, &parent_ref_frame,
547                                   &parent_mode, &parent_ref_mv, mb_row, mb_col);
548 #endif
549
550     mode_mv = mode_mv_sb[sign_bias];
551     best_ref_mv.as_int = 0;
552     vpx_memset(mode_mv_sb, 0, sizeof(mode_mv_sb));
553     vpx_memset(&best_mbmode, 0, sizeof(best_mbmode));
554
555     /* Setup search priorities */
556     get_reference_search_order(cpi, ref_frame_map);
557
558     /* Check to see if there is at least 1 valid reference frame that we need
559      * to calculate near_mvs.
560      */
561     if (ref_frame_map[1] > 0)
562     {
563         sign_bias = vp8_find_near_mvs_bias(&x->e_mbd,
564                                            x->e_mbd.mode_info_context,
565                                            mode_mv_sb,
566                                            best_ref_mv_sb,
567                                            mdcounts,
568                                            ref_frame_map[1],
569                                            cpi->common.ref_frame_sign_bias);
570
571         mode_mv = mode_mv_sb[sign_bias];
572         best_ref_mv.as_int = best_ref_mv_sb[sign_bias].as_int;
573     }
574
575     get_predictor_pointers(cpi, plane, recon_yoffset, recon_uvoffset);
576
577     cpi->mbs_tested_so_far++; // Count of the number of MBs tested so far this frame
578
579     *returnintra = INT_MAX;
580     x->skip = 0;
581
582     x->e_mbd.mode_info_context->mbmi.ref_frame = INTRA_FRAME;
583
584     // if we encode a new mv this is important
585     // find the best new motion vector
586     for (mode_index = 0; mode_index < MAX_MODES; mode_index++)
587     {
588         int frame_cost;
589         int this_rd = INT_MAX;
590         int this_ref_frame = ref_frame_map[vp8_ref_frame_order[mode_index]];
591
592         if (best_rd <= cpi->rd_threshes[mode_index])
593             continue;
594
595         if (this_ref_frame < 0)
596             continue;
597
598         x->e_mbd.mode_info_context->mbmi.ref_frame = this_ref_frame;
599
600 #if CONFIG_MULTI_RES_ENCODING
601         if (cpi->oxcf.mr_encoder_id)
602         {
603             /* If parent MB is intra, child MB is intra. */
604             if (!parent_ref_frame && this_ref_frame)
605                 continue;
606
607             /* If parent MB is inter, and it is unlikely there are multiple
608              * objects in parent MB, we use parent ref frame as child MB's
609              * ref frame. */
610             if (parent_ref_frame && dissim < 8
611                 && parent_ref_frame != this_ref_frame)
612                 continue;
613         }
614 #endif
615
616         // everything but intra
617         if (x->e_mbd.mode_info_context->mbmi.ref_frame)
618         {
619             x->e_mbd.pre.y_buffer = plane[this_ref_frame][0];
620             x->e_mbd.pre.u_buffer = plane[this_ref_frame][1];
621             x->e_mbd.pre.v_buffer = plane[this_ref_frame][2];
622
623             if (sign_bias != cpi->common.ref_frame_sign_bias[this_ref_frame])
624             {
625                 sign_bias = cpi->common.ref_frame_sign_bias[this_ref_frame];
626                 mode_mv = mode_mv_sb[sign_bias];
627                 best_ref_mv.as_int = best_ref_mv_sb[sign_bias].as_int;
628             }
629
630 #if CONFIG_MULTI_RES_ENCODING
631             if (cpi->oxcf.mr_encoder_id)
632             {
633                 if (vp8_mode_order[mode_index] == NEARESTMV &&
634                     mode_mv[NEARESTMV].as_int ==0)
635                     continue;
636                 if (vp8_mode_order[mode_index] == NEARMV &&
637                     mode_mv[NEARMV].as_int ==0)
638                     continue;
639
640                 if (vp8_mode_order[mode_index] == NEWMV && parent_mode == ZEROMV
641                     && best_ref_mv.as_int==0) //&& dissim==0
642                     continue;
643                 else if(vp8_mode_order[mode_index] == NEWMV && dissim==0
644                     && best_ref_mv.as_int==parent_ref_mv.as_int)
645                     continue;
646             }
647 #endif
648         }
649
650         /* Check to see if the testing frequency for this mode is at its max
651          * If so then prevent it from being tested and increase the threshold
652          * for its testing */
653         if (cpi->mode_test_hit_counts[mode_index] &&
654                                          (cpi->mode_check_freq[mode_index] > 1))
655         {
656             if (cpi->mbs_tested_so_far <= (cpi->mode_check_freq[mode_index] *
657                                          cpi->mode_test_hit_counts[mode_index]))
658             {
659                 /* Increase the threshold for coding this mode to make it less
660                  * likely to be chosen */
661                 cpi->rd_thresh_mult[mode_index] += 4;
662
663                 if (cpi->rd_thresh_mult[mode_index] > MAX_THRESHMULT)
664                     cpi->rd_thresh_mult[mode_index] = MAX_THRESHMULT;
665
666                 cpi->rd_threshes[mode_index] =
667                                  (cpi->rd_baseline_thresh[mode_index] >> 7) *
668                                  cpi->rd_thresh_mult[mode_index];
669                 continue;
670             }
671         }
672
673         /* We have now reached the point where we are going to test the current
674          * mode so increment the counter for the number of times it has been
675          * tested */
676         cpi->mode_test_hit_counts[mode_index] ++;
677
678         rate2 = 0;
679         distortion2 = 0;
680
681         this_mode = vp8_mode_order[mode_index];
682
683         x->e_mbd.mode_info_context->mbmi.mode = this_mode;
684         x->e_mbd.mode_info_context->mbmi.uv_mode = DC_PRED;
685
686         /* Work out the cost assosciated with selecting the reference frame */
687         frame_cost =
688             x->ref_frame_cost[x->e_mbd.mode_info_context->mbmi.ref_frame];
689         rate2 += frame_cost;
690
691         /* Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
692          * unless ARNR filtering is enabled in which case we want
693          * an unfiltered alternative */
694         if (cpi->is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
695         {
696             if (this_mode != ZEROMV ||
697                 x->e_mbd.mode_info_context->mbmi.ref_frame != ALTREF_FRAME)
698                 continue;
699         }
700
701         switch (this_mode)
702         {
703         case B_PRED:
704             /* Pass best so far to pick_intra4x4mby_modes to use as breakout */
705             distortion2 = best_rd_sse;
706             pick_intra4x4mby_modes(x, &rate, &distortion2);
707
708             if (distortion2 == INT_MAX)
709             {
710                 this_rd = INT_MAX;
711             }
712             else
713             {
714                 rate2 += rate;
715                 distortion2 = vp8_variance16x16(
716                                     *(b->base_src), b->src_stride,
717                                     x->e_mbd.predictor, 16, &sse);
718                 this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
719
720                 if (this_rd < best_intra_rd)
721                 {
722                     best_intra_rd = this_rd;
723                     *returnintra = distortion2;
724                 }
725             }
726
727             break;
728
729         case SPLITMV:
730
731             // Split MV modes currently not supported when RD is nopt enabled.
732             break;
733
734         case DC_PRED:
735         case V_PRED:
736         case H_PRED:
737         case TM_PRED:
738             vp8_build_intra_predictors_mby_s(xd,
739                                              xd->dst.y_buffer - xd->dst.y_stride,
740                                              xd->dst.y_buffer - 1,
741                                              xd->dst.y_stride,
742                                              xd->predictor,
743                                              16);
744             distortion2 = vp8_variance16x16
745                                           (*(b->base_src), b->src_stride,
746                                           x->e_mbd.predictor, 16, &sse);
747             rate2 += x->mbmode_cost[x->e_mbd.frame_type][x->e_mbd.mode_info_context->mbmi.mode];
748             this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
749
750             if (this_rd < best_intra_rd)
751             {
752                 best_intra_rd = this_rd;
753                 *returnintra = distortion2;
754             }
755             break;
756
757         case NEWMV:
758         {
759             int thissme;
760             int step_param;
761             int further_steps;
762             int n = 0;
763             int sadpb = x->sadperbit16;
764             int_mv mvp_full;
765
766             int col_min = ((best_ref_mv.as_mv.col+7)>>3) - MAX_FULL_PEL_VAL;
767             int row_min = ((best_ref_mv.as_mv.row+7)>>3) - MAX_FULL_PEL_VAL;
768             int col_max = (best_ref_mv.as_mv.col>>3)
769                          + MAX_FULL_PEL_VAL;
770             int row_max = (best_ref_mv.as_mv.row>>3)
771                          + MAX_FULL_PEL_VAL;
772
773             int tmp_col_min = x->mv_col_min;
774             int tmp_col_max = x->mv_col_max;
775             int tmp_row_min = x->mv_row_min;
776             int tmp_row_max = x->mv_row_max;
777
778             int speed_adjust = (cpi->Speed > 5) ? ((cpi->Speed >= 8)? 3 : 2) : 1;
779
780             // Further step/diamond searches as necessary
781             step_param = cpi->sf.first_step + speed_adjust;
782
783 #if CONFIG_MULTI_RES_ENCODING
784             if (cpi->oxcf.mr_encoder_id)
785             {
786                 // Use parent MV as predictor. Adjust search range accordingly.
787                 mvp.as_int = parent_ref_mv.as_int;
788                 mvp_full.as_mv.col = parent_ref_mv.as_mv.col>>3;
789                 mvp_full.as_mv.row = parent_ref_mv.as_mv.row>>3;
790
791                 if(dissim <=32) step_param += 3;
792                 else if(dissim <=128) step_param += 2;
793                 else step_param += 1;
794             }else
795 #endif
796             {
797                 if(cpi->sf.improved_mv_pred)
798                 {
799                     if(!saddone)
800                     {
801                         vp8_cal_sad(cpi,xd,x, recon_yoffset ,&near_sadidx[0] );
802                         saddone = 1;
803                     }
804
805                     vp8_mv_pred(cpi, &x->e_mbd, x->e_mbd.mode_info_context,
806                                 &mvp,x->e_mbd.mode_info_context->mbmi.ref_frame,
807                                 cpi->common.ref_frame_sign_bias, &sr,
808                                 &near_sadidx[0]);
809
810                     sr += speed_adjust;
811                     //adjust search range according to sr from mv prediction
812                     if(sr > step_param)
813                         step_param = sr;
814
815                     mvp_full.as_mv.col = mvp.as_mv.col>>3;
816                     mvp_full.as_mv.row = mvp.as_mv.row>>3;
817                 }else
818                 {
819                     mvp.as_int = best_ref_mv.as_int;
820                     mvp_full.as_mv.col = best_ref_mv.as_mv.col>>3;
821                     mvp_full.as_mv.row = best_ref_mv.as_mv.row>>3;
822                 }
823             }
824
825 #if CONFIG_MULTI_RES_ENCODING
826             if (cpi->oxcf.mr_encoder_id && dissim <= 2 &&
827                 MAX(abs(best_ref_mv.as_mv.row - parent_ref_mv.as_mv.row),
828                     abs(best_ref_mv.as_mv.col - parent_ref_mv.as_mv.col)) <= 4)
829             {
830                 d->bmi.mv.as_int = mvp_full.as_int;
831                 mode_mv[NEWMV].as_int = mvp_full.as_int;
832
833                 cpi->find_fractional_mv_step(x, b, d, &d->bmi.mv, &best_ref_mv,
834                                              x->errorperbit,
835                                              &cpi->fn_ptr[BLOCK_16X16],
836                                              cpi->mb.mvcost,
837                                              &distortion2,&sse);
838             }else
839 #endif
840             {
841                 /* Get intersection of UMV window and valid MV window to
842                  * reduce # of checks in diamond search. */
843                 if (x->mv_col_min < col_min )
844                     x->mv_col_min = col_min;
845                 if (x->mv_col_max > col_max )
846                     x->mv_col_max = col_max;
847                 if (x->mv_row_min < row_min )
848                     x->mv_row_min = row_min;
849                 if (x->mv_row_max > row_max )
850                     x->mv_row_max = row_max;
851
852                 further_steps = (cpi->Speed >= 8)?
853                            0: (cpi->sf.max_step_search_steps - 1 - step_param);
854
855                 if (cpi->sf.search_method == HEX)
856                 {
857 #if CONFIG_MULTI_RES_ENCODING
858                 /* TODO: In higher-res pick_inter_mode, step_param is used to
859                  * modify hex search range. Here, set step_param to 0 not to
860                  * change the behavior in lowest-resolution encoder.
861                  * Will improve it later.
862                  */
863                 if (!cpi->oxcf.mr_encoder_id)
864                     step_param = 0;
865 #endif
866                     bestsme = vp8_hex_search(x, b, d, &mvp_full, &d->bmi.mv,
867                                           step_param, sadpb,
868                                           &cpi->fn_ptr[BLOCK_16X16],
869                                           x->mvsadcost, x->mvcost, &best_ref_mv);
870                     mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
871                 }
872                 else
873                 {
874                     bestsme = cpi->diamond_search_sad(x, b, d, &mvp_full,
875                                           &d->bmi.mv, step_param, sadpb, &num00,
876                                           &cpi->fn_ptr[BLOCK_16X16],
877                                           x->mvcost, &best_ref_mv);
878                     mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
879
880                     // Further step/diamond searches as necessary
881                     n = 0;
882                     //further_steps = (cpi->sf.max_step_search_steps - 1) - step_param;
883
884                     n = num00;
885                     num00 = 0;
886
887                     while (n < further_steps)
888                     {
889                         n++;
890
891                         if (num00)
892                             num00--;
893                         else
894                         {
895                             thissme =
896                             cpi->diamond_search_sad(x, b, d, &mvp_full,
897                                                     &d->bmi.mv,
898                                                     step_param + n,
899                                                     sadpb, &num00,
900                                                     &cpi->fn_ptr[BLOCK_16X16],
901                                                     x->mvcost, &best_ref_mv);
902                             if (thissme < bestsme)
903                             {
904                                 bestsme = thissme;
905                                 mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
906                             }
907                             else
908                             {
909                                 d->bmi.mv.as_int = mode_mv[NEWMV].as_int;
910                             }
911                         }
912                     }
913                 }
914
915                 x->mv_col_min = tmp_col_min;
916                 x->mv_col_max = tmp_col_max;
917                 x->mv_row_min = tmp_row_min;
918                 x->mv_row_max = tmp_row_max;
919
920                 if (bestsme < INT_MAX)
921                     cpi->find_fractional_mv_step(x, b, d, &d->bmi.mv,
922                                              &best_ref_mv, x->errorperbit,
923                                              &cpi->fn_ptr[BLOCK_16X16],
924                                              cpi->mb.mvcost,
925                                              &distortion2,&sse);
926             }
927
928             mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
929
930             // mv cost;
931             rate2 += vp8_mv_bit_cost(&mode_mv[NEWMV], &best_ref_mv,
932                                      cpi->mb.mvcost, 128);
933         }
934
935         case NEARESTMV:
936         case NEARMV:
937
938             if (mode_mv[this_mode].as_int == 0)
939                 continue;
940
941         case ZEROMV:
942
943             /* Trap vectors that reach beyond the UMV borders
944              * Note that ALL New MV, Nearest MV Near MV and Zero MV code drops
945              * through to this point because of the lack of break statements
946              * in the previous two cases.
947              */
948             if (((mode_mv[this_mode].as_mv.row >> 3) < x->mv_row_min) ||
949                 ((mode_mv[this_mode].as_mv.row >> 3) > x->mv_row_max) ||
950                 ((mode_mv[this_mode].as_mv.col >> 3) < x->mv_col_min) ||
951                 ((mode_mv[this_mode].as_mv.col >> 3) > x->mv_col_max))
952                 continue;
953
954             rate2 += vp8_cost_mv_ref(this_mode, mdcounts);
955             x->e_mbd.mode_info_context->mbmi.mv.as_int =
956                                                     mode_mv[this_mode].as_int;
957             this_rd = evaluate_inter_mode(&sse, rate2, &distortion2, cpi, x);
958
959             break;
960         default:
961             break;
962         }
963
964 #if CONFIG_TEMPORAL_DENOISING
965         if (cpi->oxcf.noise_sensitivity)
966         {
967           // Store for later use by denoiser.
968           if (this_mode == ZEROMV &&
969               x->e_mbd.mode_info_context->mbmi.ref_frame == LAST_FRAME)
970           {
971             zero_mv_sse = sse;
972           }
973
974           // Store the best NEWMV in x for later use in the denoiser.
975           // We are restricted to the LAST_FRAME since the denoiser only keeps
976           // one filter state.
977           if (x->e_mbd.mode_info_context->mbmi.mode == NEWMV &&
978               x->e_mbd.mode_info_context->mbmi.ref_frame == LAST_FRAME)
979           {
980             best_sse = sse;
981             x->e_mbd.best_sse_inter_mode = NEWMV;
982             x->e_mbd.best_sse_mv = x->e_mbd.mode_info_context->mbmi.mv;
983             x->e_mbd.need_to_clamp_best_mvs =
984                 x->e_mbd.mode_info_context->mbmi.need_to_clamp_mvs;
985           }
986         }
987 #endif
988
989         if (this_rd < best_rd || x->skip)
990         {
991             // Note index of best mode
992             best_mode_index = mode_index;
993
994             *returnrate = rate2;
995             *returndistortion = distortion2;
996             best_rd_sse = sse;
997             best_rd = this_rd;
998             vpx_memcpy(&best_mbmode, &x->e_mbd.mode_info_context->mbmi,
999                        sizeof(MB_MODE_INFO));
1000
1001             /* Testing this mode gave rise to an improvement in best error
1002              * score. Lower threshold a bit for next time
1003              */
1004             cpi->rd_thresh_mult[mode_index] =
1005                      (cpi->rd_thresh_mult[mode_index] >= (MIN_THRESHMULT + 2)) ?
1006                      cpi->rd_thresh_mult[mode_index] - 2 : MIN_THRESHMULT;
1007             cpi->rd_threshes[mode_index] =
1008                                    (cpi->rd_baseline_thresh[mode_index] >> 7) *
1009                                    cpi->rd_thresh_mult[mode_index];
1010         }
1011
1012         /* If the mode did not help improve the best error case then raise the
1013          * threshold for testing that mode next time around.
1014          */
1015         else
1016         {
1017             cpi->rd_thresh_mult[mode_index] += 4;
1018
1019             if (cpi->rd_thresh_mult[mode_index] > MAX_THRESHMULT)
1020                 cpi->rd_thresh_mult[mode_index] = MAX_THRESHMULT;
1021
1022             cpi->rd_threshes[mode_index] =
1023                          (cpi->rd_baseline_thresh[mode_index] >> 7) *
1024                          cpi->rd_thresh_mult[mode_index];
1025         }
1026
1027         if (x->skip)
1028             break;
1029     }
1030
1031     // Reduce the activation RD thresholds for the best choice mode
1032     if ((cpi->rd_baseline_thresh[best_mode_index] > 0) && (cpi->rd_baseline_thresh[best_mode_index] < (INT_MAX >> 2)))
1033     {
1034         int best_adjustment = (cpi->rd_thresh_mult[best_mode_index] >> 3);
1035
1036         cpi->rd_thresh_mult[best_mode_index] =
1037                         (cpi->rd_thresh_mult[best_mode_index]
1038                         >= (MIN_THRESHMULT + best_adjustment)) ?
1039                         cpi->rd_thresh_mult[best_mode_index] - best_adjustment :
1040                         MIN_THRESHMULT;
1041         cpi->rd_threshes[best_mode_index] =
1042                         (cpi->rd_baseline_thresh[best_mode_index] >> 7) *
1043                         cpi->rd_thresh_mult[best_mode_index];
1044     }
1045
1046
1047     {
1048         int this_rdbin = (*returndistortion >> 7);
1049
1050         if (this_rdbin >= 1024)
1051         {
1052             this_rdbin = 1023;
1053         }
1054
1055         cpi->error_bins[this_rdbin] ++;
1056     }
1057
1058 #if CONFIG_TEMPORAL_DENOISING
1059     if (cpi->oxcf.noise_sensitivity)
1060     {
1061       if (x->e_mbd.best_sse_inter_mode == DC_PRED) {
1062         // No best MV found.
1063         x->e_mbd.best_sse_inter_mode = best_mbmode.mode;
1064         x->e_mbd.best_sse_mv = best_mbmode.mv;
1065         x->e_mbd.need_to_clamp_best_mvs = best_mbmode.need_to_clamp_mvs;
1066         best_sse = best_rd_sse;
1067       }
1068       vp8_denoiser_denoise_mb(&cpi->denoiser, x, best_sse, zero_mv_sse,
1069                               recon_yoffset, recon_uvoffset);
1070
1071       // Reevaluate ZEROMV after denoising.
1072       if (best_mbmode.ref_frame == INTRA_FRAME)
1073       {
1074         int this_rd = 0;
1075         rate2 = 0;
1076         distortion2 = 0;
1077         x->e_mbd.mode_info_context->mbmi.ref_frame = LAST_FRAME;
1078         rate2 += x->ref_frame_cost[x->e_mbd.mode_info_context->mbmi.ref_frame];
1079         this_mode = ZEROMV;
1080         rate2 += vp8_cost_mv_ref(this_mode, mdcounts);
1081         x->e_mbd.mode_info_context->mbmi.mode = this_mode;
1082         x->e_mbd.mode_info_context->mbmi.uv_mode = DC_PRED;
1083         x->e_mbd.mode_info_context->mbmi.mv.as_int = 0;
1084         this_rd = evaluate_inter_mode(&sse, rate2, &distortion2, cpi, x);
1085
1086         if (this_rd < best_rd || x->skip)
1087         {
1088             vpx_memcpy(&best_mbmode, &x->e_mbd.mode_info_context->mbmi,
1089                        sizeof(MB_MODE_INFO));
1090         }
1091       }
1092     }
1093 #endif
1094
1095     if (cpi->is_src_frame_alt_ref &&
1096         (best_mbmode.mode != ZEROMV || best_mbmode.ref_frame != ALTREF_FRAME))
1097     {
1098         x->e_mbd.mode_info_context->mbmi.mode = ZEROMV;
1099         x->e_mbd.mode_info_context->mbmi.ref_frame = ALTREF_FRAME;
1100         x->e_mbd.mode_info_context->mbmi.mv.as_int = 0;
1101         x->e_mbd.mode_info_context->mbmi.uv_mode = DC_PRED;
1102         x->e_mbd.mode_info_context->mbmi.mb_skip_coeff =
1103                                         (cpi->common.mb_no_coeff_skip);
1104         x->e_mbd.mode_info_context->mbmi.partitioning = 0;
1105
1106         return;
1107     }
1108
1109     /* set to the best mb mode, this copy can be skip if x->skip since it
1110      * already has the right content */
1111     if (!x->skip)
1112         vpx_memcpy(&x->e_mbd.mode_info_context->mbmi, &best_mbmode,
1113                    sizeof(MB_MODE_INFO));
1114
1115     if (best_mbmode.mode <= B_PRED)
1116     {
1117         /* set mode_info_context->mbmi.uv_mode */
1118         pick_intra_mbuv_mode(x);
1119     }
1120
1121     if (sign_bias
1122       != cpi->common.ref_frame_sign_bias[xd->mode_info_context->mbmi.ref_frame])
1123         best_ref_mv.as_int = best_ref_mv_sb[!sign_bias].as_int;
1124
1125     update_mvcount(cpi, &x->e_mbd, &best_ref_mv);
1126 }
1127
1128
1129 void vp8_pick_intra_mode(VP8_COMP *cpi, MACROBLOCK *x, int *rate_)
1130 {
1131     int error4x4, error16x16 = INT_MAX;
1132     int rate, best_rate = 0, distortion, best_sse;
1133     MB_PREDICTION_MODE mode, best_mode = DC_PRED;
1134     int this_rd;
1135     unsigned int sse;
1136     BLOCK *b = &x->block[0];
1137     MACROBLOCKD *xd = &x->e_mbd;
1138
1139     xd->mode_info_context->mbmi.ref_frame = INTRA_FRAME;
1140
1141     pick_intra_mbuv_mode(x);
1142
1143     for (mode = DC_PRED; mode <= TM_PRED; mode ++)
1144     {
1145         xd->mode_info_context->mbmi.mode = mode;
1146         vp8_build_intra_predictors_mby_s(xd,
1147                                          xd->dst.y_buffer - xd->dst.y_stride,
1148                                          xd->dst.y_buffer - 1,
1149                                          xd->dst.y_stride,
1150                                          xd->predictor,
1151                                          16);
1152         distortion = vp8_variance16x16
1153             (*(b->base_src), b->src_stride, xd->predictor, 16, &sse);
1154         rate = x->mbmode_cost[xd->frame_type][mode];
1155         this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1156
1157         if (error16x16 > this_rd)
1158         {
1159             error16x16 = this_rd;
1160             best_mode = mode;
1161             best_sse = sse;
1162             best_rate = rate;
1163         }
1164     }
1165     xd->mode_info_context->mbmi.mode = best_mode;
1166
1167     error4x4 = pick_intra4x4mby_modes(x, &rate,
1168                                       &best_sse);
1169     if (error4x4 < error16x16)
1170     {
1171         xd->mode_info_context->mbmi.mode = B_PRED;
1172         best_rate = rate;
1173     }
1174
1175     *rate_ = best_rate;
1176 }