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