]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_encoder.c
Merge "vp9_rd_pick_intra_mode_sb(): set interp_filter to"
[libvpx] / vp9 / encoder / vp9_encoder.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 #include <math.h>
12 #include <stdio.h>
13 #include <limits.h>
14
15 #include "./vp9_rtcd.h"
16 #include "./vpx_config.h"
17 #include "./vpx_dsp_rtcd.h"
18 #include "./vpx_scale_rtcd.h"
19 #include "vpx_dsp/psnr.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_dsp/vpx_filter.h"
22 #if CONFIG_INTERNAL_STATS
23 #include "vpx_dsp/ssim.h"
24 #endif
25 #include "vpx_ports/mem.h"
26 #include "vpx_ports/system_state.h"
27 #include "vpx_ports/vpx_timer.h"
28
29 #include "vp9/common/vp9_alloccommon.h"
30 #include "vp9/common/vp9_filter.h"
31 #include "vp9/common/vp9_idct.h"
32 #if CONFIG_VP9_POSTPROC
33 #include "vp9/common/vp9_postproc.h"
34 #endif
35 #include "vp9/common/vp9_reconinter.h"
36 #include "vp9/common/vp9_reconintra.h"
37 #include "vp9/common/vp9_tile_common.h"
38
39 #include "vp9/encoder/vp9_aq_360.h"
40 #include "vp9/encoder/vp9_aq_complexity.h"
41 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
42 #include "vp9/encoder/vp9_aq_variance.h"
43 #include "vp9/encoder/vp9_bitstream.h"
44 #include "vp9/encoder/vp9_context_tree.h"
45 #include "vp9/encoder/vp9_encodeframe.h"
46 #include "vp9/encoder/vp9_encodemv.h"
47 #include "vp9/encoder/vp9_encoder.h"
48 #include "vp9/encoder/vp9_extend.h"
49 #include "vp9/encoder/vp9_ethread.h"
50 #include "vp9/encoder/vp9_firstpass.h"
51 #include "vp9/encoder/vp9_mbgraph.h"
52 #include "vp9/encoder/vp9_noise_estimate.h"
53 #include "vp9/encoder/vp9_picklpf.h"
54 #include "vp9/encoder/vp9_ratectrl.h"
55 #include "vp9/encoder/vp9_rd.h"
56 #include "vp9/encoder/vp9_resize.h"
57 #include "vp9/encoder/vp9_segmentation.h"
58 #include "vp9/encoder/vp9_skin_detection.h"
59 #include "vp9/encoder/vp9_speed_features.h"
60 #include "vp9/encoder/vp9_svc_layercontext.h"
61 #include "vp9/encoder/vp9_temporal_filter.h"
62
63 #define AM_SEGMENT_ID_INACTIVE 7
64 #define AM_SEGMENT_ID_ACTIVE 0
65
66 #define ALTREF_HIGH_PRECISION_MV 1      // Whether to use high precision mv
67                                          //  for altref computation.
68 #define HIGH_PRECISION_MV_QTHRESH 200   // Q threshold for high precision
69                                          // mv. Choose a very high value for
70                                          // now so that HIGH_PRECISION is always
71                                          // chosen.
72 // #define OUTPUT_YUV_REC
73
74 #ifdef OUTPUT_YUV_DENOISED
75 FILE *yuv_denoised_file = NULL;
76 #endif
77 #ifdef OUTPUT_YUV_SKINMAP
78 FILE *yuv_skinmap_file = NULL;
79 #endif
80 #ifdef OUTPUT_YUV_REC
81 FILE *yuv_rec_file;
82 #endif
83
84 #if 0
85 FILE *framepsnr;
86 FILE *kf_list;
87 FILE *keyfile;
88 #endif
89
90 #ifdef ENABLE_KF_DENOISE
91 // Test condition for spatial denoise of source.
92 static int is_spatial_denoise_enabled(VP9_COMP *cpi) {
93   VP9_COMMON *const cm = &cpi->common;
94   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
95
96   return (oxcf->pass != 1) && !is_lossless_requested(&cpi->oxcf) &&
97          frame_is_intra_only(cm);
98 }
99 #endif
100
101 // Test for whether to calculate metrics for the frame.
102 static int is_psnr_calc_enabled(VP9_COMP *cpi) {
103   VP9_COMMON *const cm = &cpi->common;
104   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
105
106   return cpi->b_calculate_psnr && (oxcf->pass != 1) && cm->show_frame;
107 }
108
109 static const Vp9LevelSpec vp9_level_defs[VP9_LEVELS] = {
110   {LEVEL_1,   829440,      36864,    200,    400,   2, 1,  4,  8},
111   {LEVEL_1_1, 2764800,     73728,    800,    1000,  2, 1,  4,  8},
112   {LEVEL_2,   4608000,     122880,   1800,   1500,  2, 1,  4,  8},
113   {LEVEL_2_1, 9216000,     245760,   3600,   2800,  2, 2,  4,  8},
114   {LEVEL_3,   20736000,    552960,   7200,   6000,  2, 4,  4,  8},
115   {LEVEL_3_1, 36864000,    983040,   12000,  10000, 2, 4,  4,  8},
116   {LEVEL_4,   83558400,    2228224,  18000,  16000, 4, 4,  4,  8},
117   {LEVEL_4_1, 160432128,   2228224,  30000,  18000, 4, 4,  5,  6},
118   {LEVEL_5,   311951360,   8912896,  60000,  36000, 6, 8,  6,  4},
119   {LEVEL_5_1, 588251136,   8912896,  120000, 46000, 8, 8,  10, 4},
120   // TODO(huisu): update max_cpb_size for level 5_2 ~ 6_2 when
121   // they are finalized (currently TBD).
122   {LEVEL_5_2, 1176502272,  8912896,  180000, 0,     8, 8,  10, 4},
123   {LEVEL_6,   1176502272,  35651584, 180000, 0,     8, 16, 10, 4},
124   {LEVEL_6_1, 2353004544u, 35651584, 240000, 0,     8, 16, 10, 4},
125   {LEVEL_6_2, 4706009088u, 35651584, 480000, 0,     8, 16, 10, 4},
126 };
127
128 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
129   switch (mode) {
130     case NORMAL:
131       *hr = 1;
132       *hs = 1;
133       break;
134     case FOURFIVE:
135       *hr = 4;
136       *hs = 5;
137       break;
138     case THREEFIVE:
139       *hr = 3;
140       *hs = 5;
141     break;
142     case ONETWO:
143       *hr = 1;
144       *hs = 2;
145     break;
146     default:
147       *hr = 1;
148       *hs = 1;
149        assert(0);
150       break;
151   }
152 }
153
154 // Mark all inactive blocks as active. Other segmentation features may be set
155 // so memset cannot be used, instead only inactive blocks should be reset.
156 static void suppress_active_map(VP9_COMP *cpi) {
157   unsigned char *const seg_map = cpi->segmentation_map;
158
159   if (cpi->active_map.enabled || cpi->active_map.update) {
160     const int rows = cpi->common.mi_rows;
161     const int cols = cpi->common.mi_cols;
162     int i;
163
164     for (i = 0; i < rows * cols; ++i)
165       if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
166         seg_map[i] = AM_SEGMENT_ID_ACTIVE;
167   }
168 }
169
170 static void apply_active_map(VP9_COMP *cpi) {
171   struct segmentation *const seg = &cpi->common.seg;
172   unsigned char *const seg_map = cpi->segmentation_map;
173   const unsigned char *const active_map = cpi->active_map.map;
174   int i;
175
176   assert(AM_SEGMENT_ID_ACTIVE == CR_SEGMENT_ID_BASE);
177
178   if (frame_is_intra_only(&cpi->common)) {
179     cpi->active_map.enabled = 0;
180     cpi->active_map.update = 1;
181   }
182
183   if (cpi->active_map.update) {
184     if (cpi->active_map.enabled) {
185       for (i = 0; i < cpi->common.mi_rows * cpi->common.mi_cols; ++i)
186         if (seg_map[i] == AM_SEGMENT_ID_ACTIVE) seg_map[i] = active_map[i];
187       vp9_enable_segmentation(seg);
188       vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
189       vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
190       // Setting the data to -MAX_LOOP_FILTER will result in the computed loop
191       // filter level being zero regardless of the value of seg->abs_delta.
192       vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE,
193                       SEG_LVL_ALT_LF, -MAX_LOOP_FILTER);
194     } else {
195       vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
196       vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
197       if (seg->enabled) {
198         seg->update_data = 1;
199         seg->update_map = 1;
200       }
201     }
202     cpi->active_map.update = 0;
203   }
204 }
205
206 static void init_level_info(Vp9LevelInfo *level_info) {
207   Vp9LevelStats *const level_stats = &level_info->level_stats;
208   Vp9LevelSpec *const level_spec = &level_info->level_spec;
209
210   memset(level_stats, 0, sizeof(*level_stats));
211   memset(level_spec, 0, sizeof(*level_spec));
212   level_spec->level = LEVEL_UNKNOWN;
213   level_spec->min_altref_distance = INT_MAX;
214 }
215
216 VP9_LEVEL vp9_get_level(const Vp9LevelSpec * const level_spec) {
217   int i;
218   const Vp9LevelSpec *this_level;
219
220   vpx_clear_system_state();
221
222   for (i = 0; i < VP9_LEVELS; ++i) {
223     this_level = &vp9_level_defs[i];
224     if ((double)level_spec->max_luma_sample_rate * (1 + SAMPLE_RATE_GRACE_P) >
225         (double)this_level->max_luma_sample_rate ||
226         level_spec->max_luma_picture_size > this_level->max_luma_picture_size ||
227         level_spec->average_bitrate > this_level->average_bitrate ||
228         level_spec->max_cpb_size > this_level->max_cpb_size ||
229         level_spec->compression_ratio < this_level->compression_ratio ||
230         level_spec->max_col_tiles > this_level->max_col_tiles ||
231         level_spec->min_altref_distance < this_level->min_altref_distance ||
232         level_spec->max_ref_frame_buffers > this_level->max_ref_frame_buffers)
233       continue;
234     break;
235   }
236   return (i == VP9_LEVELS) ? LEVEL_UNKNOWN : vp9_level_defs[i].level;
237 }
238
239 int vp9_set_active_map(VP9_COMP* cpi,
240                        unsigned char* new_map_16x16,
241                        int rows,
242                        int cols) {
243   if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
244     unsigned char *const active_map_8x8 = cpi->active_map.map;
245     const int mi_rows = cpi->common.mi_rows;
246     const int mi_cols = cpi->common.mi_cols;
247     cpi->active_map.update = 1;
248     if (new_map_16x16) {
249       int r, c;
250       for (r = 0; r < mi_rows; ++r) {
251         for (c = 0; c < mi_cols; ++c) {
252           active_map_8x8[r * mi_cols + c] =
253               new_map_16x16[(r >> 1) * cols + (c >> 1)]
254                   ? AM_SEGMENT_ID_ACTIVE
255                   : AM_SEGMENT_ID_INACTIVE;
256         }
257       }
258       cpi->active_map.enabled = 1;
259     } else {
260       cpi->active_map.enabled = 0;
261     }
262     return 0;
263   } else {
264     return -1;
265   }
266 }
267
268 int vp9_get_active_map(VP9_COMP* cpi,
269                        unsigned char* new_map_16x16,
270                        int rows,
271                        int cols) {
272   if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
273       new_map_16x16) {
274     unsigned char* const seg_map_8x8 = cpi->segmentation_map;
275     const int mi_rows = cpi->common.mi_rows;
276     const int mi_cols = cpi->common.mi_cols;
277     memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
278     if (cpi->active_map.enabled) {
279       int r, c;
280       for (r = 0; r < mi_rows; ++r) {
281         for (c = 0; c < mi_cols; ++c) {
282           // Cyclic refresh segments are considered active despite not having
283           // AM_SEGMENT_ID_ACTIVE
284           new_map_16x16[(r >> 1) * cols + (c >> 1)] |=
285               seg_map_8x8[r * mi_cols + c] != AM_SEGMENT_ID_INACTIVE;
286         }
287       }
288     }
289     return 0;
290   } else {
291     return -1;
292   }
293 }
294
295 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
296   MACROBLOCK *const mb = &cpi->td.mb;
297   cpi->common.allow_high_precision_mv = allow_high_precision_mv;
298   if (cpi->common.allow_high_precision_mv) {
299     mb->mvcost = mb->nmvcost_hp;
300     mb->mvsadcost = mb->nmvsadcost_hp;
301   } else {
302     mb->mvcost = mb->nmvcost;
303     mb->mvsadcost = mb->nmvsadcost;
304   }
305 }
306
307 static void setup_frame(VP9_COMP *cpi) {
308   VP9_COMMON *const cm = &cpi->common;
309   // Set up entropy context depending on frame type. The decoder mandates
310   // the use of the default context, index 0, for keyframes and inter
311   // frames where the error_resilient_mode or intra_only flag is set. For
312   // other inter-frames the encoder currently uses only two contexts;
313   // context 1 for ALTREF frames and context 0 for the others.
314   if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
315     vp9_setup_past_independence(cm);
316   } else {
317     if (!cpi->use_svc)
318       cm->frame_context_idx = cpi->refresh_alt_ref_frame;
319   }
320
321   if (cm->frame_type == KEY_FRAME) {
322     if (!is_two_pass_svc(cpi))
323       cpi->refresh_golden_frame = 1;
324     cpi->refresh_alt_ref_frame = 1;
325     vp9_zero(cpi->interp_filter_selected);
326   } else {
327     *cm->fc = cm->frame_contexts[cm->frame_context_idx];
328     vp9_zero(cpi->interp_filter_selected[0]);
329   }
330 }
331
332 static void vp9_enc_setup_mi(VP9_COMMON *cm) {
333   int i;
334   cm->mi = cm->mip + cm->mi_stride + 1;
335   memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
336   cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
337   // Clear top border row
338   memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
339   // Clear left border column
340   for (i = 1; i < cm->mi_rows + 1; ++i)
341     memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
342
343   cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
344   cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
345
346   memset(cm->mi_grid_base, 0,
347          cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
348 }
349
350 static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
351   cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
352   if (!cm->mip)
353     return 1;
354   cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
355   if (!cm->prev_mip)
356     return 1;
357   cm->mi_alloc_size = mi_size;
358
359   cm->mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO*));
360   if (!cm->mi_grid_base)
361     return 1;
362   cm->prev_mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO*));
363   if (!cm->prev_mi_grid_base)
364     return 1;
365
366   return 0;
367 }
368
369 static void vp9_enc_free_mi(VP9_COMMON *cm) {
370   vpx_free(cm->mip);
371   cm->mip = NULL;
372   vpx_free(cm->prev_mip);
373   cm->prev_mip = NULL;
374   vpx_free(cm->mi_grid_base);
375   cm->mi_grid_base = NULL;
376   vpx_free(cm->prev_mi_grid_base);
377   cm->prev_mi_grid_base = NULL;
378 }
379
380 static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
381   // Current mip will be the prev_mip for the next frame.
382   MODE_INFO **temp_base = cm->prev_mi_grid_base;
383   MODE_INFO *temp = cm->prev_mip;
384   cm->prev_mip = cm->mip;
385   cm->mip = temp;
386
387   // Update the upper left visible macroblock ptrs.
388   cm->mi = cm->mip + cm->mi_stride + 1;
389   cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
390
391   cm->prev_mi_grid_base = cm->mi_grid_base;
392   cm->mi_grid_base = temp_base;
393   cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
394   cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
395 }
396
397 void vp9_initialize_enc(void) {
398   static volatile int init_done = 0;
399
400   if (!init_done) {
401     vp9_rtcd();
402     vpx_dsp_rtcd();
403     vpx_scale_rtcd();
404     vp9_init_intra_predictors();
405     vp9_init_me_luts();
406     vp9_rc_init_minq_luts();
407     vp9_entropy_mv_init();
408     vp9_temporal_filter_init();
409     init_done = 1;
410   }
411 }
412
413 static void dealloc_compressor_data(VP9_COMP *cpi) {
414   VP9_COMMON *const cm = &cpi->common;
415   int i;
416
417   vpx_free(cpi->mbmi_ext_base);
418   cpi->mbmi_ext_base = NULL;
419
420   vpx_free(cpi->tile_data);
421   cpi->tile_data = NULL;
422
423   // Delete sementation map
424   vpx_free(cpi->segmentation_map);
425   cpi->segmentation_map = NULL;
426   vpx_free(cpi->coding_context.last_frame_seg_map_copy);
427   cpi->coding_context.last_frame_seg_map_copy = NULL;
428
429   vpx_free(cpi->nmvcosts[0]);
430   vpx_free(cpi->nmvcosts[1]);
431   cpi->nmvcosts[0] = NULL;
432   cpi->nmvcosts[1] = NULL;
433
434   vpx_free(cpi->nmvcosts_hp[0]);
435   vpx_free(cpi->nmvcosts_hp[1]);
436   cpi->nmvcosts_hp[0] = NULL;
437   cpi->nmvcosts_hp[1] = NULL;
438
439   vpx_free(cpi->nmvsadcosts[0]);
440   vpx_free(cpi->nmvsadcosts[1]);
441   cpi->nmvsadcosts[0] = NULL;
442   cpi->nmvsadcosts[1] = NULL;
443
444   vpx_free(cpi->nmvsadcosts_hp[0]);
445   vpx_free(cpi->nmvsadcosts_hp[1]);
446   cpi->nmvsadcosts_hp[0] = NULL;
447   cpi->nmvsadcosts_hp[1] = NULL;
448
449   vp9_cyclic_refresh_free(cpi->cyclic_refresh);
450   cpi->cyclic_refresh = NULL;
451
452   vpx_free(cpi->active_map.map);
453   cpi->active_map.map = NULL;
454
455   vpx_free(cpi->consec_zero_mv);
456   cpi->consec_zero_mv = NULL;
457
458   vp9_free_ref_frame_buffers(cm->buffer_pool);
459 #if CONFIG_VP9_POSTPROC
460   vp9_free_postproc_buffers(cm);
461 #endif
462   vp9_free_context_buffers(cm);
463
464   vpx_free_frame_buffer(&cpi->last_frame_uf);
465   vpx_free_frame_buffer(&cpi->scaled_source);
466   vpx_free_frame_buffer(&cpi->scaled_last_source);
467   vpx_free_frame_buffer(&cpi->alt_ref_buffer);
468 #ifdef ENABLE_KF_DENOISE
469   vpx_free_frame_buffer(&cpi->raw_unscaled_source);
470   vpx_free_frame_buffer(&cpi->raw_scaled_source);
471 #endif
472
473   vp9_lookahead_destroy(cpi->lookahead);
474
475   vpx_free(cpi->tile_tok[0][0]);
476   cpi->tile_tok[0][0] = 0;
477
478   vp9_free_pc_tree(&cpi->td);
479
480   for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
481     LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
482     vpx_free(lc->rc_twopass_stats_in.buf);
483     lc->rc_twopass_stats_in.buf = NULL;
484     lc->rc_twopass_stats_in.sz = 0;
485   }
486
487   if (cpi->source_diff_var != NULL) {
488     vpx_free(cpi->source_diff_var);
489     cpi->source_diff_var = NULL;
490   }
491
492   for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
493     vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]);
494   }
495   memset(&cpi->svc.scaled_frames[0], 0,
496          MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
497
498   vpx_free_frame_buffer(&cpi->svc.scaled_temp);
499   memset(&cpi->svc.scaled_temp, 0, sizeof(cpi->svc.scaled_temp));
500
501   vpx_free_frame_buffer(&cpi->svc.empty_frame.img);
502   memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
503
504   vp9_free_svc_cyclic_refresh(cpi);
505 }
506
507 static void save_coding_context(VP9_COMP *cpi) {
508   CODING_CONTEXT *const cc = &cpi->coding_context;
509   VP9_COMMON *cm = &cpi->common;
510
511   // Stores a snapshot of key state variables which can subsequently be
512   // restored with a call to vp9_restore_coding_context. These functions are
513   // intended for use in a re-code loop in vp9_compress_frame where the
514   // quantizer value is adjusted between loop iterations.
515   vp9_copy(cc->nmvjointcost,  cpi->td.mb.nmvjointcost);
516
517   memcpy(cc->nmvcosts[0], cpi->nmvcosts[0],
518          MV_VALS * sizeof(*cpi->nmvcosts[0]));
519   memcpy(cc->nmvcosts[1], cpi->nmvcosts[1],
520          MV_VALS * sizeof(*cpi->nmvcosts[1]));
521   memcpy(cc->nmvcosts_hp[0], cpi->nmvcosts_hp[0],
522          MV_VALS * sizeof(*cpi->nmvcosts_hp[0]));
523   memcpy(cc->nmvcosts_hp[1], cpi->nmvcosts_hp[1],
524          MV_VALS * sizeof(*cpi->nmvcosts_hp[1]));
525
526   vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
527
528   memcpy(cpi->coding_context.last_frame_seg_map_copy,
529          cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
530
531   vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
532   vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
533
534   cc->fc = *cm->fc;
535 }
536
537 static void restore_coding_context(VP9_COMP *cpi) {
538   CODING_CONTEXT *const cc = &cpi->coding_context;
539   VP9_COMMON *cm = &cpi->common;
540
541   // Restore key state variables to the snapshot state stored in the
542   // previous call to vp9_save_coding_context.
543   vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
544
545   memcpy(cpi->nmvcosts[0], cc->nmvcosts[0], MV_VALS * sizeof(*cc->nmvcosts[0]));
546   memcpy(cpi->nmvcosts[1], cc->nmvcosts[1], MV_VALS * sizeof(*cc->nmvcosts[1]));
547   memcpy(cpi->nmvcosts_hp[0], cc->nmvcosts_hp[0],
548          MV_VALS * sizeof(*cc->nmvcosts_hp[0]));
549   memcpy(cpi->nmvcosts_hp[1], cc->nmvcosts_hp[1],
550          MV_VALS * sizeof(*cc->nmvcosts_hp[1]));
551
552   vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
553
554   memcpy(cm->last_frame_seg_map,
555          cpi->coding_context.last_frame_seg_map_copy,
556          (cm->mi_rows * cm->mi_cols));
557
558   vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
559   vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
560
561   *cm->fc = cc->fc;
562 }
563
564 static void configure_static_seg_features(VP9_COMP *cpi) {
565   VP9_COMMON *const cm = &cpi->common;
566   const RATE_CONTROL *const rc = &cpi->rc;
567   struct segmentation *const seg = &cm->seg;
568
569   int high_q = (int)(rc->avg_q > 48.0);
570   int qi_delta;
571
572   // Disable and clear down for KF
573   if (cm->frame_type == KEY_FRAME) {
574     // Clear down the global segmentation map
575     memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
576     seg->update_map = 0;
577     seg->update_data = 0;
578     cpi->static_mb_pct = 0;
579
580     // Disable segmentation
581     vp9_disable_segmentation(seg);
582
583     // Clear down the segment features.
584     vp9_clearall_segfeatures(seg);
585   } else if (cpi->refresh_alt_ref_frame) {
586     // If this is an alt ref frame
587     // Clear down the global segmentation map
588     memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
589     seg->update_map = 0;
590     seg->update_data = 0;
591     cpi->static_mb_pct = 0;
592
593     // Disable segmentation and individual segment features by default
594     vp9_disable_segmentation(seg);
595     vp9_clearall_segfeatures(seg);
596
597     // Scan frames from current to arf frame.
598     // This function re-enables segmentation if appropriate.
599     vp9_update_mbgraph_stats(cpi);
600
601     // If segmentation was enabled set those features needed for the
602     // arf itself.
603     if (seg->enabled) {
604       seg->update_map = 1;
605       seg->update_data = 1;
606
607       qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875,
608                                     cm->bit_depth);
609       vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
610       vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
611
612       vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
613       vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
614
615       // Where relevant assume segment data is delta data
616       seg->abs_delta = SEGMENT_DELTADATA;
617     }
618   } else if (seg->enabled) {
619     // All other frames if segmentation has been enabled
620
621     // First normal frame in a valid gf or alt ref group
622     if (rc->frames_since_golden == 0) {
623       // Set up segment features for normal frames in an arf group
624       if (rc->source_alt_ref_active) {
625         seg->update_map = 0;
626         seg->update_data = 1;
627         seg->abs_delta = SEGMENT_DELTADATA;
628
629         qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125,
630                                       cm->bit_depth);
631         vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
632         vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
633
634         vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
635         vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
636
637         // Segment coding disabled for compred testing
638         if (high_q || (cpi->static_mb_pct == 100)) {
639           vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
640           vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
641           vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
642         }
643       } else {
644         // Disable segmentation and clear down features if alt ref
645         // is not active for this group
646
647         vp9_disable_segmentation(seg);
648
649         memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
650
651         seg->update_map = 0;
652         seg->update_data = 0;
653
654         vp9_clearall_segfeatures(seg);
655       }
656     } else if (rc->is_src_frame_alt_ref) {
657       // Special case where we are coding over the top of a previous
658       // alt ref frame.
659       // Segment coding disabled for compred testing
660
661       // Enable ref frame features for segment 0 as well
662       vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
663       vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
664
665       // All mbs should use ALTREF_FRAME
666       vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
667       vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
668       vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
669       vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
670
671       // Skip all MBs if high Q (0,0 mv and skip coeffs)
672       if (high_q) {
673         vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
674         vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
675       }
676       // Enable data update
677       seg->update_data = 1;
678     } else {
679       // All other frames.
680
681       // No updates.. leave things as they are.
682       seg->update_map = 0;
683       seg->update_data = 0;
684     }
685   }
686 }
687
688 static void update_reference_segmentation_map(VP9_COMP *cpi) {
689   VP9_COMMON *const cm = &cpi->common;
690   MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
691   uint8_t *cache_ptr = cm->last_frame_seg_map;
692   int row, col;
693
694   for (row = 0; row < cm->mi_rows; row++) {
695     MODE_INFO **mi_8x8 = mi_8x8_ptr;
696     uint8_t *cache = cache_ptr;
697     for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
698       cache[0] = mi_8x8[0]->segment_id;
699     mi_8x8_ptr += cm->mi_stride;
700     cache_ptr += cm->mi_cols;
701   }
702 }
703
704 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
705   VP9_COMMON *cm = &cpi->common;
706   const VP9EncoderConfig *oxcf = &cpi->oxcf;
707
708   if (!cpi->lookahead)
709     cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
710                                         cm->subsampling_x, cm->subsampling_y,
711 #if CONFIG_VP9_HIGHBITDEPTH
712                                       cm->use_highbitdepth,
713 #endif
714                                       oxcf->lag_in_frames);
715   if (!cpi->lookahead)
716     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
717                        "Failed to allocate lag buffers");
718
719   // TODO(agrange) Check if ARF is enabled and skip allocation if not.
720   if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer,
721                                oxcf->width, oxcf->height,
722                                cm->subsampling_x, cm->subsampling_y,
723 #if CONFIG_VP9_HIGHBITDEPTH
724                                cm->use_highbitdepth,
725 #endif
726                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
727                                NULL, NULL, NULL))
728     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
729                        "Failed to allocate altref buffer");
730 }
731
732 static void alloc_util_frame_buffers(VP9_COMP *cpi) {
733   VP9_COMMON *const cm = &cpi->common;
734   if (vpx_realloc_frame_buffer(&cpi->last_frame_uf,
735                                cm->width, cm->height,
736                                cm->subsampling_x, cm->subsampling_y,
737 #if CONFIG_VP9_HIGHBITDEPTH
738                                cm->use_highbitdepth,
739 #endif
740                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
741                                NULL, NULL, NULL))
742     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
743                        "Failed to allocate last frame buffer");
744
745   if (vpx_realloc_frame_buffer(&cpi->scaled_source,
746                                cm->width, cm->height,
747                                cm->subsampling_x, cm->subsampling_y,
748 #if CONFIG_VP9_HIGHBITDEPTH
749                                cm->use_highbitdepth,
750 #endif
751                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
752                                NULL, NULL, NULL))
753     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
754                        "Failed to allocate scaled source buffer");
755
756   if (vpx_realloc_frame_buffer(&cpi->scaled_last_source,
757                                cm->width, cm->height,
758                                cm->subsampling_x, cm->subsampling_y,
759 #if CONFIG_VP9_HIGHBITDEPTH
760                                cm->use_highbitdepth,
761 #endif
762                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
763                                NULL, NULL, NULL))
764     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
765                        "Failed to allocate scaled last source buffer");
766 #ifdef ENABLE_KF_DENOISE
767   if (vpx_realloc_frame_buffer(&cpi->raw_unscaled_source,
768                                cm->width, cm->height,
769                                cm->subsampling_x, cm->subsampling_y,
770 #if CONFIG_VP9_HIGHBITDEPTH
771                                cm->use_highbitdepth,
772 #endif
773                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
774                                NULL, NULL, NULL))
775     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
776                        "Failed to allocate unscaled raw source frame buffer");
777
778   if (vpx_realloc_frame_buffer(&cpi->raw_scaled_source,
779                                cm->width, cm->height,
780                                cm->subsampling_x, cm->subsampling_y,
781 #if CONFIG_VP9_HIGHBITDEPTH
782                                cm->use_highbitdepth,
783 #endif
784                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
785                                NULL, NULL, NULL))
786     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
787                        "Failed to allocate scaled raw source frame buffer");
788 #endif
789 }
790
791
792 static int alloc_context_buffers_ext(VP9_COMP *cpi) {
793   VP9_COMMON *cm = &cpi->common;
794   int mi_size = cm->mi_cols * cm->mi_rows;
795
796   cpi->mbmi_ext_base = vpx_calloc(mi_size, sizeof(*cpi->mbmi_ext_base));
797   if (!cpi->mbmi_ext_base)
798     return 1;
799
800   return 0;
801 }
802
803 static void alloc_compressor_data(VP9_COMP *cpi) {
804   VP9_COMMON *cm = &cpi->common;
805
806   vp9_alloc_context_buffers(cm, cm->width, cm->height);
807
808   alloc_context_buffers_ext(cpi);
809
810   vpx_free(cpi->tile_tok[0][0]);
811
812   {
813     unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
814     CHECK_MEM_ERROR(cm, cpi->tile_tok[0][0],
815         vpx_calloc(tokens, sizeof(*cpi->tile_tok[0][0])));
816   }
817
818   vp9_setup_pc_tree(&cpi->common, &cpi->td);
819 }
820
821 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
822   cpi->framerate = framerate < 0.1 ? 30 : framerate;
823   vp9_rc_update_framerate(cpi);
824 }
825
826 static void set_tile_limits(VP9_COMP *cpi) {
827   VP9_COMMON *const cm = &cpi->common;
828
829   int min_log2_tile_cols, max_log2_tile_cols;
830   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
831
832   if (is_two_pass_svc(cpi) &&
833       (cpi->svc.encode_empty_frame_state == ENCODING ||
834       cpi->svc.number_spatial_layers > 1)) {
835     cm->log2_tile_cols = 0;
836     cm->log2_tile_rows = 0;
837   } else {
838     cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
839                                min_log2_tile_cols, max_log2_tile_cols);
840     cm->log2_tile_rows = cpi->oxcf.tile_rows;
841   }
842 }
843
844 static void update_frame_size(VP9_COMP *cpi) {
845   VP9_COMMON *const cm = &cpi->common;
846   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
847
848   vp9_set_mb_mi(cm, cm->width, cm->height);
849   vp9_init_context_buffers(cm);
850   vp9_init_macroblockd(cm, xd, NULL);
851   cpi->td.mb.mbmi_ext_base = cpi->mbmi_ext_base;
852   memset(cpi->mbmi_ext_base, 0,
853          cm->mi_rows * cm->mi_cols * sizeof(*cpi->mbmi_ext_base));
854
855   set_tile_limits(cpi);
856
857   if (is_two_pass_svc(cpi)) {
858     if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer,
859                                  cm->width, cm->height,
860                                  cm->subsampling_x, cm->subsampling_y,
861 #if CONFIG_VP9_HIGHBITDEPTH
862                                  cm->use_highbitdepth,
863 #endif
864                                  VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
865                                  NULL, NULL, NULL))
866       vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
867                          "Failed to reallocate alt_ref_buffer");
868   }
869 }
870
871 static void init_buffer_indices(VP9_COMP *cpi) {
872   cpi->lst_fb_idx = 0;
873   cpi->gld_fb_idx = 1;
874   cpi->alt_fb_idx = 2;
875 }
876
877 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
878   VP9_COMMON *const cm = &cpi->common;
879
880   cpi->oxcf = *oxcf;
881   cpi->framerate = oxcf->init_framerate;
882   cm->profile = oxcf->profile;
883   cm->bit_depth = oxcf->bit_depth;
884 #if CONFIG_VP9_HIGHBITDEPTH
885   cm->use_highbitdepth = oxcf->use_highbitdepth;
886 #endif
887   cm->color_space = oxcf->color_space;
888   cm->color_range = oxcf->color_range;
889
890   cpi->target_level = oxcf->target_level;
891   cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
892
893   cm->width = oxcf->width;
894   cm->height = oxcf->height;
895   alloc_compressor_data(cpi);
896
897   cpi->svc.temporal_layering_mode = oxcf->temporal_layering_mode;
898
899   // Single thread case: use counts in common.
900   cpi->td.counts = &cm->counts;
901
902   // Spatial scalability.
903   cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
904   // Temporal scalability.
905   cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
906
907   if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
908       ((cpi->svc.number_temporal_layers > 1 ||
909         cpi->svc.number_spatial_layers > 1) &&
910        cpi->oxcf.pass != 1)) {
911     vp9_init_layer_context(cpi);
912   }
913
914   // change includes all joint functionality
915   vp9_change_config(cpi, oxcf);
916
917   cpi->static_mb_pct = 0;
918   cpi->ref_frame_flags = 0;
919
920   init_buffer_indices(cpi);
921
922   vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
923 }
924
925 static void set_rc_buffer_sizes(RATE_CONTROL *rc,
926                                 const VP9EncoderConfig *oxcf) {
927   const int64_t bandwidth = oxcf->target_bandwidth;
928   const int64_t starting = oxcf->starting_buffer_level_ms;
929   const int64_t optimal = oxcf->optimal_buffer_level_ms;
930   const int64_t maximum = oxcf->maximum_buffer_size_ms;
931
932   rc->starting_buffer_level = starting * bandwidth / 1000;
933   rc->optimal_buffer_level = (optimal == 0) ? bandwidth / 8
934                                             : optimal * bandwidth / 1000;
935   rc->maximum_buffer_size = (maximum == 0) ? bandwidth / 8
936                                            : maximum * bandwidth / 1000;
937 }
938
939 #if CONFIG_VP9_HIGHBITDEPTH
940 #define HIGHBD_BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF) \
941     cpi->fn_ptr[BT].sdf = SDF; \
942     cpi->fn_ptr[BT].sdaf = SDAF; \
943     cpi->fn_ptr[BT].vf = VF; \
944     cpi->fn_ptr[BT].svf = SVF; \
945     cpi->fn_ptr[BT].svaf = SVAF; \
946     cpi->fn_ptr[BT].sdx3f = SDX3F; \
947     cpi->fn_ptr[BT].sdx8f = SDX8F; \
948     cpi->fn_ptr[BT].sdx4df = SDX4DF;
949
950 #define MAKE_BFP_SAD_WRAPPER(fnname) \
951 static unsigned int fnname##_bits8(const uint8_t *src_ptr, \
952                                    int source_stride, \
953                                    const uint8_t *ref_ptr, \
954                                    int ref_stride) {  \
955   return fnname(src_ptr, source_stride, ref_ptr, ref_stride); \
956 } \
957 static unsigned int fnname##_bits10(const uint8_t *src_ptr, \
958                                     int source_stride, \
959                                     const uint8_t *ref_ptr, \
960                                     int ref_stride) {  \
961   return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 2; \
962 } \
963 static unsigned int fnname##_bits12(const uint8_t *src_ptr, \
964                                     int source_stride, \
965                                     const uint8_t *ref_ptr, \
966                                     int ref_stride) {  \
967   return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 4; \
968 }
969
970 #define MAKE_BFP_SADAVG_WRAPPER(fnname) static unsigned int \
971 fnname##_bits8(const uint8_t *src_ptr, \
972                int source_stride, \
973                const uint8_t *ref_ptr, \
974                int ref_stride, \
975                const uint8_t *second_pred) {  \
976   return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred); \
977 } \
978 static unsigned int fnname##_bits10(const uint8_t *src_ptr, \
979                                     int source_stride, \
980                                     const uint8_t *ref_ptr, \
981                                     int ref_stride, \
982                                     const uint8_t *second_pred) {  \
983   return fnname(src_ptr, source_stride, ref_ptr, ref_stride, \
984                 second_pred) >> 2; \
985 } \
986 static unsigned int fnname##_bits12(const uint8_t *src_ptr, \
987                                     int source_stride, \
988                                     const uint8_t *ref_ptr, \
989                                     int ref_stride, \
990                                     const uint8_t *second_pred) {  \
991   return fnname(src_ptr, source_stride, ref_ptr, ref_stride, \
992                 second_pred) >> 4; \
993 }
994
995 #define MAKE_BFP_SAD3_WRAPPER(fnname) \
996 static void fnname##_bits8(const uint8_t *src_ptr, \
997                            int source_stride, \
998                            const uint8_t *ref_ptr, \
999                            int  ref_stride, \
1000                            unsigned int *sad_array) {  \
1001   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1002 } \
1003 static void fnname##_bits10(const uint8_t *src_ptr, \
1004                             int source_stride, \
1005                             const uint8_t *ref_ptr, \
1006                             int  ref_stride, \
1007                             unsigned int *sad_array) {  \
1008   int i; \
1009   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1010   for (i = 0; i < 3; i++) \
1011     sad_array[i] >>= 2; \
1012 } \
1013 static void fnname##_bits12(const uint8_t *src_ptr, \
1014                             int source_stride, \
1015                             const uint8_t *ref_ptr, \
1016                             int  ref_stride, \
1017                             unsigned int *sad_array) {  \
1018   int i; \
1019   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1020   for (i = 0; i < 3; i++) \
1021     sad_array[i] >>= 4; \
1022 }
1023
1024 #define MAKE_BFP_SAD8_WRAPPER(fnname) \
1025 static void fnname##_bits8(const uint8_t *src_ptr, \
1026                            int source_stride, \
1027                            const uint8_t *ref_ptr, \
1028                            int  ref_stride, \
1029                            unsigned int *sad_array) {  \
1030   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1031 } \
1032 static void fnname##_bits10(const uint8_t *src_ptr, \
1033                             int source_stride, \
1034                             const uint8_t *ref_ptr, \
1035                             int  ref_stride, \
1036                             unsigned int *sad_array) {  \
1037   int i; \
1038   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1039   for (i = 0; i < 8; i++) \
1040     sad_array[i] >>= 2; \
1041 } \
1042 static void fnname##_bits12(const uint8_t *src_ptr, \
1043                             int source_stride, \
1044                             const uint8_t *ref_ptr, \
1045                             int  ref_stride, \
1046                             unsigned int *sad_array) {  \
1047   int i; \
1048   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1049   for (i = 0; i < 8; i++) \
1050     sad_array[i] >>= 4; \
1051 }
1052 #define MAKE_BFP_SAD4D_WRAPPER(fnname) \
1053 static void fnname##_bits8(const uint8_t *src_ptr, \
1054                            int source_stride, \
1055                            const uint8_t* const ref_ptr[], \
1056                            int  ref_stride, \
1057                            unsigned int *sad_array) {  \
1058   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1059 } \
1060 static void fnname##_bits10(const uint8_t *src_ptr, \
1061                             int source_stride, \
1062                             const uint8_t* const ref_ptr[], \
1063                             int  ref_stride, \
1064                             unsigned int *sad_array) {  \
1065   int i; \
1066   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1067   for (i = 0; i < 4; i++) \
1068   sad_array[i] >>= 2; \
1069 } \
1070 static void fnname##_bits12(const uint8_t *src_ptr, \
1071                             int source_stride, \
1072                             const uint8_t* const ref_ptr[], \
1073                             int  ref_stride, \
1074                             unsigned int *sad_array) {  \
1075   int i; \
1076   fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1077   for (i = 0; i < 4; i++) \
1078   sad_array[i] >>= 4; \
1079 }
1080
1081 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x16)
1082 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x16_avg)
1083 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x16x4d)
1084 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x32)
1085 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x32_avg)
1086 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x32x4d)
1087 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x32)
1088 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x32_avg)
1089 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x32x4d)
1090 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x64)
1091 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x64_avg)
1092 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x64x4d)
1093 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x32)
1094 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x32_avg)
1095 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad32x32x3)
1096 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad32x32x8)
1097 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x32x4d)
1098 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x64)
1099 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x64_avg)
1100 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad64x64x3)
1101 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad64x64x8)
1102 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x64x4d)
1103 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x16)
1104 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x16_avg)
1105 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x16x3)
1106 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x16x8)
1107 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x16x4d)
1108 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x8)
1109 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x8_avg)
1110 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x8x3)
1111 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x8x8)
1112 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x8x4d)
1113 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x16)
1114 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x16_avg)
1115 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x16x3)
1116 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x16x8)
1117 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x16x4d)
1118 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x8)
1119 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x8_avg)
1120 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x8x3)
1121 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x8x8)
1122 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x8x4d)
1123 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x4)
1124 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x4_avg)
1125 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x4x8)
1126 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x4x4d)
1127 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x8)
1128 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x8_avg)
1129 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x8x8)
1130 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x8x4d)
1131 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x4)
1132 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x4_avg)
1133 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad4x4x3)
1134 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x4x8)
1135 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x4x4d)
1136
1137 static void  highbd_set_var_fns(VP9_COMP *const cpi) {
1138   VP9_COMMON *const cm = &cpi->common;
1139   if (cm->use_highbitdepth) {
1140     switch (cm->bit_depth) {
1141       case VPX_BITS_8:
1142         HIGHBD_BFP(BLOCK_32X16,
1143                    vpx_highbd_sad32x16_bits8,
1144                    vpx_highbd_sad32x16_avg_bits8,
1145                    vpx_highbd_8_variance32x16,
1146                    vpx_highbd_8_sub_pixel_variance32x16,
1147                    vpx_highbd_8_sub_pixel_avg_variance32x16,
1148                    NULL,
1149                    NULL,
1150                    vpx_highbd_sad32x16x4d_bits8)
1151
1152         HIGHBD_BFP(BLOCK_16X32,
1153                    vpx_highbd_sad16x32_bits8,
1154                    vpx_highbd_sad16x32_avg_bits8,
1155                    vpx_highbd_8_variance16x32,
1156                    vpx_highbd_8_sub_pixel_variance16x32,
1157                    vpx_highbd_8_sub_pixel_avg_variance16x32,
1158                    NULL,
1159                    NULL,
1160                    vpx_highbd_sad16x32x4d_bits8)
1161
1162         HIGHBD_BFP(BLOCK_64X32,
1163                    vpx_highbd_sad64x32_bits8,
1164                    vpx_highbd_sad64x32_avg_bits8,
1165                    vpx_highbd_8_variance64x32,
1166                    vpx_highbd_8_sub_pixel_variance64x32,
1167                    vpx_highbd_8_sub_pixel_avg_variance64x32,
1168                    NULL,
1169                    NULL,
1170                    vpx_highbd_sad64x32x4d_bits8)
1171
1172         HIGHBD_BFP(BLOCK_32X64,
1173                    vpx_highbd_sad32x64_bits8,
1174                    vpx_highbd_sad32x64_avg_bits8,
1175                    vpx_highbd_8_variance32x64,
1176                    vpx_highbd_8_sub_pixel_variance32x64,
1177                    vpx_highbd_8_sub_pixel_avg_variance32x64,
1178                    NULL,
1179                    NULL,
1180                    vpx_highbd_sad32x64x4d_bits8)
1181
1182         HIGHBD_BFP(BLOCK_32X32,
1183                    vpx_highbd_sad32x32_bits8,
1184                    vpx_highbd_sad32x32_avg_bits8,
1185                    vpx_highbd_8_variance32x32,
1186                    vpx_highbd_8_sub_pixel_variance32x32,
1187                    vpx_highbd_8_sub_pixel_avg_variance32x32,
1188                    vpx_highbd_sad32x32x3_bits8,
1189                    vpx_highbd_sad32x32x8_bits8,
1190                    vpx_highbd_sad32x32x4d_bits8)
1191
1192         HIGHBD_BFP(BLOCK_64X64,
1193                    vpx_highbd_sad64x64_bits8,
1194                    vpx_highbd_sad64x64_avg_bits8,
1195                    vpx_highbd_8_variance64x64,
1196                    vpx_highbd_8_sub_pixel_variance64x64,
1197                    vpx_highbd_8_sub_pixel_avg_variance64x64,
1198                    vpx_highbd_sad64x64x3_bits8,
1199                    vpx_highbd_sad64x64x8_bits8,
1200                    vpx_highbd_sad64x64x4d_bits8)
1201
1202         HIGHBD_BFP(BLOCK_16X16,
1203                    vpx_highbd_sad16x16_bits8,
1204                    vpx_highbd_sad16x16_avg_bits8,
1205                    vpx_highbd_8_variance16x16,
1206                    vpx_highbd_8_sub_pixel_variance16x16,
1207                    vpx_highbd_8_sub_pixel_avg_variance16x16,
1208                    vpx_highbd_sad16x16x3_bits8,
1209                    vpx_highbd_sad16x16x8_bits8,
1210                    vpx_highbd_sad16x16x4d_bits8)
1211
1212         HIGHBD_BFP(BLOCK_16X8,
1213                    vpx_highbd_sad16x8_bits8,
1214                    vpx_highbd_sad16x8_avg_bits8,
1215                    vpx_highbd_8_variance16x8,
1216                    vpx_highbd_8_sub_pixel_variance16x8,
1217                    vpx_highbd_8_sub_pixel_avg_variance16x8,
1218                    vpx_highbd_sad16x8x3_bits8,
1219                    vpx_highbd_sad16x8x8_bits8,
1220                    vpx_highbd_sad16x8x4d_bits8)
1221
1222         HIGHBD_BFP(BLOCK_8X16,
1223                    vpx_highbd_sad8x16_bits8,
1224                    vpx_highbd_sad8x16_avg_bits8,
1225                    vpx_highbd_8_variance8x16,
1226                    vpx_highbd_8_sub_pixel_variance8x16,
1227                    vpx_highbd_8_sub_pixel_avg_variance8x16,
1228                    vpx_highbd_sad8x16x3_bits8,
1229                    vpx_highbd_sad8x16x8_bits8,
1230                    vpx_highbd_sad8x16x4d_bits8)
1231
1232         HIGHBD_BFP(BLOCK_8X8,
1233                    vpx_highbd_sad8x8_bits8,
1234                    vpx_highbd_sad8x8_avg_bits8,
1235                    vpx_highbd_8_variance8x8,
1236                    vpx_highbd_8_sub_pixel_variance8x8,
1237                    vpx_highbd_8_sub_pixel_avg_variance8x8,
1238                    vpx_highbd_sad8x8x3_bits8,
1239                    vpx_highbd_sad8x8x8_bits8,
1240                    vpx_highbd_sad8x8x4d_bits8)
1241
1242         HIGHBD_BFP(BLOCK_8X4,
1243                    vpx_highbd_sad8x4_bits8,
1244                    vpx_highbd_sad8x4_avg_bits8,
1245                    vpx_highbd_8_variance8x4,
1246                    vpx_highbd_8_sub_pixel_variance8x4,
1247                    vpx_highbd_8_sub_pixel_avg_variance8x4,
1248                    NULL,
1249                    vpx_highbd_sad8x4x8_bits8,
1250                    vpx_highbd_sad8x4x4d_bits8)
1251
1252         HIGHBD_BFP(BLOCK_4X8,
1253                    vpx_highbd_sad4x8_bits8,
1254                    vpx_highbd_sad4x8_avg_bits8,
1255                    vpx_highbd_8_variance4x8,
1256                    vpx_highbd_8_sub_pixel_variance4x8,
1257                    vpx_highbd_8_sub_pixel_avg_variance4x8,
1258                    NULL,
1259                    vpx_highbd_sad4x8x8_bits8,
1260                    vpx_highbd_sad4x8x4d_bits8)
1261
1262         HIGHBD_BFP(BLOCK_4X4,
1263                    vpx_highbd_sad4x4_bits8,
1264                    vpx_highbd_sad4x4_avg_bits8,
1265                    vpx_highbd_8_variance4x4,
1266                    vpx_highbd_8_sub_pixel_variance4x4,
1267                    vpx_highbd_8_sub_pixel_avg_variance4x4,
1268                    vpx_highbd_sad4x4x3_bits8,
1269                    vpx_highbd_sad4x4x8_bits8,
1270                    vpx_highbd_sad4x4x4d_bits8)
1271         break;
1272
1273       case VPX_BITS_10:
1274         HIGHBD_BFP(BLOCK_32X16,
1275                    vpx_highbd_sad32x16_bits10,
1276                    vpx_highbd_sad32x16_avg_bits10,
1277                    vpx_highbd_10_variance32x16,
1278                    vpx_highbd_10_sub_pixel_variance32x16,
1279                    vpx_highbd_10_sub_pixel_avg_variance32x16,
1280                    NULL,
1281                    NULL,
1282                    vpx_highbd_sad32x16x4d_bits10)
1283
1284         HIGHBD_BFP(BLOCK_16X32,
1285                    vpx_highbd_sad16x32_bits10,
1286                    vpx_highbd_sad16x32_avg_bits10,
1287                    vpx_highbd_10_variance16x32,
1288                    vpx_highbd_10_sub_pixel_variance16x32,
1289                    vpx_highbd_10_sub_pixel_avg_variance16x32,
1290                    NULL,
1291                    NULL,
1292                    vpx_highbd_sad16x32x4d_bits10)
1293
1294         HIGHBD_BFP(BLOCK_64X32,
1295                    vpx_highbd_sad64x32_bits10,
1296                    vpx_highbd_sad64x32_avg_bits10,
1297                    vpx_highbd_10_variance64x32,
1298                    vpx_highbd_10_sub_pixel_variance64x32,
1299                    vpx_highbd_10_sub_pixel_avg_variance64x32,
1300                    NULL,
1301                    NULL,
1302                    vpx_highbd_sad64x32x4d_bits10)
1303
1304         HIGHBD_BFP(BLOCK_32X64,
1305                    vpx_highbd_sad32x64_bits10,
1306                    vpx_highbd_sad32x64_avg_bits10,
1307                    vpx_highbd_10_variance32x64,
1308                    vpx_highbd_10_sub_pixel_variance32x64,
1309                    vpx_highbd_10_sub_pixel_avg_variance32x64,
1310                    NULL,
1311                    NULL,
1312                    vpx_highbd_sad32x64x4d_bits10)
1313
1314         HIGHBD_BFP(BLOCK_32X32,
1315                    vpx_highbd_sad32x32_bits10,
1316                    vpx_highbd_sad32x32_avg_bits10,
1317                    vpx_highbd_10_variance32x32,
1318                    vpx_highbd_10_sub_pixel_variance32x32,
1319                    vpx_highbd_10_sub_pixel_avg_variance32x32,
1320                    vpx_highbd_sad32x32x3_bits10,
1321                    vpx_highbd_sad32x32x8_bits10,
1322                    vpx_highbd_sad32x32x4d_bits10)
1323
1324         HIGHBD_BFP(BLOCK_64X64,
1325                    vpx_highbd_sad64x64_bits10,
1326                    vpx_highbd_sad64x64_avg_bits10,
1327                    vpx_highbd_10_variance64x64,
1328                    vpx_highbd_10_sub_pixel_variance64x64,
1329                    vpx_highbd_10_sub_pixel_avg_variance64x64,
1330                    vpx_highbd_sad64x64x3_bits10,
1331                    vpx_highbd_sad64x64x8_bits10,
1332                    vpx_highbd_sad64x64x4d_bits10)
1333
1334         HIGHBD_BFP(BLOCK_16X16,
1335                    vpx_highbd_sad16x16_bits10,
1336                    vpx_highbd_sad16x16_avg_bits10,
1337                    vpx_highbd_10_variance16x16,
1338                    vpx_highbd_10_sub_pixel_variance16x16,
1339                    vpx_highbd_10_sub_pixel_avg_variance16x16,
1340                    vpx_highbd_sad16x16x3_bits10,
1341                    vpx_highbd_sad16x16x8_bits10,
1342                    vpx_highbd_sad16x16x4d_bits10)
1343
1344         HIGHBD_BFP(BLOCK_16X8,
1345                    vpx_highbd_sad16x8_bits10,
1346                    vpx_highbd_sad16x8_avg_bits10,
1347                    vpx_highbd_10_variance16x8,
1348                    vpx_highbd_10_sub_pixel_variance16x8,
1349                    vpx_highbd_10_sub_pixel_avg_variance16x8,
1350                    vpx_highbd_sad16x8x3_bits10,
1351                    vpx_highbd_sad16x8x8_bits10,
1352                    vpx_highbd_sad16x8x4d_bits10)
1353
1354         HIGHBD_BFP(BLOCK_8X16,
1355                    vpx_highbd_sad8x16_bits10,
1356                    vpx_highbd_sad8x16_avg_bits10,
1357                    vpx_highbd_10_variance8x16,
1358                    vpx_highbd_10_sub_pixel_variance8x16,
1359                    vpx_highbd_10_sub_pixel_avg_variance8x16,
1360                    vpx_highbd_sad8x16x3_bits10,
1361                    vpx_highbd_sad8x16x8_bits10,
1362                    vpx_highbd_sad8x16x4d_bits10)
1363
1364         HIGHBD_BFP(BLOCK_8X8,
1365                    vpx_highbd_sad8x8_bits10,
1366                    vpx_highbd_sad8x8_avg_bits10,
1367                    vpx_highbd_10_variance8x8,
1368                    vpx_highbd_10_sub_pixel_variance8x8,
1369                    vpx_highbd_10_sub_pixel_avg_variance8x8,
1370                    vpx_highbd_sad8x8x3_bits10,
1371                    vpx_highbd_sad8x8x8_bits10,
1372                    vpx_highbd_sad8x8x4d_bits10)
1373
1374         HIGHBD_BFP(BLOCK_8X4,
1375                    vpx_highbd_sad8x4_bits10,
1376                    vpx_highbd_sad8x4_avg_bits10,
1377                    vpx_highbd_10_variance8x4,
1378                    vpx_highbd_10_sub_pixel_variance8x4,
1379                    vpx_highbd_10_sub_pixel_avg_variance8x4,
1380                    NULL,
1381                    vpx_highbd_sad8x4x8_bits10,
1382                    vpx_highbd_sad8x4x4d_bits10)
1383
1384         HIGHBD_BFP(BLOCK_4X8,
1385                    vpx_highbd_sad4x8_bits10,
1386                    vpx_highbd_sad4x8_avg_bits10,
1387                    vpx_highbd_10_variance4x8,
1388                    vpx_highbd_10_sub_pixel_variance4x8,
1389                    vpx_highbd_10_sub_pixel_avg_variance4x8,
1390                    NULL,
1391                    vpx_highbd_sad4x8x8_bits10,
1392                    vpx_highbd_sad4x8x4d_bits10)
1393
1394         HIGHBD_BFP(BLOCK_4X4,
1395                    vpx_highbd_sad4x4_bits10,
1396                    vpx_highbd_sad4x4_avg_bits10,
1397                    vpx_highbd_10_variance4x4,
1398                    vpx_highbd_10_sub_pixel_variance4x4,
1399                    vpx_highbd_10_sub_pixel_avg_variance4x4,
1400                    vpx_highbd_sad4x4x3_bits10,
1401                    vpx_highbd_sad4x4x8_bits10,
1402                    vpx_highbd_sad4x4x4d_bits10)
1403         break;
1404
1405       case VPX_BITS_12:
1406         HIGHBD_BFP(BLOCK_32X16,
1407                    vpx_highbd_sad32x16_bits12,
1408                    vpx_highbd_sad32x16_avg_bits12,
1409                    vpx_highbd_12_variance32x16,
1410                    vpx_highbd_12_sub_pixel_variance32x16,
1411                    vpx_highbd_12_sub_pixel_avg_variance32x16,
1412                    NULL,
1413                    NULL,
1414                    vpx_highbd_sad32x16x4d_bits12)
1415
1416         HIGHBD_BFP(BLOCK_16X32,
1417                    vpx_highbd_sad16x32_bits12,
1418                    vpx_highbd_sad16x32_avg_bits12,
1419                    vpx_highbd_12_variance16x32,
1420                    vpx_highbd_12_sub_pixel_variance16x32,
1421                    vpx_highbd_12_sub_pixel_avg_variance16x32,
1422                    NULL,
1423                    NULL,
1424                    vpx_highbd_sad16x32x4d_bits12)
1425
1426         HIGHBD_BFP(BLOCK_64X32,
1427                    vpx_highbd_sad64x32_bits12,
1428                    vpx_highbd_sad64x32_avg_bits12,
1429                    vpx_highbd_12_variance64x32,
1430                    vpx_highbd_12_sub_pixel_variance64x32,
1431                    vpx_highbd_12_sub_pixel_avg_variance64x32,
1432                    NULL,
1433                    NULL,
1434                    vpx_highbd_sad64x32x4d_bits12)
1435
1436         HIGHBD_BFP(BLOCK_32X64,
1437                    vpx_highbd_sad32x64_bits12,
1438                    vpx_highbd_sad32x64_avg_bits12,
1439                    vpx_highbd_12_variance32x64,
1440                    vpx_highbd_12_sub_pixel_variance32x64,
1441                    vpx_highbd_12_sub_pixel_avg_variance32x64,
1442                    NULL,
1443                    NULL,
1444                    vpx_highbd_sad32x64x4d_bits12)
1445
1446         HIGHBD_BFP(BLOCK_32X32,
1447                    vpx_highbd_sad32x32_bits12,
1448                    vpx_highbd_sad32x32_avg_bits12,
1449                    vpx_highbd_12_variance32x32,
1450                    vpx_highbd_12_sub_pixel_variance32x32,
1451                    vpx_highbd_12_sub_pixel_avg_variance32x32,
1452                    vpx_highbd_sad32x32x3_bits12,
1453                    vpx_highbd_sad32x32x8_bits12,
1454                    vpx_highbd_sad32x32x4d_bits12)
1455
1456         HIGHBD_BFP(BLOCK_64X64,
1457                    vpx_highbd_sad64x64_bits12,
1458                    vpx_highbd_sad64x64_avg_bits12,
1459                    vpx_highbd_12_variance64x64,
1460                    vpx_highbd_12_sub_pixel_variance64x64,
1461                    vpx_highbd_12_sub_pixel_avg_variance64x64,
1462                    vpx_highbd_sad64x64x3_bits12,
1463                    vpx_highbd_sad64x64x8_bits12,
1464                    vpx_highbd_sad64x64x4d_bits12)
1465
1466         HIGHBD_BFP(BLOCK_16X16,
1467                    vpx_highbd_sad16x16_bits12,
1468                    vpx_highbd_sad16x16_avg_bits12,
1469                    vpx_highbd_12_variance16x16,
1470                    vpx_highbd_12_sub_pixel_variance16x16,
1471                    vpx_highbd_12_sub_pixel_avg_variance16x16,
1472                    vpx_highbd_sad16x16x3_bits12,
1473                    vpx_highbd_sad16x16x8_bits12,
1474                    vpx_highbd_sad16x16x4d_bits12)
1475
1476         HIGHBD_BFP(BLOCK_16X8,
1477                    vpx_highbd_sad16x8_bits12,
1478                    vpx_highbd_sad16x8_avg_bits12,
1479                    vpx_highbd_12_variance16x8,
1480                    vpx_highbd_12_sub_pixel_variance16x8,
1481                    vpx_highbd_12_sub_pixel_avg_variance16x8,
1482                    vpx_highbd_sad16x8x3_bits12,
1483                    vpx_highbd_sad16x8x8_bits12,
1484                    vpx_highbd_sad16x8x4d_bits12)
1485
1486         HIGHBD_BFP(BLOCK_8X16,
1487                    vpx_highbd_sad8x16_bits12,
1488                    vpx_highbd_sad8x16_avg_bits12,
1489                    vpx_highbd_12_variance8x16,
1490                    vpx_highbd_12_sub_pixel_variance8x16,
1491                    vpx_highbd_12_sub_pixel_avg_variance8x16,
1492                    vpx_highbd_sad8x16x3_bits12,
1493                    vpx_highbd_sad8x16x8_bits12,
1494                    vpx_highbd_sad8x16x4d_bits12)
1495
1496         HIGHBD_BFP(BLOCK_8X8,
1497                    vpx_highbd_sad8x8_bits12,
1498                    vpx_highbd_sad8x8_avg_bits12,
1499                    vpx_highbd_12_variance8x8,
1500                    vpx_highbd_12_sub_pixel_variance8x8,
1501                    vpx_highbd_12_sub_pixel_avg_variance8x8,
1502                    vpx_highbd_sad8x8x3_bits12,
1503                    vpx_highbd_sad8x8x8_bits12,
1504                    vpx_highbd_sad8x8x4d_bits12)
1505
1506         HIGHBD_BFP(BLOCK_8X4,
1507                    vpx_highbd_sad8x4_bits12,
1508                    vpx_highbd_sad8x4_avg_bits12,
1509                    vpx_highbd_12_variance8x4,
1510                    vpx_highbd_12_sub_pixel_variance8x4,
1511                    vpx_highbd_12_sub_pixel_avg_variance8x4,
1512                    NULL,
1513                    vpx_highbd_sad8x4x8_bits12,
1514                    vpx_highbd_sad8x4x4d_bits12)
1515
1516         HIGHBD_BFP(BLOCK_4X8,
1517                    vpx_highbd_sad4x8_bits12,
1518                    vpx_highbd_sad4x8_avg_bits12,
1519                    vpx_highbd_12_variance4x8,
1520                    vpx_highbd_12_sub_pixel_variance4x8,
1521                    vpx_highbd_12_sub_pixel_avg_variance4x8,
1522                    NULL,
1523                    vpx_highbd_sad4x8x8_bits12,
1524                    vpx_highbd_sad4x8x4d_bits12)
1525
1526         HIGHBD_BFP(BLOCK_4X4,
1527                    vpx_highbd_sad4x4_bits12,
1528                    vpx_highbd_sad4x4_avg_bits12,
1529                    vpx_highbd_12_variance4x4,
1530                    vpx_highbd_12_sub_pixel_variance4x4,
1531                    vpx_highbd_12_sub_pixel_avg_variance4x4,
1532                    vpx_highbd_sad4x4x3_bits12,
1533                    vpx_highbd_sad4x4x8_bits12,
1534                    vpx_highbd_sad4x4x4d_bits12)
1535         break;
1536
1537       default:
1538         assert(0 && "cm->bit_depth should be VPX_BITS_8, "
1539                     "VPX_BITS_10 or VPX_BITS_12");
1540     }
1541   }
1542 }
1543 #endif  // CONFIG_VP9_HIGHBITDEPTH
1544
1545 static void realloc_segmentation_maps(VP9_COMP *cpi) {
1546   VP9_COMMON *const cm = &cpi->common;
1547
1548   // Create the encoder segmentation map and set all entries to 0
1549   vpx_free(cpi->segmentation_map);
1550   CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1551                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1552
1553   // Create a map used for cyclic background refresh.
1554   if (cpi->cyclic_refresh)
1555     vp9_cyclic_refresh_free(cpi->cyclic_refresh);
1556   CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
1557                   vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
1558
1559   // Create a map used to mark inactive areas.
1560   vpx_free(cpi->active_map.map);
1561   CHECK_MEM_ERROR(cm, cpi->active_map.map,
1562                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1563
1564   // And a place holder structure is the coding context
1565   // for use if we want to save and restore it
1566   vpx_free(cpi->coding_context.last_frame_seg_map_copy);
1567   CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1568                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1569 }
1570
1571 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
1572   VP9_COMMON *const cm = &cpi->common;
1573   RATE_CONTROL *const rc = &cpi->rc;
1574   int last_w = cpi->oxcf.width;
1575   int last_h = cpi->oxcf.height;
1576
1577   if (cm->profile != oxcf->profile)
1578     cm->profile = oxcf->profile;
1579   cm->bit_depth = oxcf->bit_depth;
1580   cm->color_space = oxcf->color_space;
1581   cm->color_range = oxcf->color_range;
1582
1583   cpi->target_level = oxcf->target_level;
1584   cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
1585
1586   if (cm->profile <= PROFILE_1)
1587     assert(cm->bit_depth == VPX_BITS_8);
1588   else
1589     assert(cm->bit_depth > VPX_BITS_8);
1590
1591   cpi->oxcf = *oxcf;
1592 #if CONFIG_VP9_HIGHBITDEPTH
1593   cpi->td.mb.e_mbd.bd = (int)cm->bit_depth;
1594 #endif  // CONFIG_VP9_HIGHBITDEPTH
1595
1596   if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
1597     rc->baseline_gf_interval = FIXED_GF_INTERVAL;
1598   } else {
1599     rc->baseline_gf_interval = (MIN_GF_INTERVAL + MAX_GF_INTERVAL) / 2;
1600   }
1601
1602   cpi->refresh_golden_frame = 0;
1603   cpi->refresh_last_frame = 1;
1604   cm->refresh_frame_context = 1;
1605   cm->reset_frame_context = 0;
1606
1607   vp9_reset_segment_features(&cm->seg);
1608   vp9_set_high_precision_mv(cpi, 0);
1609
1610   {
1611     int i;
1612
1613     for (i = 0; i < MAX_SEGMENTS; i++)
1614       cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1615   }
1616   cpi->encode_breakout = cpi->oxcf.encode_breakout;
1617
1618   set_rc_buffer_sizes(rc, &cpi->oxcf);
1619
1620   // Under a configuration change, where maximum_buffer_size may change,
1621   // keep buffer level clipped to the maximum allowed buffer size.
1622   rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
1623   rc->buffer_level = VPXMIN(rc->buffer_level, rc->maximum_buffer_size);
1624
1625   // Set up frame rate and related parameters rate control values.
1626   vp9_new_framerate(cpi, cpi->framerate);
1627
1628   // Set absolute upper and lower quality limits
1629   rc->worst_quality = cpi->oxcf.worst_allowed_q;
1630   rc->best_quality = cpi->oxcf.best_allowed_q;
1631
1632   cm->interp_filter = cpi->sf.default_interp_filter;
1633
1634   if (cpi->oxcf.render_width > 0 && cpi->oxcf.render_height > 0) {
1635     cm->render_width = cpi->oxcf.render_width;
1636     cm->render_height = cpi->oxcf.render_height;
1637   } else {
1638     cm->render_width = cpi->oxcf.width;
1639     cm->render_height = cpi->oxcf.height;
1640   }
1641   if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1642     cm->width = cpi->oxcf.width;
1643     cm->height = cpi->oxcf.height;
1644     cpi->external_resize = 1;
1645   }
1646
1647   if (cpi->initial_width) {
1648     int new_mi_size = 0;
1649     vp9_set_mb_mi(cm, cm->width, cm->height);
1650     new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows);
1651     if (cm->mi_alloc_size < new_mi_size) {
1652       vp9_free_context_buffers(cm);
1653       alloc_compressor_data(cpi);
1654       realloc_segmentation_maps(cpi);
1655       cpi->initial_width = cpi->initial_height = 0;
1656       cpi->external_resize = 0;
1657     } else if (cm->mi_alloc_size == new_mi_size &&
1658              (cpi->oxcf.width > last_w || cpi->oxcf.height > last_h)) {
1659         vp9_alloc_loop_filter(cm);
1660     }
1661   }
1662
1663   update_frame_size(cpi);
1664
1665   if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1666     memset(cpi->consec_zero_mv, 0,
1667                cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
1668     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1669       vp9_cyclic_refresh_reset_resize(cpi);
1670   }
1671
1672   if ((cpi->svc.number_temporal_layers > 1 &&
1673       cpi->oxcf.rc_mode == VPX_CBR) ||
1674       ((cpi->svc.number_temporal_layers > 1 ||
1675         cpi->svc.number_spatial_layers > 1) &&
1676        cpi->oxcf.pass != 1)) {
1677     vp9_update_layer_context_change_config(cpi,
1678                                            (int)cpi->oxcf.target_bandwidth);
1679   }
1680
1681   cpi->alt_ref_source = NULL;
1682   rc->is_src_frame_alt_ref = 0;
1683
1684 #if 0
1685   // Experimental RD Code
1686   cpi->frame_distortion = 0;
1687   cpi->last_frame_distortion = 0;
1688 #endif
1689
1690   set_tile_limits(cpi);
1691
1692   cpi->ext_refresh_frame_flags_pending = 0;
1693   cpi->ext_refresh_frame_context_pending = 0;
1694
1695 #if CONFIG_VP9_HIGHBITDEPTH
1696   highbd_set_var_fns(cpi);
1697 #endif
1698 }
1699
1700 #ifndef M_LOG2_E
1701 #define M_LOG2_E 0.693147180559945309417
1702 #endif
1703 #define log2f(x) (log (x) / (float) M_LOG2_E)
1704
1705 /***********************************************************************
1706  * Read before modifying 'cal_nmvjointsadcost' or 'cal_nmvsadcosts'    *
1707  ***********************************************************************
1708  * The following 2 functions ('cal_nmvjointsadcost' and                *
1709  * 'cal_nmvsadcosts') are used to calculate cost lookup tables         *
1710  * used by 'vp9_diamond_search_sad'. The C implementation of the       *
1711  * function is generic, but the AVX intrinsics optimised version       *
1712  * relies on the following properties of the computed tables:          *
1713  * For cal_nmvjointsadcost:                                            *
1714  *   - mvjointsadcost[1] == mvjointsadcost[2] == mvjointsadcost[3]     *
1715  * For cal_nmvsadcosts:                                                *
1716  *   - For all i: mvsadcost[0][i] == mvsadcost[1][i]                   *
1717  *         (Equal costs for both components)                           *
1718  *   - For all i: mvsadcost[0][i] == mvsadcost[0][-i]                  *
1719  *         (Cost function is even)                                     *
1720  * If these do not hold, then the AVX optimised version of the         *
1721  * 'vp9_diamond_search_sad' function cannot be used as it is, in which *
1722  * case you can revert to using the C function instead.                *
1723  ***********************************************************************/
1724
1725 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1726   /*********************************************************************
1727    * Warning: Read the comments above before modifying this function   *
1728    *********************************************************************/
1729   mvjointsadcost[0] = 600;
1730   mvjointsadcost[1] = 300;
1731   mvjointsadcost[2] = 300;
1732   mvjointsadcost[3] = 300;
1733 }
1734
1735 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1736   /*********************************************************************
1737    * Warning: Read the comments above before modifying this function   *
1738    *********************************************************************/
1739   int i = 1;
1740
1741   mvsadcost[0][0] = 0;
1742   mvsadcost[1][0] = 0;
1743
1744   do {
1745     double z = 256 * (2 * (log2f(8 * i) + .6));
1746     mvsadcost[0][i] = (int)z;
1747     mvsadcost[1][i] = (int)z;
1748     mvsadcost[0][-i] = (int)z;
1749     mvsadcost[1][-i] = (int)z;
1750   } while (++i <= MV_MAX);
1751 }
1752
1753 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1754   int i = 1;
1755
1756   mvsadcost[0][0] = 0;
1757   mvsadcost[1][0] = 0;
1758
1759   do {
1760     double z = 256 * (2 * (log2f(8 * i) + .6));
1761     mvsadcost[0][i] = (int)z;
1762     mvsadcost[1][i] = (int)z;
1763     mvsadcost[0][-i] = (int)z;
1764     mvsadcost[1][-i] = (int)z;
1765   } while (++i <= MV_MAX);
1766 }
1767
1768 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf,
1769                                 BufferPool *const pool) {
1770   unsigned int i;
1771   VP9_COMP *volatile const cpi = vpx_memalign(32, sizeof(VP9_COMP));
1772   VP9_COMMON *volatile const cm = cpi != NULL ? &cpi->common : NULL;
1773
1774   if (!cm)
1775     return NULL;
1776
1777   vp9_zero(*cpi);
1778
1779   if (setjmp(cm->error.jmp)) {
1780     cm->error.setjmp = 0;
1781     vp9_remove_compressor(cpi);
1782     return 0;
1783   }
1784
1785   cm->error.setjmp = 1;
1786   cm->alloc_mi = vp9_enc_alloc_mi;
1787   cm->free_mi = vp9_enc_free_mi;
1788   cm->setup_mi = vp9_enc_setup_mi;
1789
1790   CHECK_MEM_ERROR(cm, cm->fc,
1791                   (FRAME_CONTEXT *)vpx_calloc(1, sizeof(*cm->fc)));
1792   CHECK_MEM_ERROR(cm, cm->frame_contexts,
1793                   (FRAME_CONTEXT *)vpx_calloc(FRAME_CONTEXTS,
1794                   sizeof(*cm->frame_contexts)));
1795
1796   cpi->use_svc = 0;
1797   cpi->resize_state = 0;
1798   cpi->external_resize = 0;
1799   cpi->resize_avg_qp = 0;
1800   cpi->resize_buffer_underflow = 0;
1801   cpi->use_skin_detection = 0;
1802   cpi->common.buffer_pool = pool;
1803
1804   init_config(cpi, oxcf);
1805   vp9_rc_init(&cpi->oxcf, oxcf->pass, &cpi->rc);
1806
1807   cm->current_video_frame = 0;
1808   cpi->partition_search_skippable_frame = 0;
1809   cpi->tile_data = NULL;
1810
1811   realloc_segmentation_maps(cpi);
1812
1813   CHECK_MEM_ERROR(cm, cpi->consec_zero_mv,
1814                   vpx_calloc(cm->mi_rows * cm->mi_cols,
1815                              sizeof(*cpi->consec_zero_mv)));
1816
1817   CHECK_MEM_ERROR(cm, cpi->nmvcosts[0],
1818                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[0])));
1819   CHECK_MEM_ERROR(cm, cpi->nmvcosts[1],
1820                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[1])));
1821   CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[0],
1822                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[0])));
1823   CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[1],
1824                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[1])));
1825   CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[0],
1826                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[0])));
1827   CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[1],
1828                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[1])));
1829   CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[0],
1830                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[0])));
1831   CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[1],
1832                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[1])));
1833
1834   for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1835                    sizeof(cpi->mbgraph_stats[0])); i++) {
1836     CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1837                     vpx_calloc(cm->MBs *
1838                                sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1839   }
1840
1841 #if CONFIG_FP_MB_STATS
1842   cpi->use_fp_mb_stats = 0;
1843   if (cpi->use_fp_mb_stats) {
1844     // a place holder used to store the first pass mb stats in the first pass
1845     CHECK_MEM_ERROR(cm, cpi->twopass.frame_mb_stats_buf,
1846                     vpx_calloc(cm->MBs * sizeof(uint8_t), 1));
1847   } else {
1848     cpi->twopass.frame_mb_stats_buf = NULL;
1849   }
1850 #endif
1851
1852   cpi->refresh_alt_ref_frame = 0;
1853   cpi->multi_arf_last_grp_enabled = 0;
1854
1855   cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1856
1857   init_level_info(&cpi->level_info);
1858
1859 #if CONFIG_INTERNAL_STATS
1860   cpi->b_calculate_blockiness = 1;
1861   cpi->b_calculate_consistency = 1;
1862   cpi->total_inconsistency = 0;
1863   cpi->psnr.worst = 100.0;
1864   cpi->worst_ssim = 100.0;
1865
1866   cpi->count = 0;
1867   cpi->bytes = 0;
1868
1869   if (cpi->b_calculate_psnr) {
1870     cpi->total_sq_error = 0;
1871     cpi->total_samples = 0;
1872
1873     cpi->totalp_sq_error = 0;
1874     cpi->totalp_samples = 0;
1875
1876     cpi->tot_recode_hits = 0;
1877     cpi->summed_quality = 0;
1878     cpi->summed_weights = 0;
1879     cpi->summedp_quality = 0;
1880     cpi->summedp_weights = 0;
1881   }
1882
1883   cpi->fastssim.worst = 100.0;
1884
1885   cpi->psnrhvs.worst = 100.0;
1886
1887   if (cpi->b_calculate_blockiness) {
1888     cpi->total_blockiness = 0;
1889     cpi->worst_blockiness = 0.0;
1890   }
1891
1892   if (cpi->b_calculate_consistency) {
1893     CHECK_MEM_ERROR(cm, cpi->ssim_vars,
1894                     vpx_malloc(sizeof(*cpi->ssim_vars) * 4 *
1895                                cpi->common.mi_rows * cpi->common.mi_cols));
1896     cpi->worst_consistency = 100.0;
1897   }
1898
1899 #endif
1900
1901   cpi->first_time_stamp_ever = INT64_MAX;
1902
1903   /*********************************************************************
1904    * Warning: Read the comments around 'cal_nmvjointsadcost' and       *
1905    * 'cal_nmvsadcosts' before modifying how these tables are computed. *
1906    *********************************************************************/
1907   cal_nmvjointsadcost(cpi->td.mb.nmvjointsadcost);
1908   cpi->td.mb.nmvcost[0] = &cpi->nmvcosts[0][MV_MAX];
1909   cpi->td.mb.nmvcost[1] = &cpi->nmvcosts[1][MV_MAX];
1910   cpi->td.mb.nmvsadcost[0] = &cpi->nmvsadcosts[0][MV_MAX];
1911   cpi->td.mb.nmvsadcost[1] = &cpi->nmvsadcosts[1][MV_MAX];
1912   cal_nmvsadcosts(cpi->td.mb.nmvsadcost);
1913
1914   cpi->td.mb.nmvcost_hp[0] = &cpi->nmvcosts_hp[0][MV_MAX];
1915   cpi->td.mb.nmvcost_hp[1] = &cpi->nmvcosts_hp[1][MV_MAX];
1916   cpi->td.mb.nmvsadcost_hp[0] = &cpi->nmvsadcosts_hp[0][MV_MAX];
1917   cpi->td.mb.nmvsadcost_hp[1] = &cpi->nmvsadcosts_hp[1][MV_MAX];
1918   cal_nmvsadcosts_hp(cpi->td.mb.nmvsadcost_hp);
1919
1920 #if CONFIG_VP9_TEMPORAL_DENOISING
1921 #ifdef OUTPUT_YUV_DENOISED
1922   yuv_denoised_file = fopen("denoised.yuv", "ab");
1923 #endif
1924 #endif
1925 #ifdef OUTPUT_YUV_SKINMAP
1926   yuv_skinmap_file = fopen("skinmap.yuv", "ab");
1927 #endif
1928 #ifdef OUTPUT_YUV_REC
1929   yuv_rec_file = fopen("rec.yuv", "wb");
1930 #endif
1931
1932 #if 0
1933   framepsnr = fopen("framepsnr.stt", "a");
1934   kf_list = fopen("kf_list.stt", "w");
1935 #endif
1936
1937   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
1938
1939   if (oxcf->pass == 1) {
1940     vp9_init_first_pass(cpi);
1941   } else if (oxcf->pass == 2) {
1942     const size_t packet_sz = sizeof(FIRSTPASS_STATS);
1943     const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1944
1945     if (cpi->svc.number_spatial_layers > 1
1946         || cpi->svc.number_temporal_layers > 1) {
1947       FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
1948       FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = {0};
1949       int i;
1950
1951       for (i = 0; i < oxcf->ss_number_layers; ++i) {
1952         FIRSTPASS_STATS *const last_packet_for_layer =
1953             &stats[packets - oxcf->ss_number_layers + i];
1954         const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
1955         const int packets_in_layer = (int)last_packet_for_layer->count + 1;
1956         if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
1957           LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
1958
1959           vpx_free(lc->rc_twopass_stats_in.buf);
1960
1961           lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
1962           CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
1963                           vpx_malloc(lc->rc_twopass_stats_in.sz));
1964           lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
1965           lc->twopass.stats_in = lc->twopass.stats_in_start;
1966           lc->twopass.stats_in_end = lc->twopass.stats_in_start
1967                                      + packets_in_layer - 1;
1968           stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
1969         }
1970       }
1971
1972       for (i = 0; i < packets; ++i) {
1973         const int layer_id = (int)stats[i].spatial_layer_id;
1974         if (layer_id >= 0 && layer_id < oxcf->ss_number_layers
1975             && stats_copy[layer_id] != NULL) {
1976           *stats_copy[layer_id] = stats[i];
1977           ++stats_copy[layer_id];
1978         }
1979       }
1980
1981       vp9_init_second_pass_spatial_svc(cpi);
1982     } else {
1983 #if CONFIG_FP_MB_STATS
1984       if (cpi->use_fp_mb_stats) {
1985         const size_t psz = cpi->common.MBs * sizeof(uint8_t);
1986         const int ps = (int)(oxcf->firstpass_mb_stats_in.sz / psz);
1987
1988         cpi->twopass.firstpass_mb_stats.mb_stats_start =
1989             oxcf->firstpass_mb_stats_in.buf;
1990         cpi->twopass.firstpass_mb_stats.mb_stats_end =
1991             cpi->twopass.firstpass_mb_stats.mb_stats_start +
1992             (ps - 1) * cpi->common.MBs * sizeof(uint8_t);
1993       }
1994 #endif
1995
1996       cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1997       cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1998       cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
1999
2000       vp9_init_second_pass(cpi);
2001     }
2002   }
2003
2004   vp9_set_speed_features_framesize_independent(cpi);
2005   vp9_set_speed_features_framesize_dependent(cpi);
2006
2007   // Allocate memory to store variances for a frame.
2008   CHECK_MEM_ERROR(cm, cpi->source_diff_var,
2009                   vpx_calloc(cm->MBs, sizeof(diff)));
2010   cpi->source_var_thresh = 0;
2011   cpi->frames_till_next_var_check = 0;
2012
2013 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF)\
2014     cpi->fn_ptr[BT].sdf            = SDF; \
2015     cpi->fn_ptr[BT].sdaf           = SDAF; \
2016     cpi->fn_ptr[BT].vf             = VF; \
2017     cpi->fn_ptr[BT].svf            = SVF; \
2018     cpi->fn_ptr[BT].svaf           = SVAF; \
2019     cpi->fn_ptr[BT].sdx3f          = SDX3F; \
2020     cpi->fn_ptr[BT].sdx8f          = SDX8F; \
2021     cpi->fn_ptr[BT].sdx4df         = SDX4DF;
2022
2023   BFP(BLOCK_32X16, vpx_sad32x16, vpx_sad32x16_avg,
2024       vpx_variance32x16, vpx_sub_pixel_variance32x16,
2025       vpx_sub_pixel_avg_variance32x16, NULL, NULL, vpx_sad32x16x4d)
2026
2027   BFP(BLOCK_16X32, vpx_sad16x32, vpx_sad16x32_avg,
2028       vpx_variance16x32, vpx_sub_pixel_variance16x32,
2029       vpx_sub_pixel_avg_variance16x32, NULL, NULL, vpx_sad16x32x4d)
2030
2031   BFP(BLOCK_64X32, vpx_sad64x32, vpx_sad64x32_avg,
2032       vpx_variance64x32, vpx_sub_pixel_variance64x32,
2033       vpx_sub_pixel_avg_variance64x32, NULL, NULL, vpx_sad64x32x4d)
2034
2035   BFP(BLOCK_32X64, vpx_sad32x64, vpx_sad32x64_avg,
2036       vpx_variance32x64, vpx_sub_pixel_variance32x64,
2037       vpx_sub_pixel_avg_variance32x64, NULL, NULL, vpx_sad32x64x4d)
2038
2039   BFP(BLOCK_32X32, vpx_sad32x32, vpx_sad32x32_avg,
2040       vpx_variance32x32, vpx_sub_pixel_variance32x32,
2041       vpx_sub_pixel_avg_variance32x32, vpx_sad32x32x3, vpx_sad32x32x8,
2042       vpx_sad32x32x4d)
2043
2044   BFP(BLOCK_64X64, vpx_sad64x64, vpx_sad64x64_avg,
2045       vpx_variance64x64, vpx_sub_pixel_variance64x64,
2046       vpx_sub_pixel_avg_variance64x64, vpx_sad64x64x3, vpx_sad64x64x8,
2047       vpx_sad64x64x4d)
2048
2049   BFP(BLOCK_16X16, vpx_sad16x16, vpx_sad16x16_avg,
2050       vpx_variance16x16, vpx_sub_pixel_variance16x16,
2051       vpx_sub_pixel_avg_variance16x16, vpx_sad16x16x3, vpx_sad16x16x8,
2052       vpx_sad16x16x4d)
2053
2054   BFP(BLOCK_16X8, vpx_sad16x8, vpx_sad16x8_avg,
2055       vpx_variance16x8, vpx_sub_pixel_variance16x8,
2056       vpx_sub_pixel_avg_variance16x8,
2057       vpx_sad16x8x3, vpx_sad16x8x8, vpx_sad16x8x4d)
2058
2059   BFP(BLOCK_8X16, vpx_sad8x16, vpx_sad8x16_avg,
2060       vpx_variance8x16, vpx_sub_pixel_variance8x16,
2061       vpx_sub_pixel_avg_variance8x16,
2062       vpx_sad8x16x3, vpx_sad8x16x8, vpx_sad8x16x4d)
2063
2064   BFP(BLOCK_8X8, vpx_sad8x8, vpx_sad8x8_avg,
2065       vpx_variance8x8, vpx_sub_pixel_variance8x8,
2066       vpx_sub_pixel_avg_variance8x8,
2067       vpx_sad8x8x3, vpx_sad8x8x8, vpx_sad8x8x4d)
2068
2069   BFP(BLOCK_8X4, vpx_sad8x4, vpx_sad8x4_avg,
2070       vpx_variance8x4, vpx_sub_pixel_variance8x4,
2071       vpx_sub_pixel_avg_variance8x4, NULL, vpx_sad8x4x8, vpx_sad8x4x4d)
2072
2073   BFP(BLOCK_4X8, vpx_sad4x8, vpx_sad4x8_avg,
2074       vpx_variance4x8, vpx_sub_pixel_variance4x8,
2075       vpx_sub_pixel_avg_variance4x8, NULL, vpx_sad4x8x8, vpx_sad4x8x4d)
2076
2077   BFP(BLOCK_4X4, vpx_sad4x4, vpx_sad4x4_avg,
2078       vpx_variance4x4, vpx_sub_pixel_variance4x4,
2079       vpx_sub_pixel_avg_variance4x4,
2080       vpx_sad4x4x3, vpx_sad4x4x8, vpx_sad4x4x4d)
2081
2082 #if CONFIG_VP9_HIGHBITDEPTH
2083   highbd_set_var_fns(cpi);
2084 #endif
2085
2086   /* vp9_init_quantizer() is first called here. Add check in
2087    * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
2088    * called later when needed. This will avoid unnecessary calls of
2089    * vp9_init_quantizer() for every frame.
2090    */
2091   vp9_init_quantizer(cpi);
2092
2093   vp9_loop_filter_init(cm);
2094
2095   cm->error.setjmp = 0;
2096
2097   return cpi;
2098 }
2099
2100 #if CONFIG_INTERNAL_STATS
2101 #define SNPRINT(H, T) \
2102   snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T))
2103
2104 #define SNPRINT2(H, T, V) \
2105   snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T), (V))
2106 #endif  // CONFIG_INTERNAL_STATS
2107
2108 void vp9_remove_compressor(VP9_COMP *cpi) {
2109   VP9_COMMON *cm;
2110   unsigned int i;
2111   int t;
2112
2113   if (!cpi)
2114     return;
2115
2116   cm = &cpi->common;
2117   if (cm->current_video_frame > 0) {
2118 #if CONFIG_INTERNAL_STATS
2119     vpx_clear_system_state();
2120
2121     if (cpi->oxcf.pass != 1) {
2122       char headings[512] = {0};
2123       char results[512] = {0};
2124       FILE *f = fopen("opsnr.stt", "a");
2125       double time_encoded = (cpi->last_end_time_stamp_seen
2126                              - cpi->first_time_stamp_ever) / 10000000.000;
2127       double total_encode_time = (cpi->time_receive_data +
2128                                   cpi->time_compress_data)   / 1000.000;
2129       const double dr =
2130           (double)cpi->bytes * (double) 8 / (double)1000 / time_encoded;
2131       const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
2132       const double target_rate = (double)cpi->oxcf.target_bandwidth / 1000;
2133       const double rate_err = ((100.0 * (dr - target_rate)) / target_rate);
2134
2135       if (cpi->b_calculate_psnr) {
2136         const double total_psnr =
2137             vpx_sse_to_psnr((double)cpi->total_samples, peak,
2138                             (double)cpi->total_sq_error);
2139         const double totalp_psnr =
2140             vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
2141                             (double)cpi->totalp_sq_error);
2142         const double total_ssim = 100 * pow(cpi->summed_quality /
2143                                             cpi->summed_weights, 8.0);
2144         const double totalp_ssim = 100 * pow(cpi->summedp_quality /
2145                                              cpi->summedp_weights, 8.0);
2146
2147         snprintf(headings, sizeof(headings),
2148                  "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
2149                  "VPXSSIM\tVPSSIMP\tFASTSIM\tPSNRHVS\t"
2150                  "WstPsnr\tWstSsim\tWstFast\tWstHVS");
2151         snprintf(results, sizeof(results),
2152                  "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2153                  "%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2154                  "%7.3f\t%7.3f\t%7.3f\t%7.3f",
2155                  dr, cpi->psnr.stat[ALL] / cpi->count, total_psnr,
2156                  cpi->psnrp.stat[ALL] / cpi->count, totalp_psnr,
2157                  total_ssim, totalp_ssim,
2158                  cpi->fastssim.stat[ALL] / cpi->count,
2159                  cpi->psnrhvs.stat[ALL] / cpi->count,
2160                  cpi->psnr.worst, cpi->worst_ssim, cpi->fastssim.worst,
2161                  cpi->psnrhvs.worst);
2162
2163         if (cpi->b_calculate_blockiness) {
2164           SNPRINT(headings, "\t  Block\tWstBlck");
2165           SNPRINT2(results, "\t%7.3f", cpi->total_blockiness / cpi->count);
2166           SNPRINT2(results, "\t%7.3f", cpi->worst_blockiness);
2167         }
2168
2169         if (cpi->b_calculate_consistency) {
2170           double consistency =
2171               vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
2172                               (double)cpi->total_inconsistency);
2173
2174           SNPRINT(headings, "\tConsist\tWstCons");
2175           SNPRINT2(results, "\t%7.3f", consistency);
2176           SNPRINT2(results, "\t%7.3f", cpi->worst_consistency);
2177         }
2178         fprintf(f, "%s\t    Time  Rc-Err Abs Err\n", headings);
2179         fprintf(f, "%s\t%8.0f %7.2f %7.2f\n", results,
2180                 total_encode_time, rate_err, fabs(rate_err));
2181       }
2182
2183       fclose(f);
2184     }
2185
2186 #endif
2187
2188 #if 0
2189     {
2190       printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2191       printf("\n_frames recive_data encod_mb_row compress_frame  Total\n");
2192       printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
2193              cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
2194              cpi->time_compress_data / 1000,
2195              (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2196     }
2197 #endif
2198   }
2199
2200 #if CONFIG_VP9_TEMPORAL_DENOISING
2201   vp9_denoiser_free(&(cpi->denoiser));
2202 #endif
2203
2204   for (t = 0; t < cpi->num_workers; ++t) {
2205     VPxWorker *const worker = &cpi->workers[t];
2206     EncWorkerData *const thread_data = &cpi->tile_thr_data[t];
2207
2208     // Deallocate allocated threads.
2209     vpx_get_worker_interface()->end(worker);
2210
2211     // Deallocate allocated thread data.
2212     if (t < cpi->num_workers - 1) {
2213       vpx_free(thread_data->td->counts);
2214       vp9_free_pc_tree(thread_data->td);
2215       vpx_free(thread_data->td);
2216     }
2217   }
2218   vpx_free(cpi->tile_thr_data);
2219   vpx_free(cpi->workers);
2220
2221   if (cpi->num_workers > 1)
2222     vp9_loop_filter_dealloc(&cpi->lf_row_sync);
2223
2224   dealloc_compressor_data(cpi);
2225
2226   for (i = 0; i < sizeof(cpi->mbgraph_stats) /
2227                   sizeof(cpi->mbgraph_stats[0]); ++i) {
2228     vpx_free(cpi->mbgraph_stats[i].mb_stats);
2229   }
2230
2231 #if CONFIG_FP_MB_STATS
2232   if (cpi->use_fp_mb_stats) {
2233     vpx_free(cpi->twopass.frame_mb_stats_buf);
2234     cpi->twopass.frame_mb_stats_buf = NULL;
2235   }
2236 #endif
2237
2238   vp9_remove_common(cm);
2239   vp9_free_ref_frame_buffers(cm->buffer_pool);
2240 #if CONFIG_VP9_POSTPROC
2241   vp9_free_postproc_buffers(cm);
2242 #endif
2243   vpx_free(cpi);
2244
2245 #if CONFIG_VP9_TEMPORAL_DENOISING
2246 #ifdef OUTPUT_YUV_DENOISED
2247   fclose(yuv_denoised_file);
2248 #endif
2249 #endif
2250 #ifdef OUTPUT_YUV_SKINMAP
2251   fclose(yuv_skinmap_file);
2252 #endif
2253 #ifdef OUTPUT_YUV_REC
2254   fclose(yuv_rec_file);
2255 #endif
2256
2257 #if 0
2258
2259   if (keyfile)
2260     fclose(keyfile);
2261
2262   if (framepsnr)
2263     fclose(framepsnr);
2264
2265   if (kf_list)
2266     fclose(kf_list);
2267
2268 #endif
2269 }
2270
2271 static void generate_psnr_packet(VP9_COMP *cpi) {
2272   struct vpx_codec_cx_pkt pkt;
2273   int i;
2274   PSNR_STATS psnr;
2275 #if CONFIG_VP9_HIGHBITDEPTH
2276   vpx_calc_highbd_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr,
2277                        cpi->td.mb.e_mbd.bd, cpi->oxcf.input_bit_depth);
2278 #else
2279   vpx_calc_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr);
2280 #endif
2281
2282   for (i = 0; i < 4; ++i) {
2283     pkt.data.psnr.samples[i] = psnr.samples[i];
2284     pkt.data.psnr.sse[i] = psnr.sse[i];
2285     pkt.data.psnr.psnr[i] = psnr.psnr[i];
2286   }
2287   pkt.kind = VPX_CODEC_PSNR_PKT;
2288   if (cpi->use_svc)
2289     cpi->svc.layer_context[cpi->svc.spatial_layer_id *
2290         cpi->svc.number_temporal_layers].psnr_pkt = pkt.data.psnr;
2291   else
2292     vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2293 }
2294
2295 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
2296   if (ref_frame_flags > 7)
2297     return -1;
2298
2299   cpi->ref_frame_flags = ref_frame_flags;
2300   return 0;
2301 }
2302
2303 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
2304   cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
2305   cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
2306   cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
2307   cpi->ext_refresh_frame_flags_pending = 1;
2308 }
2309
2310 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
2311                                 VP9_REFFRAME ref_frame_flag) {
2312   MV_REFERENCE_FRAME ref_frame = NONE;
2313   if (ref_frame_flag == VP9_LAST_FLAG)
2314     ref_frame = LAST_FRAME;
2315   else if (ref_frame_flag == VP9_GOLD_FLAG)
2316     ref_frame = GOLDEN_FRAME;
2317   else if (ref_frame_flag == VP9_ALT_FLAG)
2318     ref_frame = ALTREF_FRAME;
2319
2320   return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
2321 }
2322
2323 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2324                            YV12_BUFFER_CONFIG *sd) {
2325   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2326   if (cfg) {
2327     vp8_yv12_copy_frame(cfg, sd);
2328     return 0;
2329   } else {
2330     return -1;
2331   }
2332 }
2333
2334 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2335                           YV12_BUFFER_CONFIG *sd) {
2336   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2337   if (cfg) {
2338     vp8_yv12_copy_frame(sd, cfg);
2339     return 0;
2340   } else {
2341     return -1;
2342   }
2343 }
2344
2345 int vp9_update_entropy(VP9_COMP * cpi, int update) {
2346   cpi->ext_refresh_frame_context = update;
2347   cpi->ext_refresh_frame_context_pending = 1;
2348   return 0;
2349 }
2350
2351 #if defined(OUTPUT_YUV_DENOISED) || defined(OUTPUT_YUV_SKINMAP)
2352 // The denoiser buffer is allocated as a YUV 440 buffer. This function writes it
2353 // as YUV 420. We simply use the top-left pixels of the UV buffers, since we do
2354 // not denoise the UV channels at this time. If ever we implement UV channel
2355 // denoising we will have to modify this.
2356 void vp9_write_yuv_frame_420(YV12_BUFFER_CONFIG *s, FILE *f) {
2357   uint8_t *src = s->y_buffer;
2358   int h = s->y_height;
2359
2360   do {
2361     fwrite(src, s->y_width, 1, f);
2362     src += s->y_stride;
2363   } while (--h);
2364
2365   src = s->u_buffer;
2366   h = s->uv_height;
2367
2368   do {
2369     fwrite(src, s->uv_width, 1, f);
2370     src += s->uv_stride;
2371   } while (--h);
2372
2373   src = s->v_buffer;
2374   h = s->uv_height;
2375
2376   do {
2377     fwrite(src, s->uv_width, 1, f);
2378     src += s->uv_stride;
2379   } while (--h);
2380 }
2381 #endif
2382
2383 #ifdef OUTPUT_YUV_REC
2384 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2385   YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2386   uint8_t *src = s->y_buffer;
2387   int h = cm->height;
2388
2389 #if CONFIG_VP9_HIGHBITDEPTH
2390   if (s->flags & YV12_FLAG_HIGHBITDEPTH) {
2391     uint16_t *src16 = CONVERT_TO_SHORTPTR(s->y_buffer);
2392
2393     do {
2394       fwrite(src16, s->y_width, 2,  yuv_rec_file);
2395       src16 += s->y_stride;
2396     } while (--h);
2397
2398     src16 = CONVERT_TO_SHORTPTR(s->u_buffer);
2399     h = s->uv_height;
2400
2401     do {
2402       fwrite(src16, s->uv_width, 2,  yuv_rec_file);
2403       src16 += s->uv_stride;
2404     } while (--h);
2405
2406     src16 = CONVERT_TO_SHORTPTR(s->v_buffer);
2407     h = s->uv_height;
2408
2409     do {
2410       fwrite(src16, s->uv_width, 2, yuv_rec_file);
2411       src16 += s->uv_stride;
2412     } while (--h);
2413
2414     fflush(yuv_rec_file);
2415     return;
2416   }
2417 #endif  // CONFIG_VP9_HIGHBITDEPTH
2418
2419   do {
2420     fwrite(src, s->y_width, 1,  yuv_rec_file);
2421     src += s->y_stride;
2422   } while (--h);
2423
2424   src = s->u_buffer;
2425   h = s->uv_height;
2426
2427   do {
2428     fwrite(src, s->uv_width, 1,  yuv_rec_file);
2429     src += s->uv_stride;
2430   } while (--h);
2431
2432   src = s->v_buffer;
2433   h = s->uv_height;
2434
2435   do {
2436     fwrite(src, s->uv_width, 1, yuv_rec_file);
2437     src += s->uv_stride;
2438   } while (--h);
2439
2440   fflush(yuv_rec_file);
2441 }
2442 #endif
2443
2444 #if CONFIG_VP9_HIGHBITDEPTH
2445 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2446                                                 YV12_BUFFER_CONFIG *dst,
2447                                                 int bd) {
2448 #else
2449 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2450                                                 YV12_BUFFER_CONFIG *dst) {
2451 #endif  // CONFIG_VP9_HIGHBITDEPTH
2452   // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
2453   int i;
2454   const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
2455   const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
2456   const int src_widths[3] = {src->y_crop_width, src->uv_crop_width,
2457                              src->uv_crop_width };
2458   const int src_heights[3] = {src->y_crop_height, src->uv_crop_height,
2459                               src->uv_crop_height};
2460   uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
2461   const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
2462   const int dst_widths[3] = {dst->y_crop_width, dst->uv_crop_width,
2463                              dst->uv_crop_width};
2464   const int dst_heights[3] = {dst->y_crop_height, dst->uv_crop_height,
2465                               dst->uv_crop_height};
2466
2467   for (i = 0; i < MAX_MB_PLANE; ++i) {
2468 #if CONFIG_VP9_HIGHBITDEPTH
2469     if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2470       vp9_highbd_resize_plane(srcs[i], src_heights[i], src_widths[i],
2471                               src_strides[i], dsts[i], dst_heights[i],
2472                               dst_widths[i], dst_strides[i], bd);
2473     } else {
2474       vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2475                        dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2476     }
2477 #else
2478     vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2479                      dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2480 #endif  // CONFIG_VP9_HIGHBITDEPTH
2481   }
2482   vpx_extend_frame_borders(dst);
2483 }
2484
2485 #if CONFIG_VP9_HIGHBITDEPTH
2486 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
2487                                    YV12_BUFFER_CONFIG *dst, int bd) {
2488   const int src_w = src->y_crop_width;
2489   const int src_h = src->y_crop_height;
2490   const int dst_w = dst->y_crop_width;
2491   const int dst_h = dst->y_crop_height;
2492   const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
2493   const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
2494   uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
2495   const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
2496   const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2497   int x, y, i;
2498
2499   for (i = 0; i < MAX_MB_PLANE; ++i) {
2500     const int factor = (i == 0 || i == 3 ? 1 : 2);
2501     const int src_stride = src_strides[i];
2502     const int dst_stride = dst_strides[i];
2503     for (y = 0; y < dst_h; y += 16) {
2504       const int y_q4 = y * (16 / factor) * src_h / dst_h;
2505       for (x = 0; x < dst_w; x += 16) {
2506         const int x_q4 = x * (16 / factor) * src_w / dst_w;
2507         const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
2508                                    src_stride + (x / factor) * src_w / dst_w;
2509         uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2510
2511         if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2512           vpx_highbd_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
2513                                kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2514                                kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2515                                16 / factor, 16 / factor, bd);
2516         } else {
2517           vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2518                         kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2519                         kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2520                         16 / factor, 16 / factor);
2521         }
2522       }
2523     }
2524   }
2525
2526   vpx_extend_frame_borders(dst);
2527 }
2528 #else
2529 void vp9_scale_and_extend_frame_c(const YV12_BUFFER_CONFIG *src,
2530                                   YV12_BUFFER_CONFIG *dst) {
2531   const int src_w = src->y_crop_width;
2532   const int src_h = src->y_crop_height;
2533   const int dst_w = dst->y_crop_width;
2534   const int dst_h = dst->y_crop_height;
2535   const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
2536   const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
2537   uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
2538   const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
2539   const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2540   int x, y, i;
2541
2542   for (i = 0; i < MAX_MB_PLANE; ++i) {
2543     const int factor = (i == 0 || i == 3 ? 1 : 2);
2544     const int src_stride = src_strides[i];
2545     const int dst_stride = dst_strides[i];
2546     for (y = 0; y < dst_h; y += 16) {
2547       const int y_q4 = y * (16 / factor) * src_h / dst_h;
2548       for (x = 0; x < dst_w; x += 16) {
2549         const int x_q4 = x * (16 / factor) * src_w / dst_w;
2550         const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
2551                                    src_stride + (x / factor) * src_w / dst_w;
2552         uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2553
2554         vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2555                       kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2556                       kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2557                       16 / factor, 16 / factor);
2558       }
2559     }
2560   }
2561
2562   vpx_extend_frame_borders(dst);
2563 }
2564 #endif  // CONFIG_VP9_HIGHBITDEPTH
2565
2566 static int scale_down(VP9_COMP *cpi, int q) {
2567   RATE_CONTROL *const rc = &cpi->rc;
2568   GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2569   int scale = 0;
2570   assert(frame_is_kf_gf_arf(cpi));
2571
2572   if (rc->frame_size_selector == UNSCALED &&
2573       q >= rc->rf_level_maxq[gf_group->rf_level[gf_group->index]]) {
2574     const int max_size_thresh = (int)(rate_thresh_mult[SCALE_STEP1]
2575         * VPXMAX(rc->this_frame_target, rc->avg_frame_bandwidth));
2576     scale = rc->projected_frame_size > max_size_thresh ? 1 : 0;
2577   }
2578   return scale;
2579 }
2580
2581 static int big_rate_miss(VP9_COMP *cpi, int high_limit, int low_limit) {
2582   const RATE_CONTROL *const rc = &cpi->rc;
2583
2584   return (rc->projected_frame_size > ((high_limit * 3) / 2)) ||
2585          (rc->projected_frame_size < (low_limit / 2));
2586 }
2587
2588 // Function to test for conditions that indicate we should loop
2589 // back and recode a frame.
2590 static int recode_loop_test(VP9_COMP *cpi,
2591                             int high_limit, int low_limit,
2592                             int q, int maxq, int minq) {
2593   const RATE_CONTROL *const rc = &cpi->rc;
2594   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2595   const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
2596   int force_recode = 0;
2597
2598   if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
2599       big_rate_miss(cpi, high_limit, low_limit) ||
2600       (cpi->sf.recode_loop == ALLOW_RECODE) ||
2601       (frame_is_kfgfarf &&
2602        (cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF))) {
2603     if (frame_is_kfgfarf &&
2604         (oxcf->resize_mode == RESIZE_DYNAMIC) &&
2605         scale_down(cpi, q)) {
2606         // Code this group at a lower resolution.
2607         cpi->resize_pending = 1;
2608         return 1;
2609     }
2610
2611     // TODO(agrange) high_limit could be greater than the scale-down threshold.
2612     if ((rc->projected_frame_size > high_limit && q < maxq) ||
2613         (rc->projected_frame_size < low_limit && q > minq)) {
2614       force_recode = 1;
2615     } else if (cpi->oxcf.rc_mode == VPX_CQ) {
2616       // Deal with frame undershoot and whether or not we are
2617       // below the automatically set cq level.
2618       if (q > oxcf->cq_level &&
2619           rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
2620         force_recode = 1;
2621       }
2622     }
2623   }
2624   return force_recode;
2625 }
2626
2627 void vp9_update_reference_frames(VP9_COMP *cpi) {
2628   VP9_COMMON * const cm = &cpi->common;
2629   BufferPool *const pool = cm->buffer_pool;
2630
2631   // At this point the new frame has been encoded.
2632   // If any buffer copy / swapping is signaled it should be done here.
2633   if (cm->frame_type == KEY_FRAME) {
2634     ref_cnt_fb(pool->frame_bufs,
2635                &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2636     ref_cnt_fb(pool->frame_bufs,
2637                &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2638   } else if (vp9_preserve_existing_gf(cpi)) {
2639     // We have decided to preserve the previously existing golden frame as our
2640     // new ARF frame. However, in the short term in function
2641     // vp9_get_refresh_mask() we left it in the GF slot and, if
2642     // we're updating the GF with the current decoded frame, we save it to the
2643     // ARF slot instead.
2644     // We now have to update the ARF with the current frame and swap gld_fb_idx
2645     // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
2646     // slot and, if we're updating the GF, the current frame becomes the new GF.
2647     int tmp;
2648
2649     ref_cnt_fb(pool->frame_bufs,
2650                &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2651
2652     tmp = cpi->alt_fb_idx;
2653     cpi->alt_fb_idx = cpi->gld_fb_idx;
2654     cpi->gld_fb_idx = tmp;
2655
2656     if (is_two_pass_svc(cpi)) {
2657       cpi->svc.layer_context[0].gold_ref_idx = cpi->gld_fb_idx;
2658       cpi->svc.layer_context[0].alt_ref_idx = cpi->alt_fb_idx;
2659     }
2660   } else { /* For non key/golden frames */
2661     if (cpi->refresh_alt_ref_frame) {
2662       int arf_idx = cpi->alt_fb_idx;
2663       if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
2664         const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2665         arf_idx = gf_group->arf_update_idx[gf_group->index];
2666       }
2667
2668       ref_cnt_fb(pool->frame_bufs,
2669                  &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2670       memcpy(cpi->interp_filter_selected[ALTREF_FRAME],
2671              cpi->interp_filter_selected[0],
2672              sizeof(cpi->interp_filter_selected[0]));
2673     }
2674
2675     if (cpi->refresh_golden_frame) {
2676       ref_cnt_fb(pool->frame_bufs,
2677                  &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2678       if (!cpi->rc.is_src_frame_alt_ref)
2679         memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2680                cpi->interp_filter_selected[0],
2681                sizeof(cpi->interp_filter_selected[0]));
2682       else
2683         memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2684                cpi->interp_filter_selected[ALTREF_FRAME],
2685                sizeof(cpi->interp_filter_selected[ALTREF_FRAME]));
2686     }
2687   }
2688
2689   if (cpi->refresh_last_frame) {
2690     ref_cnt_fb(pool->frame_bufs,
2691                &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
2692     if (!cpi->rc.is_src_frame_alt_ref)
2693       memcpy(cpi->interp_filter_selected[LAST_FRAME],
2694              cpi->interp_filter_selected[0],
2695              sizeof(cpi->interp_filter_selected[0]));
2696   }
2697 #if CONFIG_VP9_TEMPORAL_DENOISING
2698   if (cpi->oxcf.noise_sensitivity > 0 &&
2699       cpi->denoiser.denoising_level > kDenLowLow) {
2700     vp9_denoiser_update_frame_info(&cpi->denoiser,
2701                                    *cpi->Source,
2702                                    cpi->common.frame_type,
2703                                    cpi->refresh_alt_ref_frame,
2704                                    cpi->refresh_golden_frame,
2705                                    cpi->refresh_last_frame,
2706                                    cpi->resize_pending);
2707   }
2708 #endif
2709   if (is_one_pass_cbr_svc(cpi)) {
2710     // Keep track of frame index for each reference frame.
2711     SVC *const svc = &cpi->svc;
2712     if (cm->frame_type == KEY_FRAME) {
2713       svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2714       svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2715       svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2716     } else {
2717       if (cpi->refresh_last_frame)
2718         svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2719       if (cpi->refresh_golden_frame)
2720         svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2721       if (cpi->refresh_alt_ref_frame)
2722         svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2723     }
2724   }
2725 }
2726
2727 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2728   MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
2729   struct loopfilter *lf = &cm->lf;
2730
2731   if (xd->lossless) {
2732       lf->filter_level = 0;
2733       lf->last_filt_level = 0;
2734   } else {
2735     struct vpx_usec_timer timer;
2736
2737     vpx_clear_system_state();
2738
2739     vpx_usec_timer_start(&timer);
2740
2741     if (!cpi->rc.is_src_frame_alt_ref) {
2742       if ((cpi->common.frame_type == KEY_FRAME) &&
2743           (!cpi->rc.this_key_frame_forced)) {
2744         lf->last_filt_level = 0;
2745       }
2746       vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
2747       lf->last_filt_level = lf->filter_level;
2748     } else {
2749       lf->filter_level = 0;
2750     }
2751
2752     vpx_usec_timer_mark(&timer);
2753     cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2754   }
2755
2756   if (lf->filter_level > 0) {
2757     vp9_build_mask_frame(cm, lf->filter_level, 0);
2758
2759     if (cpi->num_workers > 1)
2760       vp9_loop_filter_frame_mt(cm->frame_to_show, cm, xd->plane,
2761                                lf->filter_level, 0, 0,
2762                                cpi->workers, cpi->num_workers,
2763                                &cpi->lf_row_sync);
2764     else
2765       vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
2766   }
2767
2768   vpx_extend_frame_inner_borders(cm->frame_to_show);
2769 }
2770
2771 static INLINE void alloc_frame_mvs(VP9_COMMON *const cm,
2772                                    int buffer_idx) {
2773   RefCntBuffer *const new_fb_ptr = &cm->buffer_pool->frame_bufs[buffer_idx];
2774   if (new_fb_ptr->mvs == NULL ||
2775       new_fb_ptr->mi_rows < cm->mi_rows ||
2776       new_fb_ptr->mi_cols < cm->mi_cols) {
2777     vpx_free(new_fb_ptr->mvs);
2778     CHECK_MEM_ERROR(cm, new_fb_ptr->mvs,
2779                     (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
2780                                          sizeof(*new_fb_ptr->mvs)));
2781     new_fb_ptr->mi_rows = cm->mi_rows;
2782     new_fb_ptr->mi_cols = cm->mi_cols;
2783   }
2784 }
2785
2786 void vp9_scale_references(VP9_COMP *cpi) {
2787   VP9_COMMON *cm = &cpi->common;
2788   MV_REFERENCE_FRAME ref_frame;
2789   const VP9_REFFRAME ref_mask[3] = {VP9_LAST_FLAG, VP9_GOLD_FLAG, VP9_ALT_FLAG};
2790
2791   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2792     // Need to convert from VP9_REFFRAME to index into ref_mask (subtract 1).
2793     if (cpi->ref_frame_flags & ref_mask[ref_frame - 1]) {
2794       BufferPool *const pool = cm->buffer_pool;
2795       const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi,
2796                                                                  ref_frame);
2797
2798       if (ref == NULL) {
2799         cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2800         continue;
2801       }
2802
2803 #if CONFIG_VP9_HIGHBITDEPTH
2804       if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2805         RefCntBuffer *new_fb_ptr = NULL;
2806         int force_scaling = 0;
2807         int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2808         if (new_fb == INVALID_IDX) {
2809           new_fb = get_free_fb(cm);
2810           force_scaling = 1;
2811         }
2812         if (new_fb == INVALID_IDX)
2813           return;
2814         new_fb_ptr = &pool->frame_bufs[new_fb];
2815         if (force_scaling ||
2816             new_fb_ptr->buf.y_crop_width != cm->width ||
2817             new_fb_ptr->buf.y_crop_height != cm->height) {
2818           if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2819                                        cm->subsampling_x, cm->subsampling_y,
2820                                        cm->use_highbitdepth,
2821                                        VP9_ENC_BORDER_IN_PIXELS,
2822                                        cm->byte_alignment, NULL, NULL, NULL))
2823             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2824                                "Failed to allocate frame buffer");
2825           scale_and_extend_frame(ref, &new_fb_ptr->buf, (int)cm->bit_depth);
2826           cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2827           alloc_frame_mvs(cm, new_fb);
2828         }
2829 #else
2830       if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2831         RefCntBuffer *new_fb_ptr = NULL;
2832         int force_scaling = 0;
2833         int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2834         if (new_fb == INVALID_IDX) {
2835           new_fb = get_free_fb(cm);
2836           force_scaling = 1;
2837         }
2838         if (new_fb == INVALID_IDX)
2839           return;
2840         new_fb_ptr = &pool->frame_bufs[new_fb];
2841         if (force_scaling ||
2842             new_fb_ptr->buf.y_crop_width != cm->width ||
2843             new_fb_ptr->buf.y_crop_height != cm->height) {
2844           if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2845                                        cm->subsampling_x, cm->subsampling_y,
2846                                        VP9_ENC_BORDER_IN_PIXELS,
2847                                        cm->byte_alignment, NULL, NULL, NULL))
2848             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2849                                "Failed to allocate frame buffer");
2850           vp9_scale_and_extend_frame(ref, &new_fb_ptr->buf);
2851           cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2852           alloc_frame_mvs(cm, new_fb);
2853         }
2854 #endif  // CONFIG_VP9_HIGHBITDEPTH
2855       } else {
2856         int buf_idx;
2857         RefCntBuffer *buf = NULL;
2858         if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2859           // Check for release of scaled reference.
2860           buf_idx = cpi->scaled_ref_idx[ref_frame - 1];
2861           buf = (buf_idx != INVALID_IDX) ? &pool->frame_bufs[buf_idx] : NULL;
2862           if (buf != NULL) {
2863             --buf->ref_count;
2864             cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2865           }
2866         }
2867         buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
2868         buf = &pool->frame_bufs[buf_idx];
2869         buf->buf.y_crop_width = ref->y_crop_width;
2870         buf->buf.y_crop_height = ref->y_crop_height;
2871         cpi->scaled_ref_idx[ref_frame - 1] = buf_idx;
2872         ++buf->ref_count;
2873       }
2874     } else {
2875       if (cpi->oxcf.pass != 0 || cpi->use_svc)
2876         cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2877     }
2878   }
2879 }
2880
2881 static void release_scaled_references(VP9_COMP *cpi) {
2882   VP9_COMMON *cm = &cpi->common;
2883   int i;
2884   if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2885     // Only release scaled references under certain conditions:
2886     // if reference will be updated, or if scaled reference has same resolution.
2887     int refresh[3];
2888     refresh[0] = (cpi->refresh_last_frame) ? 1 : 0;
2889     refresh[1] = (cpi->refresh_golden_frame) ? 1 : 0;
2890     refresh[2] = (cpi->refresh_alt_ref_frame) ? 1 : 0;
2891     for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2892       const int idx = cpi->scaled_ref_idx[i - 1];
2893       RefCntBuffer *const buf = idx != INVALID_IDX ?
2894           &cm->buffer_pool->frame_bufs[idx] : NULL;
2895       const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, i);
2896       if (buf != NULL &&
2897           (refresh[i - 1] ||
2898           (buf->buf.y_crop_width == ref->y_crop_width &&
2899            buf->buf.y_crop_height == ref->y_crop_height))) {
2900         --buf->ref_count;
2901         cpi->scaled_ref_idx[i -1] = INVALID_IDX;
2902       }
2903     }
2904   } else {
2905     for (i = 0; i < MAX_REF_FRAMES; ++i) {
2906       const int idx = cpi->scaled_ref_idx[i];
2907       RefCntBuffer *const buf = idx != INVALID_IDX ?
2908           &cm->buffer_pool->frame_bufs[idx] : NULL;
2909       if (buf != NULL) {
2910         --buf->ref_count;
2911         cpi->scaled_ref_idx[i] = INVALID_IDX;
2912       }
2913     }
2914   }
2915 }
2916
2917 static void full_to_model_count(unsigned int *model_count,
2918                                 unsigned int *full_count) {
2919   int n;
2920   model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2921   model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2922   model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2923   for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
2924     model_count[TWO_TOKEN] += full_count[n];
2925   model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
2926 }
2927
2928 static void full_to_model_counts(vp9_coeff_count_model *model_count,
2929                                  vp9_coeff_count *full_count) {
2930   int i, j, k, l;
2931
2932   for (i = 0; i < PLANE_TYPES; ++i)
2933     for (j = 0; j < REF_TYPES; ++j)
2934       for (k = 0; k < COEF_BANDS; ++k)
2935         for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
2936           full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2937 }
2938
2939 #if 0 && CONFIG_INTERNAL_STATS
2940 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2941   VP9_COMMON *const cm = &cpi->common;
2942   FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2943   int64_t recon_err;
2944
2945   vpx_clear_system_state();
2946
2947 #if CONFIG_VP9_HIGHBITDEPTH
2948   if (cm->use_highbitdepth) {
2949     recon_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2950   } else {
2951     recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2952   }
2953 #else
2954   recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2955 #endif  // CONFIG_VP9_HIGHBITDEPTH
2956
2957
2958   if (cpi->twopass.total_left_stats.coded_error != 0.0) {
2959     double dc_quant_devisor;
2960 #if CONFIG_VP9_HIGHBITDEPTH
2961     switch (cm->bit_depth) {
2962       case VPX_BITS_8:
2963         dc_quant_devisor = 4.0;
2964         break;
2965       case VPX_BITS_10:
2966         dc_quant_devisor = 16.0;
2967         break;
2968       case VPX_BITS_12:
2969         dc_quant_devisor = 64.0;
2970         break;
2971       default:
2972         assert(0 && "bit_depth must be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
2973         break;
2974     }
2975 #else
2976     dc_quant_devisor = 4.0;
2977 #endif
2978
2979     fprintf(f, "%10u %dx%d %10d %10d %d %d %10d %10d %10d %10d"
2980        "%10"PRId64" %10"PRId64" %5d %5d %10"PRId64" "
2981        "%10"PRId64" %10"PRId64" %10d "
2982        "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
2983         "%6d %6d %5d %5d %5d "
2984         "%10"PRId64" %10.3lf"
2985         "%10lf %8u %10"PRId64" %10d %10d %10d %10d %10d\n",
2986         cpi->common.current_video_frame,
2987         cm->width, cm->height,
2988         cpi->td.rd_counts.m_search_count,
2989         cpi->td.rd_counts.ex_search_count,
2990         cpi->rc.source_alt_ref_pending,
2991         cpi->rc.source_alt_ref_active,
2992         cpi->rc.this_frame_target,
2993         cpi->rc.projected_frame_size,
2994         cpi->rc.projected_frame_size / cpi->common.MBs,
2995         (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2996         cpi->rc.vbr_bits_off_target,
2997         cpi->rc.vbr_bits_off_target_fast,
2998         cpi->twopass.extend_minq,
2999         cpi->twopass.extend_minq_fast,
3000         cpi->rc.total_target_vs_actual,
3001         (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
3002         cpi->rc.total_actual_bits, cm->base_qindex,
3003         vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth),
3004         (double)vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) /
3005             dc_quant_devisor,
3006         vp9_convert_qindex_to_q(cpi->twopass.active_worst_quality,
3007                                 cm->bit_depth),
3008         cpi->rc.avg_q,
3009         vp9_convert_qindex_to_q(cpi->oxcf.cq_level, cm->bit_depth),
3010         cpi->refresh_last_frame, cpi->refresh_golden_frame,
3011         cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
3012         cpi->twopass.bits_left,
3013         cpi->twopass.total_left_stats.coded_error,
3014         cpi->twopass.bits_left /
3015             (1 + cpi->twopass.total_left_stats.coded_error),
3016         cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
3017         cpi->twopass.kf_zeromotion_pct,
3018         cpi->twopass.fr_content_type,
3019         cm->lf.filter_level,
3020         cm->seg.aq_av_offset);
3021   }
3022   fclose(f);
3023
3024   if (0) {
3025     FILE *const fmodes = fopen("Modes.stt", "a");
3026     int i;
3027
3028     fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
3029             cm->frame_type, cpi->refresh_golden_frame,
3030             cpi->refresh_alt_ref_frame);
3031
3032     for (i = 0; i < MAX_MODES; ++i)
3033       fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
3034
3035     fprintf(fmodes, "\n");
3036
3037     fclose(fmodes);
3038   }
3039 }
3040 #endif
3041
3042 static void set_mv_search_params(VP9_COMP *cpi) {
3043   const VP9_COMMON *const cm = &cpi->common;
3044   const unsigned int max_mv_def = VPXMIN(cm->width, cm->height);
3045
3046   // Default based on max resolution.
3047   cpi->mv_step_param = vp9_init_search_range(max_mv_def);
3048
3049   if (cpi->sf.mv.auto_mv_step_size) {
3050     if (frame_is_intra_only(cm)) {
3051       // Initialize max_mv_magnitude for use in the first INTER frame
3052       // after a key/intra-only frame.
3053       cpi->max_mv_magnitude = max_mv_def;
3054     } else {
3055       if (cm->show_frame) {
3056         // Allow mv_steps to correspond to twice the max mv magnitude found
3057         // in the previous frame, capped by the default max_mv_magnitude based
3058         // on resolution.
3059         cpi->mv_step_param = vp9_init_search_range(
3060             VPXMIN(max_mv_def, 2 * cpi->max_mv_magnitude));
3061       }
3062       cpi->max_mv_magnitude = 0;
3063     }
3064   }
3065 }
3066
3067 static void set_size_independent_vars(VP9_COMP *cpi) {
3068   vp9_set_speed_features_framesize_independent(cpi);
3069   vp9_set_rd_speed_thresholds(cpi);
3070   vp9_set_rd_speed_thresholds_sub8x8(cpi);
3071   cpi->common.interp_filter = cpi->sf.default_interp_filter;
3072 }
3073
3074 static void set_size_dependent_vars(VP9_COMP *cpi, int *q,
3075                                     int *bottom_index, int *top_index) {
3076   VP9_COMMON *const cm = &cpi->common;
3077   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3078
3079   // Setup variables that depend on the dimensions of the frame.
3080   vp9_set_speed_features_framesize_dependent(cpi);
3081
3082   // Decide q and q bounds.
3083   *q = vp9_rc_pick_q_and_bounds(cpi, bottom_index, top_index);
3084
3085   if (!frame_is_intra_only(cm)) {
3086     vp9_set_high_precision_mv(cpi, (*q) < HIGH_PRECISION_MV_QTHRESH);
3087   }
3088
3089   // Configure experimental use of segmentation for enhanced coding of
3090   // static regions if indicated.
3091   // Only allowed in the second pass of a two pass encode, as it requires
3092   // lagged coding, and if the relevant speed feature flag is set.
3093   if (oxcf->pass == 2 && cpi->sf.static_segmentation)
3094     configure_static_seg_features(cpi);
3095
3096 #if CONFIG_VP9_POSTPROC && !(CONFIG_VP9_TEMPORAL_DENOISING)
3097   if (oxcf->noise_sensitivity > 0) {
3098     int l = 0;
3099     switch (oxcf->noise_sensitivity) {
3100       case 1:
3101         l = 20;
3102         break;
3103       case 2:
3104         l = 40;
3105         break;
3106       case 3:
3107         l = 60;
3108         break;
3109       case 4:
3110       case 5:
3111         l = 100;
3112         break;
3113       case 6:
3114         l = 150;
3115         break;
3116     }
3117     vp9_denoise(cpi->Source, cpi->Source, l);
3118   }
3119 #endif  // CONFIG_VP9_POSTPROC
3120 }
3121
3122 #if CONFIG_VP9_TEMPORAL_DENOISING
3123 static void setup_denoiser_buffer(VP9_COMP *cpi) {
3124   VP9_COMMON *const cm = &cpi->common;
3125   if (cpi->oxcf.noise_sensitivity > 0 &&
3126       !cpi->denoiser.frame_buffer_initialized) {
3127     if (vp9_denoiser_alloc(&cpi->denoiser, cm->width, cm->height,
3128                            cm->subsampling_x, cm->subsampling_y,
3129 #if CONFIG_VP9_HIGHBITDEPTH
3130                            cm->use_highbitdepth,
3131 #endif
3132                            VP9_ENC_BORDER_IN_PIXELS))
3133       vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3134                          "Failed to allocate denoiser");
3135   }
3136 }
3137 #endif
3138
3139 static void init_motion_estimation(VP9_COMP *cpi) {
3140   int y_stride = cpi->scaled_source.y_stride;
3141
3142   if (cpi->sf.mv.search_method == NSTEP) {
3143     vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
3144   } else if (cpi->sf.mv.search_method == DIAMOND) {
3145     vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
3146   }
3147 }
3148
3149 static void set_frame_size(VP9_COMP *cpi) {
3150   int ref_frame;
3151   VP9_COMMON *const cm = &cpi->common;
3152   VP9EncoderConfig *const oxcf = &cpi->oxcf;
3153   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
3154
3155   if (oxcf->pass == 2 &&
3156       oxcf->rc_mode == VPX_VBR &&
3157       ((oxcf->resize_mode == RESIZE_FIXED && cm->current_video_frame == 0) ||
3158         (oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending))) {
3159     calculate_coded_size(
3160         cpi, &oxcf->scaled_frame_width, &oxcf->scaled_frame_height);
3161
3162     // There has been a change in frame size.
3163     vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
3164                          oxcf->scaled_frame_height);
3165   }
3166
3167   if (oxcf->pass == 0 &&
3168       oxcf->rc_mode == VPX_CBR &&
3169       !cpi->use_svc &&
3170       oxcf->resize_mode == RESIZE_DYNAMIC &&
3171       cpi->resize_pending != 0) {
3172     oxcf->scaled_frame_width =
3173         (oxcf->width * cpi->resize_scale_num) / cpi->resize_scale_den;
3174     oxcf->scaled_frame_height =
3175         (oxcf->height * cpi->resize_scale_num) /cpi->resize_scale_den;
3176     // There has been a change in frame size.
3177     vp9_set_size_literal(cpi,
3178                          oxcf->scaled_frame_width,
3179                          oxcf->scaled_frame_height);
3180
3181     // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3182     set_mv_search_params(cpi);
3183
3184     vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
3185 #if CONFIG_VP9_TEMPORAL_DENOISING
3186     // Reset the denoiser on the resized frame.
3187     if (cpi->oxcf.noise_sensitivity > 0) {
3188       vp9_denoiser_free(&(cpi->denoiser));
3189       setup_denoiser_buffer(cpi);
3190       // Dynamic resize is only triggered for non-SVC, so we can force
3191       // golden frame update here as temporary fix to denoiser.
3192       cpi->refresh_golden_frame = 1;
3193     }
3194 #endif
3195   }
3196
3197   if ((oxcf->pass == 2) &&
3198       (!cpi->use_svc ||
3199           (is_two_pass_svc(cpi) &&
3200               cpi->svc.encode_empty_frame_state != ENCODING))) {
3201     vp9_set_target_rate(cpi);
3202   }
3203
3204   alloc_frame_mvs(cm, cm->new_fb_idx);
3205
3206   // Reset the frame pointers to the current frame size.
3207   if (vpx_realloc_frame_buffer(get_frame_new_buffer(cm), cm->width, cm->height,
3208                                cm->subsampling_x, cm->subsampling_y,
3209 #if CONFIG_VP9_HIGHBITDEPTH
3210                                cm->use_highbitdepth,
3211 #endif
3212                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
3213                                NULL, NULL, NULL))
3214     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3215                        "Failed to allocate frame buffer");
3216
3217   alloc_util_frame_buffers(cpi);
3218   init_motion_estimation(cpi);
3219
3220   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3221     RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3222     const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
3223
3224     ref_buf->idx = buf_idx;
3225
3226     if (buf_idx != INVALID_IDX) {
3227       YV12_BUFFER_CONFIG *const buf = &cm->buffer_pool->frame_bufs[buf_idx].buf;
3228       ref_buf->buf = buf;
3229 #if CONFIG_VP9_HIGHBITDEPTH
3230       vp9_setup_scale_factors_for_frame(&ref_buf->sf,
3231                                         buf->y_crop_width, buf->y_crop_height,
3232                                         cm->width, cm->height,
3233                                         (buf->flags & YV12_FLAG_HIGHBITDEPTH) ?
3234                                             1 : 0);
3235 #else
3236       vp9_setup_scale_factors_for_frame(&ref_buf->sf,
3237                                         buf->y_crop_width, buf->y_crop_height,
3238                                         cm->width, cm->height);
3239 #endif  // CONFIG_VP9_HIGHBITDEPTH
3240       if (vp9_is_scaled(&ref_buf->sf))
3241         vpx_extend_frame_borders(buf);
3242     } else {
3243       ref_buf->buf = NULL;
3244     }
3245   }
3246
3247   set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
3248 }
3249
3250 static void encode_without_recode_loop(VP9_COMP *cpi,
3251                                        size_t *size,
3252                                        uint8_t *dest) {
3253   VP9_COMMON *const cm = &cpi->common;
3254   int q = 0, bottom_index = 0, top_index = 0;  // Dummy variables.
3255
3256   vpx_clear_system_state();
3257
3258   set_frame_size(cpi);
3259
3260   if (is_one_pass_cbr_svc(cpi) &&
3261       cpi->un_scaled_source->y_width == cm->width << 2 &&
3262       cpi->un_scaled_source->y_height == cm->height << 2 &&
3263       cpi->svc.scaled_temp.y_width == cm->width << 1 &&
3264       cpi->svc.scaled_temp.y_height == cm->height << 1) {
3265     cpi->Source = vp9_svc_twostage_scale(cm,
3266                                          cpi->un_scaled_source,
3267                                          &cpi->scaled_source,
3268                                          &cpi->svc.scaled_temp);
3269   } else {
3270     cpi->Source = vp9_scale_if_required(cm,
3271                                         cpi->un_scaled_source,
3272                                         &cpi->scaled_source,
3273                                         (cpi->oxcf.pass == 0));
3274   }
3275   // Unfiltered raw source used in metrics calculation if the source
3276   // has been filtered.
3277   if (is_psnr_calc_enabled(cpi)) {
3278 #ifdef ENABLE_KF_DENOISE
3279     if (is_spatial_denoise_enabled(cpi)) {
3280       cpi->raw_source_frame =
3281           vp9_scale_if_required(cm, &cpi->raw_unscaled_source,
3282                                 &cpi->raw_scaled_source,
3283                                 (cpi->oxcf.pass == 0));
3284     } else {
3285       cpi->raw_source_frame = cpi->Source;
3286     }
3287 #else
3288     cpi->raw_source_frame = cpi->Source;
3289 #endif
3290   }
3291
3292   // Avoid scaling last_source unless its needed.
3293   // Last source is needed if vp9_avg_source_sad() is used, or if
3294   // partition_search_type == SOURCE_VAR_BASED_PARTITION, or if noise
3295   // estimation is enabled.
3296   if (cpi->unscaled_last_source != NULL &&
3297       (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3298       (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_VBR &&
3299       cpi->oxcf.mode == REALTIME && cpi->oxcf.speed >= 5) ||
3300       cpi->sf.partition_search_type == SOURCE_VAR_BASED_PARTITION ||
3301       cpi->noise_estimate.enabled))
3302     cpi->Last_Source = vp9_scale_if_required(cm,
3303                                              cpi->unscaled_last_source,
3304                                              &cpi->scaled_last_source,
3305                                              (cpi->oxcf.pass == 0));
3306
3307   if (cm->frame_type == KEY_FRAME || cpi->resize_pending != 0) {
3308     memset(cpi->consec_zero_mv, 0,
3309            cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
3310   }
3311
3312   vp9_update_noise_estimate(cpi);
3313
3314   if (cpi->oxcf.pass == 0 &&
3315       cpi->oxcf.mode == REALTIME &&
3316       cpi->oxcf.speed >= 5 &&
3317       cpi->resize_state == 0 &&
3318       cm->frame_type != KEY_FRAME &&
3319       (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3320        cpi->oxcf.rc_mode == VPX_VBR))
3321     vp9_avg_source_sad(cpi);
3322
3323   // For 1 pass SVC, since only ZEROMV is allowed for upsampled reference
3324   // frame (i.e, svc->force_zero_mode_spatial_ref = 0), we can avoid this
3325   // frame-level upsampling.
3326   if (frame_is_intra_only(cm) == 0 && !is_one_pass_cbr_svc(cpi)) {
3327     vp9_scale_references(cpi);
3328   }
3329
3330   set_size_independent_vars(cpi);
3331   set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3332
3333   if (cpi->oxcf.speed >= 5 &&
3334       cpi->oxcf.pass == 0 &&
3335       cpi->oxcf.rc_mode == VPX_CBR &&
3336       cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
3337       cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3338     cpi->use_skin_detection = 1;
3339   }
3340
3341   vp9_set_quantizer(cm, q);
3342   vp9_set_variance_partition_thresholds(cpi, q);
3343
3344   setup_frame(cpi);
3345
3346   suppress_active_map(cpi);
3347   // Variance adaptive and in frame q adjustment experiments are mutually
3348   // exclusive.
3349   if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3350     vp9_vaq_frame_setup(cpi);
3351   } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3352     vp9_360aq_frame_setup(cpi);
3353   } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3354     vp9_setup_in_frame_q_adj(cpi);
3355   } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3356     vp9_cyclic_refresh_setup(cpi);
3357   }
3358   apply_active_map(cpi);
3359
3360   // transform / motion compensation build reconstruction frame
3361   vp9_encode_frame(cpi);
3362
3363   // Check if we should drop this frame because of high overshoot.
3364   // Only for frames where high temporal-source sad is detected.
3365   if (cpi->oxcf.pass == 0 &&
3366       cpi->oxcf.rc_mode == VPX_CBR &&
3367       cpi->resize_state == 0 &&
3368       cm->frame_type != KEY_FRAME &&
3369       cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
3370       cpi->rc.high_source_sad == 1) {
3371     int frame_size = 0;
3372     // Get an estimate of the encoded frame size.
3373     save_coding_context(cpi);
3374     vp9_pack_bitstream(cpi, dest, size);
3375     restore_coding_context(cpi);
3376     frame_size = (int)(*size) << 3;
3377     // Check if encoded frame will overshoot too much, and if so, set the q and
3378     // adjust some rate control parameters, and return to re-encode the frame.
3379     if (vp9_encodedframe_overshoot(cpi, frame_size, &q)) {
3380       vpx_clear_system_state();
3381       vp9_set_quantizer(cm, q);
3382       vp9_set_variance_partition_thresholds(cpi, q);
3383       suppress_active_map(cpi);
3384       // Turn-off cyclic refresh for re-encoded frame.
3385       if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3386         unsigned char *const seg_map = cpi->segmentation_map;
3387         memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
3388         vp9_disable_segmentation(&cm->seg);
3389       }
3390       apply_active_map(cpi);
3391       vp9_encode_frame(cpi);
3392     }
3393   }
3394
3395   // Update some stats from cyclic refresh, and check if we should not update
3396   // golden reference, for non-SVC 1 pass CBR.
3397   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
3398       cm->frame_type != KEY_FRAME &&
3399       !cpi->use_svc &&
3400       cpi->ext_refresh_frame_flags_pending == 0 &&
3401       (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR))
3402     vp9_cyclic_refresh_check_golden_update(cpi);
3403
3404   // Update the skip mb flag probabilities based on the distribution
3405   // seen in the last encoder iteration.
3406   // update_base_skip_probs(cpi);
3407   vpx_clear_system_state();
3408 }
3409
3410 static void encode_with_recode_loop(VP9_COMP *cpi,
3411                                     size_t *size,
3412                                     uint8_t *dest) {
3413   VP9_COMMON *const cm = &cpi->common;
3414   RATE_CONTROL *const rc = &cpi->rc;
3415   int bottom_index, top_index;
3416   int loop_count = 0;
3417   int loop_at_this_size = 0;
3418   int loop = 0;
3419   int overshoot_seen = 0;
3420   int undershoot_seen = 0;
3421   int frame_over_shoot_limit;
3422   int frame_under_shoot_limit;
3423   int q = 0, q_low = 0, q_high = 0;
3424
3425   set_size_independent_vars(cpi);
3426
3427   do {
3428     vpx_clear_system_state();
3429
3430     set_frame_size(cpi);
3431
3432     if (loop_count == 0 || cpi->resize_pending != 0) {
3433       set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3434
3435       // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3436       set_mv_search_params(cpi);
3437
3438       // Reset the loop state for new frame size.
3439       overshoot_seen = 0;
3440       undershoot_seen = 0;
3441
3442       // Reconfiguration for change in frame size has concluded.
3443       cpi->resize_pending = 0;
3444
3445       q_low = bottom_index;
3446       q_high = top_index;
3447
3448       loop_at_this_size = 0;
3449     }
3450
3451     // Decide frame size bounds first time through.
3452     if (loop_count == 0) {
3453       vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
3454                                        &frame_under_shoot_limit,
3455                                        &frame_over_shoot_limit);
3456     }
3457
3458     cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
3459                                       &cpi->scaled_source,
3460                                       (cpi->oxcf.pass == 0));
3461
3462     // Unfiltered raw source used in metrics calculation if the source
3463     // has been filtered.
3464     if (is_psnr_calc_enabled(cpi)) {
3465 #ifdef ENABLE_KF_DENOISE
3466       if (is_spatial_denoise_enabled(cpi)) {
3467         cpi->raw_source_frame =
3468             vp9_scale_if_required(cm, &cpi->raw_unscaled_source,
3469                                   &cpi->raw_scaled_source,
3470                                   (cpi->oxcf.pass == 0));
3471       } else {
3472         cpi->raw_source_frame = cpi->Source;
3473       }
3474 #else
3475       cpi->raw_source_frame = cpi->Source;
3476 #endif
3477     }
3478
3479     if (cpi->unscaled_last_source != NULL)
3480       cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
3481                                                &cpi->scaled_last_source,
3482                                                (cpi->oxcf.pass == 0));
3483
3484     if (frame_is_intra_only(cm) == 0) {
3485       if (loop_count > 0) {
3486         release_scaled_references(cpi);
3487       }
3488       vp9_scale_references(cpi);
3489     }
3490
3491     vp9_set_quantizer(cm, q);
3492
3493     if (loop_count == 0)
3494       setup_frame(cpi);
3495
3496     // Variance adaptive and in frame q adjustment experiments are mutually
3497     // exclusive.
3498     if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3499       vp9_vaq_frame_setup(cpi);
3500     } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3501       vp9_360aq_frame_setup(cpi);
3502     } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3503       vp9_setup_in_frame_q_adj(cpi);
3504     }
3505
3506     // transform / motion compensation build reconstruction frame
3507     vp9_encode_frame(cpi);
3508
3509     // Update the skip mb flag probabilities based on the distribution
3510     // seen in the last encoder iteration.
3511     // update_base_skip_probs(cpi);
3512
3513     vpx_clear_system_state();
3514
3515     // Dummy pack of the bitstream using up to date stats to get an
3516     // accurate estimate of output frame size to determine if we need
3517     // to recode.
3518     if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
3519       save_coding_context(cpi);
3520       if (!cpi->sf.use_nonrd_pick_mode)
3521         vp9_pack_bitstream(cpi, dest, size);
3522
3523       rc->projected_frame_size = (int)(*size) << 3;
3524       restore_coding_context(cpi);
3525
3526       if (frame_over_shoot_limit == 0)
3527         frame_over_shoot_limit = 1;
3528     }
3529
3530     if (cpi->oxcf.rc_mode == VPX_Q) {
3531       loop = 0;
3532     } else {
3533       if ((cm->frame_type == KEY_FRAME) &&
3534            rc->this_key_frame_forced &&
3535            (rc->projected_frame_size < rc->max_frame_bandwidth)) {
3536         int last_q = q;
3537         int64_t kf_err;
3538
3539         int64_t high_err_target = cpi->ambient_err;
3540         int64_t low_err_target = cpi->ambient_err >> 1;
3541
3542 #if CONFIG_VP9_HIGHBITDEPTH
3543         if (cm->use_highbitdepth) {
3544           kf_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3545         } else {
3546           kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3547         }
3548 #else
3549         kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3550 #endif  // CONFIG_VP9_HIGHBITDEPTH
3551
3552         // Prevent possible divide by zero error below for perfect KF
3553         kf_err += !kf_err;
3554
3555         // The key frame is not good enough or we can afford
3556         // to make it better without undue risk of popping.
3557         if ((kf_err > high_err_target &&
3558              rc->projected_frame_size <= frame_over_shoot_limit) ||
3559             (kf_err > low_err_target &&
3560              rc->projected_frame_size <= frame_under_shoot_limit)) {
3561           // Lower q_high
3562           q_high = q > q_low ? q - 1 : q_low;
3563
3564           // Adjust Q
3565           q = (int)((q * high_err_target) / kf_err);
3566           q = VPXMIN(q, (q_high + q_low) >> 1);
3567         } else if (kf_err < low_err_target &&
3568                    rc->projected_frame_size >= frame_under_shoot_limit) {
3569           // The key frame is much better than the previous frame
3570           // Raise q_low
3571           q_low = q < q_high ? q + 1 : q_high;
3572
3573           // Adjust Q
3574           q = (int)((q * low_err_target) / kf_err);
3575           q = VPXMIN(q, (q_high + q_low + 1) >> 1);
3576         }
3577
3578         // Clamp Q to upper and lower limits:
3579         q = clamp(q, q_low, q_high);
3580
3581         loop = q != last_q;
3582       } else if (recode_loop_test(
3583           cpi, frame_over_shoot_limit, frame_under_shoot_limit,
3584           q, VPXMAX(q_high, top_index), bottom_index)) {
3585         // Is the projected frame size out of range and are we allowed
3586         // to attempt to recode.
3587         int last_q = q;
3588         int retries = 0;
3589
3590         if (cpi->resize_pending == 1) {
3591           // Change in frame size so go back around the recode loop.
3592           cpi->rc.frame_size_selector =
3593               SCALE_STEP1 - cpi->rc.frame_size_selector;
3594           cpi->rc.next_frame_size_selector = cpi->rc.frame_size_selector;
3595
3596 #if CONFIG_INTERNAL_STATS
3597           ++cpi->tot_recode_hits;
3598 #endif
3599           ++loop_count;
3600           loop = 1;
3601           continue;
3602         }
3603
3604         // Frame size out of permitted range:
3605         // Update correction factor & compute new Q to try...
3606
3607         // Frame is too large
3608         if (rc->projected_frame_size > rc->this_frame_target) {
3609           // Special case if the projected size is > the max allowed.
3610           if (rc->projected_frame_size >= rc->max_frame_bandwidth)
3611             q_high = rc->worst_quality;
3612
3613           // Raise Qlow as to at least the current value
3614           q_low = q < q_high ? q + 1 : q_high;
3615
3616           if (undershoot_seen || loop_at_this_size > 1) {
3617             // Update rate_correction_factor unless
3618             vp9_rc_update_rate_correction_factors(cpi);
3619
3620             q = (q_high + q_low + 1) / 2;
3621           } else {
3622             // Update rate_correction_factor unless
3623             vp9_rc_update_rate_correction_factors(cpi);
3624
3625             q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3626                                   bottom_index, VPXMAX(q_high, top_index));
3627
3628             while (q < q_low && retries < 10) {
3629               vp9_rc_update_rate_correction_factors(cpi);
3630               q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3631                                     bottom_index, VPXMAX(q_high, top_index));
3632               retries++;
3633             }
3634           }
3635
3636           overshoot_seen = 1;
3637         } else {
3638           // Frame is too small
3639           q_high = q > q_low ? q - 1 : q_low;
3640
3641           if (overshoot_seen || loop_at_this_size > 1) {
3642             vp9_rc_update_rate_correction_factors(cpi);
3643             q = (q_high + q_low) / 2;
3644           } else {
3645             vp9_rc_update_rate_correction_factors(cpi);
3646             q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3647                                    bottom_index, top_index);
3648             // Special case reset for qlow for constrained quality.
3649             // This should only trigger where there is very substantial
3650             // undershoot on a frame and the auto cq level is above
3651             // the user passsed in value.
3652             if (cpi->oxcf.rc_mode == VPX_CQ &&
3653                 q < q_low) {
3654               q_low = q;
3655             }
3656
3657             while (q > q_high && retries < 10) {
3658               vp9_rc_update_rate_correction_factors(cpi);
3659               q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3660                                      bottom_index, top_index);
3661               retries++;
3662             }
3663           }
3664
3665           undershoot_seen = 1;
3666         }
3667
3668         // Clamp Q to upper and lower limits:
3669         q = clamp(q, q_low, q_high);
3670
3671         loop = (q != last_q);
3672       } else {
3673         loop = 0;
3674       }
3675     }
3676
3677     // Special case for overlay frame.
3678     if (rc->is_src_frame_alt_ref &&
3679         rc->projected_frame_size < rc->max_frame_bandwidth)
3680       loop = 0;
3681
3682     if (loop) {
3683       ++loop_count;
3684       ++loop_at_this_size;
3685
3686 #if CONFIG_INTERNAL_STATS
3687       ++cpi->tot_recode_hits;
3688 #endif
3689     }
3690   } while (loop);
3691 }
3692
3693 static int get_ref_frame_flags(const VP9_COMP *cpi) {
3694   const int *const map = cpi->common.ref_frame_map;
3695   const int gold_is_last = map[cpi->gld_fb_idx] == map[cpi->lst_fb_idx];
3696   const int alt_is_last = map[cpi->alt_fb_idx] == map[cpi->lst_fb_idx];
3697   const int gold_is_alt = map[cpi->gld_fb_idx] == map[cpi->alt_fb_idx];
3698   int flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3699
3700   if (gold_is_last)
3701     flags &= ~VP9_GOLD_FLAG;
3702
3703   if (cpi->rc.frames_till_gf_update_due == INT_MAX &&
3704       (cpi->svc.number_temporal_layers == 1 &&
3705        cpi->svc.number_spatial_layers == 1))
3706     flags &= ~VP9_GOLD_FLAG;
3707
3708   if (alt_is_last)
3709     flags &= ~VP9_ALT_FLAG;
3710
3711   if (gold_is_alt)
3712     flags &= ~VP9_ALT_FLAG;
3713
3714   return flags;
3715 }
3716
3717 static void set_ext_overrides(VP9_COMP *cpi) {
3718   // Overrides the defaults with the externally supplied values with
3719   // vp9_update_reference() and vp9_update_entropy() calls
3720   // Note: The overrides are valid only for the next frame passed
3721   // to encode_frame_to_data_rate() function
3722   if (cpi->ext_refresh_frame_context_pending) {
3723     cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
3724     cpi->ext_refresh_frame_context_pending = 0;
3725   }
3726   if (cpi->ext_refresh_frame_flags_pending) {
3727     cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
3728     cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
3729     cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
3730   }
3731 }
3732
3733 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(VP9_COMMON *cm,
3734                                            YV12_BUFFER_CONFIG *unscaled,
3735                                            YV12_BUFFER_CONFIG *scaled,
3736                                            YV12_BUFFER_CONFIG *scaled_temp) {
3737   if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3738       cm->mi_rows * MI_SIZE != unscaled->y_height) {
3739 #if CONFIG_VP9_HIGHBITDEPTH
3740     scale_and_extend_frame(unscaled, scaled_temp, (int)cm->bit_depth);
3741     scale_and_extend_frame(scaled_temp, scaled, (int)cm->bit_depth);
3742 #else
3743     vp9_scale_and_extend_frame(unscaled, scaled_temp);
3744     vp9_scale_and_extend_frame(scaled_temp, scaled);
3745 #endif  // CONFIG_VP9_HIGHBITDEPTH
3746     return scaled;
3747   } else {
3748     return unscaled;
3749   }
3750 }
3751
3752 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
3753                                           YV12_BUFFER_CONFIG *unscaled,
3754                                           YV12_BUFFER_CONFIG *scaled,
3755                                           int use_normative_scaler) {
3756   if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3757       cm->mi_rows * MI_SIZE != unscaled->y_height) {
3758 #if CONFIG_VP9_HIGHBITDEPTH
3759     if (use_normative_scaler &&
3760         unscaled->y_width <= (scaled->y_width << 1) &&
3761         unscaled->y_height <= (scaled->y_height << 1))
3762       scale_and_extend_frame(unscaled, scaled, (int)cm->bit_depth);
3763     else
3764       scale_and_extend_frame_nonnormative(unscaled, scaled, (int)cm->bit_depth);
3765 #else
3766     if (use_normative_scaler &&
3767         unscaled->y_width <= (scaled->y_width << 1) &&
3768         unscaled->y_height <= (scaled->y_height << 1))
3769       vp9_scale_and_extend_frame(unscaled, scaled);
3770     else
3771       scale_and_extend_frame_nonnormative(unscaled, scaled);
3772 #endif  // CONFIG_VP9_HIGHBITDEPTH
3773     return scaled;
3774   } else {
3775     return unscaled;
3776   }
3777 }
3778
3779 static void set_arf_sign_bias(VP9_COMP *cpi) {
3780   VP9_COMMON *const cm = &cpi->common;
3781   int arf_sign_bias;
3782
3783   if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
3784     const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3785     arf_sign_bias = cpi->rc.source_alt_ref_active &&
3786                     (!cpi->refresh_alt_ref_frame ||
3787                      (gf_group->rf_level[gf_group->index] == GF_ARF_LOW));
3788   } else {
3789     arf_sign_bias =
3790       (cpi->rc.source_alt_ref_active && !cpi->refresh_alt_ref_frame);
3791   }
3792   cm->ref_frame_sign_bias[ALTREF_FRAME] = arf_sign_bias;
3793 }
3794
3795 static int setup_interp_filter_search_mask(VP9_COMP *cpi) {
3796   INTERP_FILTER ifilter;
3797   int ref_total[MAX_REF_FRAMES] = {0};
3798   MV_REFERENCE_FRAME ref;
3799   int mask = 0;
3800   if (cpi->common.last_frame_type == KEY_FRAME ||
3801       cpi->refresh_alt_ref_frame)
3802     return mask;
3803   for (ref = LAST_FRAME; ref <= ALTREF_FRAME; ++ref)
3804     for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter)
3805       ref_total[ref] += cpi->interp_filter_selected[ref][ifilter];
3806
3807   for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter) {
3808     if ((ref_total[LAST_FRAME] &&
3809         cpi->interp_filter_selected[LAST_FRAME][ifilter] == 0) &&
3810         (ref_total[GOLDEN_FRAME] == 0 ||
3811          cpi->interp_filter_selected[GOLDEN_FRAME][ifilter] * 50
3812            < ref_total[GOLDEN_FRAME]) &&
3813         (ref_total[ALTREF_FRAME] == 0 ||
3814          cpi->interp_filter_selected[ALTREF_FRAME][ifilter] * 50
3815            < ref_total[ALTREF_FRAME]))
3816       mask |= 1 << ifilter;
3817   }
3818   return mask;
3819 }
3820
3821 #ifdef ENABLE_KF_DENOISE
3822 // Baseline Kernal weights for denoise
3823 static uint8_t dn_kernal_3[9] = {
3824   1, 2, 1,
3825   2, 4, 2,
3826   1, 2, 1};
3827 static uint8_t dn_kernal_5[25] = {
3828   1, 1, 1, 1, 1,
3829   1, 1, 2, 1, 1,
3830   1, 2, 4, 2, 1,
3831   1, 1, 2, 1, 1,
3832   1, 1, 1, 1, 1};
3833
3834 static INLINE void add_denoise_point(int centre_val, int data_val,
3835                                      int thresh, uint8_t point_weight,
3836                                      int *sum_val, int *sum_weight) {
3837   if (abs(centre_val - data_val) <= thresh) {
3838     *sum_weight += point_weight;
3839     *sum_val += (int)data_val * (int)point_weight;
3840   }
3841 }
3842
3843 static void spatial_denoise_point(uint8_t *src_ptr, const int stride,
3844                                   const int strength) {
3845   int sum_weight = 0;
3846   int sum_val = 0;
3847   int thresh = strength;
3848   int kernal_size = 5;
3849   int half_k_size = 2;
3850   int i, j;
3851   int max_diff = 0;
3852   uint8_t *tmp_ptr;
3853   uint8_t *kernal_ptr;
3854
3855   // Find the maximum deviation from the source point in the locale.
3856   tmp_ptr = src_ptr -  (stride * (half_k_size + 1)) - (half_k_size + 1);
3857   for (i = 0; i < kernal_size + 2; ++i) {
3858     for (j = 0; j < kernal_size + 2; ++j) {
3859       max_diff = VPXMAX(max_diff, abs((int)*src_ptr - (int)tmp_ptr[j]));
3860     }
3861     tmp_ptr += stride;
3862   }
3863
3864   // Select the kernal size.
3865   if (max_diff > (strength + (strength >> 1))) {
3866     kernal_size = 3;
3867     half_k_size = 1;
3868     thresh = thresh >> 1;
3869   }
3870   kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
3871
3872   // Apply the kernal
3873   tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
3874   for (i = 0; i < kernal_size; ++i) {
3875     for (j = 0; j < kernal_size; ++j) {
3876       add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh,
3877                         *kernal_ptr, &sum_val, &sum_weight);
3878       ++kernal_ptr;
3879     }
3880     tmp_ptr += stride;
3881   }
3882
3883   // Update the source value with the new filtered value
3884   *src_ptr = (uint8_t)((sum_val + (sum_weight >> 1)) / sum_weight);
3885 }
3886
3887 #if CONFIG_VP9_HIGHBITDEPTH
3888 static void highbd_spatial_denoise_point(uint16_t *src_ptr, const int stride,
3889                                         const int strength) {
3890   int sum_weight = 0;
3891   int sum_val = 0;
3892   int thresh = strength;
3893   int kernal_size = 5;
3894   int half_k_size = 2;
3895   int i, j;
3896   int max_diff = 0;
3897   uint16_t *tmp_ptr;
3898   uint8_t *kernal_ptr;
3899
3900   // Find the maximum deviation from the source point in the locale.
3901   tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
3902   for (i = 0; i < kernal_size + 2; ++i) {
3903     for (j = 0; j < kernal_size + 2; ++j) {
3904       max_diff = VPXMAX(max_diff, abs((int)src_ptr - (int)tmp_ptr[j]));
3905     }
3906     tmp_ptr += stride;
3907   }
3908
3909   // Select the kernal size.
3910   if (max_diff > (strength + (strength >> 1))) {
3911     kernal_size = 3;
3912     half_k_size = 1;
3913     thresh = thresh >> 1;
3914   }
3915   kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
3916
3917   // Apply the kernal
3918   tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
3919   for (i = 0; i < kernal_size; ++i) {
3920     for (j = 0; j < kernal_size; ++j) {
3921       add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh,
3922                         *kernal_ptr, &sum_val, &sum_weight);
3923       ++kernal_ptr;
3924     }
3925     tmp_ptr += stride;
3926   }
3927
3928   // Update the source value with the new filtered value
3929   *src_ptr = (uint16_t)((sum_val + (sum_weight >> 1)) / sum_weight);
3930 }
3931 #endif  // CONFIG_VP9_HIGHBITDEPTH
3932
3933 // Apply thresholded spatial noise supression to a given buffer.
3934 static void spatial_denoise_buffer(VP9_COMP *cpi,
3935                                    uint8_t * buffer, const int stride,
3936                                    const int width, const int height,
3937                                    const int strength) {
3938   VP9_COMMON *const cm = &cpi->common;
3939   uint8_t * src_ptr = buffer;
3940   int row;
3941   int col;
3942
3943   for (row = 0; row < height; ++row) {
3944     for (col = 0; col < width; ++col) {
3945 #if CONFIG_VP9_HIGHBITDEPTH
3946       if (cm->use_highbitdepth)
3947         highbd_spatial_denoise_point(
3948             CONVERT_TO_SHORTPTR(&src_ptr[col]), stride, strength);
3949       else
3950         spatial_denoise_point(&src_ptr[col], stride, strength);
3951 #else
3952       spatial_denoise_point(&src_ptr[col], stride, strength);
3953 #endif  // CONFIG_VP9_HIGHBITDEPTH
3954     }
3955     src_ptr += stride;
3956   }
3957 }
3958
3959 // Apply thresholded spatial noise supression to source.
3960 static void spatial_denoise_frame(VP9_COMP *cpi) {
3961   YV12_BUFFER_CONFIG *src = cpi->Source;
3962   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3963   TWO_PASS *const twopass = &cpi->twopass;
3964   VP9_COMMON *const cm = &cpi->common;
3965
3966   // Base the filter strength on the current active max Q.
3967   const int q = (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
3968                                               cm->bit_depth));
3969   int strength =
3970       VPXMAX(oxcf->arnr_strength >> 2, VPXMIN(oxcf->arnr_strength, (q >> 4)));
3971
3972   // Denoise each of Y,U and V buffers.
3973   spatial_denoise_buffer(cpi, src->y_buffer, src->y_stride,
3974                          src->y_width, src->y_height, strength);
3975
3976   strength += (strength >> 1);
3977   spatial_denoise_buffer(cpi, src->u_buffer, src->uv_stride,
3978                          src->uv_width, src->uv_height, strength << 1);
3979
3980   spatial_denoise_buffer(cpi, src->v_buffer, src->uv_stride,
3981                          src->uv_width, src->uv_height, strength << 1);
3982 }
3983 #endif  // ENABLE_KF_DENOISE
3984
3985 static void encode_frame_to_data_rate(VP9_COMP *cpi,
3986                                       size_t *size,
3987                                       uint8_t *dest,
3988                                       unsigned int *frame_flags) {
3989   VP9_COMMON *const cm = &cpi->common;
3990   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3991   struct segmentation *const seg = &cm->seg;
3992   TX_SIZE t;
3993
3994   set_ext_overrides(cpi);
3995   vpx_clear_system_state();
3996
3997 #ifdef ENABLE_KF_DENOISE
3998   // Spatial denoise of key frame.
3999   if (is_spatial_denoise_enabled(cpi))
4000     spatial_denoise_frame(cpi);
4001 #endif
4002
4003   // Set the arf sign bias for this frame.
4004   set_arf_sign_bias(cpi);
4005
4006   // Set default state for segment based loop filter update flags.
4007   cm->lf.mode_ref_delta_update = 0;
4008
4009   if (cpi->oxcf.pass == 2 &&
4010       cpi->sf.adaptive_interp_filter_search)
4011     cpi->sf.interp_filter_search_mask =
4012         setup_interp_filter_search_mask(cpi);
4013
4014   // Set various flags etc to special state if it is a key frame.
4015   if (frame_is_intra_only(cm)) {
4016     // Reset the loop filter deltas and segmentation map.
4017     vp9_reset_segment_features(&cm->seg);
4018
4019     // If segmentation is enabled force a map update for key frames.
4020     if (seg->enabled) {
4021       seg->update_map = 1;
4022       seg->update_data = 1;
4023     }
4024
4025     // The alternate reference frame cannot be active for a key frame.
4026     cpi->rc.source_alt_ref_active = 0;
4027
4028     cm->error_resilient_mode = oxcf->error_resilient_mode;
4029     cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
4030
4031     // By default, encoder assumes decoder can use prev_mi.
4032     if (cm->error_resilient_mode) {
4033       cm->frame_parallel_decoding_mode = 1;
4034       cm->reset_frame_context = 0;
4035       cm->refresh_frame_context = 0;
4036     } else if (cm->intra_only) {
4037       // Only reset the current context.
4038       cm->reset_frame_context = 2;
4039     }
4040   }
4041   if (is_two_pass_svc(cpi) && cm->error_resilient_mode == 0) {
4042     // Use context 0 for intra only empty frame, but the last frame context
4043     // for other empty frames.
4044     if (cpi->svc.encode_empty_frame_state == ENCODING) {
4045       if (cpi->svc.encode_intra_empty_frame != 0)
4046         cm->frame_context_idx = 0;
4047       else
4048         cm->frame_context_idx = FRAME_CONTEXTS - 1;
4049     } else {
4050     cm->frame_context_idx =
4051         cpi->svc.spatial_layer_id * cpi->svc.number_temporal_layers +
4052         cpi->svc.temporal_layer_id;
4053     }
4054
4055     cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
4056
4057     // The probs will be updated based on the frame type of its previous
4058     // frame if frame_parallel_decoding_mode is 0. The type may vary for
4059     // the frame after a key frame in base layer since we may drop enhancement
4060     // layers. So set frame_parallel_decoding_mode to 1 in this case.
4061     if (cm->frame_parallel_decoding_mode == 0) {
4062       if (cpi->svc.number_temporal_layers == 1) {
4063         if (cpi->svc.spatial_layer_id == 0 &&
4064             cpi->svc.layer_context[0].last_frame_type == KEY_FRAME)
4065           cm->frame_parallel_decoding_mode = 1;
4066       } else if (cpi->svc.spatial_layer_id == 0) {
4067         // Find the 2nd frame in temporal base layer and 1st frame in temporal
4068         // enhancement layers from the key frame.
4069         int i;
4070         for (i = 0; i < cpi->svc.number_temporal_layers; ++i) {
4071           if (cpi->svc.layer_context[0].frames_from_key_frame == 1 << i) {
4072             cm->frame_parallel_decoding_mode = 1;
4073             break;
4074           }
4075         }
4076       }
4077     }
4078   }
4079
4080   // For 1 pass CBR, check if we are dropping this frame.
4081   // For spatial layers, for now only check for frame-dropping on first spatial
4082   // layer, and if decision is to drop, we drop whole super-frame.
4083   if (oxcf->pass == 0 &&
4084       oxcf->rc_mode == VPX_CBR &&
4085       cm->frame_type != KEY_FRAME) {
4086     if (vp9_rc_drop_frame(cpi) ||
4087         (is_one_pass_cbr_svc(cpi) && cpi->svc.rc_drop_superframe == 1)) {
4088       vp9_rc_postencode_update_drop_frame(cpi);
4089       ++cm->current_video_frame;
4090       cpi->ext_refresh_frame_flags_pending = 0;
4091       cpi->svc.rc_drop_superframe = 1;
4092       // TODO(marpan): Advancing the svc counters on dropped frames can break
4093       // the referencing scheme for the fixed svc patterns defined in
4094       // vp9_one_pass_cbr_svc_start_layer(). Look into fixing this issue, but
4095       // for now, don't advance the svc frame counters on dropped frame.
4096       // if (cpi->use_svc)
4097       //   vp9_inc_frame_in_layer(cpi);
4098       return;
4099     }
4100   }
4101
4102   vpx_clear_system_state();
4103
4104 #if CONFIG_INTERNAL_STATS
4105   memset(cpi->mode_chosen_counts, 0,
4106          MAX_MODES * sizeof(*cpi->mode_chosen_counts));
4107 #endif
4108
4109   if (cpi->sf.recode_loop == DISALLOW_RECODE) {
4110     encode_without_recode_loop(cpi, size, dest);
4111   } else {
4112     encode_with_recode_loop(cpi, size, dest);
4113   }
4114
4115 #if CONFIG_VP9_TEMPORAL_DENOISING
4116 #ifdef OUTPUT_YUV_DENOISED
4117   if (oxcf->noise_sensitivity > 0) {
4118     vp9_write_yuv_frame_420(&cpi->denoiser.running_avg_y[INTRA_FRAME],
4119                             yuv_denoised_file);
4120   }
4121 #endif
4122 #endif
4123 #ifdef OUTPUT_YUV_SKINMAP
4124   if (cpi->common.current_video_frame > 1) {
4125     vp9_compute_skin_map(cpi, yuv_skinmap_file);
4126   }
4127 #endif
4128
4129   // Special case code to reduce pulsing when key frames are forced at a
4130   // fixed interval. Note the reconstruction error if it is the frame before
4131   // the force key frame
4132   if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
4133 #if CONFIG_VP9_HIGHBITDEPTH
4134     if (cm->use_highbitdepth) {
4135       cpi->ambient_err = vpx_highbd_get_y_sse(cpi->Source,
4136                                               get_frame_new_buffer(cm));
4137     } else {
4138       cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
4139     }
4140 #else
4141     cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
4142 #endif  // CONFIG_VP9_HIGHBITDEPTH
4143   }
4144
4145   // If the encoder forced a KEY_FRAME decision
4146   if (cm->frame_type == KEY_FRAME)
4147     cpi->refresh_last_frame = 1;
4148
4149   cm->frame_to_show = get_frame_new_buffer(cm);
4150   cm->frame_to_show->color_space = cm->color_space;
4151   cm->frame_to_show->color_range = cm->color_range;
4152   cm->frame_to_show->render_width  = cm->render_width;
4153   cm->frame_to_show->render_height = cm->render_height;
4154
4155   // Pick the loop filter level for the frame.
4156   loopfilter_frame(cpi, cm);
4157
4158   // build the bitstream
4159   vp9_pack_bitstream(cpi, dest, size);
4160
4161   if (cm->seg.update_map)
4162     update_reference_segmentation_map(cpi);
4163
4164   if (frame_is_intra_only(cm) == 0) {
4165     release_scaled_references(cpi);
4166   }
4167   vp9_update_reference_frames(cpi);
4168
4169   for (t = TX_4X4; t <= TX_32X32; t++)
4170     full_to_model_counts(cpi->td.counts->coef[t],
4171                          cpi->td.rd_counts.coef_counts[t]);
4172
4173   if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
4174     vp9_adapt_coef_probs(cm);
4175
4176   if (!frame_is_intra_only(cm)) {
4177     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
4178       vp9_adapt_mode_probs(cm);
4179       vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
4180     }
4181   }
4182
4183   cpi->ext_refresh_frame_flags_pending = 0;
4184
4185   if (cpi->refresh_golden_frame == 1)
4186     cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
4187   else
4188     cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
4189
4190   if (cpi->refresh_alt_ref_frame == 1)
4191     cpi->frame_flags |= FRAMEFLAGS_ALTREF;
4192   else
4193     cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
4194
4195   cpi->ref_frame_flags = get_ref_frame_flags(cpi);
4196
4197   cm->last_frame_type = cm->frame_type;
4198
4199   if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
4200     vp9_rc_postencode_update(cpi, *size);
4201
4202 #if 0
4203   output_frame_level_debug_stats(cpi);
4204 #endif
4205
4206   if (cm->frame_type == KEY_FRAME) {
4207     // Tell the caller that the frame was coded as a key frame
4208     *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
4209   } else {
4210     *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
4211   }
4212
4213   // Clear the one shot update flags for segmentation map and mode/ref loop
4214   // filter deltas.
4215   cm->seg.update_map = 0;
4216   cm->seg.update_data = 0;
4217   cm->lf.mode_ref_delta_update = 0;
4218
4219   // keep track of the last coded dimensions
4220   cm->last_width = cm->width;
4221   cm->last_height = cm->height;
4222
4223   // reset to normal state now that we are done.
4224   if (!cm->show_existing_frame)
4225     cm->last_show_frame = cm->show_frame;
4226
4227   if (cm->show_frame) {
4228     vp9_swap_mi_and_prev_mi(cm);
4229     // Don't increment frame counters if this was an altref buffer
4230     // update not a real frame
4231     ++cm->current_video_frame;
4232     if (cpi->use_svc)
4233       vp9_inc_frame_in_layer(cpi);
4234   }
4235   cm->prev_frame = cm->cur_frame;
4236
4237   if (cpi->use_svc)
4238     cpi->svc.layer_context[cpi->svc.spatial_layer_id *
4239                            cpi->svc.number_temporal_layers +
4240                            cpi->svc.temporal_layer_id].last_frame_type =
4241                                cm->frame_type;
4242 }
4243
4244 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4245                       unsigned int *frame_flags) {
4246   vp9_rc_get_svc_params(cpi);
4247   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4248 }
4249
4250 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4251                         unsigned int *frame_flags) {
4252   if (cpi->oxcf.rc_mode == VPX_CBR) {
4253     vp9_rc_get_one_pass_cbr_params(cpi);
4254   } else {
4255     vp9_rc_get_one_pass_vbr_params(cpi);
4256   }
4257   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4258 }
4259
4260 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
4261                         uint8_t *dest, unsigned int *frame_flags) {
4262   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
4263   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4264
4265   if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
4266     vp9_twopass_postencode_update(cpi);
4267 }
4268
4269 static void init_ref_frame_bufs(VP9_COMMON *cm) {
4270   int i;
4271   BufferPool *const pool = cm->buffer_pool;
4272   cm->new_fb_idx = INVALID_IDX;
4273   for (i = 0; i < REF_FRAMES; ++i) {
4274     cm->ref_frame_map[i] = INVALID_IDX;
4275     pool->frame_bufs[i].ref_count = 0;
4276   }
4277 }
4278
4279 static void check_initial_width(VP9_COMP *cpi,
4280 #if CONFIG_VP9_HIGHBITDEPTH
4281                                 int use_highbitdepth,
4282 #endif
4283                                 int subsampling_x, int subsampling_y) {
4284   VP9_COMMON *const cm = &cpi->common;
4285
4286   if (!cpi->initial_width ||
4287 #if CONFIG_VP9_HIGHBITDEPTH
4288       cm->use_highbitdepth != use_highbitdepth ||
4289 #endif
4290       cm->subsampling_x != subsampling_x ||
4291       cm->subsampling_y != subsampling_y) {
4292     cm->subsampling_x = subsampling_x;
4293     cm->subsampling_y = subsampling_y;
4294 #if CONFIG_VP9_HIGHBITDEPTH
4295     cm->use_highbitdepth = use_highbitdepth;
4296 #endif
4297
4298     alloc_raw_frame_buffers(cpi);
4299     init_ref_frame_bufs(cm);
4300     alloc_util_frame_buffers(cpi);
4301
4302     init_motion_estimation(cpi);  // TODO(agrange) This can be removed.
4303
4304     cpi->initial_width = cm->width;
4305     cpi->initial_height = cm->height;
4306     cpi->initial_mbs = cm->MBs;
4307   }
4308 }
4309
4310 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
4311                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
4312                           int64_t end_time) {
4313   VP9_COMMON *const cm = &cpi->common;
4314   struct vpx_usec_timer timer;
4315   int res = 0;
4316   const int subsampling_x = sd->subsampling_x;
4317   const int subsampling_y = sd->subsampling_y;
4318 #if CONFIG_VP9_HIGHBITDEPTH
4319   const int use_highbitdepth = (sd->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
4320 #endif
4321
4322 #if CONFIG_VP9_HIGHBITDEPTH
4323   check_initial_width(cpi, use_highbitdepth, subsampling_x, subsampling_y);
4324 #else
4325   check_initial_width(cpi, subsampling_x, subsampling_y);
4326 #endif  // CONFIG_VP9_HIGHBITDEPTH
4327
4328 #if CONFIG_VP9_TEMPORAL_DENOISING
4329   setup_denoiser_buffer(cpi);
4330 #endif
4331   vpx_usec_timer_start(&timer);
4332
4333   if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4334 #if CONFIG_VP9_HIGHBITDEPTH
4335                          use_highbitdepth,
4336 #endif  // CONFIG_VP9_HIGHBITDEPTH
4337                          frame_flags))
4338     res = -1;
4339   vpx_usec_timer_mark(&timer);
4340   cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4341
4342   if ((cm->profile == PROFILE_0 || cm->profile == PROFILE_2) &&
4343       (subsampling_x != 1 || subsampling_y != 1)) {
4344     vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4345                        "Non-4:2:0 color format requires profile 1 or 3");
4346     res = -1;
4347   }
4348   if ((cm->profile == PROFILE_1 || cm->profile == PROFILE_3) &&
4349       (subsampling_x == 1 && subsampling_y == 1)) {
4350     vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4351                        "4:2:0 color format requires profile 0 or 2");
4352     res = -1;
4353   }
4354
4355   return res;
4356 }
4357
4358
4359 static int frame_is_reference(const VP9_COMP *cpi) {
4360   const VP9_COMMON *cm = &cpi->common;
4361
4362   return cm->frame_type == KEY_FRAME ||
4363          cpi->refresh_last_frame ||
4364          cpi->refresh_golden_frame ||
4365          cpi->refresh_alt_ref_frame ||
4366          cm->refresh_frame_context ||
4367          cm->lf.mode_ref_delta_update ||
4368          cm->seg.update_map ||
4369          cm->seg.update_data;
4370 }
4371
4372 static void adjust_frame_rate(VP9_COMP *cpi,
4373                               const struct lookahead_entry *source) {
4374   int64_t this_duration;
4375   int step = 0;
4376
4377   if (source->ts_start == cpi->first_time_stamp_ever) {
4378     this_duration = source->ts_end - source->ts_start;
4379     step = 1;
4380   } else {
4381     int64_t last_duration = cpi->last_end_time_stamp_seen
4382         - cpi->last_time_stamp_seen;
4383
4384     this_duration = source->ts_end - cpi->last_end_time_stamp_seen;
4385
4386     // do a step update if the duration changes by 10%
4387     if (last_duration)
4388       step = (int)((this_duration - last_duration) * 10 / last_duration);
4389   }
4390
4391   if (this_duration) {
4392     if (step) {
4393       vp9_new_framerate(cpi, 10000000.0 / this_duration);
4394     } else {
4395       // Average this frame's rate into the last second's average
4396       // frame rate. If we haven't seen 1 second yet, then average
4397       // over the whole interval seen.
4398       const double interval = VPXMIN(
4399           (double)(source->ts_end - cpi->first_time_stamp_ever), 10000000.0);
4400       double avg_duration = 10000000.0 / cpi->framerate;
4401       avg_duration *= (interval - avg_duration + this_duration);
4402       avg_duration /= interval;
4403
4404       vp9_new_framerate(cpi, 10000000.0 / avg_duration);
4405     }
4406   }
4407   cpi->last_time_stamp_seen = source->ts_start;
4408   cpi->last_end_time_stamp_seen = source->ts_end;
4409 }
4410
4411 // Returns 0 if this is not an alt ref else the offset of the source frame
4412 // used as the arf midpoint.
4413 static int get_arf_src_index(VP9_COMP *cpi) {
4414   RATE_CONTROL *const rc = &cpi->rc;
4415   int arf_src_index = 0;
4416   if (is_altref_enabled(cpi)) {
4417     if (cpi->oxcf.pass == 2) {
4418       const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4419       if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
4420         arf_src_index = gf_group->arf_src_offset[gf_group->index];
4421       }
4422     } else if (rc->source_alt_ref_pending) {
4423       arf_src_index = rc->frames_till_gf_update_due;
4424     }
4425   }
4426   return arf_src_index;
4427 }
4428
4429 static void check_src_altref(VP9_COMP *cpi,
4430                              const struct lookahead_entry *source) {
4431   RATE_CONTROL *const rc = &cpi->rc;
4432
4433   if (cpi->oxcf.pass == 2) {
4434     const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4435     rc->is_src_frame_alt_ref =
4436       (gf_group->update_type[gf_group->index] == OVERLAY_UPDATE);
4437   } else {
4438     rc->is_src_frame_alt_ref = cpi->alt_ref_source &&
4439                                (source == cpi->alt_ref_source);
4440   }
4441
4442   if (rc->is_src_frame_alt_ref) {
4443     // Current frame is an ARF overlay frame.
4444     cpi->alt_ref_source = NULL;
4445
4446     // Don't refresh the last buffer for an ARF overlay frame. It will
4447     // become the GF so preserve last as an alternative prediction option.
4448     cpi->refresh_last_frame = 0;
4449   }
4450 }
4451
4452 #if CONFIG_INTERNAL_STATS
4453 extern double vp9_get_blockiness(const uint8_t *img1, int img1_pitch,
4454                                  const uint8_t *img2, int img2_pitch,
4455                                  int width, int height);
4456
4457 static void adjust_image_stat(double y, double u, double v, double all,
4458                               ImageStat *s) {
4459   s->stat[Y] += y;
4460   s->stat[U] += u;
4461   s->stat[V] += v;
4462   s->stat[ALL] += all;
4463   s->worst = VPXMIN(s->worst, all);
4464 }
4465 #endif  // CONFIG_INTERNAL_STATS
4466
4467 static void update_level_info(VP9_COMP *cpi, size_t *size, int arf_src_index) {
4468   VP9_COMMON *const cm = &cpi->common;
4469   Vp9LevelInfo *const level_info = &cpi->level_info;
4470   Vp9LevelSpec *const level_spec = &level_info->level_spec;
4471   Vp9LevelStats *const level_stats = &level_info->level_stats;
4472   int i, idx;
4473   uint64_t luma_samples, dur_end;
4474   const uint32_t luma_pic_size = cm->width * cm->height;
4475   double cpb_data_size;
4476
4477   vpx_clear_system_state();
4478
4479   // update level_stats
4480   level_stats->total_compressed_size += *size;
4481   if (cm->show_frame) {
4482     level_stats->total_uncompressed_size +=
4483         luma_pic_size +
4484         2 * (luma_pic_size >> (cm->subsampling_x + cm->subsampling_y));
4485     level_stats->time_encoded =
4486         (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
4487         (double)TICKS_PER_SEC;
4488   }
4489
4490   if (arf_src_index > 0) {
4491     if (!level_stats->seen_first_altref) {
4492       level_stats->seen_first_altref = 1;
4493     } else if (level_stats->frames_since_last_altref <
4494              level_spec->min_altref_distance) {
4495       level_spec->min_altref_distance = level_stats->frames_since_last_altref;
4496     }
4497     level_stats->frames_since_last_altref = 0;
4498   } else {
4499     ++level_stats->frames_since_last_altref;
4500   }
4501
4502   if (level_stats->frame_window_buffer.len < FRAME_WINDOW_SIZE - 1) {
4503     idx = (level_stats->frame_window_buffer.start +
4504            level_stats->frame_window_buffer.len++) % FRAME_WINDOW_SIZE;
4505   } else {
4506     idx = level_stats->frame_window_buffer.start;
4507     level_stats->frame_window_buffer.start = (idx + 1) % FRAME_WINDOW_SIZE;
4508   }
4509   level_stats->frame_window_buffer.buf[idx].ts = cpi->last_time_stamp_seen;
4510   level_stats->frame_window_buffer.buf[idx].size = (uint32_t)(*size);
4511   level_stats->frame_window_buffer.buf[idx].luma_samples = luma_pic_size;
4512
4513   if (cm->frame_type == KEY_FRAME) {
4514     level_stats->ref_refresh_map = 0;
4515   } else {
4516     int count = 0;
4517     level_stats->ref_refresh_map |= vp9_get_refresh_mask(cpi);
4518     // Also need to consider the case where the encoder refers to a buffer
4519     // that has been implicitly refreshed after encoding a keyframe.
4520     if (!cm->intra_only) {
4521       level_stats->ref_refresh_map |= (1 << cpi->lst_fb_idx);
4522       level_stats->ref_refresh_map |= (1 << cpi->gld_fb_idx);
4523       level_stats->ref_refresh_map |= (1 << cpi->alt_fb_idx);
4524     }
4525     for (i = 0; i < REF_FRAMES; ++i) {
4526       count += (level_stats->ref_refresh_map >> i) & 1;
4527     }
4528     if (count > level_spec->max_ref_frame_buffers) {
4529       level_spec->max_ref_frame_buffers = count;
4530     }
4531   }
4532
4533   // update average_bitrate
4534   level_spec->average_bitrate =
4535       (double)level_stats->total_compressed_size / 125.0 /
4536       level_stats->time_encoded;
4537
4538   // update max_luma_sample_rate
4539   luma_samples = 0;
4540   for (i = 0; i < level_stats->frame_window_buffer.len; ++i) {
4541     idx = (level_stats->frame_window_buffer.start +
4542            level_stats->frame_window_buffer.len - 1 - i) % FRAME_WINDOW_SIZE;
4543     if (i == 0) {
4544       dur_end = level_stats->frame_window_buffer.buf[idx].ts;
4545     }
4546     if (dur_end - level_stats->frame_window_buffer.buf[idx].ts >=
4547         TICKS_PER_SEC) {
4548       break;
4549     }
4550     luma_samples += level_stats->frame_window_buffer.buf[idx].luma_samples;
4551   }
4552   if (luma_samples > level_spec->max_luma_sample_rate) {
4553     level_spec->max_luma_sample_rate = luma_samples;
4554   }
4555
4556   // update max_cpb_size
4557   cpb_data_size = 0;
4558   for (i = 0; i < CPB_WINDOW_SIZE; ++i) {
4559     if (i >= level_stats->frame_window_buffer.len) break;
4560     idx = (level_stats->frame_window_buffer.start +
4561            level_stats->frame_window_buffer.len - 1 - i) % FRAME_WINDOW_SIZE;
4562     cpb_data_size += level_stats->frame_window_buffer.buf[idx].size;
4563   }
4564   cpb_data_size = cpb_data_size / 125.0;
4565   if (cpb_data_size > level_spec->max_cpb_size) {
4566     level_spec->max_cpb_size = cpb_data_size;
4567   }
4568
4569   // update max_luma_picture_size
4570   if (luma_pic_size > level_spec->max_luma_picture_size) {
4571     level_spec->max_luma_picture_size = luma_pic_size;
4572   }
4573
4574   // update compression_ratio
4575   level_spec->compression_ratio =
4576       (double)level_stats->total_uncompressed_size * cm->bit_depth /
4577       level_stats->total_compressed_size / 8.0;
4578
4579   // update max_col_tiles
4580   if (level_spec->max_col_tiles < (1 << cm->log2_tile_cols)) {
4581     level_spec->max_col_tiles = (1 << cm->log2_tile_cols);
4582   }
4583 }
4584
4585 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
4586                             size_t *size, uint8_t *dest,
4587                             int64_t *time_stamp, int64_t *time_end, int flush) {
4588   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
4589   VP9_COMMON *const cm = &cpi->common;
4590   BufferPool *const pool = cm->buffer_pool;
4591   RATE_CONTROL *const rc = &cpi->rc;
4592   struct vpx_usec_timer  cmptimer;
4593   YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4594   struct lookahead_entry *last_source = NULL;
4595   struct lookahead_entry *source = NULL;
4596   int arf_src_index;
4597   int i;
4598
4599   if (is_two_pass_svc(cpi)) {
4600 #if CONFIG_SPATIAL_SVC
4601     vp9_svc_start_frame(cpi);
4602     // Use a small empty frame instead of a real frame
4603     if (cpi->svc.encode_empty_frame_state == ENCODING)
4604       source = &cpi->svc.empty_frame;
4605 #endif
4606     if (oxcf->pass == 2)
4607       vp9_restore_layer_context(cpi);
4608   } else if (is_one_pass_cbr_svc(cpi)) {
4609     vp9_one_pass_cbr_svc_start_layer(cpi);
4610   }
4611
4612   vpx_usec_timer_start(&cmptimer);
4613
4614   vp9_set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
4615
4616   // Is multi-arf enabled.
4617   // Note that at the moment multi_arf is only configured for 2 pass VBR and
4618   // will not work properly with svc.
4619   if ((oxcf->pass == 2) && !cpi->use_svc &&
4620       (cpi->oxcf.enable_auto_arf > 1))
4621     cpi->multi_arf_allowed = 1;
4622   else
4623     cpi->multi_arf_allowed = 0;
4624
4625   // Normal defaults
4626   cm->reset_frame_context = 0;
4627   cm->refresh_frame_context = 1;
4628   if (!is_one_pass_cbr_svc(cpi)) {
4629     cpi->refresh_last_frame = 1;
4630     cpi->refresh_golden_frame = 0;
4631     cpi->refresh_alt_ref_frame = 0;
4632   }
4633
4634   // Should we encode an arf frame.
4635   arf_src_index = get_arf_src_index(cpi);
4636
4637   // Skip alt frame if we encode the empty frame
4638   if (is_two_pass_svc(cpi) && source != NULL)
4639     arf_src_index = 0;
4640
4641   if (arf_src_index) {
4642     for (i = 0; i <= arf_src_index; ++i) {
4643       struct lookahead_entry *e = vp9_lookahead_peek(cpi->lookahead, i);
4644       // Avoid creating an alt-ref if there's a forced keyframe pending.
4645       if (e == NULL) {
4646         break;
4647       } else if (e->flags == VPX_EFLAG_FORCE_KF) {
4648         arf_src_index = 0;
4649         flush = 1;
4650         break;
4651       }
4652     }
4653   }
4654
4655   if (arf_src_index) {
4656     assert(arf_src_index <= rc->frames_to_key);
4657
4658     if ((source = vp9_lookahead_peek(cpi->lookahead, arf_src_index)) != NULL) {
4659       cpi->alt_ref_source = source;
4660
4661 #if CONFIG_SPATIAL_SVC
4662       if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0) {
4663         int i;
4664         // Reference a hidden frame from a lower layer
4665         for (i = cpi->svc.spatial_layer_id - 1; i >= 0; --i) {
4666           if (oxcf->ss_enable_auto_arf[i]) {
4667             cpi->gld_fb_idx = cpi->svc.layer_context[i].alt_ref_idx;
4668             break;
4669           }
4670         }
4671       }
4672       cpi->svc.layer_context[cpi->svc.spatial_layer_id].has_alt_frame = 1;
4673 #endif
4674
4675       if ((oxcf->arnr_max_frames > 0) && (oxcf->arnr_strength > 0)) {
4676         // Produce the filtered ARF frame.
4677         vp9_temporal_filter(cpi, arf_src_index);
4678         vpx_extend_frame_borders(&cpi->alt_ref_buffer);
4679         force_src_buffer = &cpi->alt_ref_buffer;
4680       }
4681
4682       cm->show_frame = 0;
4683       cm->intra_only = 0;
4684       cpi->refresh_alt_ref_frame = 1;
4685       cpi->refresh_golden_frame = 0;
4686       cpi->refresh_last_frame = 0;
4687       rc->is_src_frame_alt_ref = 0;
4688       rc->source_alt_ref_pending = 0;
4689     } else {
4690       rc->source_alt_ref_pending = 0;
4691     }
4692   }
4693
4694   if (!source) {
4695     // Get last frame source.
4696     if (cm->current_video_frame > 0) {
4697       if ((last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
4698         return -1;
4699     }
4700
4701     // Read in the source frame.
4702     if (cpi->use_svc)
4703       source = vp9_svc_lookahead_pop(cpi, cpi->lookahead, flush);
4704     else
4705       source = vp9_lookahead_pop(cpi->lookahead, flush);
4706
4707     if (source != NULL) {
4708       cm->show_frame = 1;
4709       cm->intra_only = 0;
4710       // if the flags indicate intra frame, but if the current picture is for
4711       // non-zero spatial layer, it should not be an intra picture.
4712       // TODO(Won Kap): this needs to change if per-layer intra frame is
4713       // allowed.
4714       if ((source->flags & VPX_EFLAG_FORCE_KF) &&
4715           cpi->svc.spatial_layer_id > cpi->svc.first_spatial_layer_to_encode) {
4716         source->flags &= ~(unsigned int)(VPX_EFLAG_FORCE_KF);
4717       }
4718
4719       // Check to see if the frame should be encoded as an arf overlay.
4720       check_src_altref(cpi, source);
4721     }
4722   }
4723
4724   if (source) {
4725     cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
4726                                                            : &source->img;
4727
4728 #ifdef ENABLE_KF_DENOISE
4729     // Copy of raw source for metrics calculation.
4730     if (is_psnr_calc_enabled(cpi))
4731       vp9_copy_and_extend_frame(cpi->Source, &cpi->raw_unscaled_source);
4732 #endif
4733
4734     cpi->unscaled_last_source = last_source != NULL ? &last_source->img : NULL;
4735
4736     *time_stamp = source->ts_start;
4737     *time_end = source->ts_end;
4738     *frame_flags = (source->flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
4739
4740   } else {
4741     *size = 0;
4742     if (flush && oxcf->pass == 1 && !cpi->twopass.first_pass_done) {
4743       vp9_end_first_pass(cpi);    /* get last stats packet */
4744       cpi->twopass.first_pass_done = 1;
4745     }
4746     return -1;
4747   }
4748
4749   if (source->ts_start < cpi->first_time_stamp_ever) {
4750     cpi->first_time_stamp_ever = source->ts_start;
4751     cpi->last_end_time_stamp_seen = source->ts_start;
4752   }
4753
4754   // Clear down mmx registers
4755   vpx_clear_system_state();
4756
4757   // adjust frame rates based on timestamps given
4758   if (cm->show_frame) {
4759     adjust_frame_rate(cpi, source);
4760   }
4761
4762   if (is_one_pass_cbr_svc(cpi)) {
4763     vp9_update_temporal_layer_framerate(cpi);
4764     vp9_restore_layer_context(cpi);
4765   }
4766
4767   // Find a free buffer for the new frame, releasing the reference previously
4768   // held.
4769   if (cm->new_fb_idx != INVALID_IDX) {
4770     --pool->frame_bufs[cm->new_fb_idx].ref_count;
4771   }
4772   cm->new_fb_idx = get_free_fb(cm);
4773
4774   if (cm->new_fb_idx == INVALID_IDX)
4775     return -1;
4776
4777   cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx];
4778
4779   if (!cpi->use_svc && cpi->multi_arf_allowed) {
4780     if (cm->frame_type == KEY_FRAME) {
4781       init_buffer_indices(cpi);
4782     } else if (oxcf->pass == 2) {
4783       const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4784       cpi->alt_fb_idx = gf_group->arf_ref_idx[gf_group->index];
4785     }
4786   }
4787
4788   // Start with a 0 size frame.
4789   *size = 0;
4790
4791   cpi->frame_flags = *frame_flags;
4792
4793   if ((oxcf->pass == 2) &&
4794       (!cpi->use_svc ||
4795           (is_two_pass_svc(cpi) &&
4796               cpi->svc.encode_empty_frame_state != ENCODING))) {
4797     vp9_rc_get_second_pass_params(cpi);
4798   } else if (oxcf->pass == 1) {
4799     set_frame_size(cpi);
4800   }
4801
4802   if (cpi->oxcf.pass != 0 ||
4803       cpi->use_svc ||
4804       frame_is_intra_only(cm) == 1) {
4805     for (i = 0; i < MAX_REF_FRAMES; ++i)
4806       cpi->scaled_ref_idx[i] = INVALID_IDX;
4807   }
4808
4809   if (oxcf->pass == 1 &&
4810       (!cpi->use_svc || is_two_pass_svc(cpi))) {
4811     const int lossless = is_lossless_requested(oxcf);
4812 #if CONFIG_VP9_HIGHBITDEPTH
4813     if (cpi->oxcf.use_highbitdepth)
4814       cpi->td.mb.fwd_txm4x4 = lossless ?
4815           vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
4816     else
4817       cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4818     cpi->td.mb.highbd_itxm_add = lossless ? vp9_highbd_iwht4x4_add :
4819                                          vp9_highbd_idct4x4_add;
4820 #else
4821     cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4822 #endif  // CONFIG_VP9_HIGHBITDEPTH
4823     cpi->td.mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
4824     vp9_first_pass(cpi, source);
4825   } else if (oxcf->pass == 2 &&
4826       (!cpi->use_svc || is_two_pass_svc(cpi))) {
4827     Pass2Encode(cpi, size, dest, frame_flags);
4828   } else if (cpi->use_svc) {
4829     SvcEncode(cpi, size, dest, frame_flags);
4830   } else {
4831     // One pass encode
4832     Pass0Encode(cpi, size, dest, frame_flags);
4833   }
4834
4835   if (cm->refresh_frame_context)
4836     cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
4837
4838   // No frame encoded, or frame was dropped, release scaled references.
4839   if ((*size == 0) && (frame_is_intra_only(cm) == 0)) {
4840     release_scaled_references(cpi);
4841   }
4842
4843   if (*size > 0) {
4844     cpi->droppable = !frame_is_reference(cpi);
4845   }
4846
4847   // Save layer specific state.
4848   if (is_one_pass_cbr_svc(cpi) ||
4849         ((cpi->svc.number_temporal_layers > 1 ||
4850           cpi->svc.number_spatial_layers > 1) &&
4851          oxcf->pass == 2)) {
4852     vp9_save_layer_context(cpi);
4853   }
4854
4855   vpx_usec_timer_mark(&cmptimer);
4856   cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4857
4858   // Should we calculate metrics for the frame.
4859   if (is_psnr_calc_enabled(cpi))
4860     generate_psnr_packet(cpi);
4861
4862   if (cpi->keep_level_stats && oxcf->pass != 1)
4863     update_level_info(cpi, size, arf_src_index);
4864
4865 #if CONFIG_INTERNAL_STATS
4866
4867   if (oxcf->pass != 1) {
4868     double samples = 0.0;
4869     cpi->bytes += (int)(*size);
4870
4871     if (cm->show_frame) {
4872       uint32_t bit_depth = 8;
4873       uint32_t in_bit_depth = 8;
4874       cpi->count++;
4875 #if CONFIG_VP9_HIGHBITDEPTH
4876     if (cm->use_highbitdepth) {
4877       in_bit_depth = cpi->oxcf.input_bit_depth;
4878       bit_depth = cm->bit_depth;
4879     }
4880 #endif
4881
4882       if (cpi->b_calculate_psnr) {
4883         YV12_BUFFER_CONFIG *orig = cpi->raw_source_frame;
4884         YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4885         YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4886         PSNR_STATS psnr;
4887 #if CONFIG_VP9_HIGHBITDEPTH
4888         vpx_calc_highbd_psnr(orig, recon, &psnr, cpi->td.mb.e_mbd.bd,
4889                              in_bit_depth);
4890 #else
4891         vpx_calc_psnr(orig, recon, &psnr);
4892 #endif  // CONFIG_VP9_HIGHBITDEPTH
4893
4894         adjust_image_stat(psnr.psnr[1], psnr.psnr[2], psnr.psnr[3],
4895                           psnr.psnr[0], &cpi->psnr);
4896         cpi->total_sq_error += psnr.sse[0];
4897         cpi->total_samples += psnr.samples[0];
4898         samples = psnr.samples[0];
4899
4900         {
4901           PSNR_STATS psnr2;
4902           double frame_ssim2 = 0, weight = 0;
4903 #if CONFIG_VP9_POSTPROC
4904           if (vpx_alloc_frame_buffer(pp,
4905                                      recon->y_crop_width, recon->y_crop_height,
4906                                      cm->subsampling_x, cm->subsampling_y,
4907 #if CONFIG_VP9_HIGHBITDEPTH
4908                                      cm->use_highbitdepth,
4909 #endif
4910                                      VP9_ENC_BORDER_IN_PIXELS,
4911                                      cm->byte_alignment) < 0) {
4912             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
4913                                "Failed to allocate post processing buffer");
4914           }
4915
4916           vp9_deblock(cm->frame_to_show, pp,
4917                       cm->lf.filter_level * 10 / 6);
4918 #endif
4919           vpx_clear_system_state();
4920
4921 #if CONFIG_VP9_HIGHBITDEPTH
4922           vpx_calc_highbd_psnr(orig, pp, &psnr2, cpi->td.mb.e_mbd.bd,
4923                            cpi->oxcf.input_bit_depth);
4924 #else
4925           vpx_calc_psnr(orig, pp, &psnr2);
4926 #endif  // CONFIG_VP9_HIGHBITDEPTH
4927
4928           cpi->totalp_sq_error += psnr2.sse[0];
4929           cpi->totalp_samples += psnr2.samples[0];
4930           adjust_image_stat(psnr2.psnr[1], psnr2.psnr[2], psnr2.psnr[3],
4931                             psnr2.psnr[0], &cpi->psnrp);
4932
4933 #if CONFIG_VP9_HIGHBITDEPTH
4934           if (cm->use_highbitdepth) {
4935             frame_ssim2 = vpx_highbd_calc_ssim(orig, recon, &weight,
4936                                                bit_depth, in_bit_depth);
4937           } else {
4938             frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4939           }
4940 #else
4941           frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4942 #endif  // CONFIG_VP9_HIGHBITDEPTH
4943
4944           cpi->worst_ssim = VPXMIN(cpi->worst_ssim, frame_ssim2);
4945           cpi->summed_quality += frame_ssim2 * weight;
4946           cpi->summed_weights += weight;
4947
4948 #if CONFIG_VP9_HIGHBITDEPTH
4949           if (cm->use_highbitdepth) {
4950             frame_ssim2 = vpx_highbd_calc_ssim(
4951                 orig, pp, &weight, bit_depth, in_bit_depth);
4952           } else {
4953             frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4954           }
4955 #else
4956           frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4957 #endif  // CONFIG_VP9_HIGHBITDEPTH
4958
4959           cpi->summedp_quality += frame_ssim2 * weight;
4960           cpi->summedp_weights += weight;
4961 #if 0
4962           {
4963             FILE *f = fopen("q_used.stt", "a");
4964             fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
4965                     cpi->common.current_video_frame, y2, u2, v2,
4966                     frame_psnr2, frame_ssim2);
4967             fclose(f);
4968           }
4969 #endif
4970         }
4971       }
4972       if (cpi->b_calculate_blockiness) {
4973 #if CONFIG_VP9_HIGHBITDEPTH
4974         if (!cm->use_highbitdepth)
4975 #endif
4976         {
4977           double frame_blockiness = vp9_get_blockiness(
4978               cpi->Source->y_buffer, cpi->Source->y_stride,
4979               cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4980               cpi->Source->y_width, cpi->Source->y_height);
4981           cpi->worst_blockiness =
4982               VPXMAX(cpi->worst_blockiness, frame_blockiness);
4983           cpi->total_blockiness += frame_blockiness;
4984         }
4985       }
4986
4987       if (cpi->b_calculate_consistency) {
4988 #if CONFIG_VP9_HIGHBITDEPTH
4989         if (!cm->use_highbitdepth)
4990 #endif
4991         {
4992           double this_inconsistency = vpx_get_ssim_metrics(
4993               cpi->Source->y_buffer, cpi->Source->y_stride,
4994               cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4995               cpi->Source->y_width, cpi->Source->y_height, cpi->ssim_vars,
4996               &cpi->metrics, 1);
4997
4998           const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
4999           double consistency = vpx_sse_to_psnr(samples, peak,
5000                                              (double)cpi->total_inconsistency);
5001           if (consistency > 0.0)
5002             cpi->worst_consistency =
5003                 VPXMIN(cpi->worst_consistency, consistency);
5004           cpi->total_inconsistency += this_inconsistency;
5005         }
5006       }
5007
5008       {
5009         double y, u, v, frame_all;
5010         frame_all = vpx_calc_fastssim(cpi->Source, cm->frame_to_show, &y, &u,
5011                                       &v, bit_depth, in_bit_depth);
5012         adjust_image_stat(y, u, v, frame_all, &cpi->fastssim);
5013       }
5014       {
5015         double y, u, v, frame_all;
5016         frame_all = vpx_psnrhvs(cpi->Source, cm->frame_to_show, &y, &u, &v,
5017                                 bit_depth, in_bit_depth);
5018         adjust_image_stat(y, u, v, frame_all, &cpi->psnrhvs);
5019       }
5020     }
5021   }
5022
5023 #endif
5024
5025   if (is_two_pass_svc(cpi)) {
5026     if (cpi->svc.encode_empty_frame_state == ENCODING) {
5027       cpi->svc.encode_empty_frame_state = ENCODED;
5028       cpi->svc.encode_intra_empty_frame = 0;
5029     }
5030
5031     if (cm->show_frame) {
5032       ++cpi->svc.spatial_layer_to_encode;
5033       if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
5034         cpi->svc.spatial_layer_to_encode = 0;
5035
5036       // May need the empty frame after an visible frame.
5037       cpi->svc.encode_empty_frame_state = NEED_TO_ENCODE;
5038     }
5039   } else if (is_one_pass_cbr_svc(cpi)) {
5040     if (cm->show_frame) {
5041       ++cpi->svc.spatial_layer_to_encode;
5042       if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
5043         cpi->svc.spatial_layer_to_encode = 0;
5044     }
5045   }
5046   vpx_clear_system_state();
5047   return 0;
5048 }
5049
5050 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
5051                               vp9_ppflags_t *flags) {
5052   VP9_COMMON *cm = &cpi->common;
5053 #if !CONFIG_VP9_POSTPROC
5054   (void)flags;
5055 #endif
5056
5057   if (!cm->show_frame) {
5058     return -1;
5059   } else {
5060     int ret;
5061 #if CONFIG_VP9_POSTPROC
5062     ret = vp9_post_proc_frame(cm, dest, flags);
5063 #else
5064     if (cm->frame_to_show) {
5065       *dest = *cm->frame_to_show;
5066       dest->y_width = cm->width;
5067       dest->y_height = cm->height;
5068       dest->uv_width = cm->width >> cm->subsampling_x;
5069       dest->uv_height = cm->height >> cm->subsampling_y;
5070       ret = 0;
5071     } else {
5072       ret = -1;
5073     }
5074 #endif  // !CONFIG_VP9_POSTPROC
5075     vpx_clear_system_state();
5076     return ret;
5077   }
5078 }
5079
5080 int vp9_set_internal_size(VP9_COMP *cpi,
5081                           VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
5082   VP9_COMMON *cm = &cpi->common;
5083   int hr = 0, hs = 0, vr = 0, vs = 0;
5084
5085   if (horiz_mode > ONETWO || vert_mode > ONETWO)
5086     return -1;
5087
5088   Scale2Ratio(horiz_mode, &hr, &hs);
5089   Scale2Ratio(vert_mode, &vr, &vs);
5090
5091   // always go to the next whole number
5092   cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
5093   cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
5094   if (cm->current_video_frame) {
5095     assert(cm->width <= cpi->initial_width);
5096     assert(cm->height <= cpi->initial_height);
5097   }
5098
5099   update_frame_size(cpi);
5100
5101   return 0;
5102 }
5103
5104 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
5105                          unsigned int height) {
5106   VP9_COMMON *cm = &cpi->common;
5107 #if CONFIG_VP9_HIGHBITDEPTH
5108   check_initial_width(cpi, cm->use_highbitdepth, 1, 1);
5109 #else
5110   check_initial_width(cpi, 1, 1);
5111 #endif  // CONFIG_VP9_HIGHBITDEPTH
5112
5113 #if CONFIG_VP9_TEMPORAL_DENOISING
5114   setup_denoiser_buffer(cpi);
5115 #endif
5116
5117   if (width) {
5118     cm->width = width;
5119     if (cm->width > cpi->initial_width) {
5120       cm->width = cpi->initial_width;
5121       printf("Warning: Desired width too large, changed to %d\n", cm->width);
5122     }
5123   }
5124
5125   if (height) {
5126     cm->height = height;
5127     if (cm->height > cpi->initial_height) {
5128       cm->height = cpi->initial_height;
5129       printf("Warning: Desired height too large, changed to %d\n", cm->height);
5130     }
5131   }
5132   assert(cm->width <= cpi->initial_width);
5133   assert(cm->height <= cpi->initial_height);
5134
5135   update_frame_size(cpi);
5136
5137   return 0;
5138 }
5139
5140 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
5141   cpi->use_svc = use_svc;
5142   return;
5143 }
5144
5145 int vp9_get_quantizer(VP9_COMP *cpi) {
5146   return cpi->common.base_qindex;
5147 }
5148
5149 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags) {
5150   if (flags & (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF |
5151                VP8_EFLAG_NO_REF_ARF)) {
5152     int ref = 7;
5153
5154     if (flags & VP8_EFLAG_NO_REF_LAST)
5155       ref ^= VP9_LAST_FLAG;
5156
5157     if (flags & VP8_EFLAG_NO_REF_GF)
5158       ref ^= VP9_GOLD_FLAG;
5159
5160     if (flags & VP8_EFLAG_NO_REF_ARF)
5161       ref ^= VP9_ALT_FLAG;
5162
5163     vp9_use_as_reference(cpi, ref);
5164   }
5165
5166   if (flags & (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF |
5167                VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_FORCE_GF |
5168                VP8_EFLAG_FORCE_ARF)) {
5169     int upd = 7;
5170
5171     if (flags & VP8_EFLAG_NO_UPD_LAST)
5172       upd ^= VP9_LAST_FLAG;
5173
5174     if (flags & VP8_EFLAG_NO_UPD_GF)
5175       upd ^= VP9_GOLD_FLAG;
5176
5177     if (flags & VP8_EFLAG_NO_UPD_ARF)
5178       upd ^= VP9_ALT_FLAG;
5179
5180     vp9_update_reference(cpi, upd);
5181   }
5182
5183   if (flags & VP8_EFLAG_NO_UPD_ENTROPY) {
5184     vp9_update_entropy(cpi, 0);
5185   }
5186 }