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