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