]> granicus.if.org Git - libvpx/blob - vp8/encoder/pickinter.c
Merge "Extend the external fb interface to allocate individual planes."
[libvpx] / 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 "./vpx_dsp_rtcd.h"
15 #include "onyx_int.h"
16 #include "modecosts.h"
17 #include "encodeintra.h"
18 #include "vp8/common/common.h"
19 #include "vp8/common/entropymode.h"
20 #include "pickinter.h"
21 #include "vp8/common/findnearmv.h"
22 #include "encodemb.h"
23 #include "vp8/common/reconinter.h"
24 #include "vp8/common/reconintra.h"
25 #include "vp8/common/reconintra4x4.h"
26 #include "vpx_dsp/variance.h"
27 #include "mcomp.h"
28 #include "rdopt.h"
29 #include "vpx_dsp/vpx_dsp_common.h"
30 #include "vpx_mem/vpx_mem.h"
31 #if CONFIG_TEMPORAL_DENOISING
32 #include "denoising.h"
33 #endif
34
35 #ifdef SPEEDSTATS
36 extern unsigned int cnt_pm;
37 #endif
38
39 #define MODEL_MODE 1
40
41 extern const int vp8_ref_frame_order[MAX_MODES];
42 extern const MB_PREDICTION_MODE vp8_mode_order[MAX_MODES];
43
44 // Fixed point implementation of a skin color classifier. Skin color
45 // is model by a Gaussian distribution in the CbCr color space.
46 // See ../../test/skin_color_detector_test.cc where the reference
47 // skin color classifier is defined.
48
49 // Fixed-point skin color model parameters.
50 static const int skin_mean[5][2] =
51     {{7463, 9614}, {6400, 10240}, {7040, 10240}, {8320, 9280}, {6800, 9614}};
52 static const int skin_inv_cov[4] = {4107, 1663, 1663, 2157};  // q16
53 static const int skin_threshold[6] = {1570636, 1400000, 800000, 800000, 800000,
54     800000};  // q18
55
56 // Evaluates the Mahalanobis distance measure for the input CbCr values.
57 static int evaluate_skin_color_difference(int cb, int cr, int idx) {
58   const int cb_q6 = cb << 6;
59   const int cr_q6 = cr << 6;
60   const int cb_diff_q12 =
61       (cb_q6 - skin_mean[idx][0]) * (cb_q6 - skin_mean[idx][0]);
62   const int cbcr_diff_q12 =
63       (cb_q6 - skin_mean[idx][0]) * (cr_q6 - skin_mean[idx][1]);
64   const int cr_diff_q12 =
65       (cr_q6 - skin_mean[idx][1]) * (cr_q6 - skin_mean[idx][1]);
66   const int cb_diff_q2 = (cb_diff_q12 + (1 << 9)) >> 10;
67   const int cbcr_diff_q2 = (cbcr_diff_q12 + (1 << 9)) >> 10;
68   const int cr_diff_q2 = (cr_diff_q12 + (1 << 9)) >> 10;
69   const int skin_diff = skin_inv_cov[0] * cb_diff_q2 +
70       skin_inv_cov[1] * cbcr_diff_q2 +
71       skin_inv_cov[2] * cbcr_diff_q2 +
72       skin_inv_cov[3] * cr_diff_q2;
73   return skin_diff;
74 }
75
76 // Checks if the input yCbCr values corresponds to skin color.
77 static int is_skin_color(int y, int cb, int cr, int consec_zeromv)
78 {
79   if (y < 40 || y > 220)
80   {
81     return 0;
82   }
83   else
84   {
85     if (MODEL_MODE == 0)
86     {
87       return (evaluate_skin_color_difference(cb, cr, 0) < skin_threshold[0]);
88     }
89     else
90     {
91       int i = 0;
92       // No skin if block has been zero motion for long consecutive time.
93       if (consec_zeromv > 60)
94         return 0;
95       // Exit on grey.
96        if (cb == 128 && cr == 128)
97          return 0;
98        // Exit on very strong cb.
99        if (cb > 150 && cr < 110)
100          return 0;
101        for (; i < 5; i++) {
102          int skin_color_diff = evaluate_skin_color_difference(cb, cr, i);
103          if (skin_color_diff < skin_threshold[i + 1]) {
104             if (y < 60 && skin_color_diff > 3 * (skin_threshold[i + 1] >> 2))
105               return 0;
106             else if (consec_zeromv > 25 &&
107                      skin_color_diff > (skin_threshold[i + 1] >> 1))
108               return 0;
109             else
110              return 1;
111          }
112          // Exit if difference is much large than the threshold.
113          if (skin_color_diff > (skin_threshold[i + 1] << 3)) {
114            return 0;
115          }
116        }
117       return 0;
118     }
119   }
120 }
121
122 static int macroblock_corner_grad(unsigned char* signal, int stride,
123                                   int offsetx, int offsety, int sgnx, int sgny)
124 {
125   int y1 = signal[offsetx * stride + offsety];
126   int y2 = signal[offsetx * stride + offsety + sgny];
127   int y3 = signal[(offsetx + sgnx) * stride + offsety];
128   int y4 = signal[(offsetx + sgnx) * stride + offsety + sgny];
129   return VPXMAX(VPXMAX(abs(y1 - y2), abs(y1 - y3)), abs(y1 - y4));
130 }
131
132 static int check_dot_artifact_candidate(VP8_COMP *cpi,
133                                         MACROBLOCK *x,
134                                         unsigned char *target_last,
135                                         int stride,
136                                         unsigned char* last_ref,
137                                         int mb_row,
138                                         int mb_col,
139                                         int channel)
140 {
141   int threshold1 = 6;
142   int threshold2 = 3;
143   unsigned int max_num = (cpi->common.MBs) / 10;
144   int grad_last = 0;
145   int grad_source = 0;
146   int index = mb_row * cpi->common.mb_cols + mb_col;
147   // Threshold for #consecutive (base layer) frames using zero_last mode.
148   int num_frames = 30;
149   int shift = 15;
150   if (channel > 0) {
151     shift = 7;
152   }
153   if (cpi->oxcf.number_of_layers > 1)
154   {
155     num_frames = 20;
156   }
157   x->zero_last_dot_suppress = 0;
158   // Blocks on base layer frames that have been using ZEROMV_LAST repeatedly
159   // (i.e, at least |x| consecutive frames are candidates for increasing the
160   // rd adjustment for zero_last mode.
161   // Only allow this for at most |max_num| blocks per frame.
162   // Don't allow this for screen content input.
163   if (cpi->current_layer == 0 &&
164       cpi->consec_zero_last_mvbias[index] > num_frames &&
165       x->mbs_zero_last_dot_suppress < max_num &&
166       !cpi->oxcf.screen_content_mode)
167   {
168     // If this block is checked here, label it so we don't check it again until
169     // ~|x| framaes later.
170     x->zero_last_dot_suppress = 1;
171     // Dot artifact is noticeable as strong gradient at corners of macroblock,
172     // for flat areas. As a simple detector for now, we look for a high
173     // corner gradient on last ref, and a smaller gradient on source.
174     // Check 4 corners, return if any satisfy condition.
175     // Top-left:
176     grad_last = macroblock_corner_grad(last_ref, stride, 0, 0, 1, 1);
177     grad_source = macroblock_corner_grad(target_last, stride, 0, 0, 1, 1);
178     if (grad_last >= threshold1 && grad_source <= threshold2)
179     {
180        x->mbs_zero_last_dot_suppress++;
181        return 1;
182     }
183     // Top-right:
184     grad_last = macroblock_corner_grad(last_ref, stride, 0, shift, 1, -1);
185     grad_source = macroblock_corner_grad(target_last, stride, 0, shift, 1, -1);
186     if (grad_last >= threshold1 && grad_source <= threshold2)
187     {
188       x->mbs_zero_last_dot_suppress++;
189       return 1;
190     }
191     // Bottom-left:
192     grad_last = macroblock_corner_grad(last_ref, stride, shift, 0, -1, 1);
193     grad_source = macroblock_corner_grad(target_last, stride, shift, 0, -1, 1);
194     if (grad_last >= threshold1 && grad_source <= threshold2)
195     {
196       x->mbs_zero_last_dot_suppress++;
197       return 1;
198     }
199     // Bottom-right:
200     grad_last = macroblock_corner_grad(last_ref, stride, shift, shift, -1, -1);
201     grad_source = macroblock_corner_grad(target_last, stride, shift, shift, -1, -1);
202     if (grad_last >= threshold1 && grad_source <= threshold2)
203     {
204       x->mbs_zero_last_dot_suppress++;
205       return 1;
206     }
207     return 0;
208   }
209   return 0;
210 }
211
212 int vp8_skip_fractional_mv_step(MACROBLOCK *mb, BLOCK *b, BLOCKD *d,
213                                 int_mv *bestmv, int_mv *ref_mv,
214                                 int error_per_bit,
215                                 const vp8_variance_fn_ptr_t *vfp,
216                                 int *mvcost[2], int *distortion,
217                                 unsigned int *sse)
218 {
219     (void) b;
220     (void) d;
221     (void) ref_mv;
222     (void) error_per_bit;
223     (void) vfp;
224     (void) mb;
225     (void) mvcost;
226     (void) distortion;
227     (void) sse;
228     bestmv->as_mv.row <<= 3;
229     bestmv->as_mv.col <<= 3;
230     return 0;
231 }
232
233
234 int vp8_get_inter_mbpred_error(MACROBLOCK *mb,
235                                   const vp8_variance_fn_ptr_t *vfp,
236                                   unsigned int *sse,
237                                   int_mv this_mv)
238 {
239
240     BLOCK *b = &mb->block[0];
241     BLOCKD *d = &mb->e_mbd.block[0];
242     unsigned char *what = (*(b->base_src) + b->src);
243     int what_stride = b->src_stride;
244     int pre_stride = mb->e_mbd.pre.y_stride;
245     unsigned char *in_what = mb->e_mbd.pre.y_buffer + d->offset ;
246     int in_what_stride = pre_stride;
247     int xoffset = this_mv.as_mv.col & 7;
248     int yoffset = this_mv.as_mv.row & 7;
249
250     in_what += (this_mv.as_mv.row >> 3) * pre_stride + (this_mv.as_mv.col >> 3);
251
252     if (xoffset | yoffset)
253     {
254         return vfp->svf(in_what, in_what_stride, xoffset, yoffset, what, what_stride, sse);
255     }
256     else
257     {
258         return vfp->vf(what, what_stride, in_what, in_what_stride, sse);
259     }
260
261 }
262
263 static int get_prediction_error(BLOCK *be, BLOCKD *b)
264 {
265     unsigned char *sptr;
266     unsigned char *dptr;
267     sptr = (*(be->base_src) + be->src);
268     dptr = b->predictor;
269
270     return vpx_get4x4sse_cs(sptr, be->src_stride, dptr, 16);
271
272 }
273
274 static int pick_intra4x4block(
275     MACROBLOCK *x,
276     int ib,
277     B_PREDICTION_MODE *best_mode,
278     const int *mode_costs,
279
280     int *bestrate,
281     int *bestdistortion)
282 {
283
284     BLOCKD *b = &x->e_mbd.block[ib];
285     BLOCK *be = &x->block[ib];
286     int dst_stride = x->e_mbd.dst.y_stride;
287     unsigned char *dst = x->e_mbd.dst.y_buffer + b->offset;
288     B_PREDICTION_MODE mode;
289     int best_rd = INT_MAX;
290     int rate;
291     int distortion;
292
293     unsigned char *Above = dst - dst_stride;
294     unsigned char *yleft = dst - 1;
295     unsigned char top_left = Above[-1];
296
297     for (mode = B_DC_PRED; mode <= B_HE_PRED; mode++)
298     {
299         int this_rd;
300
301         rate = mode_costs[mode];
302
303         vp8_intra4x4_predict(Above, yleft, dst_stride, mode,
304                              b->predictor, 16, top_left);
305         distortion = get_prediction_error(be, b);
306         this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
307
308         if (this_rd < best_rd)
309         {
310             *bestrate = rate;
311             *bestdistortion = distortion;
312             best_rd = this_rd;
313             *best_mode = mode;
314         }
315     }
316
317     b->bmi.as_mode = *best_mode;
318     vp8_encode_intra4x4block(x, ib);
319     return best_rd;
320 }
321
322
323 static int pick_intra4x4mby_modes
324 (
325     MACROBLOCK *mb,
326     int *Rate,
327     int *best_dist
328 )
329 {
330     MACROBLOCKD *const xd = &mb->e_mbd;
331     int i;
332     int cost = mb->mbmode_cost [xd->frame_type] [B_PRED];
333     int error;
334     int distortion = 0;
335     const int *bmode_costs;
336
337     intra_prediction_down_copy(xd, xd->dst.y_buffer - xd->dst.y_stride + 16);
338
339     bmode_costs = mb->inter_bmode_costs;
340
341     for (i = 0; i < 16; i++)
342     {
343         MODE_INFO *const mic = xd->mode_info_context;
344         const int mis = xd->mode_info_stride;
345
346         B_PREDICTION_MODE UNINITIALIZED_IS_SAFE(best_mode);
347         int UNINITIALIZED_IS_SAFE(r), UNINITIALIZED_IS_SAFE(d);
348
349         if (mb->e_mbd.frame_type == KEY_FRAME)
350         {
351             const B_PREDICTION_MODE A = above_block_mode(mic, i, mis);
352             const B_PREDICTION_MODE L = left_block_mode(mic, i);
353
354             bmode_costs  = mb->bmode_costs[A][L];
355         }
356
357
358         pick_intra4x4block(mb, i, &best_mode, bmode_costs, &r, &d);
359
360         cost += r;
361         distortion += d;
362         mic->bmi[i].as_mode = best_mode;
363
364         /* Break out case where we have already exceeded best so far value
365          * that was passed in
366          */
367         if (distortion > *best_dist)
368             break;
369     }
370
371     *Rate = cost;
372
373     if (i == 16)
374     {
375         *best_dist = distortion;
376         error = RDCOST(mb->rdmult, mb->rddiv, cost, distortion);
377     }
378     else
379     {
380         *best_dist = INT_MAX;
381         error = INT_MAX;
382     }
383
384     return error;
385 }
386
387 static void pick_intra_mbuv_mode(MACROBLOCK *mb)
388 {
389
390     MACROBLOCKD *x = &mb->e_mbd;
391     unsigned char *uabove_row = x->dst.u_buffer - x->dst.uv_stride;
392     unsigned char *vabove_row = x->dst.v_buffer - x->dst.uv_stride;
393     unsigned char *usrc_ptr = (mb->block[16].src + *mb->block[16].base_src);
394     unsigned char *vsrc_ptr = (mb->block[20].src + *mb->block[20].base_src);
395     int uvsrc_stride = mb->block[16].src_stride;
396     unsigned char uleft_col[8];
397     unsigned char vleft_col[8];
398     unsigned char utop_left = uabove_row[-1];
399     unsigned char vtop_left = vabove_row[-1];
400     int i, j;
401     int expected_udc;
402     int expected_vdc;
403     int shift;
404     int Uaverage = 0;
405     int Vaverage = 0;
406     int diff;
407     int pred_error[4] = {0, 0, 0, 0}, best_error = INT_MAX;
408     MB_PREDICTION_MODE UNINITIALIZED_IS_SAFE(best_mode);
409
410
411     for (i = 0; i < 8; i++)
412     {
413         uleft_col[i] = x->dst.u_buffer [i* x->dst.uv_stride -1];
414         vleft_col[i] = x->dst.v_buffer [i* x->dst.uv_stride -1];
415     }
416
417     if (!x->up_available && !x->left_available)
418     {
419         expected_udc = 128;
420         expected_vdc = 128;
421     }
422     else
423     {
424         shift = 2;
425
426         if (x->up_available)
427         {
428
429             for (i = 0; i < 8; i++)
430             {
431                 Uaverage += uabove_row[i];
432                 Vaverage += vabove_row[i];
433             }
434
435             shift ++;
436
437         }
438
439         if (x->left_available)
440         {
441             for (i = 0; i < 8; i++)
442             {
443                 Uaverage += uleft_col[i];
444                 Vaverage += vleft_col[i];
445             }
446
447             shift ++;
448
449         }
450
451         expected_udc = (Uaverage + (1 << (shift - 1))) >> shift;
452         expected_vdc = (Vaverage + (1 << (shift - 1))) >> shift;
453     }
454
455
456     for (i = 0; i < 8; i++)
457     {
458         for (j = 0; j < 8; j++)
459         {
460
461             int predu = uleft_col[i] + uabove_row[j] - utop_left;
462             int predv = vleft_col[i] + vabove_row[j] - vtop_left;
463             int u_p, v_p;
464
465             u_p = usrc_ptr[j];
466             v_p = vsrc_ptr[j];
467
468             if (predu < 0)
469                 predu = 0;
470
471             if (predu > 255)
472                 predu = 255;
473
474             if (predv < 0)
475                 predv = 0;
476
477             if (predv > 255)
478                 predv = 255;
479
480
481             diff = u_p - expected_udc;
482             pred_error[DC_PRED] += diff * diff;
483             diff = v_p - expected_vdc;
484             pred_error[DC_PRED] += diff * diff;
485
486
487             diff = u_p - uabove_row[j];
488             pred_error[V_PRED] += diff * diff;
489             diff = v_p - vabove_row[j];
490             pred_error[V_PRED] += diff * diff;
491
492
493             diff = u_p - uleft_col[i];
494             pred_error[H_PRED] += diff * diff;
495             diff = v_p - vleft_col[i];
496             pred_error[H_PRED] += diff * diff;
497
498
499             diff = u_p - predu;
500             pred_error[TM_PRED] += diff * diff;
501             diff = v_p - predv;
502             pred_error[TM_PRED] += diff * diff;
503
504
505         }
506
507         usrc_ptr += uvsrc_stride;
508         vsrc_ptr += uvsrc_stride;
509
510         if (i == 3)
511         {
512             usrc_ptr = (mb->block[18].src + *mb->block[18].base_src);
513             vsrc_ptr = (mb->block[22].src + *mb->block[22].base_src);
514         }
515
516
517
518     }
519
520
521     for (i = DC_PRED; i <= TM_PRED; i++)
522     {
523         if (best_error > pred_error[i])
524         {
525             best_error = pred_error[i];
526             best_mode = (MB_PREDICTION_MODE)i;
527         }
528     }
529
530
531     mb->e_mbd.mode_info_context->mbmi.uv_mode = best_mode;
532
533 }
534
535 static void update_mvcount(MACROBLOCK *x, int_mv *best_ref_mv)
536 {
537     MACROBLOCKD *xd = &x->e_mbd;
538     /* Split MV modes currently not supported when RD is nopt enabled,
539      * therefore, only need to modify MVcount in NEWMV mode. */
540     if (xd->mode_info_context->mbmi.mode == NEWMV)
541     {
542         x->MVcount[0][mv_max+((xd->mode_info_context->mbmi.mv.as_mv.row -
543                                       best_ref_mv->as_mv.row) >> 1)]++;
544         x->MVcount[1][mv_max+((xd->mode_info_context->mbmi.mv.as_mv.col -
545                                       best_ref_mv->as_mv.col) >> 1)]++;
546     }
547 }
548
549
550 #if CONFIG_MULTI_RES_ENCODING
551 static
552 void get_lower_res_motion_info(VP8_COMP *cpi, MACROBLOCKD *xd, int *dissim,
553                                int *parent_ref_frame,
554                                MB_PREDICTION_MODE *parent_mode,
555                                int_mv *parent_ref_mv, int mb_row, int mb_col)
556 {
557     LOWER_RES_MB_INFO* store_mode_info
558                           = ((LOWER_RES_FRAME_INFO*)cpi->oxcf.mr_low_res_mode_info)->mb_info;
559     unsigned int parent_mb_index;
560
561     /* Consider different down_sampling_factor.  */
562     {
563         /* TODO: Removed the loop that supports special down_sampling_factor
564          * such as 2, 4, 8. Will revisit it if needed.
565          * Should also try using a look-up table to see if it helps
566          * performance. */
567         int parent_mb_row, parent_mb_col;
568
569         parent_mb_row = mb_row*cpi->oxcf.mr_down_sampling_factor.den
570                     /cpi->oxcf.mr_down_sampling_factor.num;
571         parent_mb_col = mb_col*cpi->oxcf.mr_down_sampling_factor.den
572                     /cpi->oxcf.mr_down_sampling_factor.num;
573         parent_mb_index = parent_mb_row*cpi->mr_low_res_mb_cols + parent_mb_col;
574     }
575
576     /* Read lower-resolution mode & motion result from memory.*/
577     *parent_ref_frame = store_mode_info[parent_mb_index].ref_frame;
578     *parent_mode =  store_mode_info[parent_mb_index].mode;
579     *dissim = store_mode_info[parent_mb_index].dissim;
580
581     /* For highest-resolution encoder, adjust dissim value. Lower its quality
582      * for good performance. */
583     if (cpi->oxcf.mr_encoder_id == (cpi->oxcf.mr_total_resolutions - 1))
584         *dissim>>=1;
585
586     if(*parent_ref_frame != INTRA_FRAME)
587     {
588         /* Consider different down_sampling_factor.
589          * The result can be rounded to be more precise, but it takes more time.
590          */
591         (*parent_ref_mv).as_mv.row = store_mode_info[parent_mb_index].mv.as_mv.row
592                                   *cpi->oxcf.mr_down_sampling_factor.num
593                                   /cpi->oxcf.mr_down_sampling_factor.den;
594         (*parent_ref_mv).as_mv.col = store_mode_info[parent_mb_index].mv.as_mv.col
595                                   *cpi->oxcf.mr_down_sampling_factor.num
596                                   /cpi->oxcf.mr_down_sampling_factor.den;
597
598         vp8_clamp_mv2(parent_ref_mv, xd);
599     }
600 }
601 #endif
602
603 static void check_for_encode_breakout(unsigned int sse, MACROBLOCK* x)
604 {
605     MACROBLOCKD *xd = &x->e_mbd;
606
607     unsigned int threshold = (xd->block[0].dequant[1]
608         * xd->block[0].dequant[1] >>4);
609
610     if(threshold < x->encode_breakout)
611         threshold = x->encode_breakout;
612
613     if (sse < threshold )
614     {
615         /* Check u and v to make sure skip is ok */
616         unsigned int sse2 = 0;
617
618         sse2 = VP8_UVSSE(x);
619
620         if (sse2 * 2 < x->encode_breakout)
621             x->skip = 1;
622         else
623             x->skip = 0;
624     }
625 }
626
627 static int evaluate_inter_mode(unsigned int* sse, int rate2, int* distortion2,
628                                VP8_COMP *cpi, MACROBLOCK *x, int rd_adj)
629 {
630     MB_PREDICTION_MODE this_mode = x->e_mbd.mode_info_context->mbmi.mode;
631     int_mv mv = x->e_mbd.mode_info_context->mbmi.mv;
632     int this_rd;
633     int denoise_aggressive = 0;
634     /* Exit early and don't compute the distortion if this macroblock
635      * is marked inactive. */
636     if (cpi->active_map_enabled && x->active_ptr[0] == 0)
637     {
638         *sse = 0;
639         *distortion2 = 0;
640         x->skip = 1;
641         return INT_MAX;
642     }
643
644     if((this_mode != NEWMV) ||
645         !(cpi->sf.half_pixel_search) || cpi->common.full_pixel==1)
646         *distortion2 = vp8_get_inter_mbpred_error(x,
647                                               &cpi->fn_ptr[BLOCK_16X16],
648                                               sse, mv);
649
650     this_rd = RDCOST(x->rdmult, x->rddiv, rate2, *distortion2);
651
652 #if CONFIG_TEMPORAL_DENOISING
653     if (cpi->oxcf.noise_sensitivity > 0) {
654       denoise_aggressive =
655         (cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) ? 1 : 0;
656     }
657 #endif
658
659     // Adjust rd for ZEROMV and LAST, if LAST is the closest reference frame.
660     // TODO: We should also add condition on distance of closest to current.
661     if(!cpi->oxcf.screen_content_mode &&
662        this_mode == ZEROMV &&
663        x->e_mbd.mode_info_context->mbmi.ref_frame == LAST_FRAME &&
664        (denoise_aggressive || (cpi->closest_reference_frame == LAST_FRAME)))
665     {
666         // No adjustment if block is considered to be skin area.
667         if(x->is_skin)
668             rd_adj = 100;
669
670         this_rd = ((int64_t)this_rd) * rd_adj / 100;
671     }
672
673     check_for_encode_breakout(*sse, x);
674     return this_rd;
675 }
676
677 static void calculate_zeromv_rd_adjustment(VP8_COMP *cpi, MACROBLOCK *x,
678                                     int *rd_adjustment)
679 {
680     MODE_INFO *mic = x->e_mbd.mode_info_context;
681     int_mv mv_l, mv_a, mv_al;
682     int local_motion_check = 0;
683
684     if (cpi->lf_zeromv_pct > 40)
685     {
686         /* left mb */
687         mic -= 1;
688         mv_l = mic->mbmi.mv;
689
690         if (mic->mbmi.ref_frame != INTRA_FRAME)
691             if( abs(mv_l.as_mv.row) < 8 && abs(mv_l.as_mv.col) < 8)
692                 local_motion_check++;
693
694         /* above-left mb */
695         mic -= x->e_mbd.mode_info_stride;
696         mv_al = mic->mbmi.mv;
697
698         if (mic->mbmi.ref_frame != INTRA_FRAME)
699             if( abs(mv_al.as_mv.row) < 8 && abs(mv_al.as_mv.col) < 8)
700                 local_motion_check++;
701
702         /* above mb */
703         mic += 1;
704         mv_a = mic->mbmi.mv;
705
706         if (mic->mbmi.ref_frame != INTRA_FRAME)
707             if( abs(mv_a.as_mv.row) < 8 && abs(mv_a.as_mv.col) < 8)
708                 local_motion_check++;
709
710         if (((!x->e_mbd.mb_to_top_edge || !x->e_mbd.mb_to_left_edge)
711             && local_motion_check >0) ||  local_motion_check >2 )
712             *rd_adjustment = 80;
713         else if (local_motion_check > 0)
714             *rd_adjustment = 90;
715     }
716 }
717
718 void vp8_pick_inter_mode(VP8_COMP *cpi, MACROBLOCK *x, int recon_yoffset,
719                          int recon_uvoffset, int *returnrate,
720                          int *returndistortion, int *returnintra, int mb_row,
721                          int mb_col)
722 {
723     BLOCK *b = &x->block[0];
724     BLOCKD *d = &x->e_mbd.block[0];
725     MACROBLOCKD *xd = &x->e_mbd;
726     MB_MODE_INFO best_mbmode;
727
728     int_mv best_ref_mv_sb[2];
729     int_mv mode_mv_sb[2][MB_MODE_COUNT];
730     int_mv best_ref_mv;
731     int_mv *mode_mv;
732     MB_PREDICTION_MODE this_mode;
733     int num00;
734     int mdcounts[4];
735     int best_rd = INT_MAX;
736     int rd_adjustment = 100;
737     int best_intra_rd = INT_MAX;
738     int mode_index;
739     int rate;
740     int rate2;
741     int distortion2;
742     int bestsme = INT_MAX;
743     int best_mode_index = 0;
744     unsigned int sse = UINT_MAX, best_rd_sse = UINT_MAX;
745 #if CONFIG_TEMPORAL_DENOISING
746     unsigned int zero_mv_sse = UINT_MAX, best_sse = UINT_MAX;
747 #endif
748
749     int sf_improved_mv_pred = cpi->sf.improved_mv_pred;
750
751 #if CONFIG_MULTI_RES_ENCODING
752     int dissim = INT_MAX;
753     int parent_ref_frame = 0;
754     int_mv parent_ref_mv;
755     MB_PREDICTION_MODE parent_mode = 0;
756     int parent_ref_valid = 0;
757 #endif
758
759     int_mv mvp;
760
761     int near_sadidx[8] = {0, 1, 2, 3, 4, 5, 6, 7};
762     int saddone=0;
763     /* search range got from mv_pred(). It uses step_param levels. (0-7) */
764     int sr=0;
765
766     unsigned char *plane[4][3];
767     int ref_frame_map[4];
768     int sign_bias = 0;
769     int dot_artifact_candidate = 0;
770     get_predictor_pointers(cpi, plane, recon_yoffset, recon_uvoffset);
771
772     // If the current frame is using LAST as a reference, check for
773     // biasing the mode selection for dot artifacts.
774     if (cpi->ref_frame_flags & VP8_LAST_FRAME) {
775       unsigned char* target_y = x->src.y_buffer;
776       unsigned char* target_u = x->block[16].src + *x->block[16].base_src;
777       unsigned char* target_v = x->block[20].src + *x->block[20].base_src;
778       int stride = x->src.y_stride;
779       int stride_uv = x->block[16].src_stride;
780 #if CONFIG_TEMPORAL_DENOISING
781       if (cpi->oxcf.noise_sensitivity) {
782         const int uv_denoise = (cpi->oxcf.noise_sensitivity >= 2) ? 1 : 0;
783         target_y =
784             cpi->denoiser.yv12_running_avg[LAST_FRAME].y_buffer + recon_yoffset;
785         stride = cpi->denoiser.yv12_running_avg[LAST_FRAME].y_stride;
786         if (uv_denoise) {
787           target_u =
788               cpi->denoiser.yv12_running_avg[LAST_FRAME].u_buffer +
789                   recon_uvoffset;
790           target_v =
791               cpi->denoiser.yv12_running_avg[LAST_FRAME].v_buffer +
792                   recon_uvoffset;
793           stride_uv = cpi->denoiser.yv12_running_avg[LAST_FRAME].uv_stride;
794         }
795       }
796 #endif
797       dot_artifact_candidate =
798           check_dot_artifact_candidate(cpi, x, target_y, stride,
799               plane[LAST_FRAME][0], mb_row, mb_col, 0);
800       // If not found in Y channel, check UV channel.
801       if (!dot_artifact_candidate) {
802         dot_artifact_candidate =
803             check_dot_artifact_candidate(cpi, x, target_u, stride_uv,
804                 plane[LAST_FRAME][1], mb_row, mb_col, 1);
805         if (!dot_artifact_candidate) {
806           dot_artifact_candidate =
807               check_dot_artifact_candidate(cpi, x, target_v, stride_uv,
808                   plane[LAST_FRAME][2], mb_row, mb_col, 2);
809         }
810       }
811     }
812
813 #if CONFIG_MULTI_RES_ENCODING
814     // |parent_ref_valid| will be set here if potentially we can do mv resue for
815     // this higher resol (|cpi->oxcf.mr_encoder_id| > 0) frame.
816     // |parent_ref_valid| may be reset depending on |parent_ref_frame| for
817     // the current macroblock below.
818     parent_ref_valid = cpi->oxcf.mr_encoder_id && cpi->mr_low_res_mv_avail;
819     if (parent_ref_valid)
820     {
821         int parent_ref_flag;
822
823         get_lower_res_motion_info(cpi, xd, &dissim, &parent_ref_frame,
824                                   &parent_mode, &parent_ref_mv, mb_row, mb_col);
825
826         /* TODO(jkoleszar): The references available (ref_frame_flags) to the
827          * lower res encoder should match those available to this encoder, but
828          * there seems to be a situation where this mismatch can happen in the
829          * case of frame dropping and temporal layers. For example,
830          * GOLD being disallowed in ref_frame_flags, but being returned as
831          * parent_ref_frame.
832          *
833          * In this event, take the conservative approach of disabling the
834          * lower res info for this MB.
835          */
836
837         parent_ref_flag = 0;
838         // Note availability for mv reuse is only based on last and golden.
839         if (parent_ref_frame == LAST_FRAME)
840             parent_ref_flag = (cpi->ref_frame_flags & VP8_LAST_FRAME);
841         else if (parent_ref_frame == GOLDEN_FRAME)
842             parent_ref_flag = (cpi->ref_frame_flags & VP8_GOLD_FRAME);
843
844         //assert(!parent_ref_frame || parent_ref_flag);
845
846         // If |parent_ref_frame| did not match either last or golden then
847         // shut off mv reuse.
848         if (parent_ref_frame && !parent_ref_flag)
849             parent_ref_valid = 0;
850
851         // Don't do mv reuse since we want to allow for another mode besides
852         // ZEROMV_LAST to remove dot artifact.
853         if (dot_artifact_candidate)
854           parent_ref_valid = 0;
855     }
856 #endif
857
858     // Check if current macroblock is in skin area.
859     {
860     const int y = (x->src.y_buffer[7 * x->src.y_stride + 7] +
861         x->src.y_buffer[7 * x->src.y_stride + 8] +
862         x->src.y_buffer[8 * x->src.y_stride + 7] +
863         x->src.y_buffer[8 * x->src.y_stride + 8]) >> 2;
864     const int cb = (x->src.u_buffer[3 * x->src.uv_stride + 3] +
865         x->src.u_buffer[3 * x->src.uv_stride + 4] +
866         x->src.u_buffer[4 * x->src.uv_stride + 3] +
867         x->src.u_buffer[4 * x->src.uv_stride + 4]) >> 2;
868     const int cr = (x->src.v_buffer[3 * x->src.uv_stride + 3] +
869         x->src.v_buffer[3 * x->src.uv_stride + 4] +
870         x->src.v_buffer[4 * x->src.uv_stride + 3] +
871         x->src.v_buffer[4 * x->src.uv_stride + 4]) >> 2;
872     x->is_skin = 0;
873     if (!cpi->oxcf.screen_content_mode) {
874       int block_index = mb_row * cpi->common.mb_cols + mb_col;
875       x->is_skin = is_skin_color(y, cb, cr, cpi->consec_zero_last[block_index]);
876     }
877     }
878 #if CONFIG_TEMPORAL_DENOISING
879     if (cpi->oxcf.noise_sensitivity) {
880       // Under aggressive denoising mode, should we use skin map to reduce denoiser
881       // and ZEROMV bias? Will need to revisit the accuracy of this detection for
882       // very noisy input. For now keep this as is (i.e., don't turn it off).
883       // if (cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive)
884       //   x->is_skin = 0;
885     }
886 #endif
887
888     mode_mv = mode_mv_sb[sign_bias];
889     best_ref_mv.as_int = 0;
890     memset(mode_mv_sb, 0, sizeof(mode_mv_sb));
891     memset(&best_mbmode, 0, sizeof(best_mbmode));
892
893     /* Setup search priorities */
894 #if CONFIG_MULTI_RES_ENCODING
895     if (parent_ref_valid && parent_ref_frame && dissim < 8)
896     {
897         ref_frame_map[0] = -1;
898         ref_frame_map[1] = parent_ref_frame;
899         ref_frame_map[2] = -1;
900         ref_frame_map[3] = -1;
901     } else
902 #endif
903     get_reference_search_order(cpi, ref_frame_map);
904
905     /* Check to see if there is at least 1 valid reference frame that we need
906      * to calculate near_mvs.
907      */
908     if (ref_frame_map[1] > 0)
909     {
910         sign_bias = vp8_find_near_mvs_bias(&x->e_mbd,
911                                            x->e_mbd.mode_info_context,
912                                            mode_mv_sb,
913                                            best_ref_mv_sb,
914                                            mdcounts,
915                                            ref_frame_map[1],
916                                            cpi->common.ref_frame_sign_bias);
917
918         mode_mv = mode_mv_sb[sign_bias];
919         best_ref_mv.as_int = best_ref_mv_sb[sign_bias].as_int;
920     }
921
922     /* Count of the number of MBs tested so far this frame */
923     x->mbs_tested_so_far++;
924
925     *returnintra = INT_MAX;
926     x->skip = 0;
927
928     x->e_mbd.mode_info_context->mbmi.ref_frame = INTRA_FRAME;
929
930     /* If the frame has big static background and current MB is in low
931     *  motion area, its mode decision is biased to ZEROMV mode.
932     *  No adjustment if cpu_used is <= -12 (i.e., cpi->Speed >= 12).
933     *  At such speed settings, ZEROMV is already heavily favored.
934     */
935     if (cpi->Speed < 12) {
936       calculate_zeromv_rd_adjustment(cpi, x, &rd_adjustment);
937     }
938
939 #if CONFIG_TEMPORAL_DENOISING
940     if (cpi->oxcf.noise_sensitivity) {
941       rd_adjustment = (int)(rd_adjustment *
942           cpi->denoiser.denoise_pars.pickmode_mv_bias / 100);
943     }
944 #endif
945
946     if (dot_artifact_candidate)
947     {
948         // Bias against ZEROMV_LAST mode.
949         rd_adjustment = 150;
950     }
951
952
953     /* if we encode a new mv this is important
954      * find the best new motion vector
955      */
956     for (mode_index = 0; mode_index < MAX_MODES; mode_index++)
957     {
958         int frame_cost;
959         int this_rd = INT_MAX;
960         int this_ref_frame = ref_frame_map[vp8_ref_frame_order[mode_index]];
961
962         if (best_rd <= x->rd_threshes[mode_index])
963             continue;
964
965         if (this_ref_frame < 0)
966             continue;
967
968         x->e_mbd.mode_info_context->mbmi.ref_frame = this_ref_frame;
969
970         /* everything but intra */
971         if (x->e_mbd.mode_info_context->mbmi.ref_frame)
972         {
973             x->e_mbd.pre.y_buffer = plane[this_ref_frame][0];
974             x->e_mbd.pre.u_buffer = plane[this_ref_frame][1];
975             x->e_mbd.pre.v_buffer = plane[this_ref_frame][2];
976
977             if (sign_bias != cpi->common.ref_frame_sign_bias[this_ref_frame])
978             {
979                 sign_bias = cpi->common.ref_frame_sign_bias[this_ref_frame];
980                 mode_mv = mode_mv_sb[sign_bias];
981                 best_ref_mv.as_int = best_ref_mv_sb[sign_bias].as_int;
982             }
983
984 #if CONFIG_MULTI_RES_ENCODING
985             if (parent_ref_valid)
986             {
987                 if (vp8_mode_order[mode_index] == NEARESTMV &&
988                     mode_mv[NEARESTMV].as_int ==0)
989                     continue;
990                 if (vp8_mode_order[mode_index] == NEARMV &&
991                     mode_mv[NEARMV].as_int ==0)
992                     continue;
993
994                 if (vp8_mode_order[mode_index] == NEWMV && parent_mode == ZEROMV
995                     && best_ref_mv.as_int==0)
996                     continue;
997                 else if(vp8_mode_order[mode_index] == NEWMV && dissim==0
998                     && best_ref_mv.as_int==parent_ref_mv.as_int)
999                     continue;
1000             }
1001 #endif
1002         }
1003
1004         /* Check to see if the testing frequency for this mode is at its max
1005          * If so then prevent it from being tested and increase the threshold
1006          * for its testing */
1007         if (x->mode_test_hit_counts[mode_index] &&
1008                                          (cpi->mode_check_freq[mode_index] > 1))
1009         {
1010             if (x->mbs_tested_so_far <= (cpi->mode_check_freq[mode_index] *
1011                                          x->mode_test_hit_counts[mode_index]))
1012             {
1013                 /* Increase the threshold for coding this mode to make it less
1014                  * likely to be chosen */
1015                 x->rd_thresh_mult[mode_index] += 4;
1016
1017                 if (x->rd_thresh_mult[mode_index] > MAX_THRESHMULT)
1018                     x->rd_thresh_mult[mode_index] = MAX_THRESHMULT;
1019
1020                 x->rd_threshes[mode_index] =
1021                                  (cpi->rd_baseline_thresh[mode_index] >> 7) *
1022                                  x->rd_thresh_mult[mode_index];
1023                 continue;
1024             }
1025         }
1026
1027         /* We have now reached the point where we are going to test the current
1028          * mode so increment the counter for the number of times it has been
1029          * tested */
1030         x->mode_test_hit_counts[mode_index] ++;
1031
1032         rate2 = 0;
1033         distortion2 = 0;
1034
1035         this_mode = vp8_mode_order[mode_index];
1036
1037         x->e_mbd.mode_info_context->mbmi.mode = this_mode;
1038         x->e_mbd.mode_info_context->mbmi.uv_mode = DC_PRED;
1039
1040         /* Work out the cost assosciated with selecting the reference frame */
1041         frame_cost =
1042             x->ref_frame_cost[x->e_mbd.mode_info_context->mbmi.ref_frame];
1043         rate2 += frame_cost;
1044
1045         /* Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
1046          * unless ARNR filtering is enabled in which case we want
1047          * an unfiltered alternative */
1048         if (cpi->is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
1049         {
1050             if (this_mode != ZEROMV ||
1051                 x->e_mbd.mode_info_context->mbmi.ref_frame != ALTREF_FRAME)
1052                 continue;
1053         }
1054
1055         switch (this_mode)
1056         {
1057         case B_PRED:
1058             /* Pass best so far to pick_intra4x4mby_modes to use as breakout */
1059             distortion2 = best_rd_sse;
1060             pick_intra4x4mby_modes(x, &rate, &distortion2);
1061
1062             if (distortion2 == INT_MAX)
1063             {
1064                 this_rd = INT_MAX;
1065             }
1066             else
1067             {
1068                 rate2 += rate;
1069                 distortion2 = vpx_variance16x16(
1070                                     *(b->base_src), b->src_stride,
1071                                     x->e_mbd.predictor, 16, &sse);
1072                 this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
1073
1074                 if (this_rd < best_intra_rd)
1075                 {
1076                     best_intra_rd = this_rd;
1077                     *returnintra = distortion2;
1078                 }
1079             }
1080
1081             break;
1082
1083         case SPLITMV:
1084
1085             /* Split MV modes currently not supported when RD is not enabled. */
1086             break;
1087
1088         case DC_PRED:
1089         case V_PRED:
1090         case H_PRED:
1091         case TM_PRED:
1092             vp8_build_intra_predictors_mby_s(xd,
1093                                              xd->dst.y_buffer - xd->dst.y_stride,
1094                                              xd->dst.y_buffer - 1,
1095                                              xd->dst.y_stride,
1096                                              xd->predictor,
1097                                              16);
1098             distortion2 = vpx_variance16x16
1099                                           (*(b->base_src), b->src_stride,
1100                                           x->e_mbd.predictor, 16, &sse);
1101             rate2 += x->mbmode_cost[x->e_mbd.frame_type][x->e_mbd.mode_info_context->mbmi.mode];
1102             this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
1103
1104             if (this_rd < best_intra_rd)
1105             {
1106                 best_intra_rd = this_rd;
1107                 *returnintra = distortion2;
1108             }
1109             break;
1110
1111         case NEWMV:
1112         {
1113             int thissme;
1114             int step_param;
1115             int further_steps;
1116             int n = 0;
1117             int sadpb = x->sadperbit16;
1118             int_mv mvp_full;
1119
1120             int col_min = ((best_ref_mv.as_mv.col+7)>>3) - MAX_FULL_PEL_VAL;
1121             int row_min = ((best_ref_mv.as_mv.row+7)>>3) - MAX_FULL_PEL_VAL;
1122             int col_max = (best_ref_mv.as_mv.col>>3)
1123                          + MAX_FULL_PEL_VAL;
1124             int row_max = (best_ref_mv.as_mv.row>>3)
1125                          + MAX_FULL_PEL_VAL;
1126
1127             int tmp_col_min = x->mv_col_min;
1128             int tmp_col_max = x->mv_col_max;
1129             int tmp_row_min = x->mv_row_min;
1130             int tmp_row_max = x->mv_row_max;
1131
1132             int speed_adjust = (cpi->Speed > 5) ? ((cpi->Speed >= 8)? 3 : 2) : 1;
1133
1134             /* Further step/diamond searches as necessary */
1135             step_param = cpi->sf.first_step + speed_adjust;
1136
1137 #if CONFIG_MULTI_RES_ENCODING
1138             /* If lower-res frame is not available for mv reuse (because of
1139                frame dropping or different temporal layer pattern), then higher
1140                resol encoder does motion search without any previous knowledge.
1141                Also, since last frame motion info is not stored, then we can not
1142                use improved_mv_pred. */
1143             if (cpi->oxcf.mr_encoder_id)
1144                 sf_improved_mv_pred = 0;
1145
1146             // Only use parent MV as predictor if this candidate reference frame
1147             // (|this_ref_frame|) is equal to |parent_ref_frame|.
1148             if (parent_ref_valid && (parent_ref_frame == this_ref_frame))
1149             {
1150                 /* Use parent MV as predictor. Adjust search range
1151                  * accordingly.
1152                  */
1153                 mvp.as_int = parent_ref_mv.as_int;
1154                 mvp_full.as_mv.col = parent_ref_mv.as_mv.col>>3;
1155                 mvp_full.as_mv.row = parent_ref_mv.as_mv.row>>3;
1156
1157                 if(dissim <=32) step_param += 3;
1158                 else if(dissim <=128) step_param += 2;
1159                 else step_param += 1;
1160             }else
1161 #endif
1162             {
1163                 if(sf_improved_mv_pred)
1164                 {
1165                     if(!saddone)
1166                     {
1167                         vp8_cal_sad(cpi,xd,x, recon_yoffset ,&near_sadidx[0] );
1168                         saddone = 1;
1169                     }
1170
1171                     vp8_mv_pred(cpi, &x->e_mbd, x->e_mbd.mode_info_context,
1172                                 &mvp,x->e_mbd.mode_info_context->mbmi.ref_frame,
1173                                 cpi->common.ref_frame_sign_bias, &sr,
1174                                 &near_sadidx[0]);
1175
1176                     sr += speed_adjust;
1177                     /* adjust search range according to sr from mv prediction */
1178                     if(sr > step_param)
1179                         step_param = sr;
1180
1181                     mvp_full.as_mv.col = mvp.as_mv.col>>3;
1182                     mvp_full.as_mv.row = mvp.as_mv.row>>3;
1183                 }else
1184                 {
1185                     mvp.as_int = best_ref_mv.as_int;
1186                     mvp_full.as_mv.col = best_ref_mv.as_mv.col>>3;
1187                     mvp_full.as_mv.row = best_ref_mv.as_mv.row>>3;
1188                 }
1189             }
1190
1191 #if CONFIG_MULTI_RES_ENCODING
1192             if (parent_ref_valid && (parent_ref_frame == this_ref_frame) &&
1193                 dissim <= 2 &&
1194                 VPXMAX(abs(best_ref_mv.as_mv.row - parent_ref_mv.as_mv.row),
1195                        abs(best_ref_mv.as_mv.col - parent_ref_mv.as_mv.col)) <=
1196                     4)
1197             {
1198                 d->bmi.mv.as_int = mvp_full.as_int;
1199                 mode_mv[NEWMV].as_int = mvp_full.as_int;
1200
1201                 cpi->find_fractional_mv_step(x, b, d, &d->bmi.mv, &best_ref_mv,
1202                                              x->errorperbit,
1203                                              &cpi->fn_ptr[BLOCK_16X16],
1204                                              cpi->mb.mvcost,
1205                                              &distortion2,&sse);
1206             }else
1207 #endif
1208             {
1209                 /* Get intersection of UMV window and valid MV window to
1210                  * reduce # of checks in diamond search. */
1211                 if (x->mv_col_min < col_min )
1212                     x->mv_col_min = col_min;
1213                 if (x->mv_col_max > col_max )
1214                     x->mv_col_max = col_max;
1215                 if (x->mv_row_min < row_min )
1216                     x->mv_row_min = row_min;
1217                 if (x->mv_row_max > row_max )
1218                     x->mv_row_max = row_max;
1219
1220                 further_steps = (cpi->Speed >= 8)?
1221                            0: (cpi->sf.max_step_search_steps - 1 - step_param);
1222
1223                 if (cpi->sf.search_method == HEX)
1224                 {
1225 #if CONFIG_MULTI_RES_ENCODING
1226                 /* TODO: In higher-res pick_inter_mode, step_param is used to
1227                  * modify hex search range. Here, set step_param to 0 not to
1228                  * change the behavior in lowest-resolution encoder.
1229                  * Will improve it later.
1230                  */
1231                 /* Set step_param to 0 to ensure large-range motion search
1232                  * when mv reuse if not valid (i.e. |parent_ref_valid| = 0),
1233                  * or if this candidate reference frame (|this_ref_frame|) is
1234                  * not equal to |parent_ref_frame|.
1235                  */
1236                 if (!parent_ref_valid || (parent_ref_frame != this_ref_frame))
1237                     step_param = 0;
1238 #endif
1239                     bestsme = vp8_hex_search(x, b, d, &mvp_full, &d->bmi.mv,
1240                                           step_param, sadpb,
1241                                           &cpi->fn_ptr[BLOCK_16X16],
1242                                           x->mvsadcost, x->mvcost, &best_ref_mv);
1243                     mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
1244                 }
1245                 else
1246                 {
1247                     bestsme = cpi->diamond_search_sad(x, b, d, &mvp_full,
1248                                           &d->bmi.mv, step_param, sadpb, &num00,
1249                                           &cpi->fn_ptr[BLOCK_16X16],
1250                                           x->mvcost, &best_ref_mv);
1251                     mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
1252
1253                     /* Further step/diamond searches as necessary */
1254                     n = num00;
1255                     num00 = 0;
1256
1257                     while (n < further_steps)
1258                     {
1259                         n++;
1260
1261                         if (num00)
1262                             num00--;
1263                         else
1264                         {
1265                             thissme =
1266                             cpi->diamond_search_sad(x, b, d, &mvp_full,
1267                                                     &d->bmi.mv,
1268                                                     step_param + n,
1269                                                     sadpb, &num00,
1270                                                     &cpi->fn_ptr[BLOCK_16X16],
1271                                                     x->mvcost, &best_ref_mv);
1272                             if (thissme < bestsme)
1273                             {
1274                                 bestsme = thissme;
1275                                 mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
1276                             }
1277                             else
1278                             {
1279                                 d->bmi.mv.as_int = mode_mv[NEWMV].as_int;
1280                             }
1281                         }
1282                     }
1283                 }
1284
1285                 x->mv_col_min = tmp_col_min;
1286                 x->mv_col_max = tmp_col_max;
1287                 x->mv_row_min = tmp_row_min;
1288                 x->mv_row_max = tmp_row_max;
1289
1290                 if (bestsme < INT_MAX)
1291                     cpi->find_fractional_mv_step(x, b, d, &d->bmi.mv,
1292                                              &best_ref_mv, x->errorperbit,
1293                                              &cpi->fn_ptr[BLOCK_16X16],
1294                                              cpi->mb.mvcost,
1295                                              &distortion2,&sse);
1296             }
1297
1298             mode_mv[NEWMV].as_int = d->bmi.mv.as_int;
1299             // The clamp below is not necessary from the perspective
1300             // of VP8 bitstream, but is added to improve ChromeCast
1301             // mirroring's robustness. Please do not remove.
1302             vp8_clamp_mv2(&mode_mv[this_mode], xd);
1303             /* mv cost; */
1304             rate2 += vp8_mv_bit_cost(&mode_mv[NEWMV], &best_ref_mv,
1305                                      cpi->mb.mvcost, 128);
1306         }
1307
1308         case NEARESTMV:
1309         case NEARMV:
1310             if (mode_mv[this_mode].as_int == 0)
1311                 continue;
1312
1313         case ZEROMV:
1314
1315             /* Trap vectors that reach beyond the UMV borders
1316              * Note that ALL New MV, Nearest MV Near MV and Zero MV code drops
1317              * through to this point because of the lack of break statements
1318              * in the previous two cases.
1319              */
1320             if (((mode_mv[this_mode].as_mv.row >> 3) < x->mv_row_min) ||
1321                 ((mode_mv[this_mode].as_mv.row >> 3) > x->mv_row_max) ||
1322                 ((mode_mv[this_mode].as_mv.col >> 3) < x->mv_col_min) ||
1323                 ((mode_mv[this_mode].as_mv.col >> 3) > x->mv_col_max))
1324                 continue;
1325
1326             rate2 += vp8_cost_mv_ref(this_mode, mdcounts);
1327             x->e_mbd.mode_info_context->mbmi.mv.as_int =
1328                                                     mode_mv[this_mode].as_int;
1329             this_rd = evaluate_inter_mode(&sse, rate2, &distortion2, cpi, x,
1330                                           rd_adjustment);
1331
1332             break;
1333         default:
1334             break;
1335         }
1336
1337 #if CONFIG_TEMPORAL_DENOISING
1338         if (cpi->oxcf.noise_sensitivity)
1339         {
1340             /* Store for later use by denoiser. */
1341             // Dont' denoise with GOLDEN OR ALTREF is they are old reference
1342             // frames (greater than MAX_GF_ARF_DENOISE_RANGE frames in past).
1343             int skip_old_reference = ((this_ref_frame != LAST_FRAME) &&
1344                 (cpi->common.current_video_frame -
1345                  cpi->current_ref_frames[this_ref_frame] >
1346                  MAX_GF_ARF_DENOISE_RANGE)) ? 1 : 0;
1347             if (this_mode == ZEROMV && sse < zero_mv_sse &&
1348                 !skip_old_reference)
1349             {
1350                 zero_mv_sse = sse;
1351                 x->best_zeromv_reference_frame =
1352                         x->e_mbd.mode_info_context->mbmi.ref_frame;
1353             }
1354
1355             // Store the best NEWMV in x for later use in the denoiser.
1356             if (x->e_mbd.mode_info_context->mbmi.mode == NEWMV &&
1357                 sse < best_sse && !skip_old_reference)
1358             {
1359                 best_sse = sse;
1360                 x->best_sse_inter_mode = NEWMV;
1361                 x->best_sse_mv = x->e_mbd.mode_info_context->mbmi.mv;
1362                 x->need_to_clamp_best_mvs =
1363                     x->e_mbd.mode_info_context->mbmi.need_to_clamp_mvs;
1364                 x->best_reference_frame =
1365                     x->e_mbd.mode_info_context->mbmi.ref_frame;
1366             }
1367         }
1368 #endif
1369
1370         if (this_rd < best_rd || x->skip)
1371         {
1372             /* Note index of best mode */
1373             best_mode_index = mode_index;
1374
1375             *returnrate = rate2;
1376             *returndistortion = distortion2;
1377             best_rd_sse = sse;
1378             best_rd = this_rd;
1379             memcpy(&best_mbmode, &x->e_mbd.mode_info_context->mbmi,
1380                    sizeof(MB_MODE_INFO));
1381
1382             /* Testing this mode gave rise to an improvement in best error
1383              * score. Lower threshold a bit for next time
1384              */
1385             x->rd_thresh_mult[mode_index] =
1386                      (x->rd_thresh_mult[mode_index] >= (MIN_THRESHMULT + 2)) ?
1387                      x->rd_thresh_mult[mode_index] - 2 : MIN_THRESHMULT;
1388             x->rd_threshes[mode_index] =
1389                                    (cpi->rd_baseline_thresh[mode_index] >> 7) *
1390                                    x->rd_thresh_mult[mode_index];
1391         }
1392
1393         /* If the mode did not help improve the best error case then raise the
1394          * threshold for testing that mode next time around.
1395          */
1396         else
1397         {
1398             x->rd_thresh_mult[mode_index] += 4;
1399
1400             if (x->rd_thresh_mult[mode_index] > MAX_THRESHMULT)
1401                 x->rd_thresh_mult[mode_index] = MAX_THRESHMULT;
1402
1403             x->rd_threshes[mode_index] =
1404                          (cpi->rd_baseline_thresh[mode_index] >> 7) *
1405                          x->rd_thresh_mult[mode_index];
1406         }
1407
1408         if (x->skip)
1409             break;
1410     }
1411
1412     /* Reduce the activation RD thresholds for the best choice mode */
1413     if ((cpi->rd_baseline_thresh[best_mode_index] > 0) && (cpi->rd_baseline_thresh[best_mode_index] < (INT_MAX >> 2)))
1414     {
1415         int best_adjustment = (x->rd_thresh_mult[best_mode_index] >> 3);
1416
1417         x->rd_thresh_mult[best_mode_index] =
1418                         (x->rd_thresh_mult[best_mode_index]
1419                         >= (MIN_THRESHMULT + best_adjustment)) ?
1420                         x->rd_thresh_mult[best_mode_index] - best_adjustment :
1421                         MIN_THRESHMULT;
1422         x->rd_threshes[best_mode_index] =
1423                         (cpi->rd_baseline_thresh[best_mode_index] >> 7) *
1424                         x->rd_thresh_mult[best_mode_index];
1425     }
1426
1427
1428     {
1429         int this_rdbin = (*returndistortion >> 7);
1430
1431         if (this_rdbin >= 1024)
1432         {
1433             this_rdbin = 1023;
1434         }
1435
1436         x->error_bins[this_rdbin] ++;
1437     }
1438
1439 #if CONFIG_TEMPORAL_DENOISING
1440     if (cpi->oxcf.noise_sensitivity)
1441     {
1442         int block_index = mb_row * cpi->common.mb_cols + mb_col;
1443         int reevaluate = 0;
1444         int is_noisy = 0;
1445         if (x->best_sse_inter_mode == DC_PRED)
1446         {
1447             /* No best MV found. */
1448             x->best_sse_inter_mode = best_mbmode.mode;
1449             x->best_sse_mv = best_mbmode.mv;
1450             x->need_to_clamp_best_mvs = best_mbmode.need_to_clamp_mvs;
1451             x->best_reference_frame = best_mbmode.ref_frame;
1452             best_sse = best_rd_sse;
1453         }
1454         // For non-skin blocks that have selected ZEROMV for this current frame,
1455         // and have been selecting ZEROMV_LAST (on the base layer frame) at
1456         // least |x~20| consecutive past frames in a row, label the block for
1457         // possible increase in denoising strength. We also condition this
1458         // labeling on there being significant denoising in the scene
1459         if  (cpi->oxcf.noise_sensitivity == 4) {
1460           if (cpi->denoiser.nmse_source_diff >
1461               70 * cpi->denoiser.threshold_aggressive_mode / 100)
1462             is_noisy = 1;
1463         } else {
1464           if (cpi->mse_source_denoised > 1000)
1465             is_noisy = 1;
1466         }
1467         x->increase_denoising = 0;
1468         if (!x->is_skin &&
1469             x->best_sse_inter_mode == ZEROMV &&
1470             (x->best_reference_frame == LAST_FRAME ||
1471             x->best_reference_frame == cpi->closest_reference_frame) &&
1472             cpi->consec_zero_last[block_index] >= 20 &&
1473             is_noisy) {
1474             x->increase_denoising = 1;
1475         }
1476         x->denoise_zeromv = 0;
1477         vp8_denoiser_denoise_mb(&cpi->denoiser, x, best_sse, zero_mv_sse,
1478                                 recon_yoffset, recon_uvoffset,
1479                                 &cpi->common.lf_info, mb_row, mb_col,
1480                                 block_index,
1481                                 cpi->consec_zero_last_mvbias[block_index]);
1482
1483         // Reevaluate ZEROMV after denoising: for large noise content
1484         // (i.e., cpi->mse_source_denoised is above threshold), do this for all
1485         // blocks that did not pick ZEROMV as best mode but are using ZEROMV
1486         // for denoising. Otherwise, always re-evaluate for blocks that picked
1487         // INTRA mode as best mode.
1488         // Avoid blocks that have been biased against ZERO_LAST
1489         // (i.e., dot artifact candidate blocks).
1490         reevaluate = (best_mbmode.ref_frame == INTRA_FRAME) ||
1491                      (best_mbmode.mode != ZEROMV &&
1492                       x->denoise_zeromv &&
1493                       cpi->mse_source_denoised > 2000);
1494         if (!dot_artifact_candidate &&
1495             reevaluate &&
1496             x->best_zeromv_reference_frame != INTRA_FRAME)
1497         {
1498             int this_rd = 0;
1499             int this_ref_frame = x->best_zeromv_reference_frame;
1500             rd_adjustment = 100;
1501             rate2 = x->ref_frame_cost[this_ref_frame] +
1502                     vp8_cost_mv_ref(ZEROMV, mdcounts);
1503             distortion2 = 0;
1504
1505             /* set up the proper prediction buffers for the frame */
1506             x->e_mbd.mode_info_context->mbmi.ref_frame = this_ref_frame;
1507             x->e_mbd.pre.y_buffer = plane[this_ref_frame][0];
1508             x->e_mbd.pre.u_buffer = plane[this_ref_frame][1];
1509             x->e_mbd.pre.v_buffer = plane[this_ref_frame][2];
1510
1511             x->e_mbd.mode_info_context->mbmi.mode = ZEROMV;
1512             x->e_mbd.mode_info_context->mbmi.uv_mode = DC_PRED;
1513             x->e_mbd.mode_info_context->mbmi.mv.as_int = 0;
1514             this_rd = evaluate_inter_mode(&sse, rate2, &distortion2, cpi, x,
1515                                           rd_adjustment);
1516
1517             if (this_rd < best_rd)
1518             {
1519                 memcpy(&best_mbmode, &x->e_mbd.mode_info_context->mbmi,
1520                        sizeof(MB_MODE_INFO));
1521             }
1522         }
1523
1524     }
1525 #endif
1526
1527     if (cpi->is_src_frame_alt_ref &&
1528         (best_mbmode.mode != ZEROMV || best_mbmode.ref_frame != ALTREF_FRAME))
1529     {
1530         x->e_mbd.mode_info_context->mbmi.mode = ZEROMV;
1531         x->e_mbd.mode_info_context->mbmi.ref_frame = ALTREF_FRAME;
1532         x->e_mbd.mode_info_context->mbmi.mv.as_int = 0;
1533         x->e_mbd.mode_info_context->mbmi.uv_mode = DC_PRED;
1534         x->e_mbd.mode_info_context->mbmi.mb_skip_coeff =
1535                                         (cpi->common.mb_no_coeff_skip);
1536         x->e_mbd.mode_info_context->mbmi.partitioning = 0;
1537
1538         return;
1539     }
1540
1541     /* set to the best mb mode, this copy can be skip if x->skip since it
1542      * already has the right content */
1543     if (!x->skip)
1544         memcpy(&x->e_mbd.mode_info_context->mbmi, &best_mbmode,
1545                sizeof(MB_MODE_INFO));
1546
1547     if (best_mbmode.mode <= B_PRED)
1548     {
1549         /* set mode_info_context->mbmi.uv_mode */
1550         pick_intra_mbuv_mode(x);
1551     }
1552
1553     if (sign_bias
1554       != cpi->common.ref_frame_sign_bias[xd->mode_info_context->mbmi.ref_frame])
1555         best_ref_mv.as_int = best_ref_mv_sb[!sign_bias].as_int;
1556
1557     update_mvcount(x, &best_ref_mv);
1558 }
1559
1560 void vp8_pick_intra_mode(MACROBLOCK *x, int *rate_)
1561 {
1562     int error4x4, error16x16 = INT_MAX;
1563     int rate, best_rate = 0, distortion, best_sse;
1564     MB_PREDICTION_MODE mode, best_mode = DC_PRED;
1565     int this_rd;
1566     unsigned int sse;
1567     BLOCK *b = &x->block[0];
1568     MACROBLOCKD *xd = &x->e_mbd;
1569
1570     xd->mode_info_context->mbmi.ref_frame = INTRA_FRAME;
1571
1572     pick_intra_mbuv_mode(x);
1573
1574     for (mode = DC_PRED; mode <= TM_PRED; mode ++)
1575     {
1576         xd->mode_info_context->mbmi.mode = mode;
1577         vp8_build_intra_predictors_mby_s(xd,
1578                                          xd->dst.y_buffer - xd->dst.y_stride,
1579                                          xd->dst.y_buffer - 1,
1580                                          xd->dst.y_stride,
1581                                          xd->predictor,
1582                                          16);
1583         distortion = vpx_variance16x16
1584             (*(b->base_src), b->src_stride, xd->predictor, 16, &sse);
1585         rate = x->mbmode_cost[xd->frame_type][mode];
1586         this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1587
1588         if (error16x16 > this_rd)
1589         {
1590             error16x16 = this_rd;
1591             best_mode = mode;
1592             best_sse = sse;
1593             best_rate = rate;
1594         }
1595     }
1596     xd->mode_info_context->mbmi.mode = best_mode;
1597
1598     error4x4 = pick_intra4x4mby_modes(x, &rate,
1599                                       &best_sse);
1600     if (error4x4 < error16x16)
1601     {
1602         xd->mode_info_context->mbmi.mode = B_PRED;
1603         best_rate = rate;
1604     }
1605
1606     *rate_ = best_rate;
1607 }