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