]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_encoder.c
Merge "Restore vp8_sixtap_predict4x4_neon"
[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
1988         fprintf(f, "%s\t    Time\tRcErr\tAbsErr\n", headings);
1989         fprintf(f, "%s\t%8.0f\t%7.2f\t%7.2f\n", results, total_encode_time,
1990                 rate_err, fabs(rate_err));
1991       }
1992
1993       fclose(f);
1994     }
1995
1996 #endif
1997
1998 #if 0
1999     {
2000       printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2001       printf("\n_frames recive_data encod_mb_row compress_frame  Total\n");
2002       printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
2003              cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
2004              cpi->time_compress_data / 1000,
2005              (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2006     }
2007 #endif
2008   }
2009
2010 #if CONFIG_VP9_TEMPORAL_DENOISING
2011   vp9_denoiser_free(&(cpi->denoiser));
2012 #endif
2013
2014   for (t = 0; t < cpi->num_workers; ++t) {
2015     VPxWorker *const worker = &cpi->workers[t];
2016     EncWorkerData *const thread_data = &cpi->tile_thr_data[t];
2017
2018     // Deallocate allocated threads.
2019     vpx_get_worker_interface()->end(worker);
2020
2021     // Deallocate allocated thread data.
2022     if (t < cpi->num_workers - 1) {
2023       vpx_free(thread_data->td->counts);
2024       vp9_free_pc_tree(thread_data->td);
2025       vpx_free(thread_data->td);
2026     }
2027   }
2028   vpx_free(cpi->tile_thr_data);
2029   vpx_free(cpi->workers);
2030
2031   if (cpi->num_workers > 1) vp9_loop_filter_dealloc(&cpi->lf_row_sync);
2032
2033   vp9_alt_ref_aq_destroy(cpi->alt_ref_aq);
2034
2035   dealloc_compressor_data(cpi);
2036
2037   for (i = 0; i < sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]);
2038        ++i) {
2039     vpx_free(cpi->mbgraph_stats[i].mb_stats);
2040   }
2041
2042 #if CONFIG_FP_MB_STATS
2043   if (cpi->use_fp_mb_stats) {
2044     vpx_free(cpi->twopass.frame_mb_stats_buf);
2045     cpi->twopass.frame_mb_stats_buf = NULL;
2046   }
2047 #endif
2048
2049   vp9_remove_common(cm);
2050   vp9_free_ref_frame_buffers(cm->buffer_pool);
2051 #if CONFIG_VP9_POSTPROC
2052   vp9_free_postproc_buffers(cm);
2053 #endif
2054   vpx_free(cpi);
2055
2056 #if CONFIG_VP9_TEMPORAL_DENOISING
2057 #ifdef OUTPUT_YUV_DENOISED
2058   fclose(yuv_denoised_file);
2059 #endif
2060 #endif
2061 #ifdef OUTPUT_YUV_SKINMAP
2062   fclose(yuv_skinmap_file);
2063 #endif
2064 #ifdef OUTPUT_YUV_REC
2065   fclose(yuv_rec_file);
2066 #endif
2067
2068 #if 0
2069
2070   if (keyfile)
2071     fclose(keyfile);
2072
2073   if (framepsnr)
2074     fclose(framepsnr);
2075
2076   if (kf_list)
2077     fclose(kf_list);
2078
2079 #endif
2080 }
2081
2082 static void generate_psnr_packet(VP9_COMP *cpi) {
2083   struct vpx_codec_cx_pkt pkt;
2084   int i;
2085   PSNR_STATS psnr;
2086 #if CONFIG_VP9_HIGHBITDEPTH
2087   vpx_calc_highbd_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr,
2088                        cpi->td.mb.e_mbd.bd, cpi->oxcf.input_bit_depth);
2089 #else
2090   vpx_calc_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr);
2091 #endif
2092
2093   for (i = 0; i < 4; ++i) {
2094     pkt.data.psnr.samples[i] = psnr.samples[i];
2095     pkt.data.psnr.sse[i] = psnr.sse[i];
2096     pkt.data.psnr.psnr[i] = psnr.psnr[i];
2097   }
2098   pkt.kind = VPX_CODEC_PSNR_PKT;
2099   if (cpi->use_svc)
2100     cpi->svc.layer_context[cpi->svc.spatial_layer_id *
2101                            cpi->svc.number_temporal_layers]
2102         .psnr_pkt = pkt.data.psnr;
2103   else
2104     vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2105 }
2106
2107 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
2108   if (ref_frame_flags > 7) return -1;
2109
2110   cpi->ref_frame_flags = ref_frame_flags;
2111   return 0;
2112 }
2113
2114 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
2115   cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
2116   cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
2117   cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
2118   cpi->ext_refresh_frame_flags_pending = 1;
2119 }
2120
2121 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(
2122     VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag) {
2123   MV_REFERENCE_FRAME ref_frame = NONE;
2124   if (ref_frame_flag == VP9_LAST_FLAG)
2125     ref_frame = LAST_FRAME;
2126   else if (ref_frame_flag == VP9_GOLD_FLAG)
2127     ref_frame = GOLDEN_FRAME;
2128   else if (ref_frame_flag == VP9_ALT_FLAG)
2129     ref_frame = ALTREF_FRAME;
2130
2131   return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
2132 }
2133
2134 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2135                            YV12_BUFFER_CONFIG *sd) {
2136   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2137   if (cfg) {
2138     vp8_yv12_copy_frame(cfg, sd);
2139     return 0;
2140   } else {
2141     return -1;
2142   }
2143 }
2144
2145 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2146                           YV12_BUFFER_CONFIG *sd) {
2147   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2148   if (cfg) {
2149     vp8_yv12_copy_frame(sd, cfg);
2150     return 0;
2151   } else {
2152     return -1;
2153   }
2154 }
2155
2156 int vp9_update_entropy(VP9_COMP *cpi, int update) {
2157   cpi->ext_refresh_frame_context = update;
2158   cpi->ext_refresh_frame_context_pending = 1;
2159   return 0;
2160 }
2161
2162 #if defined(OUTPUT_YUV_DENOISED) || defined(OUTPUT_YUV_SKINMAP)
2163 // The denoiser buffer is allocated as a YUV 440 buffer. This function writes it
2164 // as YUV 420. We simply use the top-left pixels of the UV buffers, since we do
2165 // not denoise the UV channels at this time. If ever we implement UV channel
2166 // denoising we will have to modify this.
2167 void vp9_write_yuv_frame_420(YV12_BUFFER_CONFIG *s, FILE *f) {
2168   uint8_t *src = s->y_buffer;
2169   int h = s->y_height;
2170
2171   do {
2172     fwrite(src, s->y_width, 1, f);
2173     src += s->y_stride;
2174   } while (--h);
2175
2176   src = s->u_buffer;
2177   h = s->uv_height;
2178
2179   do {
2180     fwrite(src, s->uv_width, 1, f);
2181     src += s->uv_stride;
2182   } while (--h);
2183
2184   src = s->v_buffer;
2185   h = s->uv_height;
2186
2187   do {
2188     fwrite(src, s->uv_width, 1, f);
2189     src += s->uv_stride;
2190   } while (--h);
2191 }
2192 #endif
2193
2194 #ifdef OUTPUT_YUV_REC
2195 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2196   YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2197   uint8_t *src = s->y_buffer;
2198   int h = cm->height;
2199
2200 #if CONFIG_VP9_HIGHBITDEPTH
2201   if (s->flags & YV12_FLAG_HIGHBITDEPTH) {
2202     uint16_t *src16 = CONVERT_TO_SHORTPTR(s->y_buffer);
2203
2204     do {
2205       fwrite(src16, s->y_width, 2, yuv_rec_file);
2206       src16 += s->y_stride;
2207     } while (--h);
2208
2209     src16 = CONVERT_TO_SHORTPTR(s->u_buffer);
2210     h = s->uv_height;
2211
2212     do {
2213       fwrite(src16, s->uv_width, 2, yuv_rec_file);
2214       src16 += s->uv_stride;
2215     } while (--h);
2216
2217     src16 = CONVERT_TO_SHORTPTR(s->v_buffer);
2218     h = s->uv_height;
2219
2220     do {
2221       fwrite(src16, s->uv_width, 2, yuv_rec_file);
2222       src16 += s->uv_stride;
2223     } while (--h);
2224
2225     fflush(yuv_rec_file);
2226     return;
2227   }
2228 #endif  // CONFIG_VP9_HIGHBITDEPTH
2229
2230   do {
2231     fwrite(src, s->y_width, 1, yuv_rec_file);
2232     src += s->y_stride;
2233   } while (--h);
2234
2235   src = s->u_buffer;
2236   h = s->uv_height;
2237
2238   do {
2239     fwrite(src, s->uv_width, 1, yuv_rec_file);
2240     src += s->uv_stride;
2241   } while (--h);
2242
2243   src = s->v_buffer;
2244   h = s->uv_height;
2245
2246   do {
2247     fwrite(src, s->uv_width, 1, yuv_rec_file);
2248     src += s->uv_stride;
2249   } while (--h);
2250
2251   fflush(yuv_rec_file);
2252 }
2253 #endif
2254
2255 #if CONFIG_VP9_HIGHBITDEPTH
2256 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2257                                                 YV12_BUFFER_CONFIG *dst,
2258                                                 int bd) {
2259 #else
2260 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2261                                                 YV12_BUFFER_CONFIG *dst) {
2262 #endif  // CONFIG_VP9_HIGHBITDEPTH
2263   // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
2264   int i;
2265   const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2266                                    src->v_buffer };
2267   const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2268   const int src_widths[3] = { src->y_crop_width, src->uv_crop_width,
2269                               src->uv_crop_width };
2270   const int src_heights[3] = { src->y_crop_height, src->uv_crop_height,
2271                                src->uv_crop_height };
2272   uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2273   const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2274   const int dst_widths[3] = { dst->y_crop_width, dst->uv_crop_width,
2275                               dst->uv_crop_width };
2276   const int dst_heights[3] = { dst->y_crop_height, dst->uv_crop_height,
2277                                dst->uv_crop_height };
2278
2279   for (i = 0; i < MAX_MB_PLANE; ++i) {
2280 #if CONFIG_VP9_HIGHBITDEPTH
2281     if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2282       vp9_highbd_resize_plane(srcs[i], src_heights[i], src_widths[i],
2283                               src_strides[i], dsts[i], dst_heights[i],
2284                               dst_widths[i], dst_strides[i], bd);
2285     } else {
2286       vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2287                        dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2288     }
2289 #else
2290     vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2291                      dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2292 #endif  // CONFIG_VP9_HIGHBITDEPTH
2293   }
2294   vpx_extend_frame_borders(dst);
2295 }
2296
2297 #if CONFIG_VP9_HIGHBITDEPTH
2298 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
2299                                    YV12_BUFFER_CONFIG *dst, int bd) {
2300   const int src_w = src->y_crop_width;
2301   const int src_h = src->y_crop_height;
2302   const int dst_w = dst->y_crop_width;
2303   const int dst_h = dst->y_crop_height;
2304   const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2305                                    src->v_buffer };
2306   const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2307   uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2308   const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2309   const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2310   int x, y, i;
2311
2312   for (i = 0; i < MAX_MB_PLANE; ++i) {
2313     const int factor = (i == 0 || i == 3 ? 1 : 2);
2314     const int src_stride = src_strides[i];
2315     const int dst_stride = dst_strides[i];
2316     for (y = 0; y < dst_h; y += 16) {
2317       const int y_q4 = y * (16 / factor) * src_h / dst_h;
2318       for (x = 0; x < dst_w; x += 16) {
2319         const int x_q4 = x * (16 / factor) * src_w / dst_w;
2320         const uint8_t *src_ptr = srcs[i] +
2321                                  (y / factor) * src_h / dst_h * src_stride +
2322                                  (x / factor) * src_w / dst_w;
2323         uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2324
2325         if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2326           vpx_highbd_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
2327                                kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2328                                kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2329                                16 / factor, 16 / factor, bd);
2330         } else {
2331           vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2332                         kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2333                         kernel[y_q4 & 0xf], 16 * src_h / dst_h, 16 / factor,
2334                         16 / factor);
2335         }
2336       }
2337     }
2338   }
2339
2340   vpx_extend_frame_borders(dst);
2341 }
2342 #else
2343 void vp9_scale_and_extend_frame_c(const YV12_BUFFER_CONFIG *src,
2344                                   YV12_BUFFER_CONFIG *dst) {
2345   const int src_w = src->y_crop_width;
2346   const int src_h = src->y_crop_height;
2347   const int dst_w = dst->y_crop_width;
2348   const int dst_h = dst->y_crop_height;
2349   const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2350                                    src->v_buffer };
2351   const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2352   uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2353   const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2354   const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2355   int x, y, i;
2356
2357   for (i = 0; i < MAX_MB_PLANE; ++i) {
2358     const int factor = (i == 0 || i == 3 ? 1 : 2);
2359     const int src_stride = src_strides[i];
2360     const int dst_stride = dst_strides[i];
2361     for (y = 0; y < dst_h; y += 16) {
2362       const int y_q4 = y * (16 / factor) * src_h / dst_h;
2363       for (x = 0; x < dst_w; x += 16) {
2364         const int x_q4 = x * (16 / factor) * src_w / dst_w;
2365         const uint8_t *src_ptr = srcs[i] +
2366                                  (y / factor) * src_h / dst_h * src_stride +
2367                                  (x / factor) * src_w / dst_w;
2368         uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2369
2370         vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2371                       kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2372                       kernel[y_q4 & 0xf], 16 * src_h / dst_h, 16 / factor,
2373                       16 / factor);
2374       }
2375     }
2376   }
2377
2378   vpx_extend_frame_borders(dst);
2379 }
2380 #endif  // CONFIG_VP9_HIGHBITDEPTH
2381
2382 static int scale_down(VP9_COMP *cpi, int q) {
2383   RATE_CONTROL *const rc = &cpi->rc;
2384   GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2385   int scale = 0;
2386   assert(frame_is_kf_gf_arf(cpi));
2387
2388   if (rc->frame_size_selector == UNSCALED &&
2389       q >= rc->rf_level_maxq[gf_group->rf_level[gf_group->index]]) {
2390     const int max_size_thresh =
2391         (int)(rate_thresh_mult[SCALE_STEP1] *
2392               VPXMAX(rc->this_frame_target, rc->avg_frame_bandwidth));
2393     scale = rc->projected_frame_size > max_size_thresh ? 1 : 0;
2394   }
2395   return scale;
2396 }
2397
2398 static int big_rate_miss(VP9_COMP *cpi, int high_limit, int low_limit) {
2399   const RATE_CONTROL *const rc = &cpi->rc;
2400
2401   return (rc->projected_frame_size > ((high_limit * 3) / 2)) ||
2402          (rc->projected_frame_size < (low_limit / 2));
2403 }
2404
2405 // test in two pass for the first
2406 static int two_pass_first_group_inter(VP9_COMP *cpi) {
2407   TWO_PASS *const twopass = &cpi->twopass;
2408   GF_GROUP *const gf_group = &twopass->gf_group;
2409   if ((cpi->oxcf.pass == 2) &&
2410       (gf_group->index == gf_group->first_inter_index)) {
2411     return 1;
2412   } else {
2413     return 0;
2414   }
2415 }
2416
2417 // Function to test for conditions that indicate we should loop
2418 // back and recode a frame.
2419 static int recode_loop_test(VP9_COMP *cpi, int high_limit, int low_limit, int q,
2420                             int maxq, int minq) {
2421   const RATE_CONTROL *const rc = &cpi->rc;
2422   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2423   const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
2424   int force_recode = 0;
2425
2426   if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
2427       big_rate_miss(cpi, high_limit, low_limit) ||
2428       (cpi->sf.recode_loop == ALLOW_RECODE) ||
2429       (two_pass_first_group_inter(cpi) &&
2430        (cpi->sf.recode_loop == ALLOW_RECODE_FIRST)) ||
2431       (frame_is_kfgfarf && (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF))) {
2432     if (frame_is_kfgfarf && (oxcf->resize_mode == RESIZE_DYNAMIC) &&
2433         scale_down(cpi, q)) {
2434       // Code this group at a lower resolution.
2435       cpi->resize_pending = 1;
2436       return 1;
2437     }
2438
2439     // TODO(agrange) high_limit could be greater than the scale-down threshold.
2440     if ((rc->projected_frame_size > high_limit && q < maxq) ||
2441         (rc->projected_frame_size < low_limit && q > minq)) {
2442       force_recode = 1;
2443     } else if (cpi->oxcf.rc_mode == VPX_CQ) {
2444       // Deal with frame undershoot and whether or not we are
2445       // below the automatically set cq level.
2446       if (q > oxcf->cq_level &&
2447           rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
2448         force_recode = 1;
2449       }
2450     }
2451   }
2452   return force_recode;
2453 }
2454
2455 void vp9_update_reference_frames(VP9_COMP *cpi) {
2456   VP9_COMMON *const cm = &cpi->common;
2457   BufferPool *const pool = cm->buffer_pool;
2458
2459   // At this point the new frame has been encoded.
2460   // If any buffer copy / swapping is signaled it should be done here.
2461   if (cm->frame_type == KEY_FRAME) {
2462     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
2463                cm->new_fb_idx);
2464     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->alt_fb_idx],
2465                cm->new_fb_idx);
2466   } else if (vp9_preserve_existing_gf(cpi)) {
2467     // We have decided to preserve the previously existing golden frame as our
2468     // new ARF frame. However, in the short term in function
2469     // vp9_get_refresh_mask() we left it in the GF slot and, if
2470     // we're updating the GF with the current decoded frame, we save it to the
2471     // ARF slot instead.
2472     // We now have to update the ARF with the current frame and swap gld_fb_idx
2473     // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
2474     // slot and, if we're updating the GF, the current frame becomes the new GF.
2475     int tmp;
2476
2477     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->alt_fb_idx],
2478                cm->new_fb_idx);
2479
2480     tmp = cpi->alt_fb_idx;
2481     cpi->alt_fb_idx = cpi->gld_fb_idx;
2482     cpi->gld_fb_idx = tmp;
2483
2484     if (is_two_pass_svc(cpi)) {
2485       cpi->svc.layer_context[0].gold_ref_idx = cpi->gld_fb_idx;
2486       cpi->svc.layer_context[0].alt_ref_idx = cpi->alt_fb_idx;
2487     }
2488   } else { /* For non key/golden frames */
2489     if (cpi->refresh_alt_ref_frame) {
2490       int arf_idx = cpi->alt_fb_idx;
2491       if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
2492         const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2493         arf_idx = gf_group->arf_update_idx[gf_group->index];
2494       }
2495
2496       ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2497       memcpy(cpi->interp_filter_selected[ALTREF_FRAME],
2498              cpi->interp_filter_selected[0],
2499              sizeof(cpi->interp_filter_selected[0]));
2500     }
2501
2502     if (cpi->refresh_golden_frame) {
2503       ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
2504                  cm->new_fb_idx);
2505       if (!cpi->rc.is_src_frame_alt_ref)
2506         memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2507                cpi->interp_filter_selected[0],
2508                sizeof(cpi->interp_filter_selected[0]));
2509       else
2510         memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2511                cpi->interp_filter_selected[ALTREF_FRAME],
2512                sizeof(cpi->interp_filter_selected[ALTREF_FRAME]));
2513     }
2514   }
2515
2516   if (cpi->refresh_last_frame) {
2517     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
2518                cm->new_fb_idx);
2519     if (!cpi->rc.is_src_frame_alt_ref)
2520       memcpy(cpi->interp_filter_selected[LAST_FRAME],
2521              cpi->interp_filter_selected[0],
2522              sizeof(cpi->interp_filter_selected[0]));
2523   }
2524 #if CONFIG_VP9_TEMPORAL_DENOISING
2525   if (cpi->oxcf.noise_sensitivity > 0 &&
2526       cpi->denoiser.denoising_level > kDenLowLow) {
2527     vp9_denoiser_update_frame_info(
2528         &cpi->denoiser, *cpi->Source, cpi->common.frame_type,
2529         cpi->refresh_alt_ref_frame, cpi->refresh_golden_frame,
2530         cpi->refresh_last_frame, cpi->resize_pending);
2531   }
2532 #endif
2533   if (is_one_pass_cbr_svc(cpi)) {
2534     // Keep track of frame index for each reference frame.
2535     SVC *const svc = &cpi->svc;
2536     if (cm->frame_type == KEY_FRAME) {
2537       svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2538       svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2539       svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2540     } else {
2541       if (cpi->refresh_last_frame)
2542         svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2543       if (cpi->refresh_golden_frame)
2544         svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2545       if (cpi->refresh_alt_ref_frame)
2546         svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2547     }
2548   }
2549 }
2550
2551 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2552   MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
2553   struct loopfilter *lf = &cm->lf;
2554
2555   if (xd->lossless) {
2556     lf->filter_level = 0;
2557     lf->last_filt_level = 0;
2558   } else {
2559     struct vpx_usec_timer timer;
2560
2561     vpx_clear_system_state();
2562
2563     vpx_usec_timer_start(&timer);
2564
2565     if (!cpi->rc.is_src_frame_alt_ref) {
2566       if ((cpi->common.frame_type == KEY_FRAME) &&
2567           (!cpi->rc.this_key_frame_forced)) {
2568         lf->last_filt_level = 0;
2569       }
2570       vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
2571       lf->last_filt_level = lf->filter_level;
2572     } else {
2573       lf->filter_level = 0;
2574     }
2575
2576     vpx_usec_timer_mark(&timer);
2577     cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2578   }
2579
2580   if (lf->filter_level > 0) {
2581     vp9_build_mask_frame(cm, lf->filter_level, 0);
2582
2583     if (cpi->num_workers > 1)
2584       vp9_loop_filter_frame_mt(cm->frame_to_show, cm, xd->plane,
2585                                lf->filter_level, 0, 0, cpi->workers,
2586                                cpi->num_workers, &cpi->lf_row_sync);
2587     else
2588       vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
2589   }
2590
2591   vpx_extend_frame_inner_borders(cm->frame_to_show);
2592 }
2593
2594 static INLINE void alloc_frame_mvs(VP9_COMMON *const cm, int buffer_idx) {
2595   RefCntBuffer *const new_fb_ptr = &cm->buffer_pool->frame_bufs[buffer_idx];
2596   if (new_fb_ptr->mvs == NULL || new_fb_ptr->mi_rows < cm->mi_rows ||
2597       new_fb_ptr->mi_cols < cm->mi_cols) {
2598     vpx_free(new_fb_ptr->mvs);
2599     CHECK_MEM_ERROR(cm, new_fb_ptr->mvs,
2600                     (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
2601                                          sizeof(*new_fb_ptr->mvs)));
2602     new_fb_ptr->mi_rows = cm->mi_rows;
2603     new_fb_ptr->mi_cols = cm->mi_cols;
2604   }
2605 }
2606
2607 void vp9_scale_references(VP9_COMP *cpi) {
2608   VP9_COMMON *cm = &cpi->common;
2609   MV_REFERENCE_FRAME ref_frame;
2610   const VP9_REFFRAME ref_mask[3] = { VP9_LAST_FLAG, VP9_GOLD_FLAG,
2611                                      VP9_ALT_FLAG };
2612
2613   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2614     // Need to convert from VP9_REFFRAME to index into ref_mask (subtract 1).
2615     if (cpi->ref_frame_flags & ref_mask[ref_frame - 1]) {
2616       BufferPool *const pool = cm->buffer_pool;
2617       const YV12_BUFFER_CONFIG *const ref =
2618           get_ref_frame_buffer(cpi, ref_frame);
2619
2620       if (ref == NULL) {
2621         cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2622         continue;
2623       }
2624
2625 #if CONFIG_VP9_HIGHBITDEPTH
2626       if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2627         RefCntBuffer *new_fb_ptr = NULL;
2628         int force_scaling = 0;
2629         int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2630         if (new_fb == INVALID_IDX) {
2631           new_fb = get_free_fb(cm);
2632           force_scaling = 1;
2633         }
2634         if (new_fb == INVALID_IDX) return;
2635         new_fb_ptr = &pool->frame_bufs[new_fb];
2636         if (force_scaling || new_fb_ptr->buf.y_crop_width != cm->width ||
2637             new_fb_ptr->buf.y_crop_height != cm->height) {
2638           if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2639                                        cm->subsampling_x, cm->subsampling_y,
2640                                        cm->use_highbitdepth,
2641                                        VP9_ENC_BORDER_IN_PIXELS,
2642                                        cm->byte_alignment, NULL, NULL, NULL))
2643             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2644                                "Failed to allocate frame buffer");
2645           scale_and_extend_frame(ref, &new_fb_ptr->buf, (int)cm->bit_depth);
2646           cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2647           alloc_frame_mvs(cm, new_fb);
2648         }
2649 #else
2650       if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2651         RefCntBuffer *new_fb_ptr = NULL;
2652         int force_scaling = 0;
2653         int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2654         if (new_fb == INVALID_IDX) {
2655           new_fb = get_free_fb(cm);
2656           force_scaling = 1;
2657         }
2658         if (new_fb == INVALID_IDX) return;
2659         new_fb_ptr = &pool->frame_bufs[new_fb];
2660         if (force_scaling || new_fb_ptr->buf.y_crop_width != cm->width ||
2661             new_fb_ptr->buf.y_crop_height != cm->height) {
2662           if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2663                                        cm->subsampling_x, cm->subsampling_y,
2664                                        VP9_ENC_BORDER_IN_PIXELS,
2665                                        cm->byte_alignment, NULL, NULL, NULL))
2666             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2667                                "Failed to allocate frame buffer");
2668           vp9_scale_and_extend_frame(ref, &new_fb_ptr->buf);
2669           cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2670           alloc_frame_mvs(cm, new_fb);
2671         }
2672 #endif  // CONFIG_VP9_HIGHBITDEPTH
2673       } else {
2674         int buf_idx;
2675         RefCntBuffer *buf = NULL;
2676         if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2677           // Check for release of scaled reference.
2678           buf_idx = cpi->scaled_ref_idx[ref_frame - 1];
2679           buf = (buf_idx != INVALID_IDX) ? &pool->frame_bufs[buf_idx] : NULL;
2680           if (buf != NULL) {
2681             --buf->ref_count;
2682             cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2683           }
2684         }
2685         buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
2686         buf = &pool->frame_bufs[buf_idx];
2687         buf->buf.y_crop_width = ref->y_crop_width;
2688         buf->buf.y_crop_height = ref->y_crop_height;
2689         cpi->scaled_ref_idx[ref_frame - 1] = buf_idx;
2690         ++buf->ref_count;
2691       }
2692     } else {
2693       if (cpi->oxcf.pass != 0 || cpi->use_svc)
2694         cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2695     }
2696   }
2697 }
2698
2699 static void release_scaled_references(VP9_COMP *cpi) {
2700   VP9_COMMON *cm = &cpi->common;
2701   int i;
2702   if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2703     // Only release scaled references under certain conditions:
2704     // if reference will be updated, or if scaled reference has same resolution.
2705     int refresh[3];
2706     refresh[0] = (cpi->refresh_last_frame) ? 1 : 0;
2707     refresh[1] = (cpi->refresh_golden_frame) ? 1 : 0;
2708     refresh[2] = (cpi->refresh_alt_ref_frame) ? 1 : 0;
2709     for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2710       const int idx = cpi->scaled_ref_idx[i - 1];
2711       RefCntBuffer *const buf =
2712           idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[idx] : NULL;
2713       const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, i);
2714       if (buf != NULL &&
2715           (refresh[i - 1] || (buf->buf.y_crop_width == ref->y_crop_width &&
2716                               buf->buf.y_crop_height == ref->y_crop_height))) {
2717         --buf->ref_count;
2718         cpi->scaled_ref_idx[i - 1] = INVALID_IDX;
2719       }
2720     }
2721   } else {
2722     for (i = 0; i < MAX_REF_FRAMES; ++i) {
2723       const int idx = cpi->scaled_ref_idx[i];
2724       RefCntBuffer *const buf =
2725           idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[idx] : NULL;
2726       if (buf != NULL) {
2727         --buf->ref_count;
2728         cpi->scaled_ref_idx[i] = INVALID_IDX;
2729       }
2730     }
2731   }
2732 }
2733
2734 static void full_to_model_count(unsigned int *model_count,
2735                                 unsigned int *full_count) {
2736   int n;
2737   model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2738   model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2739   model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2740   for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
2741     model_count[TWO_TOKEN] += full_count[n];
2742   model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
2743 }
2744
2745 static void full_to_model_counts(vp9_coeff_count_model *model_count,
2746                                  vp9_coeff_count *full_count) {
2747   int i, j, k, l;
2748
2749   for (i = 0; i < PLANE_TYPES; ++i)
2750     for (j = 0; j < REF_TYPES; ++j)
2751       for (k = 0; k < COEF_BANDS; ++k)
2752         for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
2753           full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2754 }
2755
2756 #if 0 && CONFIG_INTERNAL_STATS
2757 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2758   VP9_COMMON *const cm = &cpi->common;
2759   FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2760   int64_t recon_err;
2761
2762   vpx_clear_system_state();
2763
2764 #if CONFIG_VP9_HIGHBITDEPTH
2765   if (cm->use_highbitdepth) {
2766     recon_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2767   } else {
2768     recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2769   }
2770 #else
2771   recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2772 #endif  // CONFIG_VP9_HIGHBITDEPTH
2773
2774
2775   if (cpi->twopass.total_left_stats.coded_error != 0.0) {
2776     double dc_quant_devisor;
2777 #if CONFIG_VP9_HIGHBITDEPTH
2778     switch (cm->bit_depth) {
2779       case VPX_BITS_8:
2780         dc_quant_devisor = 4.0;
2781         break;
2782       case VPX_BITS_10:
2783         dc_quant_devisor = 16.0;
2784         break;
2785       case VPX_BITS_12:
2786         dc_quant_devisor = 64.0;
2787         break;
2788       default:
2789         assert(0 && "bit_depth must be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
2790         break;
2791     }
2792 #else
2793     dc_quant_devisor = 4.0;
2794 #endif
2795
2796     fprintf(f, "%10u %dx%d %10d %10d %d %d %10d %10d %10d %10d"
2797        "%10"PRId64" %10"PRId64" %5d %5d %10"PRId64" "
2798        "%10"PRId64" %10"PRId64" %10d "
2799        "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
2800         "%6d %6d %5d %5d %5d "
2801         "%10"PRId64" %10.3lf"
2802         "%10lf %8u %10"PRId64" %10d %10d %10d %10d %10d\n",
2803         cpi->common.current_video_frame,
2804         cm->width, cm->height,
2805         cpi->td.rd_counts.m_search_count,
2806         cpi->td.rd_counts.ex_search_count,
2807         cpi->rc.source_alt_ref_pending,
2808         cpi->rc.source_alt_ref_active,
2809         cpi->rc.this_frame_target,
2810         cpi->rc.projected_frame_size,
2811         cpi->rc.projected_frame_size / cpi->common.MBs,
2812         (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2813         cpi->rc.vbr_bits_off_target,
2814         cpi->rc.vbr_bits_off_target_fast,
2815         cpi->twopass.extend_minq,
2816         cpi->twopass.extend_minq_fast,
2817         cpi->rc.total_target_vs_actual,
2818         (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
2819         cpi->rc.total_actual_bits, cm->base_qindex,
2820         vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth),
2821         (double)vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) /
2822             dc_quant_devisor,
2823         vp9_convert_qindex_to_q(cpi->twopass.active_worst_quality,
2824                                 cm->bit_depth),
2825         cpi->rc.avg_q,
2826         vp9_convert_qindex_to_q(cpi->oxcf.cq_level, cm->bit_depth),
2827         cpi->refresh_last_frame, cpi->refresh_golden_frame,
2828         cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2829         cpi->twopass.bits_left,
2830         cpi->twopass.total_left_stats.coded_error,
2831         cpi->twopass.bits_left /
2832             (1 + cpi->twopass.total_left_stats.coded_error),
2833         cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2834         cpi->twopass.kf_zeromotion_pct,
2835         cpi->twopass.fr_content_type,
2836         cm->lf.filter_level,
2837         cm->seg.aq_av_offset);
2838   }
2839   fclose(f);
2840
2841   if (0) {
2842     FILE *const fmodes = fopen("Modes.stt", "a");
2843     int i;
2844
2845     fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2846             cm->frame_type, cpi->refresh_golden_frame,
2847             cpi->refresh_alt_ref_frame);
2848
2849     for (i = 0; i < MAX_MODES; ++i)
2850       fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2851
2852     fprintf(fmodes, "\n");
2853
2854     fclose(fmodes);
2855   }
2856 }
2857 #endif
2858
2859 static void set_mv_search_params(VP9_COMP *cpi) {
2860   const VP9_COMMON *const cm = &cpi->common;
2861   const unsigned int max_mv_def = VPXMIN(cm->width, cm->height);
2862
2863   // Default based on max resolution.
2864   cpi->mv_step_param = vp9_init_search_range(max_mv_def);
2865
2866   if (cpi->sf.mv.auto_mv_step_size) {
2867     if (frame_is_intra_only(cm)) {
2868       // Initialize max_mv_magnitude for use in the first INTER frame
2869       // after a key/intra-only frame.
2870       cpi->max_mv_magnitude = max_mv_def;
2871     } else {
2872       if (cm->show_frame) {
2873         // Allow mv_steps to correspond to twice the max mv magnitude found
2874         // in the previous frame, capped by the default max_mv_magnitude based
2875         // on resolution.
2876         cpi->mv_step_param = vp9_init_search_range(
2877             VPXMIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2878       }
2879       cpi->max_mv_magnitude = 0;
2880     }
2881   }
2882 }
2883
2884 static void set_size_independent_vars(VP9_COMP *cpi) {
2885   vp9_set_speed_features_framesize_independent(cpi);
2886   vp9_set_rd_speed_thresholds(cpi);
2887   vp9_set_rd_speed_thresholds_sub8x8(cpi);
2888   cpi->common.interp_filter = cpi->sf.default_interp_filter;
2889 }
2890
2891 static void set_size_dependent_vars(VP9_COMP *cpi, int *q, int *bottom_index,
2892                                     int *top_index) {
2893   VP9_COMMON *const cm = &cpi->common;
2894   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2895
2896   // Setup variables that depend on the dimensions of the frame.
2897   vp9_set_speed_features_framesize_dependent(cpi);
2898
2899   // Decide q and q bounds.
2900   *q = vp9_rc_pick_q_and_bounds(cpi, bottom_index, top_index);
2901
2902   if (!frame_is_intra_only(cm)) {
2903     vp9_set_high_precision_mv(cpi, (*q) < HIGH_PRECISION_MV_QTHRESH);
2904   }
2905
2906   // Configure experimental use of segmentation for enhanced coding of
2907   // static regions if indicated.
2908   // Only allowed in the second pass of a two pass encode, as it requires
2909   // lagged coding, and if the relevant speed feature flag is set.
2910   if (oxcf->pass == 2 && cpi->sf.static_segmentation)
2911     configure_static_seg_features(cpi);
2912
2913 #if CONFIG_VP9_POSTPROC && !(CONFIG_VP9_TEMPORAL_DENOISING)
2914   if (oxcf->noise_sensitivity > 0) {
2915     int l = 0;
2916     switch (oxcf->noise_sensitivity) {
2917       case 1: l = 20; break;
2918       case 2: l = 40; break;
2919       case 3: l = 60; break;
2920       case 4:
2921       case 5: l = 100; break;
2922       case 6: l = 150; break;
2923     }
2924     if (!cpi->common.postproc_state.limits) {
2925       cpi->common.postproc_state.limits = vpx_calloc(
2926           cpi->common.width, sizeof(*cpi->common.postproc_state.limits));
2927     }
2928     vp9_denoise(cpi->Source, cpi->Source, l, cpi->common.postproc_state.limits);
2929   }
2930 #endif  // CONFIG_VP9_POSTPROC
2931 }
2932
2933 #if CONFIG_VP9_TEMPORAL_DENOISING
2934 static void setup_denoiser_buffer(VP9_COMP *cpi) {
2935   VP9_COMMON *const cm = &cpi->common;
2936   if (cpi->oxcf.noise_sensitivity > 0 &&
2937       !cpi->denoiser.frame_buffer_initialized) {
2938     if (vp9_denoiser_alloc(&cpi->denoiser, cm->width, cm->height,
2939                            cm->subsampling_x, cm->subsampling_y,
2940 #if CONFIG_VP9_HIGHBITDEPTH
2941                            cm->use_highbitdepth,
2942 #endif
2943                            VP9_ENC_BORDER_IN_PIXELS))
2944       vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2945                          "Failed to allocate denoiser");
2946   }
2947 }
2948 #endif
2949
2950 static void init_motion_estimation(VP9_COMP *cpi) {
2951   int y_stride = cpi->scaled_source.y_stride;
2952
2953   if (cpi->sf.mv.search_method == NSTEP) {
2954     vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
2955   } else if (cpi->sf.mv.search_method == DIAMOND) {
2956     vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
2957   }
2958 }
2959
2960 static void set_frame_size(VP9_COMP *cpi) {
2961   int ref_frame;
2962   VP9_COMMON *const cm = &cpi->common;
2963   VP9EncoderConfig *const oxcf = &cpi->oxcf;
2964   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
2965
2966   if (oxcf->pass == 2 && oxcf->rc_mode == VPX_VBR &&
2967       ((oxcf->resize_mode == RESIZE_FIXED && cm->current_video_frame == 0) ||
2968        (oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending))) {
2969     calculate_coded_size(cpi, &oxcf->scaled_frame_width,
2970                          &oxcf->scaled_frame_height);
2971
2972     // There has been a change in frame size.
2973     vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
2974                          oxcf->scaled_frame_height);
2975   }
2976
2977   if (oxcf->pass == 0 && oxcf->rc_mode == VPX_CBR && !cpi->use_svc &&
2978       oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending != 0) {
2979     oxcf->scaled_frame_width =
2980         (oxcf->width * cpi->resize_scale_num) / cpi->resize_scale_den;
2981     oxcf->scaled_frame_height =
2982         (oxcf->height * cpi->resize_scale_num) / cpi->resize_scale_den;
2983     // There has been a change in frame size.
2984     vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
2985                          oxcf->scaled_frame_height);
2986
2987     // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
2988     set_mv_search_params(cpi);
2989
2990     vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
2991 #if CONFIG_VP9_TEMPORAL_DENOISING
2992     // Reset the denoiser on the resized frame.
2993     if (cpi->oxcf.noise_sensitivity > 0) {
2994       vp9_denoiser_free(&(cpi->denoiser));
2995       setup_denoiser_buffer(cpi);
2996       // Dynamic resize is only triggered for non-SVC, so we can force
2997       // golden frame update here as temporary fix to denoiser.
2998       cpi->refresh_golden_frame = 1;
2999     }
3000 #endif
3001   }
3002
3003   if ((oxcf->pass == 2) &&
3004       (!cpi->use_svc || (is_two_pass_svc(cpi) &&
3005                          cpi->svc.encode_empty_frame_state != ENCODING))) {
3006     vp9_set_target_rate(cpi);
3007   }
3008
3009   alloc_frame_mvs(cm, cm->new_fb_idx);
3010
3011   // Reset the frame pointers to the current frame size.
3012   if (vpx_realloc_frame_buffer(get_frame_new_buffer(cm), cm->width, cm->height,
3013                                cm->subsampling_x, cm->subsampling_y,
3014 #if CONFIG_VP9_HIGHBITDEPTH
3015                                cm->use_highbitdepth,
3016 #endif
3017                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
3018                                NULL, NULL, NULL))
3019     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3020                        "Failed to allocate frame buffer");
3021
3022   alloc_util_frame_buffers(cpi);
3023   init_motion_estimation(cpi);
3024
3025   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3026     RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3027     const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
3028
3029     ref_buf->idx = buf_idx;
3030
3031     if (buf_idx != INVALID_IDX) {
3032       YV12_BUFFER_CONFIG *const buf = &cm->buffer_pool->frame_bufs[buf_idx].buf;
3033       ref_buf->buf = buf;
3034 #if CONFIG_VP9_HIGHBITDEPTH
3035       vp9_setup_scale_factors_for_frame(
3036           &ref_buf->sf, buf->y_crop_width, buf->y_crop_height, cm->width,
3037           cm->height, (buf->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0);
3038 #else
3039       vp9_setup_scale_factors_for_frame(&ref_buf->sf, buf->y_crop_width,
3040                                         buf->y_crop_height, cm->width,
3041                                         cm->height);
3042 #endif  // CONFIG_VP9_HIGHBITDEPTH
3043       if (vp9_is_scaled(&ref_buf->sf)) vpx_extend_frame_borders(buf);
3044     } else {
3045       ref_buf->buf = NULL;
3046     }
3047   }
3048
3049   set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
3050 }
3051
3052 static void encode_without_recode_loop(VP9_COMP *cpi, size_t *size,
3053                                        uint8_t *dest) {
3054   VP9_COMMON *const cm = &cpi->common;
3055   int q = 0, bottom_index = 0, top_index = 0;  // Dummy variables.
3056
3057   vpx_clear_system_state();
3058
3059   set_frame_size(cpi);
3060
3061   if (is_one_pass_cbr_svc(cpi) &&
3062       cpi->un_scaled_source->y_width == cm->width << 2 &&
3063       cpi->un_scaled_source->y_height == cm->height << 2 &&
3064       cpi->svc.scaled_temp.y_width == cm->width << 1 &&
3065       cpi->svc.scaled_temp.y_height == cm->height << 1) {
3066     // For svc, if it is a 1/4x1/4 downscaling, do a two-stage scaling to take
3067     // advantage of the 1:2 optimized scaler. In the process, the 1/2x1/2
3068     // result will be saved in scaled_temp and might be used later.
3069     cpi->Source = vp9_svc_twostage_scale(
3070         cm, cpi->un_scaled_source, &cpi->scaled_source, &cpi->svc.scaled_temp);
3071     cpi->svc.scaled_one_half = 1;
3072   } else if (is_one_pass_cbr_svc(cpi) &&
3073              cpi->un_scaled_source->y_width == cm->width << 1 &&
3074              cpi->un_scaled_source->y_height == cm->height << 1 &&
3075              cpi->svc.scaled_one_half) {
3076     // If the spatial layer is 1/2x1/2 and the scaling is already done in the
3077     // two-stage scaling, use the result directly.
3078     cpi->Source = &cpi->svc.scaled_temp;
3079     cpi->svc.scaled_one_half = 0;
3080   } else {
3081     cpi->Source = vp9_scale_if_required(
3082         cm, cpi->un_scaled_source, &cpi->scaled_source, (cpi->oxcf.pass == 0));
3083   }
3084   // Unfiltered raw source used in metrics calculation if the source
3085   // has been filtered.
3086   if (is_psnr_calc_enabled(cpi)) {
3087 #ifdef ENABLE_KF_DENOISE
3088     if (is_spatial_denoise_enabled(cpi)) {
3089       cpi->raw_source_frame =
3090           vp9_scale_if_required(cm, &cpi->raw_unscaled_source,
3091                                 &cpi->raw_scaled_source, (cpi->oxcf.pass == 0));
3092     } else {
3093       cpi->raw_source_frame = cpi->Source;
3094     }
3095 #else
3096     cpi->raw_source_frame = cpi->Source;
3097 #endif
3098   }
3099
3100   // Avoid scaling last_source unless its needed.
3101   // Last source is needed if vp9_avg_source_sad() is used, or if
3102   // partition_search_type == SOURCE_VAR_BASED_PARTITION, or if noise
3103   // estimation is enabled.
3104   if (cpi->unscaled_last_source != NULL &&
3105       (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3106        (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_VBR &&
3107         cpi->oxcf.mode == REALTIME && cpi->oxcf.speed >= 5) ||
3108        cpi->sf.partition_search_type == SOURCE_VAR_BASED_PARTITION ||
3109        cpi->noise_estimate.enabled))
3110     cpi->Last_Source =
3111         vp9_scale_if_required(cm, cpi->unscaled_last_source,
3112                               &cpi->scaled_last_source, (cpi->oxcf.pass == 0));
3113
3114   if (cm->frame_type == KEY_FRAME || cpi->resize_pending != 0) {
3115     memset(cpi->consec_zero_mv, 0,
3116            cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
3117   }
3118
3119   vp9_update_noise_estimate(cpi);
3120
3121   if (cpi->oxcf.pass == 0 && cpi->oxcf.mode == REALTIME &&
3122       cpi->oxcf.speed >= 5 && cpi->resize_state == 0 &&
3123       (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3124        cpi->oxcf.rc_mode == VPX_VBR))
3125     vp9_avg_source_sad(cpi);
3126
3127   // For 1 pass SVC, since only ZEROMV is allowed for upsampled reference
3128   // frame (i.e, svc->force_zero_mode_spatial_ref = 0), we can avoid this
3129   // frame-level upsampling.
3130   if (frame_is_intra_only(cm) == 0 && !is_one_pass_cbr_svc(cpi)) {
3131     vp9_scale_references(cpi);
3132   }
3133
3134   set_size_independent_vars(cpi);
3135   set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3136
3137   if (cpi->oxcf.speed >= 5 && cpi->oxcf.pass == 0 &&
3138       cpi->oxcf.rc_mode == VPX_CBR &&
3139       cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
3140       cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3141     cpi->use_skin_detection = 1;
3142   }
3143
3144   vp9_set_quantizer(cm, q);
3145   vp9_set_variance_partition_thresholds(cpi, q);
3146
3147   setup_frame(cpi);
3148
3149   suppress_active_map(cpi);
3150
3151   // Variance adaptive and in frame q adjustment experiments are mutually
3152   // exclusive.
3153   if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3154     vp9_vaq_frame_setup(cpi);
3155   } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3156     vp9_360aq_frame_setup(cpi);
3157   } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3158     vp9_setup_in_frame_q_adj(cpi);
3159   } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3160     vp9_cyclic_refresh_setup(cpi);
3161   } else if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ) {
3162     // it may be pretty bad for rate-control,
3163     // and I should handle it somehow
3164     vp9_alt_ref_aq_setup_map(cpi->alt_ref_aq, cpi);
3165   }
3166
3167   apply_active_map(cpi);
3168
3169   vp9_encode_frame(cpi);
3170
3171   // Check if we should drop this frame because of high overshoot.
3172   // Only for frames where high temporal-source SAD is detected.
3173   if (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR &&
3174       cpi->resize_state == 0 && cm->frame_type != KEY_FRAME &&
3175       cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
3176       cpi->rc.high_source_sad == 1) {
3177     int frame_size = 0;
3178     // Get an estimate of the encoded frame size.
3179     save_coding_context(cpi);
3180     vp9_pack_bitstream(cpi, dest, size);
3181     restore_coding_context(cpi);
3182     frame_size = (int)(*size) << 3;
3183     // Check if encoded frame will overshoot too much, and if so, set the q and
3184     // adjust some rate control parameters, and return to re-encode the frame.
3185     if (vp9_encodedframe_overshoot(cpi, frame_size, &q)) {
3186       vpx_clear_system_state();
3187       vp9_set_quantizer(cm, q);
3188       vp9_set_variance_partition_thresholds(cpi, q);
3189       suppress_active_map(cpi);
3190       // Turn-off cyclic refresh for re-encoded frame.
3191       if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3192         unsigned char *const seg_map = cpi->segmentation_map;
3193         memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
3194         vp9_disable_segmentation(&cm->seg);
3195       }
3196       apply_active_map(cpi);
3197       vp9_encode_frame(cpi);
3198     }
3199   }
3200
3201   // Update some stats from cyclic refresh, and check if we should not update
3202   // golden reference, for non-SVC 1 pass CBR.
3203   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->frame_type != KEY_FRAME &&
3204       !cpi->use_svc && cpi->ext_refresh_frame_flags_pending == 0 &&
3205       (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR))
3206     vp9_cyclic_refresh_check_golden_update(cpi);
3207
3208   // Update the skip mb flag probabilities based on the distribution
3209   // seen in the last encoder iteration.
3210   // update_base_skip_probs(cpi);
3211   vpx_clear_system_state();
3212 }
3213
3214 static void encode_with_recode_loop(VP9_COMP *cpi, size_t *size,
3215                                     uint8_t *dest) {
3216   VP9_COMMON *const cm = &cpi->common;
3217   RATE_CONTROL *const rc = &cpi->rc;
3218   int bottom_index, top_index;
3219   int loop_count = 0;
3220   int loop_at_this_size = 0;
3221   int loop = 0;
3222   int overshoot_seen = 0;
3223   int undershoot_seen = 0;
3224   int frame_over_shoot_limit;
3225   int frame_under_shoot_limit;
3226   int q = 0, q_low = 0, q_high = 0;
3227
3228   set_size_independent_vars(cpi);
3229
3230   do {
3231     vpx_clear_system_state();
3232
3233     set_frame_size(cpi);
3234
3235     if (loop_count == 0 || cpi->resize_pending != 0) {
3236       set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3237
3238       // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3239       set_mv_search_params(cpi);
3240
3241       // Reset the loop state for new frame size.
3242       overshoot_seen = 0;
3243       undershoot_seen = 0;
3244
3245       // Reconfiguration for change in frame size has concluded.
3246       cpi->resize_pending = 0;
3247
3248       q_low = bottom_index;
3249       q_high = top_index;
3250
3251       loop_at_this_size = 0;
3252     }
3253
3254     // Decide frame size bounds first time through.
3255     if (loop_count == 0) {
3256       vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
3257                                        &frame_under_shoot_limit,
3258                                        &frame_over_shoot_limit);
3259     }
3260
3261     cpi->Source = vp9_scale_if_required(
3262         cm, cpi->un_scaled_source, &cpi->scaled_source, (cpi->oxcf.pass == 0));
3263
3264     // Unfiltered raw source used in metrics calculation if the source
3265     // has been filtered.
3266     if (is_psnr_calc_enabled(cpi)) {
3267 #ifdef ENABLE_KF_DENOISE
3268       if (is_spatial_denoise_enabled(cpi)) {
3269         cpi->raw_source_frame = vp9_scale_if_required(
3270             cm, &cpi->raw_unscaled_source, &cpi->raw_scaled_source,
3271             (cpi->oxcf.pass == 0));
3272       } else {
3273         cpi->raw_source_frame = cpi->Source;
3274       }
3275 #else
3276       cpi->raw_source_frame = cpi->Source;
3277 #endif
3278     }
3279
3280     if (cpi->unscaled_last_source != NULL)
3281       cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
3282                                                &cpi->scaled_last_source,
3283                                                (cpi->oxcf.pass == 0));
3284
3285     if (frame_is_intra_only(cm) == 0) {
3286       if (loop_count > 0) {
3287         release_scaled_references(cpi);
3288       }
3289       vp9_scale_references(cpi);
3290     }
3291
3292     vp9_set_quantizer(cm, q);
3293
3294     if (loop_count == 0) setup_frame(cpi);
3295
3296     // Variance adaptive and in frame q adjustment experiments are mutually
3297     // exclusive.
3298     if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3299       vp9_vaq_frame_setup(cpi);
3300     } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3301       vp9_360aq_frame_setup(cpi);
3302     } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3303       vp9_setup_in_frame_q_adj(cpi);
3304     } else if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ) {
3305       vp9_alt_ref_aq_setup_map(cpi->alt_ref_aq, cpi);
3306     }
3307
3308     vp9_encode_frame(cpi);
3309
3310     // Update the skip mb flag probabilities based on the distribution
3311     // seen in the last encoder iteration.
3312     // update_base_skip_probs(cpi);
3313
3314     vpx_clear_system_state();
3315
3316     // Dummy pack of the bitstream using up to date stats to get an
3317     // accurate estimate of output frame size to determine if we need
3318     // to recode.
3319     if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
3320       save_coding_context(cpi);
3321       if (!cpi->sf.use_nonrd_pick_mode) vp9_pack_bitstream(cpi, dest, size);
3322
3323       rc->projected_frame_size = (int)(*size) << 3;
3324       restore_coding_context(cpi);
3325
3326       if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
3327     }
3328
3329     if (cpi->oxcf.rc_mode == VPX_Q) {
3330       loop = 0;
3331     } else {
3332       if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced &&
3333           (rc->projected_frame_size < rc->max_frame_bandwidth)) {
3334         int last_q = q;
3335         int64_t kf_err;
3336
3337         int64_t high_err_target = cpi->ambient_err;
3338         int64_t low_err_target = cpi->ambient_err >> 1;
3339
3340 #if CONFIG_VP9_HIGHBITDEPTH
3341         if (cm->use_highbitdepth) {
3342           kf_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3343         } else {
3344           kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3345         }
3346 #else
3347         kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3348 #endif  // CONFIG_VP9_HIGHBITDEPTH
3349
3350         // Prevent possible divide by zero error below for perfect KF
3351         kf_err += !kf_err;
3352
3353         // The key frame is not good enough or we can afford
3354         // to make it better without undue risk of popping.
3355         if ((kf_err > high_err_target &&
3356              rc->projected_frame_size <= frame_over_shoot_limit) ||
3357             (kf_err > low_err_target &&
3358              rc->projected_frame_size <= frame_under_shoot_limit)) {
3359           // Lower q_high
3360           q_high = q > q_low ? q - 1 : q_low;
3361
3362           // Adjust Q
3363           q = (int)((q * high_err_target) / kf_err);
3364           q = VPXMIN(q, (q_high + q_low) >> 1);
3365         } else if (kf_err < low_err_target &&
3366                    rc->projected_frame_size >= frame_under_shoot_limit) {
3367           // The key frame is much better than the previous frame
3368           // Raise q_low
3369           q_low = q < q_high ? q + 1 : q_high;
3370
3371           // Adjust Q
3372           q = (int)((q * low_err_target) / kf_err);
3373           q = VPXMIN(q, (q_high + q_low + 1) >> 1);
3374         }
3375
3376         // Clamp Q to upper and lower limits:
3377         q = clamp(q, q_low, q_high);
3378
3379         loop = q != last_q;
3380       } else if (recode_loop_test(cpi, frame_over_shoot_limit,
3381                                   frame_under_shoot_limit, q,
3382                                   VPXMAX(q_high, top_index), bottom_index)) {
3383         // Is the projected frame size out of range and are we allowed
3384         // to attempt to recode.
3385         int last_q = q;
3386         int retries = 0;
3387
3388         if (cpi->resize_pending == 1) {
3389           // Change in frame size so go back around the recode loop.
3390           cpi->rc.frame_size_selector =
3391               SCALE_STEP1 - cpi->rc.frame_size_selector;
3392           cpi->rc.next_frame_size_selector = cpi->rc.frame_size_selector;
3393
3394 #if CONFIG_INTERNAL_STATS
3395           ++cpi->tot_recode_hits;
3396 #endif
3397           ++loop_count;
3398           loop = 1;
3399           continue;
3400         }
3401
3402         // Frame size out of permitted range:
3403         // Update correction factor & compute new Q to try...
3404
3405         // Frame is too large
3406         if (rc->projected_frame_size > rc->this_frame_target) {
3407           // Special case if the projected size is > the max allowed.
3408           if (rc->projected_frame_size >= rc->max_frame_bandwidth)
3409             q_high = rc->worst_quality;
3410
3411           // Raise Qlow as to at least the current value
3412           q_low = q < q_high ? q + 1 : q_high;
3413
3414           if (undershoot_seen || loop_at_this_size > 1) {
3415             // Update rate_correction_factor unless
3416             vp9_rc_update_rate_correction_factors(cpi);
3417
3418             q = (q_high + q_low + 1) / 2;
3419           } else {
3420             // Update rate_correction_factor unless
3421             vp9_rc_update_rate_correction_factors(cpi);
3422
3423             q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3424                                   VPXMAX(q_high, top_index));
3425
3426             while (q < q_low && retries < 10) {
3427               vp9_rc_update_rate_correction_factors(cpi);
3428               q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3429                                     VPXMAX(q_high, top_index));
3430               retries++;
3431             }
3432           }
3433
3434           overshoot_seen = 1;
3435         } else {
3436           // Frame is too small
3437           q_high = q > q_low ? q - 1 : q_low;
3438
3439           if (overshoot_seen || loop_at_this_size > 1) {
3440             vp9_rc_update_rate_correction_factors(cpi);
3441             q = (q_high + q_low) / 2;
3442           } else {
3443             vp9_rc_update_rate_correction_factors(cpi);
3444             q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3445                                   top_index);
3446             // Special case reset for qlow for constrained quality.
3447             // This should only trigger where there is very substantial
3448             // undershoot on a frame and the auto cq level is above
3449             // the user passsed in value.
3450             if (cpi->oxcf.rc_mode == VPX_CQ && q < q_low) {
3451               q_low = q;
3452             }
3453
3454             while (q > q_high && retries < 10) {
3455               vp9_rc_update_rate_correction_factors(cpi);
3456               q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3457                                     top_index);
3458               retries++;
3459             }
3460           }
3461
3462           undershoot_seen = 1;
3463         }
3464
3465         // Clamp Q to upper and lower limits:
3466         q = clamp(q, q_low, q_high);
3467
3468         loop = (q != last_q);
3469       } else {
3470         loop = 0;
3471       }
3472     }
3473
3474     // Special case for overlay frame.
3475     if (rc->is_src_frame_alt_ref &&
3476         rc->projected_frame_size < rc->max_frame_bandwidth)
3477       loop = 0;
3478
3479     if (loop) {
3480       ++loop_count;
3481       ++loop_at_this_size;
3482
3483 #if CONFIG_INTERNAL_STATS
3484       ++cpi->tot_recode_hits;
3485 #endif
3486     }
3487   } while (loop);
3488 }
3489
3490 static int get_ref_frame_flags(const VP9_COMP *cpi) {
3491   const int *const map = cpi->common.ref_frame_map;
3492   const int gold_is_last = map[cpi->gld_fb_idx] == map[cpi->lst_fb_idx];
3493   const int alt_is_last = map[cpi->alt_fb_idx] == map[cpi->lst_fb_idx];
3494   const int gold_is_alt = map[cpi->gld_fb_idx] == map[cpi->alt_fb_idx];
3495   int flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3496
3497   if (gold_is_last) flags &= ~VP9_GOLD_FLAG;
3498
3499   if (cpi->rc.frames_till_gf_update_due == INT_MAX &&
3500       (cpi->svc.number_temporal_layers == 1 &&
3501        cpi->svc.number_spatial_layers == 1))
3502     flags &= ~VP9_GOLD_FLAG;
3503
3504   if (alt_is_last) flags &= ~VP9_ALT_FLAG;
3505
3506   if (gold_is_alt) flags &= ~VP9_ALT_FLAG;
3507
3508   return flags;
3509 }
3510
3511 static void set_ext_overrides(VP9_COMP *cpi) {
3512   // Overrides the defaults with the externally supplied values with
3513   // vp9_update_reference() and vp9_update_entropy() calls
3514   // Note: The overrides are valid only for the next frame passed
3515   // to encode_frame_to_data_rate() function
3516   if (cpi->ext_refresh_frame_context_pending) {
3517     cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
3518     cpi->ext_refresh_frame_context_pending = 0;
3519   }
3520   if (cpi->ext_refresh_frame_flags_pending) {
3521     cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
3522     cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
3523     cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
3524   }
3525 }
3526
3527 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(VP9_COMMON *cm,
3528                                            YV12_BUFFER_CONFIG *unscaled,
3529                                            YV12_BUFFER_CONFIG *scaled,
3530                                            YV12_BUFFER_CONFIG *scaled_temp) {
3531   if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3532       cm->mi_rows * MI_SIZE != unscaled->y_height) {
3533 #if CONFIG_VP9_HIGHBITDEPTH
3534     scale_and_extend_frame(unscaled, scaled_temp, (int)cm->bit_depth);
3535     scale_and_extend_frame(scaled_temp, scaled, (int)cm->bit_depth);
3536 #else
3537     vp9_scale_and_extend_frame(unscaled, scaled_temp);
3538     vp9_scale_and_extend_frame(scaled_temp, scaled);
3539 #endif  // CONFIG_VP9_HIGHBITDEPTH
3540     return scaled;
3541   } else {
3542     return unscaled;
3543   }
3544 }
3545
3546 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
3547                                           YV12_BUFFER_CONFIG *unscaled,
3548                                           YV12_BUFFER_CONFIG *scaled,
3549                                           int use_normative_scaler) {
3550   if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3551       cm->mi_rows * MI_SIZE != unscaled->y_height) {
3552 #if CONFIG_VP9_HIGHBITDEPTH
3553     if (use_normative_scaler && unscaled->y_width <= (scaled->y_width << 1) &&
3554         unscaled->y_height <= (scaled->y_height << 1))
3555       scale_and_extend_frame(unscaled, scaled, (int)cm->bit_depth);
3556     else
3557       scale_and_extend_frame_nonnormative(unscaled, scaled, (int)cm->bit_depth);
3558 #else
3559     if (use_normative_scaler && unscaled->y_width <= (scaled->y_width << 1) &&
3560         unscaled->y_height <= (scaled->y_height << 1))
3561       vp9_scale_and_extend_frame(unscaled, scaled);
3562     else
3563       scale_and_extend_frame_nonnormative(unscaled, scaled);
3564 #endif  // CONFIG_VP9_HIGHBITDEPTH
3565     return scaled;
3566   } else {
3567     return unscaled;
3568   }
3569 }
3570
3571 static void set_arf_sign_bias(VP9_COMP *cpi) {
3572   VP9_COMMON *const cm = &cpi->common;
3573   int arf_sign_bias;
3574
3575   if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
3576     const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3577     arf_sign_bias = cpi->rc.source_alt_ref_active &&
3578                     (!cpi->refresh_alt_ref_frame ||
3579                      (gf_group->rf_level[gf_group->index] == GF_ARF_LOW));
3580   } else {
3581     arf_sign_bias =
3582         (cpi->rc.source_alt_ref_active && !cpi->refresh_alt_ref_frame);
3583   }
3584   cm->ref_frame_sign_bias[ALTREF_FRAME] = arf_sign_bias;
3585 }
3586
3587 static int setup_interp_filter_search_mask(VP9_COMP *cpi) {
3588   INTERP_FILTER ifilter;
3589   int ref_total[MAX_REF_FRAMES] = { 0 };
3590   MV_REFERENCE_FRAME ref;
3591   int mask = 0;
3592   if (cpi->common.last_frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame)
3593     return mask;
3594   for (ref = LAST_FRAME; ref <= ALTREF_FRAME; ++ref)
3595     for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter)
3596       ref_total[ref] += cpi->interp_filter_selected[ref][ifilter];
3597
3598   for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter) {
3599     if ((ref_total[LAST_FRAME] &&
3600          cpi->interp_filter_selected[LAST_FRAME][ifilter] == 0) &&
3601         (ref_total[GOLDEN_FRAME] == 0 ||
3602          cpi->interp_filter_selected[GOLDEN_FRAME][ifilter] * 50 <
3603              ref_total[GOLDEN_FRAME]) &&
3604         (ref_total[ALTREF_FRAME] == 0 ||
3605          cpi->interp_filter_selected[ALTREF_FRAME][ifilter] * 50 <
3606              ref_total[ALTREF_FRAME]))
3607       mask |= 1 << ifilter;
3608   }
3609   return mask;
3610 }
3611
3612 #ifdef ENABLE_KF_DENOISE
3613 // Baseline Kernal weights for denoise
3614 static uint8_t dn_kernal_3[9] = { 1, 2, 1, 2, 4, 2, 1, 2, 1 };
3615 static uint8_t dn_kernal_5[25] = { 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 4,
3616                                    2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1 };
3617
3618 static INLINE void add_denoise_point(int centre_val, int data_val, int thresh,
3619                                      uint8_t point_weight, int *sum_val,
3620                                      int *sum_weight) {
3621   if (abs(centre_val - data_val) <= thresh) {
3622     *sum_weight += point_weight;
3623     *sum_val += (int)data_val * (int)point_weight;
3624   }
3625 }
3626
3627 static void spatial_denoise_point(uint8_t *src_ptr, const int stride,
3628                                   const int strength) {
3629   int sum_weight = 0;
3630   int sum_val = 0;
3631   int thresh = strength;
3632   int kernal_size = 5;
3633   int half_k_size = 2;
3634   int i, j;
3635   int max_diff = 0;
3636   uint8_t *tmp_ptr;
3637   uint8_t *kernal_ptr;
3638
3639   // Find the maximum deviation from the source point in the locale.
3640   tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
3641   for (i = 0; i < kernal_size + 2; ++i) {
3642     for (j = 0; j < kernal_size + 2; ++j) {
3643       max_diff = VPXMAX(max_diff, abs((int)*src_ptr - (int)tmp_ptr[j]));
3644     }
3645     tmp_ptr += stride;
3646   }
3647
3648   // Select the kernal size.
3649   if (max_diff > (strength + (strength >> 1))) {
3650     kernal_size = 3;
3651     half_k_size = 1;
3652     thresh = thresh >> 1;
3653   }
3654   kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
3655
3656   // Apply the kernal
3657   tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
3658   for (i = 0; i < kernal_size; ++i) {
3659     for (j = 0; j < kernal_size; ++j) {
3660       add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh, *kernal_ptr,
3661                         &sum_val, &sum_weight);
3662       ++kernal_ptr;
3663     }
3664     tmp_ptr += stride;
3665   }
3666
3667   // Update the source value with the new filtered value
3668   *src_ptr = (uint8_t)((sum_val + (sum_weight >> 1)) / sum_weight);
3669 }
3670
3671 #if CONFIG_VP9_HIGHBITDEPTH
3672 static void highbd_spatial_denoise_point(uint16_t *src_ptr, const int stride,
3673                                          const int strength) {
3674   int sum_weight = 0;
3675   int sum_val = 0;
3676   int thresh = strength;
3677   int kernal_size = 5;
3678   int half_k_size = 2;
3679   int i, j;
3680   int max_diff = 0;
3681   uint16_t *tmp_ptr;
3682   uint8_t *kernal_ptr;
3683
3684   // Find the maximum deviation from the source point in the locale.
3685   tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
3686   for (i = 0; i < kernal_size + 2; ++i) {
3687     for (j = 0; j < kernal_size + 2; ++j) {
3688       max_diff = VPXMAX(max_diff, abs((int)src_ptr - (int)tmp_ptr[j]));
3689     }
3690     tmp_ptr += stride;
3691   }
3692
3693   // Select the kernal size.
3694   if (max_diff > (strength + (strength >> 1))) {
3695     kernal_size = 3;
3696     half_k_size = 1;
3697     thresh = thresh >> 1;
3698   }
3699   kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
3700
3701   // Apply the kernal
3702   tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
3703   for (i = 0; i < kernal_size; ++i) {
3704     for (j = 0; j < kernal_size; ++j) {
3705       add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh, *kernal_ptr,
3706                         &sum_val, &sum_weight);
3707       ++kernal_ptr;
3708     }
3709     tmp_ptr += stride;
3710   }
3711
3712   // Update the source value with the new filtered value
3713   *src_ptr = (uint16_t)((sum_val + (sum_weight >> 1)) / sum_weight);
3714 }
3715 #endif  // CONFIG_VP9_HIGHBITDEPTH
3716
3717 // Apply thresholded spatial noise supression to a given buffer.
3718 static void spatial_denoise_buffer(VP9_COMP *cpi, uint8_t *buffer,
3719                                    const int stride, const int width,
3720                                    const int height, const int strength) {
3721   VP9_COMMON *const cm = &cpi->common;
3722   uint8_t *src_ptr = buffer;
3723   int row;
3724   int col;
3725
3726   for (row = 0; row < height; ++row) {
3727     for (col = 0; col < width; ++col) {
3728 #if CONFIG_VP9_HIGHBITDEPTH
3729       if (cm->use_highbitdepth)
3730         highbd_spatial_denoise_point(CONVERT_TO_SHORTPTR(&src_ptr[col]), stride,
3731                                      strength);
3732       else
3733         spatial_denoise_point(&src_ptr[col], stride, strength);
3734 #else
3735       spatial_denoise_point(&src_ptr[col], stride, strength);
3736 #endif  // CONFIG_VP9_HIGHBITDEPTH
3737     }
3738     src_ptr += stride;
3739   }
3740 }
3741
3742 // Apply thresholded spatial noise supression to source.
3743 static void spatial_denoise_frame(VP9_COMP *cpi) {
3744   YV12_BUFFER_CONFIG *src = cpi->Source;
3745   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3746   TWO_PASS *const twopass = &cpi->twopass;
3747   VP9_COMMON *const cm = &cpi->common;
3748
3749   // Base the filter strength on the current active max Q.
3750   const int q = (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
3751                                               cm->bit_depth));
3752   int strength =
3753       VPXMAX(oxcf->arnr_strength >> 2, VPXMIN(oxcf->arnr_strength, (q >> 4)));
3754
3755   // Denoise each of Y,U and V buffers.
3756   spatial_denoise_buffer(cpi, src->y_buffer, src->y_stride, src->y_width,
3757                          src->y_height, strength);
3758
3759   strength += (strength >> 1);
3760   spatial_denoise_buffer(cpi, src->u_buffer, src->uv_stride, src->uv_width,
3761                          src->uv_height, strength << 1);
3762
3763   spatial_denoise_buffer(cpi, src->v_buffer, src->uv_stride, src->uv_width,
3764                          src->uv_height, strength << 1);
3765 }
3766 #endif  // ENABLE_KF_DENOISE
3767
3768 static void vp9_try_disable_lookahead_aq(VP9_COMP *cpi, size_t *size,
3769                                          uint8_t *dest) {
3770   if (cpi->common.seg.enabled)
3771     if (ALT_REF_AQ_PROTECT_GAIN) {
3772       size_t nsize = *size;
3773       int overhead;
3774
3775       // TODO(yuryg): optimize this, as
3776       // we don't really need to repack
3777
3778       save_coding_context(cpi);
3779       vp9_disable_segmentation(&cpi->common.seg);
3780       vp9_pack_bitstream(cpi, dest, &nsize);
3781       restore_coding_context(cpi);
3782
3783       overhead = (int)*size - (int)nsize;
3784
3785       if (vp9_alt_ref_aq_disable_if(cpi->alt_ref_aq, overhead, (int)*size))
3786         vp9_encode_frame(cpi);
3787       else
3788         vp9_enable_segmentation(&cpi->common.seg);
3789     }
3790 }
3791
3792 static void encode_frame_to_data_rate(VP9_COMP *cpi, size_t *size,
3793                                       uint8_t *dest,
3794                                       unsigned int *frame_flags) {
3795   VP9_COMMON *const cm = &cpi->common;
3796   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3797   struct segmentation *const seg = &cm->seg;
3798   TX_SIZE t;
3799
3800   set_ext_overrides(cpi);
3801   vpx_clear_system_state();
3802
3803 #ifdef ENABLE_KF_DENOISE
3804   // Spatial denoise of key frame.
3805   if (is_spatial_denoise_enabled(cpi)) spatial_denoise_frame(cpi);
3806 #endif
3807
3808   // Set the arf sign bias for this frame.
3809   set_arf_sign_bias(cpi);
3810
3811   // Set default state for segment based loop filter update flags.
3812   cm->lf.mode_ref_delta_update = 0;
3813
3814   if (cpi->oxcf.pass == 2 && cpi->sf.adaptive_interp_filter_search)
3815     cpi->sf.interp_filter_search_mask = setup_interp_filter_search_mask(cpi);
3816
3817   // Set various flags etc to special state if it is a key frame.
3818   if (frame_is_intra_only(cm)) {
3819     // Reset the loop filter deltas and segmentation map.
3820     vp9_reset_segment_features(&cm->seg);
3821
3822     // If segmentation is enabled force a map update for key frames.
3823     if (seg->enabled) {
3824       seg->update_map = 1;
3825       seg->update_data = 1;
3826     }
3827
3828     // The alternate reference frame cannot be active for a key frame.
3829     cpi->rc.source_alt_ref_active = 0;
3830
3831     cm->error_resilient_mode = oxcf->error_resilient_mode;
3832     cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3833
3834     // By default, encoder assumes decoder can use prev_mi.
3835     if (cm->error_resilient_mode) {
3836       cm->frame_parallel_decoding_mode = 1;
3837       cm->reset_frame_context = 0;
3838       cm->refresh_frame_context = 0;
3839     } else if (cm->intra_only) {
3840       // Only reset the current context.
3841       cm->reset_frame_context = 2;
3842     }
3843   }
3844   if (is_two_pass_svc(cpi) && cm->error_resilient_mode == 0) {
3845     // Use context 0 for intra only empty frame, but the last frame context
3846     // for other empty frames.
3847     if (cpi->svc.encode_empty_frame_state == ENCODING) {
3848       if (cpi->svc.encode_intra_empty_frame != 0)
3849         cm->frame_context_idx = 0;
3850       else
3851         cm->frame_context_idx = FRAME_CONTEXTS - 1;
3852     } else {
3853       cm->frame_context_idx =
3854           cpi->svc.spatial_layer_id * cpi->svc.number_temporal_layers +
3855           cpi->svc.temporal_layer_id;
3856     }
3857
3858     cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3859
3860     // The probs will be updated based on the frame type of its previous
3861     // frame if frame_parallel_decoding_mode is 0. The type may vary for
3862     // the frame after a key frame in base layer since we may drop enhancement
3863     // layers. So set frame_parallel_decoding_mode to 1 in this case.
3864     if (cm->frame_parallel_decoding_mode == 0) {
3865       if (cpi->svc.number_temporal_layers == 1) {
3866         if (cpi->svc.spatial_layer_id == 0 &&
3867             cpi->svc.layer_context[0].last_frame_type == KEY_FRAME)
3868           cm->frame_parallel_decoding_mode = 1;
3869       } else if (cpi->svc.spatial_layer_id == 0) {
3870         // Find the 2nd frame in temporal base layer and 1st frame in temporal
3871         // enhancement layers from the key frame.
3872         int i;
3873         for (i = 0; i < cpi->svc.number_temporal_layers; ++i) {
3874           if (cpi->svc.layer_context[0].frames_from_key_frame == 1 << i) {
3875             cm->frame_parallel_decoding_mode = 1;
3876             break;
3877           }
3878         }
3879       }
3880     }
3881   }
3882
3883   // For 1 pass CBR, check if we are dropping this frame.
3884   // For spatial layers, for now only check for frame-dropping on first spatial
3885   // layer, and if decision is to drop, we drop whole super-frame.
3886   if (oxcf->pass == 0 && oxcf->rc_mode == VPX_CBR &&
3887       cm->frame_type != KEY_FRAME) {
3888     if (vp9_rc_drop_frame(cpi) ||
3889         (is_one_pass_cbr_svc(cpi) && cpi->svc.rc_drop_superframe == 1)) {
3890       vp9_rc_postencode_update_drop_frame(cpi);
3891       ++cm->current_video_frame;
3892       cpi->ext_refresh_frame_flags_pending = 0;
3893       cpi->svc.rc_drop_superframe = 1;
3894       // TODO(marpan): Advancing the svc counters on dropped frames can break
3895       // the referencing scheme for the fixed svc patterns defined in
3896       // vp9_one_pass_cbr_svc_start_layer(). Look into fixing this issue, but
3897       // for now, don't advance the svc frame counters on dropped frame.
3898       // if (cpi->use_svc)
3899       //   vp9_inc_frame_in_layer(cpi);
3900       return;
3901     }
3902   }
3903
3904   vpx_clear_system_state();
3905
3906 #if CONFIG_INTERNAL_STATS
3907   memset(cpi->mode_chosen_counts, 0,
3908          MAX_MODES * sizeof(*cpi->mode_chosen_counts));
3909 #endif
3910
3911   if (cpi->sf.recode_loop == DISALLOW_RECODE) {
3912     encode_without_recode_loop(cpi, size, dest);
3913   } else {
3914     encode_with_recode_loop(cpi, size, dest);
3915   }
3916
3917   // Disable segmentation if it decrease rate/distortion ratio
3918   if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ)
3919     vp9_try_disable_lookahead_aq(cpi, size, dest);
3920
3921 #if CONFIG_VP9_TEMPORAL_DENOISING
3922 #ifdef OUTPUT_YUV_DENOISED
3923   if (oxcf->noise_sensitivity > 0) {
3924     vp9_write_yuv_frame_420(&cpi->denoiser.running_avg_y[INTRA_FRAME],
3925                             yuv_denoised_file);
3926   }
3927 #endif
3928 #endif
3929 #ifdef OUTPUT_YUV_SKINMAP
3930   if (cpi->common.current_video_frame > 1) {
3931     vp9_compute_skin_map(cpi, yuv_skinmap_file);
3932   }
3933 #endif
3934
3935   // Special case code to reduce pulsing when key frames are forced at a
3936   // fixed interval. Note the reconstruction error if it is the frame before
3937   // the force key frame
3938   if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
3939 #if CONFIG_VP9_HIGHBITDEPTH
3940     if (cm->use_highbitdepth) {
3941       cpi->ambient_err =
3942           vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3943     } else {
3944       cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3945     }
3946 #else
3947     cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3948 #endif  // CONFIG_VP9_HIGHBITDEPTH
3949   }
3950
3951   // If the encoder forced a KEY_FRAME decision
3952   if (cm->frame_type == KEY_FRAME) cpi->refresh_last_frame = 1;
3953
3954   cm->frame_to_show = get_frame_new_buffer(cm);
3955   cm->frame_to_show->color_space = cm->color_space;
3956   cm->frame_to_show->color_range = cm->color_range;
3957   cm->frame_to_show->render_width = cm->render_width;
3958   cm->frame_to_show->render_height = cm->render_height;
3959
3960   // Pick the loop filter level for the frame.
3961   loopfilter_frame(cpi, cm);
3962
3963   // build the bitstream
3964   vp9_pack_bitstream(cpi, dest, size);
3965
3966   if (cm->seg.update_map) update_reference_segmentation_map(cpi);
3967
3968   if (frame_is_intra_only(cm) == 0) {
3969     release_scaled_references(cpi);
3970   }
3971   vp9_update_reference_frames(cpi);
3972
3973   for (t = TX_4X4; t <= TX_32X32; t++)
3974     full_to_model_counts(cpi->td.counts->coef[t],
3975                          cpi->td.rd_counts.coef_counts[t]);
3976
3977   if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
3978     vp9_adapt_coef_probs(cm);
3979
3980   if (!frame_is_intra_only(cm)) {
3981     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
3982       vp9_adapt_mode_probs(cm);
3983       vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
3984     }
3985   }
3986
3987   cpi->ext_refresh_frame_flags_pending = 0;
3988
3989   if (cpi->refresh_golden_frame == 1)
3990     cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
3991   else
3992     cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
3993
3994   if (cpi->refresh_alt_ref_frame == 1)
3995     cpi->frame_flags |= FRAMEFLAGS_ALTREF;
3996   else
3997     cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
3998
3999   cpi->ref_frame_flags = get_ref_frame_flags(cpi);
4000
4001   cm->last_frame_type = cm->frame_type;
4002
4003   if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
4004     vp9_rc_postencode_update(cpi, *size);
4005
4006 #if 0
4007   output_frame_level_debug_stats(cpi);
4008 #endif
4009
4010   if (cm->frame_type == KEY_FRAME) {
4011     // Tell the caller that the frame was coded as a key frame
4012     *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
4013   } else {
4014     *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
4015   }
4016
4017   // Clear the one shot update flags for segmentation map and mode/ref loop
4018   // filter deltas.
4019   cm->seg.update_map = 0;
4020   cm->seg.update_data = 0;
4021   cm->lf.mode_ref_delta_update = 0;
4022
4023   // keep track of the last coded dimensions
4024   cm->last_width = cm->width;
4025   cm->last_height = cm->height;
4026
4027   // reset to normal state now that we are done.
4028   if (!cm->show_existing_frame) cm->last_show_frame = cm->show_frame;
4029
4030   if (cm->show_frame) {
4031     vp9_swap_mi_and_prev_mi(cm);
4032     // Don't increment frame counters if this was an altref buffer
4033     // update not a real frame
4034     ++cm->current_video_frame;
4035     if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
4036   }
4037   cm->prev_frame = cm->cur_frame;
4038
4039   if (cpi->use_svc)
4040     cpi->svc.layer_context[cpi->svc.spatial_layer_id *
4041                                cpi->svc.number_temporal_layers +
4042                            cpi->svc.temporal_layer_id]
4043         .last_frame_type = cm->frame_type;
4044
4045   cpi->force_update_segmentation = 0;
4046
4047   if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ)
4048     vp9_alt_ref_aq_unset_all(cpi->alt_ref_aq, cpi);
4049 }
4050
4051 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4052                       unsigned int *frame_flags) {
4053   vp9_rc_get_svc_params(cpi);
4054   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4055 }
4056
4057 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4058                         unsigned int *frame_flags) {
4059   if (cpi->oxcf.rc_mode == VPX_CBR) {
4060     vp9_rc_get_one_pass_cbr_params(cpi);
4061   } else {
4062     vp9_rc_get_one_pass_vbr_params(cpi);
4063   }
4064   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4065 }
4066
4067 static void Pass2Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4068                         unsigned int *frame_flags) {
4069   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
4070   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4071
4072   if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
4073     vp9_twopass_postencode_update(cpi);
4074 }
4075
4076 static void init_ref_frame_bufs(VP9_COMMON *cm) {
4077   int i;
4078   BufferPool *const pool = cm->buffer_pool;
4079   cm->new_fb_idx = INVALID_IDX;
4080   for (i = 0; i < REF_FRAMES; ++i) {
4081     cm->ref_frame_map[i] = INVALID_IDX;
4082     pool->frame_bufs[i].ref_count = 0;
4083   }
4084 }
4085
4086 static void check_initial_width(VP9_COMP *cpi,
4087 #if CONFIG_VP9_HIGHBITDEPTH
4088                                 int use_highbitdepth,
4089 #endif
4090                                 int subsampling_x, int subsampling_y) {
4091   VP9_COMMON *const cm = &cpi->common;
4092
4093   if (!cpi->initial_width ||
4094 #if CONFIG_VP9_HIGHBITDEPTH
4095       cm->use_highbitdepth != use_highbitdepth ||
4096 #endif
4097       cm->subsampling_x != subsampling_x ||
4098       cm->subsampling_y != subsampling_y) {
4099     cm->subsampling_x = subsampling_x;
4100     cm->subsampling_y = subsampling_y;
4101 #if CONFIG_VP9_HIGHBITDEPTH
4102     cm->use_highbitdepth = use_highbitdepth;
4103 #endif
4104
4105     alloc_raw_frame_buffers(cpi);
4106     init_ref_frame_bufs(cm);
4107     alloc_util_frame_buffers(cpi);
4108
4109     init_motion_estimation(cpi);  // TODO(agrange) This can be removed.
4110
4111     cpi->initial_width = cm->width;
4112     cpi->initial_height = cm->height;
4113     cpi->initial_mbs = cm->MBs;
4114   }
4115 }
4116
4117 int vp9_receive_raw_frame(VP9_COMP *cpi, vpx_enc_frame_flags_t frame_flags,
4118                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
4119                           int64_t end_time) {
4120   VP9_COMMON *const cm = &cpi->common;
4121   struct vpx_usec_timer timer;
4122   int res = 0;
4123   const int subsampling_x = sd->subsampling_x;
4124   const int subsampling_y = sd->subsampling_y;
4125 #if CONFIG_VP9_HIGHBITDEPTH
4126   const int use_highbitdepth = (sd->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
4127 #endif
4128
4129 #if CONFIG_VP9_HIGHBITDEPTH
4130   check_initial_width(cpi, use_highbitdepth, subsampling_x, subsampling_y);
4131 #else
4132   check_initial_width(cpi, subsampling_x, subsampling_y);
4133 #endif  // CONFIG_VP9_HIGHBITDEPTH
4134
4135 #if CONFIG_VP9_TEMPORAL_DENOISING
4136   setup_denoiser_buffer(cpi);
4137 #endif
4138   vpx_usec_timer_start(&timer);
4139
4140   if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4141 #if CONFIG_VP9_HIGHBITDEPTH
4142                          use_highbitdepth,
4143 #endif  // CONFIG_VP9_HIGHBITDEPTH
4144                          frame_flags))
4145     res = -1;
4146   vpx_usec_timer_mark(&timer);
4147   cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4148
4149   if ((cm->profile == PROFILE_0 || cm->profile == PROFILE_2) &&
4150       (subsampling_x != 1 || subsampling_y != 1)) {
4151     vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4152                        "Non-4:2:0 color format requires profile 1 or 3");
4153     res = -1;
4154   }
4155   if ((cm->profile == PROFILE_1 || cm->profile == PROFILE_3) &&
4156       (subsampling_x == 1 && subsampling_y == 1)) {
4157     vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4158                        "4:2:0 color format requires profile 0 or 2");
4159     res = -1;
4160   }
4161
4162   return res;
4163 }
4164
4165 static int frame_is_reference(const VP9_COMP *cpi) {
4166   const VP9_COMMON *cm = &cpi->common;
4167
4168   return cm->frame_type == KEY_FRAME || cpi->refresh_last_frame ||
4169          cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame ||
4170          cm->refresh_frame_context || cm->lf.mode_ref_delta_update ||
4171          cm->seg.update_map || cm->seg.update_data;
4172 }
4173
4174 static void adjust_frame_rate(VP9_COMP *cpi,
4175                               const struct lookahead_entry *source) {
4176   int64_t this_duration;
4177   int step = 0;
4178
4179   if (source->ts_start == cpi->first_time_stamp_ever) {
4180     this_duration = source->ts_end - source->ts_start;
4181     step = 1;
4182   } else {
4183     int64_t last_duration =
4184         cpi->last_end_time_stamp_seen - cpi->last_time_stamp_seen;
4185
4186     this_duration = source->ts_end - cpi->last_end_time_stamp_seen;
4187
4188     // do a step update if the duration changes by 10%
4189     if (last_duration)
4190       step = (int)((this_duration - last_duration) * 10 / last_duration);
4191   }
4192
4193   if (this_duration) {
4194     if (step) {
4195       vp9_new_framerate(cpi, 10000000.0 / this_duration);
4196     } else {
4197       // Average this frame's rate into the last second's average
4198       // frame rate. If we haven't seen 1 second yet, then average
4199       // over the whole interval seen.
4200       const double interval = VPXMIN(
4201           (double)(source->ts_end - cpi->first_time_stamp_ever), 10000000.0);
4202       double avg_duration = 10000000.0 / cpi->framerate;
4203       avg_duration *= (interval - avg_duration + this_duration);
4204       avg_duration /= interval;
4205
4206       vp9_new_framerate(cpi, 10000000.0 / avg_duration);
4207     }
4208   }
4209   cpi->last_time_stamp_seen = source->ts_start;
4210   cpi->last_end_time_stamp_seen = source->ts_end;
4211 }
4212
4213 // Returns 0 if this is not an alt ref else the offset of the source frame
4214 // used as the arf midpoint.
4215 static int get_arf_src_index(VP9_COMP *cpi) {
4216   RATE_CONTROL *const rc = &cpi->rc;
4217   int arf_src_index = 0;
4218   if (is_altref_enabled(cpi)) {
4219     if (cpi->oxcf.pass == 2) {
4220       const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4221       if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
4222         arf_src_index = gf_group->arf_src_offset[gf_group->index];
4223       }
4224     } else if (rc->source_alt_ref_pending) {
4225       arf_src_index = rc->frames_till_gf_update_due;
4226     }
4227   }
4228   return arf_src_index;
4229 }
4230
4231 static void check_src_altref(VP9_COMP *cpi,
4232                              const struct lookahead_entry *source) {
4233   RATE_CONTROL *const rc = &cpi->rc;
4234
4235   if (cpi->oxcf.pass == 2) {
4236     const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4237     rc->is_src_frame_alt_ref =
4238         (gf_group->update_type[gf_group->index] == OVERLAY_UPDATE);
4239   } else {
4240     rc->is_src_frame_alt_ref =
4241         cpi->alt_ref_source && (source == cpi->alt_ref_source);
4242   }
4243
4244   if (rc->is_src_frame_alt_ref) {
4245     // Current frame is an ARF overlay frame.
4246     cpi->alt_ref_source = NULL;
4247
4248     // Don't refresh the last buffer for an ARF overlay frame. It will
4249     // become the GF so preserve last as an alternative prediction option.
4250     cpi->refresh_last_frame = 0;
4251   }
4252 }
4253
4254 #if CONFIG_INTERNAL_STATS
4255 extern double vp9_get_blockiness(const uint8_t *img1, int img1_pitch,
4256                                  const uint8_t *img2, int img2_pitch, int width,
4257                                  int height);
4258
4259 static void adjust_image_stat(double y, double u, double v, double all,
4260                               ImageStat *s) {
4261   s->stat[Y] += y;
4262   s->stat[U] += u;
4263   s->stat[V] += v;
4264   s->stat[ALL] += all;
4265   s->worst = VPXMIN(s->worst, all);
4266 }
4267 #endif  // CONFIG_INTERNAL_STATS
4268
4269 static void update_level_info(VP9_COMP *cpi, size_t *size, int arf_src_index) {
4270   VP9_COMMON *const cm = &cpi->common;
4271   Vp9LevelInfo *const level_info = &cpi->level_info;
4272   Vp9LevelSpec *const level_spec = &level_info->level_spec;
4273   Vp9LevelStats *const level_stats = &level_info->level_stats;
4274   int i, idx;
4275   uint64_t luma_samples, dur_end;
4276   const uint32_t luma_pic_size = cm->width * cm->height;
4277   double cpb_data_size;
4278
4279   vpx_clear_system_state();
4280
4281   // update level_stats
4282   level_stats->total_compressed_size += *size;
4283   if (cm->show_frame) {
4284     level_stats->total_uncompressed_size +=
4285         luma_pic_size +
4286         2 * (luma_pic_size >> (cm->subsampling_x + cm->subsampling_y));
4287     level_stats->time_encoded =
4288         (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
4289         (double)TICKS_PER_SEC;
4290   }
4291
4292   if (arf_src_index > 0) {
4293     if (!level_stats->seen_first_altref) {
4294       level_stats->seen_first_altref = 1;
4295     } else if (level_stats->frames_since_last_altref <
4296                level_spec->min_altref_distance) {
4297       level_spec->min_altref_distance = level_stats->frames_since_last_altref;
4298     }
4299     level_stats->frames_since_last_altref = 0;
4300   } else {
4301     ++level_stats->frames_since_last_altref;
4302   }
4303
4304   if (level_stats->frame_window_buffer.len < FRAME_WINDOW_SIZE - 1) {
4305     idx = (level_stats->frame_window_buffer.start +
4306            level_stats->frame_window_buffer.len++) %
4307           FRAME_WINDOW_SIZE;
4308   } else {
4309     idx = level_stats->frame_window_buffer.start;
4310     level_stats->frame_window_buffer.start = (idx + 1) % FRAME_WINDOW_SIZE;
4311   }
4312   level_stats->frame_window_buffer.buf[idx].ts = cpi->last_time_stamp_seen;
4313   level_stats->frame_window_buffer.buf[idx].size = (uint32_t)(*size);
4314   level_stats->frame_window_buffer.buf[idx].luma_samples = luma_pic_size;
4315
4316   if (cm->frame_type == KEY_FRAME) {
4317     level_stats->ref_refresh_map = 0;
4318   } else {
4319     int count = 0;
4320     level_stats->ref_refresh_map |= vp9_get_refresh_mask(cpi);
4321     // Also need to consider the case where the encoder refers to a buffer
4322     // that has been implicitly refreshed after encoding a keyframe.
4323     if (!cm->intra_only) {
4324       level_stats->ref_refresh_map |= (1 << cpi->lst_fb_idx);
4325       level_stats->ref_refresh_map |= (1 << cpi->gld_fb_idx);
4326       level_stats->ref_refresh_map |= (1 << cpi->alt_fb_idx);
4327     }
4328     for (i = 0; i < REF_FRAMES; ++i) {
4329       count += (level_stats->ref_refresh_map >> i) & 1;
4330     }
4331     if (count > level_spec->max_ref_frame_buffers) {
4332       level_spec->max_ref_frame_buffers = count;
4333     }
4334   }
4335
4336   // update average_bitrate
4337   level_spec->average_bitrate = (double)level_stats->total_compressed_size /
4338                                 125.0 / level_stats->time_encoded;
4339
4340   // update max_luma_sample_rate
4341   luma_samples = 0;
4342   for (i = 0; i < level_stats->frame_window_buffer.len; ++i) {
4343     idx = (level_stats->frame_window_buffer.start +
4344            level_stats->frame_window_buffer.len - 1 - i) %
4345           FRAME_WINDOW_SIZE;
4346     if (i == 0) {
4347       dur_end = level_stats->frame_window_buffer.buf[idx].ts;
4348     }
4349     if (dur_end - level_stats->frame_window_buffer.buf[idx].ts >=
4350         TICKS_PER_SEC) {
4351       break;
4352     }
4353     luma_samples += level_stats->frame_window_buffer.buf[idx].luma_samples;
4354   }
4355   if (luma_samples > level_spec->max_luma_sample_rate) {
4356     level_spec->max_luma_sample_rate = luma_samples;
4357   }
4358
4359   // update max_cpb_size
4360   cpb_data_size = 0;
4361   for (i = 0; i < CPB_WINDOW_SIZE; ++i) {
4362     if (i >= level_stats->frame_window_buffer.len) break;
4363     idx = (level_stats->frame_window_buffer.start +
4364            level_stats->frame_window_buffer.len - 1 - i) %
4365           FRAME_WINDOW_SIZE;
4366     cpb_data_size += level_stats->frame_window_buffer.buf[idx].size;
4367   }
4368   cpb_data_size = cpb_data_size / 125.0;
4369   if (cpb_data_size > level_spec->max_cpb_size) {
4370     level_spec->max_cpb_size = cpb_data_size;
4371   }
4372
4373   // update max_luma_picture_size
4374   if (luma_pic_size > level_spec->max_luma_picture_size) {
4375     level_spec->max_luma_picture_size = luma_pic_size;
4376   }
4377
4378   // update compression_ratio
4379   level_spec->compression_ratio = (double)level_stats->total_uncompressed_size *
4380                                   cm->bit_depth /
4381                                   level_stats->total_compressed_size / 8.0;
4382
4383   // update max_col_tiles
4384   if (level_spec->max_col_tiles < (1 << cm->log2_tile_cols)) {
4385     level_spec->max_col_tiles = (1 << cm->log2_tile_cols);
4386   }
4387 }
4388
4389 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
4390                             size_t *size, uint8_t *dest, int64_t *time_stamp,
4391                             int64_t *time_end, int flush) {
4392   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
4393   VP9_COMMON *const cm = &cpi->common;
4394   BufferPool *const pool = cm->buffer_pool;
4395   RATE_CONTROL *const rc = &cpi->rc;
4396   struct vpx_usec_timer cmptimer;
4397   YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4398   struct lookahead_entry *last_source = NULL;
4399   struct lookahead_entry *source = NULL;
4400   int arf_src_index;
4401   int i;
4402
4403   if (is_two_pass_svc(cpi)) {
4404 #if CONFIG_SPATIAL_SVC
4405     vp9_svc_start_frame(cpi);
4406     // Use a small empty frame instead of a real frame
4407     if (cpi->svc.encode_empty_frame_state == ENCODING)
4408       source = &cpi->svc.empty_frame;
4409 #endif
4410     if (oxcf->pass == 2) vp9_restore_layer_context(cpi);
4411   } else if (is_one_pass_cbr_svc(cpi)) {
4412     vp9_one_pass_cbr_svc_start_layer(cpi);
4413   }
4414
4415   vpx_usec_timer_start(&cmptimer);
4416
4417   vp9_set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
4418
4419   // Is multi-arf enabled.
4420   // Note that at the moment multi_arf is only configured for 2 pass VBR and
4421   // will not work properly with svc.
4422   if ((oxcf->pass == 2) && !cpi->use_svc && (cpi->oxcf.enable_auto_arf > 1))
4423     cpi->multi_arf_allowed = 1;
4424   else
4425     cpi->multi_arf_allowed = 0;
4426
4427   // Normal defaults
4428   cm->reset_frame_context = 0;
4429   cm->refresh_frame_context = 1;
4430   if (!is_one_pass_cbr_svc(cpi)) {
4431     cpi->refresh_last_frame = 1;
4432     cpi->refresh_golden_frame = 0;
4433     cpi->refresh_alt_ref_frame = 0;
4434   }
4435
4436   // Should we encode an arf frame.
4437   arf_src_index = get_arf_src_index(cpi);
4438
4439   // Skip alt frame if we encode the empty frame
4440   if (is_two_pass_svc(cpi) && source != NULL) arf_src_index = 0;
4441
4442   if (arf_src_index) {
4443     for (i = 0; i <= arf_src_index; ++i) {
4444       struct lookahead_entry *e = vp9_lookahead_peek(cpi->lookahead, i);
4445       // Avoid creating an alt-ref if there's a forced keyframe pending.
4446       if (e == NULL) {
4447         break;
4448       } else if (e->flags == VPX_EFLAG_FORCE_KF) {
4449         arf_src_index = 0;
4450         flush = 1;
4451         break;
4452       }
4453     }
4454   }
4455
4456   if (arf_src_index) {
4457     assert(arf_src_index <= rc->frames_to_key);
4458
4459     if ((source = vp9_lookahead_peek(cpi->lookahead, arf_src_index)) != NULL) {
4460       cpi->alt_ref_source = source;
4461
4462 #if CONFIG_SPATIAL_SVC
4463       if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0) {
4464         int i;
4465         // Reference a hidden frame from a lower layer
4466         for (i = cpi->svc.spatial_layer_id - 1; i >= 0; --i) {
4467           if (oxcf->ss_enable_auto_arf[i]) {
4468             cpi->gld_fb_idx = cpi->svc.layer_context[i].alt_ref_idx;
4469             break;
4470           }
4471         }
4472       }
4473       cpi->svc.layer_context[cpi->svc.spatial_layer_id].has_alt_frame = 1;
4474 #endif
4475
4476       if ((oxcf->arnr_max_frames > 0) && (oxcf->arnr_strength > 0)) {
4477         int bitrate = cpi->rc.avg_frame_bandwidth / 40;
4478         int not_low_bitrate = bitrate > ALT_REF_AQ_LOW_BITRATE_BOUNDARY;
4479
4480         int not_last_frame = (cpi->lookahead->sz - arf_src_index > 1);
4481         not_last_frame |= ALT_REF_AQ_APPLY_TO_LAST_FRAME;
4482
4483         // Produce the filtered ARF frame.
4484         vp9_temporal_filter(cpi, arf_src_index);
4485         vpx_extend_frame_borders(&cpi->alt_ref_buffer);
4486
4487         // for small bitrates segmentation overhead usually
4488         // eats all bitrate gain from enabling delta quantizers
4489         if (cpi->oxcf.alt_ref_aq != 0 && not_low_bitrate && not_last_frame)
4490           vp9_alt_ref_aq_setup_mode(cpi->alt_ref_aq, cpi);
4491
4492         force_src_buffer = &cpi->alt_ref_buffer;
4493       }
4494
4495       cm->show_frame = 0;
4496       cm->intra_only = 0;
4497       cpi->refresh_alt_ref_frame = 1;
4498       cpi->refresh_golden_frame = 0;
4499       cpi->refresh_last_frame = 0;
4500       rc->is_src_frame_alt_ref = 0;
4501       rc->source_alt_ref_pending = 0;
4502     } else {
4503       rc->source_alt_ref_pending = 0;
4504     }
4505   }
4506
4507   if (!source) {
4508     // Get last frame source.
4509     if (cm->current_video_frame > 0) {
4510       if ((last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
4511         return -1;
4512     }
4513
4514     // Read in the source frame.
4515     if (cpi->use_svc)
4516       source = vp9_svc_lookahead_pop(cpi, cpi->lookahead, flush);
4517     else
4518       source = vp9_lookahead_pop(cpi->lookahead, flush);
4519
4520     if (source != NULL) {
4521       cm->show_frame = 1;
4522       cm->intra_only = 0;
4523       // if the flags indicate intra frame, but if the current picture is for
4524       // non-zero spatial layer, it should not be an intra picture.
4525       // TODO(Won Kap): this needs to change if per-layer intra frame is
4526       // allowed.
4527       if ((source->flags & VPX_EFLAG_FORCE_KF) &&
4528           cpi->svc.spatial_layer_id > cpi->svc.first_spatial_layer_to_encode) {
4529         source->flags &= ~(unsigned int)(VPX_EFLAG_FORCE_KF);
4530       }
4531
4532       // Check to see if the frame should be encoded as an arf overlay.
4533       check_src_altref(cpi, source);
4534     }
4535   }
4536
4537   if (source) {
4538     cpi->un_scaled_source = cpi->Source =
4539         force_src_buffer ? force_src_buffer : &source->img;
4540
4541 #ifdef ENABLE_KF_DENOISE
4542     // Copy of raw source for metrics calculation.
4543     if (is_psnr_calc_enabled(cpi))
4544       vp9_copy_and_extend_frame(cpi->Source, &cpi->raw_unscaled_source);
4545 #endif
4546
4547     cpi->unscaled_last_source = last_source != NULL ? &last_source->img : NULL;
4548
4549     *time_stamp = source->ts_start;
4550     *time_end = source->ts_end;
4551     *frame_flags = (source->flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
4552
4553   } else {
4554     *size = 0;
4555     if (flush && oxcf->pass == 1 && !cpi->twopass.first_pass_done) {
4556       vp9_end_first_pass(cpi); /* get last stats packet */
4557       cpi->twopass.first_pass_done = 1;
4558     }
4559     return -1;
4560   }
4561
4562   if (source->ts_start < cpi->first_time_stamp_ever) {
4563     cpi->first_time_stamp_ever = source->ts_start;
4564     cpi->last_end_time_stamp_seen = source->ts_start;
4565   }
4566
4567   // Clear down mmx registers
4568   vpx_clear_system_state();
4569
4570   // adjust frame rates based on timestamps given
4571   if (cm->show_frame) {
4572     adjust_frame_rate(cpi, source);
4573   }
4574
4575   if (is_one_pass_cbr_svc(cpi)) {
4576     vp9_update_temporal_layer_framerate(cpi);
4577     vp9_restore_layer_context(cpi);
4578   }
4579
4580   // Find a free buffer for the new frame, releasing the reference previously
4581   // held.
4582   if (cm->new_fb_idx != INVALID_IDX) {
4583     --pool->frame_bufs[cm->new_fb_idx].ref_count;
4584   }
4585   cm->new_fb_idx = get_free_fb(cm);
4586
4587   if (cm->new_fb_idx == INVALID_IDX) return -1;
4588
4589   cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx];
4590
4591   if (!cpi->use_svc && cpi->multi_arf_allowed) {
4592     if (cm->frame_type == KEY_FRAME) {
4593       init_buffer_indices(cpi);
4594     } else if (oxcf->pass == 2) {
4595       const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4596       cpi->alt_fb_idx = gf_group->arf_ref_idx[gf_group->index];
4597     }
4598   }
4599
4600   // Start with a 0 size frame.
4601   *size = 0;
4602
4603   cpi->frame_flags = *frame_flags;
4604
4605   if ((oxcf->pass == 2) &&
4606       (!cpi->use_svc || (is_two_pass_svc(cpi) &&
4607                          cpi->svc.encode_empty_frame_state != ENCODING))) {
4608     vp9_rc_get_second_pass_params(cpi);
4609   } else if (oxcf->pass == 1) {
4610     set_frame_size(cpi);
4611   }
4612
4613   if (cpi->oxcf.pass != 0 || cpi->use_svc || frame_is_intra_only(cm) == 1) {
4614     for (i = 0; i < MAX_REF_FRAMES; ++i) cpi->scaled_ref_idx[i] = INVALID_IDX;
4615   }
4616
4617   if (oxcf->pass == 1 && (!cpi->use_svc || is_two_pass_svc(cpi))) {
4618     const int lossless = is_lossless_requested(oxcf);
4619 #if CONFIG_VP9_HIGHBITDEPTH
4620     if (cpi->oxcf.use_highbitdepth)
4621       cpi->td.mb.fwd_txm4x4 =
4622           lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
4623     else
4624       cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4625     cpi->td.mb.highbd_itxm_add =
4626         lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
4627 #else
4628     cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4629 #endif  // CONFIG_VP9_HIGHBITDEPTH
4630     cpi->td.mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
4631     vp9_first_pass(cpi, source);
4632   } else if (oxcf->pass == 2 && (!cpi->use_svc || is_two_pass_svc(cpi))) {
4633     Pass2Encode(cpi, size, dest, frame_flags);
4634   } else if (cpi->use_svc) {
4635     SvcEncode(cpi, size, dest, frame_flags);
4636   } else {
4637     // One pass encode
4638     Pass0Encode(cpi, size, dest, frame_flags);
4639   }
4640
4641   if (cm->refresh_frame_context)
4642     cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
4643
4644   // No frame encoded, or frame was dropped, release scaled references.
4645   if ((*size == 0) && (frame_is_intra_only(cm) == 0)) {
4646     release_scaled_references(cpi);
4647   }
4648
4649   if (*size > 0) {
4650     cpi->droppable = !frame_is_reference(cpi);
4651   }
4652
4653   // Save layer specific state.
4654   if (is_one_pass_cbr_svc(cpi) || ((cpi->svc.number_temporal_layers > 1 ||
4655                                     cpi->svc.number_spatial_layers > 1) &&
4656                                    oxcf->pass == 2)) {
4657     vp9_save_layer_context(cpi);
4658   }
4659
4660   vpx_usec_timer_mark(&cmptimer);
4661   cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4662
4663   // Should we calculate metrics for the frame.
4664   if (is_psnr_calc_enabled(cpi)) generate_psnr_packet(cpi);
4665
4666   if (cpi->keep_level_stats && oxcf->pass != 1)
4667     update_level_info(cpi, size, arf_src_index);
4668
4669 #if CONFIG_INTERNAL_STATS
4670
4671   if (oxcf->pass != 1) {
4672     double samples = 0.0;
4673     cpi->bytes += (int)(*size);
4674
4675     if (cm->show_frame) {
4676       uint32_t bit_depth = 8;
4677       uint32_t in_bit_depth = 8;
4678       cpi->count++;
4679 #if CONFIG_VP9_HIGHBITDEPTH
4680       if (cm->use_highbitdepth) {
4681         in_bit_depth = cpi->oxcf.input_bit_depth;
4682         bit_depth = cm->bit_depth;
4683       }
4684 #endif
4685
4686       if (cpi->b_calculate_psnr) {
4687         YV12_BUFFER_CONFIG *orig = cpi->raw_source_frame;
4688         YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4689         YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4690         PSNR_STATS psnr;
4691 #if CONFIG_VP9_HIGHBITDEPTH
4692         vpx_calc_highbd_psnr(orig, recon, &psnr, cpi->td.mb.e_mbd.bd,
4693                              in_bit_depth);
4694 #else
4695         vpx_calc_psnr(orig, recon, &psnr);
4696 #endif  // CONFIG_VP9_HIGHBITDEPTH
4697
4698         adjust_image_stat(psnr.psnr[1], psnr.psnr[2], psnr.psnr[3],
4699                           psnr.psnr[0], &cpi->psnr);
4700         cpi->total_sq_error += psnr.sse[0];
4701         cpi->total_samples += psnr.samples[0];
4702         samples = psnr.samples[0];
4703
4704         {
4705           PSNR_STATS psnr2;
4706           double frame_ssim2 = 0, weight = 0;
4707 #if CONFIG_VP9_POSTPROC
4708           if (vpx_alloc_frame_buffer(
4709                   pp, recon->y_crop_width, recon->y_crop_height,
4710                   cm->subsampling_x, cm->subsampling_y,
4711 #if CONFIG_VP9_HIGHBITDEPTH
4712                   cm->use_highbitdepth,
4713 #endif
4714                   VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment) < 0) {
4715             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
4716                                "Failed to allocate post processing buffer");
4717           }
4718           {
4719             vp9_ppflags_t ppflags;
4720             ppflags.post_proc_flag = VP9D_DEBLOCK;
4721             ppflags.deblocking_level = 0;  // not used in vp9_post_proc_frame()
4722             ppflags.noise_level = 0;       // not used in vp9_post_proc_frame()
4723             vp9_post_proc_frame(cm, pp, &ppflags);
4724           }
4725 #endif
4726           vpx_clear_system_state();
4727
4728 #if CONFIG_VP9_HIGHBITDEPTH
4729           vpx_calc_highbd_psnr(orig, pp, &psnr2, cpi->td.mb.e_mbd.bd,
4730                                cpi->oxcf.input_bit_depth);
4731 #else
4732           vpx_calc_psnr(orig, pp, &psnr2);
4733 #endif  // CONFIG_VP9_HIGHBITDEPTH
4734
4735           cpi->totalp_sq_error += psnr2.sse[0];
4736           cpi->totalp_samples += psnr2.samples[0];
4737           adjust_image_stat(psnr2.psnr[1], psnr2.psnr[2], psnr2.psnr[3],
4738                             psnr2.psnr[0], &cpi->psnrp);
4739
4740 #if CONFIG_VP9_HIGHBITDEPTH
4741           if (cm->use_highbitdepth) {
4742             frame_ssim2 = vpx_highbd_calc_ssim(orig, recon, &weight, bit_depth,
4743                                                in_bit_depth);
4744           } else {
4745             frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4746           }
4747 #else
4748           frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4749 #endif  // CONFIG_VP9_HIGHBITDEPTH
4750
4751           cpi->worst_ssim = VPXMIN(cpi->worst_ssim, frame_ssim2);
4752           cpi->summed_quality += frame_ssim2 * weight;
4753           cpi->summed_weights += weight;
4754
4755 #if CONFIG_VP9_HIGHBITDEPTH
4756           if (cm->use_highbitdepth) {
4757             frame_ssim2 = vpx_highbd_calc_ssim(orig, pp, &weight, bit_depth,
4758                                                in_bit_depth);
4759           } else {
4760             frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4761           }
4762 #else
4763           frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4764 #endif  // CONFIG_VP9_HIGHBITDEPTH
4765
4766           cpi->summedp_quality += frame_ssim2 * weight;
4767           cpi->summedp_weights += weight;
4768 #if 0
4769           {
4770             FILE *f = fopen("q_used.stt", "a");
4771             fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
4772                     cpi->common.current_video_frame, y2, u2, v2,
4773                     frame_psnr2, frame_ssim2);
4774             fclose(f);
4775           }
4776 #endif
4777         }
4778       }
4779       if (cpi->b_calculate_blockiness) {
4780 #if CONFIG_VP9_HIGHBITDEPTH
4781         if (!cm->use_highbitdepth)
4782 #endif
4783         {
4784           double frame_blockiness = vp9_get_blockiness(
4785               cpi->Source->y_buffer, cpi->Source->y_stride,
4786               cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4787               cpi->Source->y_width, cpi->Source->y_height);
4788           cpi->worst_blockiness =
4789               VPXMAX(cpi->worst_blockiness, frame_blockiness);
4790           cpi->total_blockiness += frame_blockiness;
4791         }
4792       }
4793
4794       if (cpi->b_calculate_consistency) {
4795 #if CONFIG_VP9_HIGHBITDEPTH
4796         if (!cm->use_highbitdepth)
4797 #endif
4798         {
4799           double this_inconsistency = vpx_get_ssim_metrics(
4800               cpi->Source->y_buffer, cpi->Source->y_stride,
4801               cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4802               cpi->Source->y_width, cpi->Source->y_height, cpi->ssim_vars,
4803               &cpi->metrics, 1);
4804
4805           const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
4806           double consistency =
4807               vpx_sse_to_psnr(samples, peak, (double)cpi->total_inconsistency);
4808           if (consistency > 0.0)
4809             cpi->worst_consistency =
4810                 VPXMIN(cpi->worst_consistency, consistency);
4811           cpi->total_inconsistency += this_inconsistency;
4812         }
4813       }
4814
4815       {
4816         double y, u, v, frame_all;
4817         frame_all = vpx_calc_fastssim(cpi->Source, cm->frame_to_show, &y, &u,
4818                                       &v, bit_depth, in_bit_depth);
4819         adjust_image_stat(y, u, v, frame_all, &cpi->fastssim);
4820       }
4821       {
4822         double y, u, v, frame_all;
4823         frame_all = vpx_psnrhvs(cpi->Source, cm->frame_to_show, &y, &u, &v,
4824                                 bit_depth, in_bit_depth);
4825         adjust_image_stat(y, u, v, frame_all, &cpi->psnrhvs);
4826       }
4827     }
4828   }
4829
4830 #endif
4831
4832   if (is_two_pass_svc(cpi)) {
4833     if (cpi->svc.encode_empty_frame_state == ENCODING) {
4834       cpi->svc.encode_empty_frame_state = ENCODED;
4835       cpi->svc.encode_intra_empty_frame = 0;
4836     }
4837
4838     if (cm->show_frame) {
4839       ++cpi->svc.spatial_layer_to_encode;
4840       if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4841         cpi->svc.spatial_layer_to_encode = 0;
4842
4843       // May need the empty frame after an visible frame.
4844       cpi->svc.encode_empty_frame_state = NEED_TO_ENCODE;
4845     }
4846   } else if (is_one_pass_cbr_svc(cpi)) {
4847     if (cm->show_frame) {
4848       ++cpi->svc.spatial_layer_to_encode;
4849       if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4850         cpi->svc.spatial_layer_to_encode = 0;
4851     }
4852   }
4853
4854   vpx_clear_system_state();
4855   return 0;
4856 }
4857
4858 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
4859                               vp9_ppflags_t *flags) {
4860   VP9_COMMON *cm = &cpi->common;
4861 #if !CONFIG_VP9_POSTPROC
4862   (void)flags;
4863 #endif
4864
4865   if (!cm->show_frame) {
4866     return -1;
4867   } else {
4868     int ret;
4869 #if CONFIG_VP9_POSTPROC
4870     ret = vp9_post_proc_frame(cm, dest, flags);
4871 #else
4872     if (cm->frame_to_show) {
4873       *dest = *cm->frame_to_show;
4874       dest->y_width = cm->width;
4875       dest->y_height = cm->height;
4876       dest->uv_width = cm->width >> cm->subsampling_x;
4877       dest->uv_height = cm->height >> cm->subsampling_y;
4878       ret = 0;
4879     } else {
4880       ret = -1;
4881     }
4882 #endif  // !CONFIG_VP9_POSTPROC
4883     vpx_clear_system_state();
4884     return ret;
4885   }
4886 }
4887
4888 int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
4889                           VPX_SCALING vert_mode) {
4890   VP9_COMMON *cm = &cpi->common;
4891   int hr = 0, hs = 0, vr = 0, vs = 0;
4892
4893   if (horiz_mode > ONETWO || vert_mode > ONETWO) return -1;
4894
4895   Scale2Ratio(horiz_mode, &hr, &hs);
4896   Scale2Ratio(vert_mode, &vr, &vs);
4897
4898   // always go to the next whole number
4899   cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
4900   cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
4901   if (cm->current_video_frame) {
4902     assert(cm->width <= cpi->initial_width);
4903     assert(cm->height <= cpi->initial_height);
4904   }
4905
4906   update_frame_size(cpi);
4907
4908   return 0;
4909 }
4910
4911 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
4912                          unsigned int height) {
4913   VP9_COMMON *cm = &cpi->common;
4914 #if CONFIG_VP9_HIGHBITDEPTH
4915   check_initial_width(cpi, cm->use_highbitdepth, 1, 1);
4916 #else
4917   check_initial_width(cpi, 1, 1);
4918 #endif  // CONFIG_VP9_HIGHBITDEPTH
4919
4920 #if CONFIG_VP9_TEMPORAL_DENOISING
4921   setup_denoiser_buffer(cpi);
4922 #endif
4923
4924   if (width) {
4925     cm->width = width;
4926     if (cm->width > cpi->initial_width) {
4927       cm->width = cpi->initial_width;
4928       printf("Warning: Desired width too large, changed to %d\n", cm->width);
4929     }
4930   }
4931
4932   if (height) {
4933     cm->height = height;
4934     if (cm->height > cpi->initial_height) {
4935       cm->height = cpi->initial_height;
4936       printf("Warning: Desired height too large, changed to %d\n", cm->height);
4937     }
4938   }
4939   assert(cm->width <= cpi->initial_width);
4940   assert(cm->height <= cpi->initial_height);
4941
4942   update_frame_size(cpi);
4943
4944   return 0;
4945 }
4946
4947 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
4948   cpi->use_svc = use_svc;
4949   return;
4950 }
4951
4952 int vp9_get_quantizer(VP9_COMP *cpi) { return cpi->common.base_qindex; }
4953
4954 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags) {
4955   if (flags &
4956       (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF)) {
4957     int ref = 7;
4958
4959     if (flags & VP8_EFLAG_NO_REF_LAST) ref ^= VP9_LAST_FLAG;
4960
4961     if (flags & VP8_EFLAG_NO_REF_GF) ref ^= VP9_GOLD_FLAG;
4962
4963     if (flags & VP8_EFLAG_NO_REF_ARF) ref ^= VP9_ALT_FLAG;
4964
4965     vp9_use_as_reference(cpi, ref);
4966   }
4967
4968   if (flags &
4969       (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF |
4970        VP8_EFLAG_FORCE_GF | VP8_EFLAG_FORCE_ARF)) {
4971     int upd = 7;
4972
4973     if (flags & VP8_EFLAG_NO_UPD_LAST) upd ^= VP9_LAST_FLAG;
4974
4975     if (flags & VP8_EFLAG_NO_UPD_GF) upd ^= VP9_GOLD_FLAG;
4976
4977     if (flags & VP8_EFLAG_NO_UPD_ARF) upd ^= VP9_ALT_FLAG;
4978
4979     vp9_update_reference(cpi, upd);
4980   }
4981
4982   if (flags & VP8_EFLAG_NO_UPD_ENTROPY) {
4983     vp9_update_entropy(cpi, 0);
4984   }
4985 }