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