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