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