ed2c17702069680791d3a5edd7fadd5d1f32c20f
[platform/upstream/libvpx.git] / vp9 / encoder / vp9_encoder.c
1 /*
2  * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <math.h>
12 #include <stdio.h>
13 #include <limits.h>
14
15 #include "./vp9_rtcd.h"
16 #include "./vpx_config.h"
17 #include "./vpx_dsp_rtcd.h"
18 #include "./vpx_scale_rtcd.h"
19 #include "vpx_dsp/psnr.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_dsp/vpx_filter.h"
22 #if CONFIG_INTERNAL_STATS
23 #include "vpx_dsp/ssim.h"
24 #endif
25 #include "vpx_ports/mem.h"
26 #include "vpx_ports/system_state.h"
27 #include "vpx_ports/vpx_timer.h"
28
29 #include "vp9/common/vp9_alloccommon.h"
30 #include "vp9/common/vp9_filter.h"
31 #include "vp9/common/vp9_idct.h"
32 #if CONFIG_VP9_POSTPROC
33 #include "vp9/common/vp9_postproc.h"
34 #endif
35 #include "vp9/common/vp9_reconinter.h"
36 #include "vp9/common/vp9_reconintra.h"
37 #include "vp9/common/vp9_tile_common.h"
38 #include "vp9/common/vp9_scan.h"
39
40 #include "vp9/encoder/vp9_alt_ref_aq.h"
41 #include "vp9/encoder/vp9_aq_360.h"
42 #include "vp9/encoder/vp9_aq_complexity.h"
43 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
44 #include "vp9/encoder/vp9_aq_variance.h"
45 #include "vp9/encoder/vp9_bitstream.h"
46 #include "vp9/encoder/vp9_context_tree.h"
47 #include "vp9/encoder/vp9_encodeframe.h"
48 #include "vp9/encoder/vp9_encodemb.h"
49 #include "vp9/encoder/vp9_encodemv.h"
50 #include "vp9/encoder/vp9_encoder.h"
51 #include "vp9/encoder/vp9_ethread.h"
52 #include "vp9/encoder/vp9_extend.h"
53 #include "vp9/encoder/vp9_firstpass.h"
54 #include "vp9/encoder/vp9_mbgraph.h"
55 #include "vp9/encoder/vp9_multi_thread.h"
56 #include "vp9/encoder/vp9_noise_estimate.h"
57 #include "vp9/encoder/vp9_picklpf.h"
58 #include "vp9/encoder/vp9_ratectrl.h"
59 #include "vp9/encoder/vp9_rd.h"
60 #include "vp9/encoder/vp9_resize.h"
61 #include "vp9/encoder/vp9_segmentation.h"
62 #include "vp9/encoder/vp9_skin_detection.h"
63 #include "vp9/encoder/vp9_speed_features.h"
64 #include "vp9/encoder/vp9_svc_layercontext.h"
65 #include "vp9/encoder/vp9_temporal_filter.h"
66
67 #define AM_SEGMENT_ID_INACTIVE 7
68 #define AM_SEGMENT_ID_ACTIVE 0
69
70 // Whether to use high precision mv for altref computation.
71 #define ALTREF_HIGH_PRECISION_MV 1
72
73 // Q threshold for high precision mv. Choose a very high value for now so that
74 // HIGH_PRECISION is always chosen.
75 #define HIGH_PRECISION_MV_QTHRESH 200
76
77 #define FRAME_SIZE_FACTOR 128  // empirical params for context model threshold
78 #define FRAME_RATE_FACTOR 8
79
80 #ifdef OUTPUT_YUV_DENOISED
81 FILE *yuv_denoised_file = NULL;
82 #endif
83 #ifdef OUTPUT_YUV_SKINMAP
84 static FILE *yuv_skinmap_file = NULL;
85 #endif
86 #ifdef OUTPUT_YUV_REC
87 FILE *yuv_rec_file;
88 #endif
89 #ifdef OUTPUT_YUV_SVC_SRC
90 FILE *yuv_svc_src[3] = { NULL, NULL, NULL };
91 #endif
92
93 #if 0
94 FILE *framepsnr;
95 FILE *kf_list;
96 FILE *keyfile;
97 #endif
98
99 #ifdef ENABLE_KF_DENOISE
100 // Test condition for spatial denoise of source.
101 static int is_spatial_denoise_enabled(VP9_COMP *cpi) {
102   VP9_COMMON *const cm = &cpi->common;
103   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
104
105   return (oxcf->pass != 1) && !is_lossless_requested(&cpi->oxcf) &&
106          frame_is_intra_only(cm);
107 }
108 #endif
109
110 // compute adaptive threshold for skip recoding
111 static int compute_context_model_thresh(const VP9_COMP *const cpi) {
112   const VP9_COMMON *const cm = &cpi->common;
113   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
114   const int frame_size = (cm->width * cm->height) >> 10;
115   const int bitrate = (int)(oxcf->target_bandwidth >> 10);
116   const int qindex_factor = cm->base_qindex + (MAXQ >> 1);
117
118   // This equation makes the threshold adaptive to frame size.
119   // Coding gain obtained by recoding comes from alternate frames of large
120   // content change. We skip recoding if the difference of previous and current
121   // frame context probability model is less than a certain threshold.
122   // The first component is the most critical part to guarantee adaptivity.
123   // Other parameters are estimated based on normal setting of hd resolution
124   // parameters. e.g frame_size = 1920x1080, bitrate = 8000, qindex_factor < 50
125   const int thresh =
126       ((FRAME_SIZE_FACTOR * frame_size - FRAME_RATE_FACTOR * bitrate) *
127        qindex_factor) >>
128       9;
129
130   return thresh;
131 }
132
133 // compute the total cost difference between current
134 // and previous frame context prob model.
135 static int compute_context_model_diff(const VP9_COMMON *const cm) {
136   const FRAME_CONTEXT *const pre_fc =
137       &cm->frame_contexts[cm->frame_context_idx];
138   const FRAME_CONTEXT *const cur_fc = cm->fc;
139   const FRAME_COUNTS *counts = &cm->counts;
140   vpx_prob pre_last_prob, cur_last_prob;
141   int diff = 0;
142   int i, j, k, l, m, n;
143
144   // y_mode_prob
145   for (i = 0; i < BLOCK_SIZE_GROUPS; ++i) {
146     for (j = 0; j < INTRA_MODES - 1; ++j) {
147       diff += (int)counts->y_mode[i][j] *
148               (pre_fc->y_mode_prob[i][j] - cur_fc->y_mode_prob[i][j]);
149     }
150     pre_last_prob = MAX_PROB - pre_fc->y_mode_prob[i][INTRA_MODES - 2];
151     cur_last_prob = MAX_PROB - cur_fc->y_mode_prob[i][INTRA_MODES - 2];
152
153     diff += (int)counts->y_mode[i][INTRA_MODES - 1] *
154             (pre_last_prob - cur_last_prob);
155   }
156
157   // uv_mode_prob
158   for (i = 0; i < INTRA_MODES; ++i) {
159     for (j = 0; j < INTRA_MODES - 1; ++j) {
160       diff += (int)counts->uv_mode[i][j] *
161               (pre_fc->uv_mode_prob[i][j] - cur_fc->uv_mode_prob[i][j]);
162     }
163     pre_last_prob = MAX_PROB - pre_fc->uv_mode_prob[i][INTRA_MODES - 2];
164     cur_last_prob = MAX_PROB - cur_fc->uv_mode_prob[i][INTRA_MODES - 2];
165
166     diff += (int)counts->uv_mode[i][INTRA_MODES - 1] *
167             (pre_last_prob - cur_last_prob);
168   }
169
170   // partition_prob
171   for (i = 0; i < PARTITION_CONTEXTS; ++i) {
172     for (j = 0; j < PARTITION_TYPES - 1; ++j) {
173       diff += (int)counts->partition[i][j] *
174               (pre_fc->partition_prob[i][j] - cur_fc->partition_prob[i][j]);
175     }
176     pre_last_prob = MAX_PROB - pre_fc->partition_prob[i][PARTITION_TYPES - 2];
177     cur_last_prob = MAX_PROB - cur_fc->partition_prob[i][PARTITION_TYPES - 2];
178
179     diff += (int)counts->partition[i][PARTITION_TYPES - 1] *
180             (pre_last_prob - cur_last_prob);
181   }
182
183   // coef_probs
184   for (i = 0; i < TX_SIZES; ++i) {
185     for (j = 0; j < PLANE_TYPES; ++j) {
186       for (k = 0; k < REF_TYPES; ++k) {
187         for (l = 0; l < COEF_BANDS; ++l) {
188           for (m = 0; m < BAND_COEFF_CONTEXTS(l); ++m) {
189             for (n = 0; n < UNCONSTRAINED_NODES; ++n) {
190               diff += (int)counts->coef[i][j][k][l][m][n] *
191                       (pre_fc->coef_probs[i][j][k][l][m][n] -
192                        cur_fc->coef_probs[i][j][k][l][m][n]);
193             }
194
195             pre_last_prob =
196                 MAX_PROB -
197                 pre_fc->coef_probs[i][j][k][l][m][UNCONSTRAINED_NODES - 1];
198             cur_last_prob =
199                 MAX_PROB -
200                 cur_fc->coef_probs[i][j][k][l][m][UNCONSTRAINED_NODES - 1];
201
202             diff += (int)counts->coef[i][j][k][l][m][UNCONSTRAINED_NODES] *
203                     (pre_last_prob - cur_last_prob);
204           }
205         }
206       }
207     }
208   }
209
210   // switchable_interp_prob
211   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) {
212     for (j = 0; j < SWITCHABLE_FILTERS - 1; ++j) {
213       diff += (int)counts->switchable_interp[i][j] *
214               (pre_fc->switchable_interp_prob[i][j] -
215                cur_fc->switchable_interp_prob[i][j]);
216     }
217     pre_last_prob =
218         MAX_PROB - pre_fc->switchable_interp_prob[i][SWITCHABLE_FILTERS - 2];
219     cur_last_prob =
220         MAX_PROB - cur_fc->switchable_interp_prob[i][SWITCHABLE_FILTERS - 2];
221
222     diff += (int)counts->switchable_interp[i][SWITCHABLE_FILTERS - 1] *
223             (pre_last_prob - cur_last_prob);
224   }
225
226   // inter_mode_probs
227   for (i = 0; i < INTER_MODE_CONTEXTS; ++i) {
228     for (j = 0; j < INTER_MODES - 1; ++j) {
229       diff += (int)counts->inter_mode[i][j] *
230               (pre_fc->inter_mode_probs[i][j] - cur_fc->inter_mode_probs[i][j]);
231     }
232     pre_last_prob = MAX_PROB - pre_fc->inter_mode_probs[i][INTER_MODES - 2];
233     cur_last_prob = MAX_PROB - cur_fc->inter_mode_probs[i][INTER_MODES - 2];
234
235     diff += (int)counts->inter_mode[i][INTER_MODES - 1] *
236             (pre_last_prob - cur_last_prob);
237   }
238
239   // intra_inter_prob
240   for (i = 0; i < INTRA_INTER_CONTEXTS; ++i) {
241     diff += (int)counts->intra_inter[i][0] *
242             (pre_fc->intra_inter_prob[i] - cur_fc->intra_inter_prob[i]);
243
244     pre_last_prob = MAX_PROB - pre_fc->intra_inter_prob[i];
245     cur_last_prob = MAX_PROB - cur_fc->intra_inter_prob[i];
246
247     diff += (int)counts->intra_inter[i][1] * (pre_last_prob - cur_last_prob);
248   }
249
250   // comp_inter_prob
251   for (i = 0; i < COMP_INTER_CONTEXTS; ++i) {
252     diff += (int)counts->comp_inter[i][0] *
253             (pre_fc->comp_inter_prob[i] - cur_fc->comp_inter_prob[i]);
254
255     pre_last_prob = MAX_PROB - pre_fc->comp_inter_prob[i];
256     cur_last_prob = MAX_PROB - cur_fc->comp_inter_prob[i];
257
258     diff += (int)counts->comp_inter[i][1] * (pre_last_prob - cur_last_prob);
259   }
260
261   // single_ref_prob
262   for (i = 0; i < REF_CONTEXTS; ++i) {
263     for (j = 0; j < 2; ++j) {
264       diff += (int)counts->single_ref[i][j][0] *
265               (pre_fc->single_ref_prob[i][j] - cur_fc->single_ref_prob[i][j]);
266
267       pre_last_prob = MAX_PROB - pre_fc->single_ref_prob[i][j];
268       cur_last_prob = MAX_PROB - cur_fc->single_ref_prob[i][j];
269
270       diff +=
271           (int)counts->single_ref[i][j][1] * (pre_last_prob - cur_last_prob);
272     }
273   }
274
275   // comp_ref_prob
276   for (i = 0; i < REF_CONTEXTS; ++i) {
277     diff += (int)counts->comp_ref[i][0] *
278             (pre_fc->comp_ref_prob[i] - cur_fc->comp_ref_prob[i]);
279
280     pre_last_prob = MAX_PROB - pre_fc->comp_ref_prob[i];
281     cur_last_prob = MAX_PROB - cur_fc->comp_ref_prob[i];
282
283     diff += (int)counts->comp_ref[i][1] * (pre_last_prob - cur_last_prob);
284   }
285
286   // tx_probs
287   for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
288     // p32x32
289     for (j = 0; j < TX_SIZES - 1; ++j) {
290       diff += (int)counts->tx.p32x32[i][j] *
291               (pre_fc->tx_probs.p32x32[i][j] - cur_fc->tx_probs.p32x32[i][j]);
292     }
293     pre_last_prob = MAX_PROB - pre_fc->tx_probs.p32x32[i][TX_SIZES - 2];
294     cur_last_prob = MAX_PROB - cur_fc->tx_probs.p32x32[i][TX_SIZES - 2];
295
296     diff += (int)counts->tx.p32x32[i][TX_SIZES - 1] *
297             (pre_last_prob - cur_last_prob);
298
299     // p16x16
300     for (j = 0; j < TX_SIZES - 2; ++j) {
301       diff += (int)counts->tx.p16x16[i][j] *
302               (pre_fc->tx_probs.p16x16[i][j] - cur_fc->tx_probs.p16x16[i][j]);
303     }
304     pre_last_prob = MAX_PROB - pre_fc->tx_probs.p16x16[i][TX_SIZES - 3];
305     cur_last_prob = MAX_PROB - cur_fc->tx_probs.p16x16[i][TX_SIZES - 3];
306
307     diff += (int)counts->tx.p16x16[i][TX_SIZES - 2] *
308             (pre_last_prob - cur_last_prob);
309
310     // p8x8
311     for (j = 0; j < TX_SIZES - 3; ++j) {
312       diff += (int)counts->tx.p8x8[i][j] *
313               (pre_fc->tx_probs.p8x8[i][j] - cur_fc->tx_probs.p8x8[i][j]);
314     }
315     pre_last_prob = MAX_PROB - pre_fc->tx_probs.p8x8[i][TX_SIZES - 4];
316     cur_last_prob = MAX_PROB - cur_fc->tx_probs.p8x8[i][TX_SIZES - 4];
317
318     diff +=
319         (int)counts->tx.p8x8[i][TX_SIZES - 3] * (pre_last_prob - cur_last_prob);
320   }
321
322   // skip_probs
323   for (i = 0; i < SKIP_CONTEXTS; ++i) {
324     diff += (int)counts->skip[i][0] *
325             (pre_fc->skip_probs[i] - cur_fc->skip_probs[i]);
326
327     pre_last_prob = MAX_PROB - pre_fc->skip_probs[i];
328     cur_last_prob = MAX_PROB - cur_fc->skip_probs[i];
329
330     diff += (int)counts->skip[i][1] * (pre_last_prob - cur_last_prob);
331   }
332
333   // mv
334   for (i = 0; i < MV_JOINTS - 1; ++i) {
335     diff += (int)counts->mv.joints[i] *
336             (pre_fc->nmvc.joints[i] - cur_fc->nmvc.joints[i]);
337   }
338   pre_last_prob = MAX_PROB - pre_fc->nmvc.joints[MV_JOINTS - 2];
339   cur_last_prob = MAX_PROB - cur_fc->nmvc.joints[MV_JOINTS - 2];
340
341   diff +=
342       (int)counts->mv.joints[MV_JOINTS - 1] * (pre_last_prob - cur_last_prob);
343
344   for (i = 0; i < 2; ++i) {
345     const nmv_component_counts *nmv_count = &counts->mv.comps[i];
346     const nmv_component *pre_nmv_prob = &pre_fc->nmvc.comps[i];
347     const nmv_component *cur_nmv_prob = &cur_fc->nmvc.comps[i];
348
349     // sign
350     diff += (int)nmv_count->sign[0] * (pre_nmv_prob->sign - cur_nmv_prob->sign);
351
352     pre_last_prob = MAX_PROB - pre_nmv_prob->sign;
353     cur_last_prob = MAX_PROB - cur_nmv_prob->sign;
354
355     diff += (int)nmv_count->sign[1] * (pre_last_prob - cur_last_prob);
356
357     // classes
358     for (j = 0; j < MV_CLASSES - 1; ++j) {
359       diff += (int)nmv_count->classes[j] *
360               (pre_nmv_prob->classes[j] - cur_nmv_prob->classes[j]);
361     }
362     pre_last_prob = MAX_PROB - pre_nmv_prob->classes[MV_CLASSES - 2];
363     cur_last_prob = MAX_PROB - cur_nmv_prob->classes[MV_CLASSES - 2];
364
365     diff += (int)nmv_count->classes[MV_CLASSES - 1] *
366             (pre_last_prob - cur_last_prob);
367
368     // class0
369     for (j = 0; j < CLASS0_SIZE - 1; ++j) {
370       diff += (int)nmv_count->class0[j] *
371               (pre_nmv_prob->class0[j] - cur_nmv_prob->class0[j]);
372     }
373     pre_last_prob = MAX_PROB - pre_nmv_prob->class0[CLASS0_SIZE - 2];
374     cur_last_prob = MAX_PROB - cur_nmv_prob->class0[CLASS0_SIZE - 2];
375
376     diff += (int)nmv_count->class0[CLASS0_SIZE - 1] *
377             (pre_last_prob - cur_last_prob);
378
379     // bits
380     for (j = 0; j < MV_OFFSET_BITS; ++j) {
381       diff += (int)nmv_count->bits[j][0] *
382               (pre_nmv_prob->bits[j] - cur_nmv_prob->bits[j]);
383
384       pre_last_prob = MAX_PROB - pre_nmv_prob->bits[j];
385       cur_last_prob = MAX_PROB - cur_nmv_prob->bits[j];
386
387       diff += (int)nmv_count->bits[j][1] * (pre_last_prob - cur_last_prob);
388     }
389
390     // class0_fp
391     for (j = 0; j < CLASS0_SIZE; ++j) {
392       for (k = 0; k < MV_FP_SIZE - 1; ++k) {
393         diff += (int)nmv_count->class0_fp[j][k] *
394                 (pre_nmv_prob->class0_fp[j][k] - cur_nmv_prob->class0_fp[j][k]);
395       }
396       pre_last_prob = MAX_PROB - pre_nmv_prob->class0_fp[j][MV_FP_SIZE - 2];
397       cur_last_prob = MAX_PROB - cur_nmv_prob->class0_fp[j][MV_FP_SIZE - 2];
398
399       diff += (int)nmv_count->class0_fp[j][MV_FP_SIZE - 1] *
400               (pre_last_prob - cur_last_prob);
401     }
402
403     // fp
404     for (j = 0; j < MV_FP_SIZE - 1; ++j) {
405       diff +=
406           (int)nmv_count->fp[j] * (pre_nmv_prob->fp[j] - cur_nmv_prob->fp[j]);
407     }
408     pre_last_prob = MAX_PROB - pre_nmv_prob->fp[MV_FP_SIZE - 2];
409     cur_last_prob = MAX_PROB - cur_nmv_prob->fp[MV_FP_SIZE - 2];
410
411     diff +=
412         (int)nmv_count->fp[MV_FP_SIZE - 1] * (pre_last_prob - cur_last_prob);
413
414     // class0_hp
415     diff += (int)nmv_count->class0_hp[0] *
416             (pre_nmv_prob->class0_hp - cur_nmv_prob->class0_hp);
417
418     pre_last_prob = MAX_PROB - pre_nmv_prob->class0_hp;
419     cur_last_prob = MAX_PROB - cur_nmv_prob->class0_hp;
420
421     diff += (int)nmv_count->class0_hp[1] * (pre_last_prob - cur_last_prob);
422
423     // hp
424     diff += (int)nmv_count->hp[0] * (pre_nmv_prob->hp - cur_nmv_prob->hp);
425
426     pre_last_prob = MAX_PROB - pre_nmv_prob->hp;
427     cur_last_prob = MAX_PROB - cur_nmv_prob->hp;
428
429     diff += (int)nmv_count->hp[1] * (pre_last_prob - cur_last_prob);
430   }
431
432   return -diff;
433 }
434
435 // Test for whether to calculate metrics for the frame.
436 static int is_psnr_calc_enabled(VP9_COMP *cpi) {
437   VP9_COMMON *const cm = &cpi->common;
438   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
439
440   return cpi->b_calculate_psnr && (oxcf->pass != 1) && cm->show_frame;
441 }
442
443 /* clang-format off */
444 const Vp9LevelSpec vp9_level_defs[VP9_LEVELS] = {
445   //         sample rate    size   breadth  bitrate  cpb
446   { LEVEL_1,   829440,      36864,    512,   200,    400,    2, 1,  4,  8 },
447   { LEVEL_1_1, 2764800,     73728,    768,   800,    1000,   2, 1,  4,  8 },
448   { LEVEL_2,   4608000,     122880,   960,   1800,   1500,   2, 1,  4,  8 },
449   { LEVEL_2_1, 9216000,     245760,   1344,  3600,   2800,   2, 2,  4,  8 },
450   { LEVEL_3,   20736000,    552960,   2048,  7200,   6000,   2, 4,  4,  8 },
451   { LEVEL_3_1, 36864000,    983040,   2752,  12000,  10000,  2, 4,  4,  8 },
452   { LEVEL_4,   83558400,    2228224,  4160,  18000,  16000,  4, 4,  4,  8 },
453   { LEVEL_4_1, 160432128,   2228224,  4160,  30000,  18000,  4, 4,  5,  6 },
454   { LEVEL_5,   311951360,   8912896,  8384,  60000,  36000,  6, 8,  6,  4 },
455   { LEVEL_5_1, 588251136,   8912896,  8384,  120000, 46000,  8, 8,  10, 4 },
456   // TODO(huisu): update max_cpb_size for level 5_2 ~ 6_2 when
457   // they are finalized (currently tentative).
458   { LEVEL_5_2, 1176502272,  8912896,  8384,  180000, 90000,  8, 8,  10, 4 },
459   { LEVEL_6,   1176502272,  35651584, 16832, 180000, 90000,  8, 16, 10, 4 },
460   { LEVEL_6_1, 2353004544u, 35651584, 16832, 240000, 180000, 8, 16, 10, 4 },
461   { LEVEL_6_2, 4706009088u, 35651584, 16832, 480000, 360000, 8, 16, 10, 4 },
462 };
463 /* clang-format on */
464
465 static const char *level_fail_messages[TARGET_LEVEL_FAIL_IDS] = {
466   "The average bit-rate is too high.",
467   "The picture size is too large.",
468   "The picture width/height is too large.",
469   "The luma sample rate is too large.",
470   "The CPB size is too large.",
471   "The compression ratio is too small",
472   "Too many column tiles are used.",
473   "The alt-ref distance is too small.",
474   "Too many reference buffers are used."
475 };
476
477 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
478   switch (mode) {
479     case NORMAL:
480       *hr = 1;
481       *hs = 1;
482       break;
483     case FOURFIVE:
484       *hr = 4;
485       *hs = 5;
486       break;
487     case THREEFIVE:
488       *hr = 3;
489       *hs = 5;
490       break;
491     default:
492       assert(mode == ONETWO);
493       *hr = 1;
494       *hs = 2;
495       break;
496   }
497 }
498
499 // Mark all inactive blocks as active. Other segmentation features may be set
500 // so memset cannot be used, instead only inactive blocks should be reset.
501 static void suppress_active_map(VP9_COMP *cpi) {
502   unsigned char *const seg_map = cpi->segmentation_map;
503
504   if (cpi->active_map.enabled || cpi->active_map.update) {
505     const int rows = cpi->common.mi_rows;
506     const int cols = cpi->common.mi_cols;
507     int i;
508
509     for (i = 0; i < rows * cols; ++i)
510       if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
511         seg_map[i] = AM_SEGMENT_ID_ACTIVE;
512   }
513 }
514
515 static void apply_active_map(VP9_COMP *cpi) {
516   struct segmentation *const seg = &cpi->common.seg;
517   unsigned char *const seg_map = cpi->segmentation_map;
518   const unsigned char *const active_map = cpi->active_map.map;
519   int i;
520
521   assert(AM_SEGMENT_ID_ACTIVE == CR_SEGMENT_ID_BASE);
522
523   if (frame_is_intra_only(&cpi->common)) {
524     cpi->active_map.enabled = 0;
525     cpi->active_map.update = 1;
526   }
527
528   if (cpi->active_map.update) {
529     if (cpi->active_map.enabled) {
530       for (i = 0; i < cpi->common.mi_rows * cpi->common.mi_cols; ++i)
531         if (seg_map[i] == AM_SEGMENT_ID_ACTIVE) seg_map[i] = active_map[i];
532       vp9_enable_segmentation(seg);
533       vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
534       vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
535       // Setting the data to -MAX_LOOP_FILTER will result in the computed loop
536       // filter level being zero regardless of the value of seg->abs_delta.
537       vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF,
538                       -MAX_LOOP_FILTER);
539     } else {
540       vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
541       vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
542       if (seg->enabled) {
543         seg->update_data = 1;
544         seg->update_map = 1;
545       }
546     }
547     cpi->active_map.update = 0;
548   }
549 }
550
551 static void apply_roi_map(VP9_COMP *cpi) {
552   VP9_COMMON *cm = &cpi->common;
553   struct segmentation *const seg = &cm->seg;
554   vpx_roi_map_t *roi = &cpi->roi;
555   const int *delta_q = roi->delta_q;
556   const int *delta_lf = roi->delta_lf;
557   const int *skip = roi->skip;
558   int ref_frame[8];
559   int internal_delta_q[MAX_SEGMENTS];
560   int i;
561   static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
562                                     VP9_ALT_FLAG };
563
564   // TODO(jianj): Investigate why ROI not working in speed < 5 or in non
565   // realtime mode.
566   if (cpi->oxcf.mode != REALTIME || cpi->oxcf.speed < 5) return;
567   if (!roi->enabled) return;
568
569   memcpy(&ref_frame, roi->ref_frame, sizeof(ref_frame));
570
571   vp9_enable_segmentation(seg);
572   vp9_clearall_segfeatures(seg);
573   // Select delta coding method;
574   seg->abs_delta = SEGMENT_DELTADATA;
575
576   memcpy(cpi->segmentation_map, roi->roi_map, (cm->mi_rows * cm->mi_cols));
577
578   for (i = 0; i < MAX_SEGMENTS; ++i) {
579     // Translate the external delta q values to internal values.
580     internal_delta_q[i] = vp9_quantizer_to_qindex(abs(delta_q[i]));
581     if (delta_q[i] < 0) internal_delta_q[i] = -internal_delta_q[i];
582     vp9_disable_segfeature(seg, i, SEG_LVL_ALT_Q);
583     vp9_disable_segfeature(seg, i, SEG_LVL_ALT_LF);
584     if (internal_delta_q[i] != 0) {
585       vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
586       vp9_set_segdata(seg, i, SEG_LVL_ALT_Q, internal_delta_q[i]);
587     }
588     if (delta_lf[i] != 0) {
589       vp9_enable_segfeature(seg, i, SEG_LVL_ALT_LF);
590       vp9_set_segdata(seg, i, SEG_LVL_ALT_LF, delta_lf[i]);
591     }
592     if (skip[i] != 0) {
593       vp9_enable_segfeature(seg, i, SEG_LVL_SKIP);
594       vp9_set_segdata(seg, i, SEG_LVL_SKIP, skip[i]);
595     }
596     if (ref_frame[i] >= 0) {
597       int valid_ref = 1;
598       // ALTREF is not used as reference for nonrd_pickmode with 0 lag.
599       if (ref_frame[i] == ALTREF_FRAME && cpi->sf.use_nonrd_pick_mode)
600         valid_ref = 0;
601       // If GOLDEN is selected, make sure it's set as reference.
602       if (ref_frame[i] == GOLDEN_FRAME &&
603           !(cpi->ref_frame_flags & flag_list[ref_frame[i]])) {
604         valid_ref = 0;
605       }
606       // GOLDEN was updated in previous encoded frame, so GOLDEN and LAST are
607       // same reference.
608       if (ref_frame[i] == GOLDEN_FRAME && cpi->rc.frames_since_golden == 0)
609         ref_frame[i] = LAST_FRAME;
610       if (valid_ref) {
611         vp9_enable_segfeature(seg, i, SEG_LVL_REF_FRAME);
612         vp9_set_segdata(seg, i, SEG_LVL_REF_FRAME, ref_frame[i]);
613       }
614     }
615   }
616   roi->enabled = 1;
617 }
618
619 static void init_level_info(Vp9LevelInfo *level_info) {
620   Vp9LevelStats *const level_stats = &level_info->level_stats;
621   Vp9LevelSpec *const level_spec = &level_info->level_spec;
622
623   memset(level_stats, 0, sizeof(*level_stats));
624   memset(level_spec, 0, sizeof(*level_spec));
625   level_spec->level = LEVEL_UNKNOWN;
626   level_spec->min_altref_distance = INT_MAX;
627 }
628
629 static int check_seg_range(int seg_data[8], int range) {
630   return !(abs(seg_data[0]) > range || abs(seg_data[1]) > range ||
631            abs(seg_data[2]) > range || abs(seg_data[3]) > range ||
632            abs(seg_data[4]) > range || abs(seg_data[5]) > range ||
633            abs(seg_data[6]) > range || abs(seg_data[7]) > range);
634 }
635
636 VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec) {
637   int i;
638   const Vp9LevelSpec *this_level;
639
640   vpx_clear_system_state();
641
642   for (i = 0; i < VP9_LEVELS; ++i) {
643     this_level = &vp9_level_defs[i];
644     if ((double)level_spec->max_luma_sample_rate >
645             (double)this_level->max_luma_sample_rate *
646                 (1 + SAMPLE_RATE_GRACE_P) ||
647         level_spec->max_luma_picture_size > this_level->max_luma_picture_size ||
648         level_spec->max_luma_picture_breadth >
649             this_level->max_luma_picture_breadth ||
650         level_spec->average_bitrate > this_level->average_bitrate ||
651         level_spec->max_cpb_size > this_level->max_cpb_size ||
652         level_spec->compression_ratio < this_level->compression_ratio ||
653         level_spec->max_col_tiles > this_level->max_col_tiles ||
654         level_spec->min_altref_distance < this_level->min_altref_distance ||
655         level_spec->max_ref_frame_buffers > this_level->max_ref_frame_buffers)
656       continue;
657     break;
658   }
659   return (i == VP9_LEVELS) ? LEVEL_UNKNOWN : vp9_level_defs[i].level;
660 }
661
662 int vp9_set_roi_map(VP9_COMP *cpi, unsigned char *map, unsigned int rows,
663                     unsigned int cols, int delta_q[8], int delta_lf[8],
664                     int skip[8], int ref_frame[8]) {
665   VP9_COMMON *cm = &cpi->common;
666   vpx_roi_map_t *roi = &cpi->roi;
667   const int range = 63;
668   const int ref_frame_range = 3;  // Alt-ref
669   const int skip_range = 1;
670   const int frame_rows = cpi->common.mi_rows;
671   const int frame_cols = cpi->common.mi_cols;
672
673   // Check number of rows and columns match
674   if (frame_rows != (int)rows || frame_cols != (int)cols) {
675     return -1;
676   }
677
678   if (!check_seg_range(delta_q, range) || !check_seg_range(delta_lf, range) ||
679       !check_seg_range(ref_frame, ref_frame_range) ||
680       !check_seg_range(skip, skip_range))
681     return -1;
682
683   // Also disable segmentation if no deltas are specified.
684   if (!map ||
685       (!(delta_q[0] | delta_q[1] | delta_q[2] | delta_q[3] | delta_q[4] |
686          delta_q[5] | delta_q[6] | delta_q[7] | delta_lf[0] | delta_lf[1] |
687          delta_lf[2] | delta_lf[3] | delta_lf[4] | delta_lf[5] | delta_lf[6] |
688          delta_lf[7] | skip[0] | skip[1] | skip[2] | skip[3] | skip[4] |
689          skip[5] | skip[6] | skip[7]) &&
690        (ref_frame[0] == -1 && ref_frame[1] == -1 && ref_frame[2] == -1 &&
691         ref_frame[3] == -1 && ref_frame[4] == -1 && ref_frame[5] == -1 &&
692         ref_frame[6] == -1 && ref_frame[7] == -1))) {
693     vp9_disable_segmentation(&cm->seg);
694     cpi->roi.enabled = 0;
695     return 0;
696   }
697
698   if (roi->roi_map) {
699     vpx_free(roi->roi_map);
700     roi->roi_map = NULL;
701   }
702   CHECK_MEM_ERROR(cm, roi->roi_map, vpx_malloc(rows * cols));
703
704   // Copy to ROI sturcture in the compressor.
705   memcpy(roi->roi_map, map, rows * cols);
706   memcpy(&roi->delta_q, delta_q, MAX_SEGMENTS * sizeof(delta_q[0]));
707   memcpy(&roi->delta_lf, delta_lf, MAX_SEGMENTS * sizeof(delta_lf[0]));
708   memcpy(&roi->skip, skip, MAX_SEGMENTS * sizeof(skip[0]));
709   memcpy(&roi->ref_frame, ref_frame, MAX_SEGMENTS * sizeof(ref_frame[0]));
710   roi->enabled = 1;
711   roi->rows = rows;
712   roi->cols = cols;
713
714   return 0;
715 }
716
717 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
718                        int cols) {
719   if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
720     unsigned char *const active_map_8x8 = cpi->active_map.map;
721     const int mi_rows = cpi->common.mi_rows;
722     const int mi_cols = cpi->common.mi_cols;
723     cpi->active_map.update = 1;
724     if (new_map_16x16) {
725       int r, c;
726       for (r = 0; r < mi_rows; ++r) {
727         for (c = 0; c < mi_cols; ++c) {
728           active_map_8x8[r * mi_cols + c] =
729               new_map_16x16[(r >> 1) * cols + (c >> 1)]
730                   ? AM_SEGMENT_ID_ACTIVE
731                   : AM_SEGMENT_ID_INACTIVE;
732         }
733       }
734       cpi->active_map.enabled = 1;
735     } else {
736       cpi->active_map.enabled = 0;
737     }
738     return 0;
739   } else {
740     return -1;
741   }
742 }
743
744 int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
745                        int cols) {
746   if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
747       new_map_16x16) {
748     unsigned char *const seg_map_8x8 = cpi->segmentation_map;
749     const int mi_rows = cpi->common.mi_rows;
750     const int mi_cols = cpi->common.mi_cols;
751     memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
752     if (cpi->active_map.enabled) {
753       int r, c;
754       for (r = 0; r < mi_rows; ++r) {
755         for (c = 0; c < mi_cols; ++c) {
756           // Cyclic refresh segments are considered active despite not having
757           // AM_SEGMENT_ID_ACTIVE
758           new_map_16x16[(r >> 1) * cols + (c >> 1)] |=
759               seg_map_8x8[r * mi_cols + c] != AM_SEGMENT_ID_INACTIVE;
760         }
761       }
762     }
763     return 0;
764   } else {
765     return -1;
766   }
767 }
768
769 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
770   MACROBLOCK *const mb = &cpi->td.mb;
771   cpi->common.allow_high_precision_mv = allow_high_precision_mv;
772   if (cpi->common.allow_high_precision_mv) {
773     mb->mvcost = mb->nmvcost_hp;
774     mb->mvsadcost = mb->nmvsadcost_hp;
775   } else {
776     mb->mvcost = mb->nmvcost;
777     mb->mvsadcost = mb->nmvsadcost;
778   }
779 }
780
781 static void setup_frame(VP9_COMP *cpi) {
782   VP9_COMMON *const cm = &cpi->common;
783   // Set up entropy context depending on frame type. The decoder mandates
784   // the use of the default context, index 0, for keyframes and inter
785   // frames where the error_resilient_mode or intra_only flag is set. For
786   // other inter-frames the encoder currently uses only two contexts;
787   // context 1 for ALTREF frames and context 0 for the others.
788   if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
789     vp9_setup_past_independence(cm);
790   } else {
791     if (!cpi->use_svc) cm->frame_context_idx = cpi->refresh_alt_ref_frame;
792   }
793
794   if (cm->frame_type == KEY_FRAME) {
795     cpi->refresh_golden_frame = 1;
796     cpi->refresh_alt_ref_frame = 1;
797     vp9_zero(cpi->interp_filter_selected);
798   } else {
799     *cm->fc = cm->frame_contexts[cm->frame_context_idx];
800     vp9_zero(cpi->interp_filter_selected[0]);
801   }
802 }
803
804 static void vp9_enc_setup_mi(VP9_COMMON *cm) {
805   int i;
806   cm->mi = cm->mip + cm->mi_stride + 1;
807   memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
808   cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
809   // Clear top border row
810   memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
811   // Clear left border column
812   for (i = 1; i < cm->mi_rows + 1; ++i)
813     memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
814
815   cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
816   cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
817
818   memset(cm->mi_grid_base, 0,
819          cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
820 }
821
822 static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
823   cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
824   if (!cm->mip) return 1;
825   cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
826   if (!cm->prev_mip) return 1;
827   cm->mi_alloc_size = mi_size;
828
829   cm->mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO *));
830   if (!cm->mi_grid_base) return 1;
831   cm->prev_mi_grid_base =
832       (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO *));
833   if (!cm->prev_mi_grid_base) return 1;
834
835   return 0;
836 }
837
838 static void vp9_enc_free_mi(VP9_COMMON *cm) {
839   vpx_free(cm->mip);
840   cm->mip = NULL;
841   vpx_free(cm->prev_mip);
842   cm->prev_mip = NULL;
843   vpx_free(cm->mi_grid_base);
844   cm->mi_grid_base = NULL;
845   vpx_free(cm->prev_mi_grid_base);
846   cm->prev_mi_grid_base = NULL;
847   cm->mi_alloc_size = 0;
848 }
849
850 static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
851   // Current mip will be the prev_mip for the next frame.
852   MODE_INFO **temp_base = cm->prev_mi_grid_base;
853   MODE_INFO *temp = cm->prev_mip;
854   cm->prev_mip = cm->mip;
855   cm->mip = temp;
856
857   // Update the upper left visible macroblock ptrs.
858   cm->mi = cm->mip + cm->mi_stride + 1;
859   cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
860
861   cm->prev_mi_grid_base = cm->mi_grid_base;
862   cm->mi_grid_base = temp_base;
863   cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
864   cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
865 }
866
867 void vp9_initialize_enc(void) {
868   static volatile int init_done = 0;
869
870   if (!init_done) {
871     vp9_rtcd();
872     vpx_dsp_rtcd();
873     vpx_scale_rtcd();
874     vp9_init_intra_predictors();
875     vp9_init_me_luts();
876     vp9_rc_init_minq_luts();
877     vp9_entropy_mv_init();
878 #if !CONFIG_REALTIME_ONLY
879     vp9_temporal_filter_init();
880 #endif
881     init_done = 1;
882   }
883 }
884
885 static void dealloc_compressor_data(VP9_COMP *cpi) {
886   VP9_COMMON *const cm = &cpi->common;
887   int i;
888
889   vpx_free(cpi->mbmi_ext_base);
890   cpi->mbmi_ext_base = NULL;
891
892   vpx_free(cpi->tile_data);
893   cpi->tile_data = NULL;
894
895   vpx_free(cpi->segmentation_map);
896   cpi->segmentation_map = NULL;
897   vpx_free(cpi->coding_context.last_frame_seg_map_copy);
898   cpi->coding_context.last_frame_seg_map_copy = NULL;
899
900   vpx_free(cpi->nmvcosts[0]);
901   vpx_free(cpi->nmvcosts[1]);
902   cpi->nmvcosts[0] = NULL;
903   cpi->nmvcosts[1] = NULL;
904
905   vpx_free(cpi->nmvcosts_hp[0]);
906   vpx_free(cpi->nmvcosts_hp[1]);
907   cpi->nmvcosts_hp[0] = NULL;
908   cpi->nmvcosts_hp[1] = NULL;
909
910   vpx_free(cpi->nmvsadcosts[0]);
911   vpx_free(cpi->nmvsadcosts[1]);
912   cpi->nmvsadcosts[0] = NULL;
913   cpi->nmvsadcosts[1] = NULL;
914
915   vpx_free(cpi->nmvsadcosts_hp[0]);
916   vpx_free(cpi->nmvsadcosts_hp[1]);
917   cpi->nmvsadcosts_hp[0] = NULL;
918   cpi->nmvsadcosts_hp[1] = NULL;
919
920   vpx_free(cpi->skin_map);
921   cpi->skin_map = NULL;
922
923   vpx_free(cpi->prev_partition);
924   cpi->prev_partition = NULL;
925
926   vpx_free(cpi->svc.prev_partition_svc);
927   cpi->svc.prev_partition_svc = NULL;
928
929   vpx_free(cpi->prev_segment_id);
930   cpi->prev_segment_id = NULL;
931
932   vpx_free(cpi->prev_variance_low);
933   cpi->prev_variance_low = NULL;
934
935   vpx_free(cpi->copied_frame_cnt);
936   cpi->copied_frame_cnt = NULL;
937
938   vpx_free(cpi->content_state_sb_fd);
939   cpi->content_state_sb_fd = NULL;
940
941   vpx_free(cpi->count_arf_frame_usage);
942   cpi->count_arf_frame_usage = NULL;
943   vpx_free(cpi->count_lastgolden_frame_usage);
944   cpi->count_lastgolden_frame_usage = NULL;
945
946   vp9_cyclic_refresh_free(cpi->cyclic_refresh);
947   cpi->cyclic_refresh = NULL;
948
949   vpx_free(cpi->active_map.map);
950   cpi->active_map.map = NULL;
951
952   vpx_free(cpi->roi.roi_map);
953   cpi->roi.roi_map = NULL;
954
955   vpx_free(cpi->consec_zero_mv);
956   cpi->consec_zero_mv = NULL;
957
958   vp9_free_ref_frame_buffers(cm->buffer_pool);
959 #if CONFIG_VP9_POSTPROC
960   vp9_free_postproc_buffers(cm);
961 #endif
962   vp9_free_context_buffers(cm);
963
964   vpx_free_frame_buffer(&cpi->last_frame_uf);
965   vpx_free_frame_buffer(&cpi->scaled_source);
966   vpx_free_frame_buffer(&cpi->scaled_last_source);
967   vpx_free_frame_buffer(&cpi->alt_ref_buffer);
968 #ifdef ENABLE_KF_DENOISE
969   vpx_free_frame_buffer(&cpi->raw_unscaled_source);
970   vpx_free_frame_buffer(&cpi->raw_scaled_source);
971 #endif
972
973   vp9_lookahead_destroy(cpi->lookahead);
974
975   vpx_free(cpi->tile_tok[0][0]);
976   cpi->tile_tok[0][0] = 0;
977
978   vpx_free(cpi->tplist[0][0]);
979   cpi->tplist[0][0] = NULL;
980
981   vp9_free_pc_tree(&cpi->td);
982
983   for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
984     LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
985     vpx_free(lc->rc_twopass_stats_in.buf);
986     lc->rc_twopass_stats_in.buf = NULL;
987     lc->rc_twopass_stats_in.sz = 0;
988   }
989
990   if (cpi->source_diff_var != NULL) {
991     vpx_free(cpi->source_diff_var);
992     cpi->source_diff_var = NULL;
993   }
994
995   for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
996     vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]);
997   }
998   memset(&cpi->svc.scaled_frames[0], 0,
999          MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
1000
1001   vpx_free_frame_buffer(&cpi->svc.scaled_temp);
1002   memset(&cpi->svc.scaled_temp, 0, sizeof(cpi->svc.scaled_temp));
1003
1004   vpx_free_frame_buffer(&cpi->svc.empty_frame.img);
1005   memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
1006
1007   vp9_free_svc_cyclic_refresh(cpi);
1008 }
1009
1010 static void save_coding_context(VP9_COMP *cpi) {
1011   CODING_CONTEXT *const cc = &cpi->coding_context;
1012   VP9_COMMON *cm = &cpi->common;
1013
1014   // Stores a snapshot of key state variables which can subsequently be
1015   // restored with a call to vp9_restore_coding_context. These functions are
1016   // intended for use in a re-code loop in vp9_compress_frame where the
1017   // quantizer value is adjusted between loop iterations.
1018   vp9_copy(cc->nmvjointcost, cpi->td.mb.nmvjointcost);
1019
1020   memcpy(cc->nmvcosts[0], cpi->nmvcosts[0],
1021          MV_VALS * sizeof(*cpi->nmvcosts[0]));
1022   memcpy(cc->nmvcosts[1], cpi->nmvcosts[1],
1023          MV_VALS * sizeof(*cpi->nmvcosts[1]));
1024   memcpy(cc->nmvcosts_hp[0], cpi->nmvcosts_hp[0],
1025          MV_VALS * sizeof(*cpi->nmvcosts_hp[0]));
1026   memcpy(cc->nmvcosts_hp[1], cpi->nmvcosts_hp[1],
1027          MV_VALS * sizeof(*cpi->nmvcosts_hp[1]));
1028
1029   vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
1030
1031   memcpy(cpi->coding_context.last_frame_seg_map_copy, cm->last_frame_seg_map,
1032          (cm->mi_rows * cm->mi_cols));
1033
1034   vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
1035   vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
1036
1037   cc->fc = *cm->fc;
1038 }
1039
1040 static void restore_coding_context(VP9_COMP *cpi) {
1041   CODING_CONTEXT *const cc = &cpi->coding_context;
1042   VP9_COMMON *cm = &cpi->common;
1043
1044   // Restore key state variables to the snapshot state stored in the
1045   // previous call to vp9_save_coding_context.
1046   vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
1047
1048   memcpy(cpi->nmvcosts[0], cc->nmvcosts[0], MV_VALS * sizeof(*cc->nmvcosts[0]));
1049   memcpy(cpi->nmvcosts[1], cc->nmvcosts[1], MV_VALS * sizeof(*cc->nmvcosts[1]));
1050   memcpy(cpi->nmvcosts_hp[0], cc->nmvcosts_hp[0],
1051          MV_VALS * sizeof(*cc->nmvcosts_hp[0]));
1052   memcpy(cpi->nmvcosts_hp[1], cc->nmvcosts_hp[1],
1053          MV_VALS * sizeof(*cc->nmvcosts_hp[1]));
1054
1055   vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
1056
1057   memcpy(cm->last_frame_seg_map, cpi->coding_context.last_frame_seg_map_copy,
1058          (cm->mi_rows * cm->mi_cols));
1059
1060   vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
1061   vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
1062
1063   *cm->fc = cc->fc;
1064 }
1065
1066 #if !CONFIG_REALTIME_ONLY
1067 static void configure_static_seg_features(VP9_COMP *cpi) {
1068   VP9_COMMON *const cm = &cpi->common;
1069   const RATE_CONTROL *const rc = &cpi->rc;
1070   struct segmentation *const seg = &cm->seg;
1071
1072   int high_q = (int)(rc->avg_q > 48.0);
1073   int qi_delta;
1074
1075   // Disable and clear down for KF
1076   if (cm->frame_type == KEY_FRAME) {
1077     // Clear down the global segmentation map
1078     memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
1079     seg->update_map = 0;
1080     seg->update_data = 0;
1081     cpi->static_mb_pct = 0;
1082
1083     // Disable segmentation
1084     vp9_disable_segmentation(seg);
1085
1086     // Clear down the segment features.
1087     vp9_clearall_segfeatures(seg);
1088   } else if (cpi->refresh_alt_ref_frame) {
1089     // If this is an alt ref frame
1090     // Clear down the global segmentation map
1091     memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
1092     seg->update_map = 0;
1093     seg->update_data = 0;
1094     cpi->static_mb_pct = 0;
1095
1096     // Disable segmentation and individual segment features by default
1097     vp9_disable_segmentation(seg);
1098     vp9_clearall_segfeatures(seg);
1099
1100     // Scan frames from current to arf frame.
1101     // This function re-enables segmentation if appropriate.
1102     vp9_update_mbgraph_stats(cpi);
1103
1104     // If segmentation was enabled set those features needed for the
1105     // arf itself.
1106     if (seg->enabled) {
1107       seg->update_map = 1;
1108       seg->update_data = 1;
1109
1110       qi_delta =
1111           vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875, cm->bit_depth);
1112       vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
1113       vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
1114
1115       vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
1116       vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
1117
1118       // Where relevant assume segment data is delta data
1119       seg->abs_delta = SEGMENT_DELTADATA;
1120     }
1121   } else if (seg->enabled) {
1122     // All other frames if segmentation has been enabled
1123
1124     // First normal frame in a valid gf or alt ref group
1125     if (rc->frames_since_golden == 0) {
1126       // Set up segment features for normal frames in an arf group
1127       if (rc->source_alt_ref_active) {
1128         seg->update_map = 0;
1129         seg->update_data = 1;
1130         seg->abs_delta = SEGMENT_DELTADATA;
1131
1132         qi_delta =
1133             vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125, cm->bit_depth);
1134         vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
1135         vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
1136
1137         vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
1138         vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
1139
1140         // Segment coding disabled for compred testing
1141         if (high_q || (cpi->static_mb_pct == 100)) {
1142           vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
1143           vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
1144           vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
1145         }
1146       } else {
1147         // Disable segmentation and clear down features if alt ref
1148         // is not active for this group
1149
1150         vp9_disable_segmentation(seg);
1151
1152         memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
1153
1154         seg->update_map = 0;
1155         seg->update_data = 0;
1156
1157         vp9_clearall_segfeatures(seg);
1158       }
1159     } else if (rc->is_src_frame_alt_ref) {
1160       // Special case where we are coding over the top of a previous
1161       // alt ref frame.
1162       // Segment coding disabled for compred testing
1163
1164       // Enable ref frame features for segment 0 as well
1165       vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
1166       vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
1167
1168       // All mbs should use ALTREF_FRAME
1169       vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
1170       vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
1171       vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
1172       vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
1173
1174       // Skip all MBs if high Q (0,0 mv and skip coeffs)
1175       if (high_q) {
1176         vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
1177         vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
1178       }
1179       // Enable data update
1180       seg->update_data = 1;
1181     } else {
1182       // All other frames.
1183
1184       // No updates.. leave things as they are.
1185       seg->update_map = 0;
1186       seg->update_data = 0;
1187     }
1188   }
1189 }
1190 #endif  // !CONFIG_REALTIME_ONLY
1191
1192 static void update_reference_segmentation_map(VP9_COMP *cpi) {
1193   VP9_COMMON *const cm = &cpi->common;
1194   MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
1195   uint8_t *cache_ptr = cm->last_frame_seg_map;
1196   int row, col;
1197
1198   for (row = 0; row < cm->mi_rows; row++) {
1199     MODE_INFO **mi_8x8 = mi_8x8_ptr;
1200     uint8_t *cache = cache_ptr;
1201     for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
1202       cache[0] = mi_8x8[0]->segment_id;
1203     mi_8x8_ptr += cm->mi_stride;
1204     cache_ptr += cm->mi_cols;
1205   }
1206 }
1207
1208 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
1209   VP9_COMMON *cm = &cpi->common;
1210   const VP9EncoderConfig *oxcf = &cpi->oxcf;
1211
1212   if (!cpi->lookahead)
1213     cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
1214                                         cm->subsampling_x, cm->subsampling_y,
1215 #if CONFIG_VP9_HIGHBITDEPTH
1216                                         cm->use_highbitdepth,
1217 #endif
1218                                         oxcf->lag_in_frames);
1219   if (!cpi->lookahead)
1220     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1221                        "Failed to allocate lag buffers");
1222
1223   // TODO(agrange) Check if ARF is enabled and skip allocation if not.
1224   if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, oxcf->width, oxcf->height,
1225                                cm->subsampling_x, cm->subsampling_y,
1226 #if CONFIG_VP9_HIGHBITDEPTH
1227                                cm->use_highbitdepth,
1228 #endif
1229                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
1230                                NULL, NULL, NULL))
1231     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1232                        "Failed to allocate altref buffer");
1233 }
1234
1235 static void alloc_util_frame_buffers(VP9_COMP *cpi) {
1236   VP9_COMMON *const cm = &cpi->common;
1237   if (vpx_realloc_frame_buffer(&cpi->last_frame_uf, cm->width, cm->height,
1238                                cm->subsampling_x, cm->subsampling_y,
1239 #if CONFIG_VP9_HIGHBITDEPTH
1240                                cm->use_highbitdepth,
1241 #endif
1242                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
1243                                NULL, NULL, NULL))
1244     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1245                        "Failed to allocate last frame buffer");
1246
1247   if (vpx_realloc_frame_buffer(&cpi->scaled_source, cm->width, cm->height,
1248                                cm->subsampling_x, cm->subsampling_y,
1249 #if CONFIG_VP9_HIGHBITDEPTH
1250                                cm->use_highbitdepth,
1251 #endif
1252                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
1253                                NULL, NULL, NULL))
1254     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1255                        "Failed to allocate scaled source buffer");
1256
1257   // For 1 pass cbr: allocate scaled_frame that may be used as an intermediate
1258   // buffer for a 2 stage down-sampling: two stages of 1:2 down-sampling for a
1259   // target of 1/4x1/4. number_spatial_layers must be greater than 2.
1260   if (is_one_pass_cbr_svc(cpi) && !cpi->svc.scaled_temp_is_alloc &&
1261       cpi->svc.number_spatial_layers > 2) {
1262     cpi->svc.scaled_temp_is_alloc = 1;
1263     if (vpx_realloc_frame_buffer(
1264             &cpi->svc.scaled_temp, cm->width >> 1, cm->height >> 1,
1265             cm->subsampling_x, cm->subsampling_y,
1266 #if CONFIG_VP9_HIGHBITDEPTH
1267             cm->use_highbitdepth,
1268 #endif
1269             VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment, NULL, NULL, NULL))
1270       vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1271                          "Failed to allocate scaled_frame for svc ");
1272   }
1273
1274   if (vpx_realloc_frame_buffer(&cpi->scaled_last_source, cm->width, cm->height,
1275                                cm->subsampling_x, cm->subsampling_y,
1276 #if CONFIG_VP9_HIGHBITDEPTH
1277                                cm->use_highbitdepth,
1278 #endif
1279                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
1280                                NULL, NULL, NULL))
1281     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1282                        "Failed to allocate scaled last source buffer");
1283 #ifdef ENABLE_KF_DENOISE
1284   if (vpx_realloc_frame_buffer(&cpi->raw_unscaled_source, cm->width, cm->height,
1285                                cm->subsampling_x, cm->subsampling_y,
1286 #if CONFIG_VP9_HIGHBITDEPTH
1287                                cm->use_highbitdepth,
1288 #endif
1289                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
1290                                NULL, NULL, NULL))
1291     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1292                        "Failed to allocate unscaled raw source frame buffer");
1293
1294   if (vpx_realloc_frame_buffer(&cpi->raw_scaled_source, cm->width, cm->height,
1295                                cm->subsampling_x, cm->subsampling_y,
1296 #if CONFIG_VP9_HIGHBITDEPTH
1297                                cm->use_highbitdepth,
1298 #endif
1299                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
1300                                NULL, NULL, NULL))
1301     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1302                        "Failed to allocate scaled raw source frame buffer");
1303 #endif
1304 }
1305
1306 static int alloc_context_buffers_ext(VP9_COMP *cpi) {
1307   VP9_COMMON *cm = &cpi->common;
1308   int mi_size = cm->mi_cols * cm->mi_rows;
1309
1310   cpi->mbmi_ext_base = vpx_calloc(mi_size, sizeof(*cpi->mbmi_ext_base));
1311   if (!cpi->mbmi_ext_base) return 1;
1312
1313   return 0;
1314 }
1315
1316 static void alloc_compressor_data(VP9_COMP *cpi) {
1317   VP9_COMMON *cm = &cpi->common;
1318   int sb_rows;
1319
1320   vp9_alloc_context_buffers(cm, cm->width, cm->height);
1321
1322   alloc_context_buffers_ext(cpi);
1323
1324   vpx_free(cpi->tile_tok[0][0]);
1325
1326   {
1327     unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
1328     CHECK_MEM_ERROR(cm, cpi->tile_tok[0][0],
1329                     vpx_calloc(tokens, sizeof(*cpi->tile_tok[0][0])));
1330   }
1331
1332   sb_rows = mi_cols_aligned_to_sb(cm->mi_rows) >> MI_BLOCK_SIZE_LOG2;
1333   vpx_free(cpi->tplist[0][0]);
1334   CHECK_MEM_ERROR(
1335       cm, cpi->tplist[0][0],
1336       vpx_calloc(sb_rows * 4 * (1 << 6), sizeof(*cpi->tplist[0][0])));
1337
1338   vp9_setup_pc_tree(&cpi->common, &cpi->td);
1339 }
1340
1341 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
1342   cpi->framerate = framerate < 0.1 ? 30 : framerate;
1343   vp9_rc_update_framerate(cpi);
1344 }
1345
1346 static void set_tile_limits(VP9_COMP *cpi) {
1347   VP9_COMMON *const cm = &cpi->common;
1348
1349   int min_log2_tile_cols, max_log2_tile_cols;
1350   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1351
1352   cm->log2_tile_cols =
1353       clamp(cpi->oxcf.tile_columns, min_log2_tile_cols, max_log2_tile_cols);
1354   cm->log2_tile_rows = cpi->oxcf.tile_rows;
1355
1356   if (cpi->oxcf.target_level == LEVEL_AUTO) {
1357     const int level_tile_cols =
1358         log_tile_cols_from_picsize_level(cpi->common.width, cpi->common.height);
1359     if (cm->log2_tile_cols > level_tile_cols) {
1360       cm->log2_tile_cols = VPXMAX(level_tile_cols, min_log2_tile_cols);
1361     }
1362   }
1363 }
1364
1365 static void update_frame_size(VP9_COMP *cpi) {
1366   VP9_COMMON *const cm = &cpi->common;
1367   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
1368
1369   vp9_set_mb_mi(cm, cm->width, cm->height);
1370   vp9_init_context_buffers(cm);
1371   vp9_init_macroblockd(cm, xd, NULL);
1372   cpi->td.mb.mbmi_ext_base = cpi->mbmi_ext_base;
1373   memset(cpi->mbmi_ext_base, 0,
1374          cm->mi_rows * cm->mi_cols * sizeof(*cpi->mbmi_ext_base));
1375
1376   set_tile_limits(cpi);
1377 }
1378
1379 static void init_buffer_indices(VP9_COMP *cpi) {
1380   int ref_frame;
1381
1382   for (ref_frame = 0; ref_frame < REF_FRAMES; ++ref_frame)
1383     cpi->ref_fb_idx[ref_frame] = ref_frame;
1384
1385   cpi->lst_fb_idx = cpi->ref_fb_idx[LAST_FRAME - 1];
1386   cpi->gld_fb_idx = cpi->ref_fb_idx[GOLDEN_FRAME - 1];
1387   cpi->alt_fb_idx = cpi->ref_fb_idx[ALTREF_FRAME - 1];
1388 }
1389
1390 static void init_level_constraint(LevelConstraint *lc) {
1391   lc->level_index = -1;
1392   lc->max_cpb_size = INT_MAX;
1393   lc->max_frame_size = INT_MAX;
1394   lc->rc_config_updated = 0;
1395   lc->fail_flag = 0;
1396 }
1397
1398 static void set_level_constraint(LevelConstraint *ls, int8_t level_index) {
1399   vpx_clear_system_state();
1400   ls->level_index = level_index;
1401   if (level_index >= 0) {
1402     ls->max_cpb_size = vp9_level_defs[level_index].max_cpb_size * (double)1000;
1403   }
1404 }
1405
1406 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
1407   VP9_COMMON *const cm = &cpi->common;
1408
1409   cpi->oxcf = *oxcf;
1410   cpi->framerate = oxcf->init_framerate;
1411   cm->profile = oxcf->profile;
1412   cm->bit_depth = oxcf->bit_depth;
1413 #if CONFIG_VP9_HIGHBITDEPTH
1414   cm->use_highbitdepth = oxcf->use_highbitdepth;
1415 #endif
1416   cm->color_space = oxcf->color_space;
1417   cm->color_range = oxcf->color_range;
1418
1419   cpi->target_level = oxcf->target_level;
1420   cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
1421   set_level_constraint(&cpi->level_constraint,
1422                        get_level_index(cpi->target_level));
1423
1424   cm->width = oxcf->width;
1425   cm->height = oxcf->height;
1426   alloc_compressor_data(cpi);
1427
1428   cpi->svc.temporal_layering_mode = oxcf->temporal_layering_mode;
1429
1430   // Single thread case: use counts in common.
1431   cpi->td.counts = &cm->counts;
1432
1433   // Spatial scalability.
1434   cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
1435   // Temporal scalability.
1436   cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
1437
1438   if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
1439       ((cpi->svc.number_temporal_layers > 1 ||
1440         cpi->svc.number_spatial_layers > 1) &&
1441        cpi->oxcf.pass != 1)) {
1442     vp9_init_layer_context(cpi);
1443   }
1444
1445   // change includes all joint functionality
1446   vp9_change_config(cpi, oxcf);
1447
1448   cpi->static_mb_pct = 0;
1449   cpi->ref_frame_flags = 0;
1450
1451   init_buffer_indices(cpi);
1452
1453   vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
1454 }
1455
1456 static void set_rc_buffer_sizes(RATE_CONTROL *rc,
1457                                 const VP9EncoderConfig *oxcf) {
1458   const int64_t bandwidth = oxcf->target_bandwidth;
1459   const int64_t starting = oxcf->starting_buffer_level_ms;
1460   const int64_t optimal = oxcf->optimal_buffer_level_ms;
1461   const int64_t maximum = oxcf->maximum_buffer_size_ms;
1462
1463   rc->starting_buffer_level = starting * bandwidth / 1000;
1464   rc->optimal_buffer_level =
1465       (optimal == 0) ? bandwidth / 8 : optimal * bandwidth / 1000;
1466   rc->maximum_buffer_size =
1467       (maximum == 0) ? bandwidth / 8 : maximum * bandwidth / 1000;
1468 }
1469
1470 #if CONFIG_VP9_HIGHBITDEPTH
1471 #define HIGHBD_BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX4DF) \
1472   cpi->fn_ptr[BT].sdf = SDF;                             \
1473   cpi->fn_ptr[BT].sdaf = SDAF;                           \
1474   cpi->fn_ptr[BT].vf = VF;                               \
1475   cpi->fn_ptr[BT].svf = SVF;                             \
1476   cpi->fn_ptr[BT].svaf = SVAF;                           \
1477   cpi->fn_ptr[BT].sdx4df = SDX4DF;
1478
1479 #define MAKE_BFP_SAD_WRAPPER(fnname)                                           \
1480   static unsigned int fnname##_bits8(const uint8_t *src_ptr,                   \
1481                                      int source_stride,                        \
1482                                      const uint8_t *ref_ptr, int ref_stride) { \
1483     return fnname(src_ptr, source_stride, ref_ptr, ref_stride);                \
1484   }                                                                            \
1485   static unsigned int fnname##_bits10(                                         \
1486       const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
1487       int ref_stride) {                                                        \
1488     return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 2;           \
1489   }                                                                            \
1490   static unsigned int fnname##_bits12(                                         \
1491       const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
1492       int ref_stride) {                                                        \
1493     return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 4;           \
1494   }
1495
1496 #define MAKE_BFP_SADAVG_WRAPPER(fnname)                                        \
1497   static unsigned int fnname##_bits8(                                          \
1498       const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
1499       int ref_stride, const uint8_t *second_pred) {                            \
1500     return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred);   \
1501   }                                                                            \
1502   static unsigned int fnname##_bits10(                                         \
1503       const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
1504       int ref_stride, const uint8_t *second_pred) {                            \
1505     return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred) >> \
1506            2;                                                                  \
1507   }                                                                            \
1508   static unsigned int fnname##_bits12(                                         \
1509       const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr,       \
1510       int ref_stride, const uint8_t *second_pred) {                            \
1511     return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred) >> \
1512            4;                                                                  \
1513   }
1514
1515 #define MAKE_BFP_SAD4D_WRAPPER(fnname)                                        \
1516   static void fnname##_bits8(const uint8_t *src_ptr, int source_stride,       \
1517                              const uint8_t *const ref_ptr[], int ref_stride,  \
1518                              unsigned int *sad_array) {                       \
1519     fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);           \
1520   }                                                                           \
1521   static void fnname##_bits10(const uint8_t *src_ptr, int source_stride,      \
1522                               const uint8_t *const ref_ptr[], int ref_stride, \
1523                               unsigned int *sad_array) {                      \
1524     int i;                                                                    \
1525     fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);           \
1526     for (i = 0; i < 4; i++) sad_array[i] >>= 2;                               \
1527   }                                                                           \
1528   static void fnname##_bits12(const uint8_t *src_ptr, int source_stride,      \
1529                               const uint8_t *const ref_ptr[], int ref_stride, \
1530                               unsigned int *sad_array) {                      \
1531     int i;                                                                    \
1532     fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array);           \
1533     for (i = 0; i < 4; i++) sad_array[i] >>= 4;                               \
1534   }
1535
1536 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x16)
1537 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x16_avg)
1538 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x16x4d)
1539 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x32)
1540 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x32_avg)
1541 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x32x4d)
1542 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x32)
1543 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x32_avg)
1544 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x32x4d)
1545 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x64)
1546 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x64_avg)
1547 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x64x4d)
1548 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x32)
1549 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x32_avg)
1550 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x32x4d)
1551 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x64)
1552 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x64_avg)
1553 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x64x4d)
1554 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x16)
1555 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x16_avg)
1556 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x16x4d)
1557 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x8)
1558 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x8_avg)
1559 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x8x4d)
1560 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x16)
1561 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x16_avg)
1562 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x16x4d)
1563 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x8)
1564 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x8_avg)
1565 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x8x4d)
1566 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x4)
1567 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x4_avg)
1568 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x4x4d)
1569 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x8)
1570 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x8_avg)
1571 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x8x4d)
1572 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x4)
1573 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x4_avg)
1574 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x4x4d)
1575
1576 static void highbd_set_var_fns(VP9_COMP *const cpi) {
1577   VP9_COMMON *const cm = &cpi->common;
1578   if (cm->use_highbitdepth) {
1579     switch (cm->bit_depth) {
1580       case VPX_BITS_8:
1581         HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits8,
1582                    vpx_highbd_sad32x16_avg_bits8, vpx_highbd_8_variance32x16,
1583                    vpx_highbd_8_sub_pixel_variance32x16,
1584                    vpx_highbd_8_sub_pixel_avg_variance32x16,
1585                    vpx_highbd_sad32x16x4d_bits8)
1586
1587         HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits8,
1588                    vpx_highbd_sad16x32_avg_bits8, vpx_highbd_8_variance16x32,
1589                    vpx_highbd_8_sub_pixel_variance16x32,
1590                    vpx_highbd_8_sub_pixel_avg_variance16x32,
1591                    vpx_highbd_sad16x32x4d_bits8)
1592
1593         HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits8,
1594                    vpx_highbd_sad64x32_avg_bits8, vpx_highbd_8_variance64x32,
1595                    vpx_highbd_8_sub_pixel_variance64x32,
1596                    vpx_highbd_8_sub_pixel_avg_variance64x32,
1597                    vpx_highbd_sad64x32x4d_bits8)
1598
1599         HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits8,
1600                    vpx_highbd_sad32x64_avg_bits8, vpx_highbd_8_variance32x64,
1601                    vpx_highbd_8_sub_pixel_variance32x64,
1602                    vpx_highbd_8_sub_pixel_avg_variance32x64,
1603                    vpx_highbd_sad32x64x4d_bits8)
1604
1605         HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits8,
1606                    vpx_highbd_sad32x32_avg_bits8, vpx_highbd_8_variance32x32,
1607                    vpx_highbd_8_sub_pixel_variance32x32,
1608                    vpx_highbd_8_sub_pixel_avg_variance32x32,
1609                    vpx_highbd_sad32x32x4d_bits8)
1610
1611         HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits8,
1612                    vpx_highbd_sad64x64_avg_bits8, vpx_highbd_8_variance64x64,
1613                    vpx_highbd_8_sub_pixel_variance64x64,
1614                    vpx_highbd_8_sub_pixel_avg_variance64x64,
1615                    vpx_highbd_sad64x64x4d_bits8)
1616
1617         HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits8,
1618                    vpx_highbd_sad16x16_avg_bits8, vpx_highbd_8_variance16x16,
1619                    vpx_highbd_8_sub_pixel_variance16x16,
1620                    vpx_highbd_8_sub_pixel_avg_variance16x16,
1621                    vpx_highbd_sad16x16x4d_bits8)
1622
1623         HIGHBD_BFP(BLOCK_16X8, vpx_highbd_sad16x8_bits8,
1624                    vpx_highbd_sad16x8_avg_bits8, vpx_highbd_8_variance16x8,
1625                    vpx_highbd_8_sub_pixel_variance16x8,
1626                    vpx_highbd_8_sub_pixel_avg_variance16x8,
1627                    vpx_highbd_sad16x8x4d_bits8)
1628
1629         HIGHBD_BFP(BLOCK_8X16, vpx_highbd_sad8x16_bits8,
1630                    vpx_highbd_sad8x16_avg_bits8, vpx_highbd_8_variance8x16,
1631                    vpx_highbd_8_sub_pixel_variance8x16,
1632                    vpx_highbd_8_sub_pixel_avg_variance8x16,
1633                    vpx_highbd_sad8x16x4d_bits8)
1634
1635         HIGHBD_BFP(
1636             BLOCK_8X8, vpx_highbd_sad8x8_bits8, vpx_highbd_sad8x8_avg_bits8,
1637             vpx_highbd_8_variance8x8, vpx_highbd_8_sub_pixel_variance8x8,
1638             vpx_highbd_8_sub_pixel_avg_variance8x8, vpx_highbd_sad8x8x4d_bits8)
1639
1640         HIGHBD_BFP(
1641             BLOCK_8X4, vpx_highbd_sad8x4_bits8, vpx_highbd_sad8x4_avg_bits8,
1642             vpx_highbd_8_variance8x4, vpx_highbd_8_sub_pixel_variance8x4,
1643             vpx_highbd_8_sub_pixel_avg_variance8x4, vpx_highbd_sad8x4x4d_bits8)
1644
1645         HIGHBD_BFP(
1646             BLOCK_4X8, vpx_highbd_sad4x8_bits8, vpx_highbd_sad4x8_avg_bits8,
1647             vpx_highbd_8_variance4x8, vpx_highbd_8_sub_pixel_variance4x8,
1648             vpx_highbd_8_sub_pixel_avg_variance4x8, vpx_highbd_sad4x8x4d_bits8)
1649
1650         HIGHBD_BFP(
1651             BLOCK_4X4, vpx_highbd_sad4x4_bits8, vpx_highbd_sad4x4_avg_bits8,
1652             vpx_highbd_8_variance4x4, vpx_highbd_8_sub_pixel_variance4x4,
1653             vpx_highbd_8_sub_pixel_avg_variance4x4, vpx_highbd_sad4x4x4d_bits8)
1654         break;
1655
1656       case VPX_BITS_10:
1657         HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits10,
1658                    vpx_highbd_sad32x16_avg_bits10, vpx_highbd_10_variance32x16,
1659                    vpx_highbd_10_sub_pixel_variance32x16,
1660                    vpx_highbd_10_sub_pixel_avg_variance32x16,
1661                    vpx_highbd_sad32x16x4d_bits10)
1662
1663         HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits10,
1664                    vpx_highbd_sad16x32_avg_bits10, vpx_highbd_10_variance16x32,
1665                    vpx_highbd_10_sub_pixel_variance16x32,
1666                    vpx_highbd_10_sub_pixel_avg_variance16x32,
1667                    vpx_highbd_sad16x32x4d_bits10)
1668
1669         HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits10,
1670                    vpx_highbd_sad64x32_avg_bits10, vpx_highbd_10_variance64x32,
1671                    vpx_highbd_10_sub_pixel_variance64x32,
1672                    vpx_highbd_10_sub_pixel_avg_variance64x32,
1673                    vpx_highbd_sad64x32x4d_bits10)
1674
1675         HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits10,
1676                    vpx_highbd_sad32x64_avg_bits10, vpx_highbd_10_variance32x64,
1677                    vpx_highbd_10_sub_pixel_variance32x64,
1678                    vpx_highbd_10_sub_pixel_avg_variance32x64,
1679                    vpx_highbd_sad32x64x4d_bits10)
1680
1681         HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits10,
1682                    vpx_highbd_sad32x32_avg_bits10, vpx_highbd_10_variance32x32,
1683                    vpx_highbd_10_sub_pixel_variance32x32,
1684                    vpx_highbd_10_sub_pixel_avg_variance32x32,
1685                    vpx_highbd_sad32x32x4d_bits10)
1686
1687         HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits10,
1688                    vpx_highbd_sad64x64_avg_bits10, vpx_highbd_10_variance64x64,
1689                    vpx_highbd_10_sub_pixel_variance64x64,
1690                    vpx_highbd_10_sub_pixel_avg_variance64x64,
1691                    vpx_highbd_sad64x64x4d_bits10)
1692
1693         HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits10,
1694                    vpx_highbd_sad16x16_avg_bits10, vpx_highbd_10_variance16x16,
1695                    vpx_highbd_10_sub_pixel_variance16x16,
1696                    vpx_highbd_10_sub_pixel_avg_variance16x16,
1697                    vpx_highbd_sad16x16x4d_bits10)
1698
1699         HIGHBD_BFP(BLOCK_16X8, vpx_highbd_sad16x8_bits10,
1700                    vpx_highbd_sad16x8_avg_bits10, vpx_highbd_10_variance16x8,
1701                    vpx_highbd_10_sub_pixel_variance16x8,
1702                    vpx_highbd_10_sub_pixel_avg_variance16x8,
1703                    vpx_highbd_sad16x8x4d_bits10)
1704
1705         HIGHBD_BFP(BLOCK_8X16, vpx_highbd_sad8x16_bits10,
1706                    vpx_highbd_sad8x16_avg_bits10, vpx_highbd_10_variance8x16,
1707                    vpx_highbd_10_sub_pixel_variance8x16,
1708                    vpx_highbd_10_sub_pixel_avg_variance8x16,
1709                    vpx_highbd_sad8x16x4d_bits10)
1710
1711         HIGHBD_BFP(BLOCK_8X8, vpx_highbd_sad8x8_bits10,
1712                    vpx_highbd_sad8x8_avg_bits10, vpx_highbd_10_variance8x8,
1713                    vpx_highbd_10_sub_pixel_variance8x8,
1714                    vpx_highbd_10_sub_pixel_avg_variance8x8,
1715                    vpx_highbd_sad8x8x4d_bits10)
1716
1717         HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits10,
1718                    vpx_highbd_sad8x4_avg_bits10, vpx_highbd_10_variance8x4,
1719                    vpx_highbd_10_sub_pixel_variance8x4,
1720                    vpx_highbd_10_sub_pixel_avg_variance8x4,
1721                    vpx_highbd_sad8x4x4d_bits10)
1722
1723         HIGHBD_BFP(BLOCK_4X8, vpx_highbd_sad4x8_bits10,
1724                    vpx_highbd_sad4x8_avg_bits10, vpx_highbd_10_variance4x8,
1725                    vpx_highbd_10_sub_pixel_variance4x8,
1726                    vpx_highbd_10_sub_pixel_avg_variance4x8,
1727                    vpx_highbd_sad4x8x4d_bits10)
1728
1729         HIGHBD_BFP(BLOCK_4X4, vpx_highbd_sad4x4_bits10,
1730                    vpx_highbd_sad4x4_avg_bits10, vpx_highbd_10_variance4x4,
1731                    vpx_highbd_10_sub_pixel_variance4x4,
1732                    vpx_highbd_10_sub_pixel_avg_variance4x4,
1733                    vpx_highbd_sad4x4x4d_bits10)
1734         break;
1735
1736       default:
1737         assert(cm->bit_depth == VPX_BITS_12);
1738         HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits12,
1739                    vpx_highbd_sad32x16_avg_bits12, vpx_highbd_12_variance32x16,
1740                    vpx_highbd_12_sub_pixel_variance32x16,
1741                    vpx_highbd_12_sub_pixel_avg_variance32x16,
1742                    vpx_highbd_sad32x16x4d_bits12)
1743
1744         HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits12,
1745                    vpx_highbd_sad16x32_avg_bits12, vpx_highbd_12_variance16x32,
1746                    vpx_highbd_12_sub_pixel_variance16x32,
1747                    vpx_highbd_12_sub_pixel_avg_variance16x32,
1748                    vpx_highbd_sad16x32x4d_bits12)
1749
1750         HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits12,
1751                    vpx_highbd_sad64x32_avg_bits12, vpx_highbd_12_variance64x32,
1752                    vpx_highbd_12_sub_pixel_variance64x32,
1753                    vpx_highbd_12_sub_pixel_avg_variance64x32,
1754                    vpx_highbd_sad64x32x4d_bits12)
1755
1756         HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits12,
1757                    vpx_highbd_sad32x64_avg_bits12, vpx_highbd_12_variance32x64,
1758                    vpx_highbd_12_sub_pixel_variance32x64,
1759                    vpx_highbd_12_sub_pixel_avg_variance32x64,
1760                    vpx_highbd_sad32x64x4d_bits12)
1761
1762         HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits12,
1763                    vpx_highbd_sad32x32_avg_bits12, vpx_highbd_12_variance32x32,
1764                    vpx_highbd_12_sub_pixel_variance32x32,
1765                    vpx_highbd_12_sub_pixel_avg_variance32x32,
1766                    vpx_highbd_sad32x32x4d_bits12)
1767
1768         HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits12,
1769                    vpx_highbd_sad64x64_avg_bits12, vpx_highbd_12_variance64x64,
1770                    vpx_highbd_12_sub_pixel_variance64x64,
1771                    vpx_highbd_12_sub_pixel_avg_variance64x64,
1772                    vpx_highbd_sad64x64x4d_bits12)
1773
1774         HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits12,
1775                    vpx_highbd_sad16x16_avg_bits12, vpx_highbd_12_variance16x16,
1776                    vpx_highbd_12_sub_pixel_variance16x16,
1777                    vpx_highbd_12_sub_pixel_avg_variance16x16,
1778                    vpx_highbd_sad16x16x4d_bits12)
1779
1780         HIGHBD_BFP(BLOCK_16X8, vpx_highbd_sad16x8_bits12,
1781                    vpx_highbd_sad16x8_avg_bits12, vpx_highbd_12_variance16x8,
1782                    vpx_highbd_12_sub_pixel_variance16x8,
1783                    vpx_highbd_12_sub_pixel_avg_variance16x8,
1784                    vpx_highbd_sad16x8x4d_bits12)
1785
1786         HIGHBD_BFP(BLOCK_8X16, vpx_highbd_sad8x16_bits12,
1787                    vpx_highbd_sad8x16_avg_bits12, vpx_highbd_12_variance8x16,
1788                    vpx_highbd_12_sub_pixel_variance8x16,
1789                    vpx_highbd_12_sub_pixel_avg_variance8x16,
1790                    vpx_highbd_sad8x16x4d_bits12)
1791
1792         HIGHBD_BFP(BLOCK_8X8, vpx_highbd_sad8x8_bits12,
1793                    vpx_highbd_sad8x8_avg_bits12, vpx_highbd_12_variance8x8,
1794                    vpx_highbd_12_sub_pixel_variance8x8,
1795                    vpx_highbd_12_sub_pixel_avg_variance8x8,
1796                    vpx_highbd_sad8x8x4d_bits12)
1797
1798         HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits12,
1799                    vpx_highbd_sad8x4_avg_bits12, vpx_highbd_12_variance8x4,
1800                    vpx_highbd_12_sub_pixel_variance8x4,
1801                    vpx_highbd_12_sub_pixel_avg_variance8x4,
1802                    vpx_highbd_sad8x4x4d_bits12)
1803
1804         HIGHBD_BFP(BLOCK_4X8, vpx_highbd_sad4x8_bits12,
1805                    vpx_highbd_sad4x8_avg_bits12, vpx_highbd_12_variance4x8,
1806                    vpx_highbd_12_sub_pixel_variance4x8,
1807                    vpx_highbd_12_sub_pixel_avg_variance4x8,
1808                    vpx_highbd_sad4x8x4d_bits12)
1809
1810         HIGHBD_BFP(BLOCK_4X4, vpx_highbd_sad4x4_bits12,
1811                    vpx_highbd_sad4x4_avg_bits12, vpx_highbd_12_variance4x4,
1812                    vpx_highbd_12_sub_pixel_variance4x4,
1813                    vpx_highbd_12_sub_pixel_avg_variance4x4,
1814                    vpx_highbd_sad4x4x4d_bits12)
1815         break;
1816     }
1817   }
1818 }
1819 #endif  // CONFIG_VP9_HIGHBITDEPTH
1820
1821 static void realloc_segmentation_maps(VP9_COMP *cpi) {
1822   VP9_COMMON *const cm = &cpi->common;
1823
1824   // Create the encoder segmentation map and set all entries to 0
1825   vpx_free(cpi->segmentation_map);
1826   CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1827                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1828
1829   // Create a map used for cyclic background refresh.
1830   if (cpi->cyclic_refresh) vp9_cyclic_refresh_free(cpi->cyclic_refresh);
1831   CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
1832                   vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
1833
1834   // Create a map used to mark inactive areas.
1835   vpx_free(cpi->active_map.map);
1836   CHECK_MEM_ERROR(cm, cpi->active_map.map,
1837                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1838
1839   // And a place holder structure is the coding context
1840   // for use if we want to save and restore it
1841   vpx_free(cpi->coding_context.last_frame_seg_map_copy);
1842   CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1843                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1844 }
1845
1846 static void alloc_copy_partition_data(VP9_COMP *cpi) {
1847   VP9_COMMON *const cm = &cpi->common;
1848   if (cpi->prev_partition == NULL) {
1849     CHECK_MEM_ERROR(cm, cpi->prev_partition,
1850                     (BLOCK_SIZE *)vpx_calloc(cm->mi_stride * cm->mi_rows,
1851                                              sizeof(*cpi->prev_partition)));
1852   }
1853   if (cpi->prev_segment_id == NULL) {
1854     CHECK_MEM_ERROR(
1855         cm, cpi->prev_segment_id,
1856         (int8_t *)vpx_calloc((cm->mi_stride >> 3) * ((cm->mi_rows >> 3) + 1),
1857                              sizeof(*cpi->prev_segment_id)));
1858   }
1859   if (cpi->prev_variance_low == NULL) {
1860     CHECK_MEM_ERROR(cm, cpi->prev_variance_low,
1861                     (uint8_t *)vpx_calloc(
1862                         (cm->mi_stride >> 3) * ((cm->mi_rows >> 3) + 1) * 25,
1863                         sizeof(*cpi->prev_variance_low)));
1864   }
1865   if (cpi->copied_frame_cnt == NULL) {
1866     CHECK_MEM_ERROR(
1867         cm, cpi->copied_frame_cnt,
1868         (uint8_t *)vpx_calloc((cm->mi_stride >> 3) * ((cm->mi_rows >> 3) + 1),
1869                               sizeof(*cpi->copied_frame_cnt)));
1870   }
1871 }
1872
1873 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
1874   VP9_COMMON *const cm = &cpi->common;
1875   RATE_CONTROL *const rc = &cpi->rc;
1876   int last_w = cpi->oxcf.width;
1877   int last_h = cpi->oxcf.height;
1878
1879   if (cm->profile != oxcf->profile) cm->profile = oxcf->profile;
1880   cm->bit_depth = oxcf->bit_depth;
1881   cm->color_space = oxcf->color_space;
1882   cm->color_range = oxcf->color_range;
1883
1884   cpi->target_level = oxcf->target_level;
1885   cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
1886   set_level_constraint(&cpi->level_constraint,
1887                        get_level_index(cpi->target_level));
1888
1889   if (cm->profile <= PROFILE_1)
1890     assert(cm->bit_depth == VPX_BITS_8);
1891   else
1892     assert(cm->bit_depth > VPX_BITS_8);
1893
1894   cpi->oxcf = *oxcf;
1895 #if CONFIG_VP9_HIGHBITDEPTH
1896   cpi->td.mb.e_mbd.bd = (int)cm->bit_depth;
1897 #endif  // CONFIG_VP9_HIGHBITDEPTH
1898
1899   if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
1900     rc->baseline_gf_interval = FIXED_GF_INTERVAL;
1901   } else {
1902     rc->baseline_gf_interval = (MIN_GF_INTERVAL + MAX_GF_INTERVAL) / 2;
1903   }
1904
1905   cpi->refresh_golden_frame = 0;
1906   cpi->refresh_last_frame = 1;
1907   cm->refresh_frame_context = 1;
1908   cm->reset_frame_context = 0;
1909
1910   vp9_reset_segment_features(&cm->seg);
1911   vp9_set_high_precision_mv(cpi, 0);
1912
1913   {
1914     int i;
1915
1916     for (i = 0; i < MAX_SEGMENTS; i++)
1917       cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1918   }
1919   cpi->encode_breakout = cpi->oxcf.encode_breakout;
1920
1921   set_rc_buffer_sizes(rc, &cpi->oxcf);
1922
1923   // Under a configuration change, where maximum_buffer_size may change,
1924   // keep buffer level clipped to the maximum allowed buffer size.
1925   rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
1926   rc->buffer_level = VPXMIN(rc->buffer_level, rc->maximum_buffer_size);
1927
1928   // Set up frame rate and related parameters rate control values.
1929   vp9_new_framerate(cpi, cpi->framerate);
1930
1931   // Set absolute upper and lower quality limits
1932   rc->worst_quality = cpi->oxcf.worst_allowed_q;
1933   rc->best_quality = cpi->oxcf.best_allowed_q;
1934
1935   cm->interp_filter = cpi->sf.default_interp_filter;
1936
1937   if (cpi->oxcf.render_width > 0 && cpi->oxcf.render_height > 0) {
1938     cm->render_width = cpi->oxcf.render_width;
1939     cm->render_height = cpi->oxcf.render_height;
1940   } else {
1941     cm->render_width = cpi->oxcf.width;
1942     cm->render_height = cpi->oxcf.height;
1943   }
1944   if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1945     cm->width = cpi->oxcf.width;
1946     cm->height = cpi->oxcf.height;
1947     cpi->external_resize = 1;
1948   }
1949
1950   if (cpi->initial_width) {
1951     int new_mi_size = 0;
1952     vp9_set_mb_mi(cm, cm->width, cm->height);
1953     new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows);
1954     if (cm->mi_alloc_size < new_mi_size) {
1955       vp9_free_context_buffers(cm);
1956       alloc_compressor_data(cpi);
1957       realloc_segmentation_maps(cpi);
1958       cpi->initial_width = cpi->initial_height = 0;
1959       cpi->external_resize = 0;
1960     } else if (cm->mi_alloc_size == new_mi_size &&
1961                (cpi->oxcf.width > last_w || cpi->oxcf.height > last_h)) {
1962       vp9_alloc_loop_filter(cm);
1963     }
1964   }
1965
1966   if (cm->current_video_frame == 0 || last_w != cpi->oxcf.width ||
1967       last_h != cpi->oxcf.height)
1968     update_frame_size(cpi);
1969
1970   if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1971     memset(cpi->consec_zero_mv, 0,
1972            cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
1973     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1974       vp9_cyclic_refresh_reset_resize(cpi);
1975     rc->rc_1_frame = 0;
1976     rc->rc_2_frame = 0;
1977   }
1978
1979   if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
1980       ((cpi->svc.number_temporal_layers > 1 ||
1981         cpi->svc.number_spatial_layers > 1) &&
1982        cpi->oxcf.pass != 1)) {
1983     vp9_update_layer_context_change_config(cpi,
1984                                            (int)cpi->oxcf.target_bandwidth);
1985   }
1986
1987   // Check for resetting the rc flags (rc_1_frame, rc_2_frame) if the
1988   // configuration change has a large change in avg_frame_bandwidth.
1989   // For SVC check for resetting based on spatial layer average bandwidth.
1990   // Also reset buffer level to optimal level.
1991   if (cm->current_video_frame > 0) {
1992     if (cpi->use_svc) {
1993       vp9_svc_check_reset_layer_rc_flag(cpi);
1994     } else {
1995       if (rc->avg_frame_bandwidth > (3 * rc->last_avg_frame_bandwidth >> 1) ||
1996           rc->avg_frame_bandwidth < (rc->last_avg_frame_bandwidth >> 1)) {
1997         rc->rc_1_frame = 0;
1998         rc->rc_2_frame = 0;
1999         rc->bits_off_target = rc->optimal_buffer_level;
2000         rc->buffer_level = rc->optimal_buffer_level;
2001       }
2002     }
2003   }
2004
2005   cpi->alt_ref_source = NULL;
2006   rc->is_src_frame_alt_ref = 0;
2007
2008 #if 0
2009   // Experimental RD Code
2010   cpi->frame_distortion = 0;
2011   cpi->last_frame_distortion = 0;
2012 #endif
2013
2014   set_tile_limits(cpi);
2015
2016   cpi->ext_refresh_frame_flags_pending = 0;
2017   cpi->ext_refresh_frame_context_pending = 0;
2018
2019 #if CONFIG_VP9_HIGHBITDEPTH
2020   highbd_set_var_fns(cpi);
2021 #endif
2022
2023   vp9_set_row_mt(cpi);
2024 }
2025
2026 #ifndef M_LOG2_E
2027 #define M_LOG2_E 0.693147180559945309417
2028 #endif
2029 #define log2f(x) (log(x) / (float)M_LOG2_E)
2030
2031 /***********************************************************************
2032  * Read before modifying 'cal_nmvjointsadcost' or 'cal_nmvsadcosts'    *
2033  ***********************************************************************
2034  * The following 2 functions ('cal_nmvjointsadcost' and                *
2035  * 'cal_nmvsadcosts') are used to calculate cost lookup tables         *
2036  * used by 'vp9_diamond_search_sad'. The C implementation of the       *
2037  * function is generic, but the AVX intrinsics optimised version       *
2038  * relies on the following properties of the computed tables:          *
2039  * For cal_nmvjointsadcost:                                            *
2040  *   - mvjointsadcost[1] == mvjointsadcost[2] == mvjointsadcost[3]     *
2041  * For cal_nmvsadcosts:                                                *
2042  *   - For all i: mvsadcost[0][i] == mvsadcost[1][i]                   *
2043  *         (Equal costs for both components)                           *
2044  *   - For all i: mvsadcost[0][i] == mvsadcost[0][-i]                  *
2045  *         (Cost function is even)                                     *
2046  * If these do not hold, then the AVX optimised version of the         *
2047  * 'vp9_diamond_search_sad' function cannot be used as it is, in which *
2048  * case you can revert to using the C function instead.                *
2049  ***********************************************************************/
2050
2051 static void cal_nmvjointsadcost(int *mvjointsadcost) {
2052   /*********************************************************************
2053    * Warning: Read the comments above before modifying this function   *
2054    *********************************************************************/
2055   mvjointsadcost[0] = 600;
2056   mvjointsadcost[1] = 300;
2057   mvjointsadcost[2] = 300;
2058   mvjointsadcost[3] = 300;
2059 }
2060
2061 static void cal_nmvsadcosts(int *mvsadcost[2]) {
2062   /*********************************************************************
2063    * Warning: Read the comments above before modifying this function   *
2064    *********************************************************************/
2065   int i = 1;
2066
2067   mvsadcost[0][0] = 0;
2068   mvsadcost[1][0] = 0;
2069
2070   do {
2071     double z = 256 * (2 * (log2f(8 * i) + .6));
2072     mvsadcost[0][i] = (int)z;
2073     mvsadcost[1][i] = (int)z;
2074     mvsadcost[0][-i] = (int)z;
2075     mvsadcost[1][-i] = (int)z;
2076   } while (++i <= MV_MAX);
2077 }
2078
2079 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
2080   int i = 1;
2081
2082   mvsadcost[0][0] = 0;
2083   mvsadcost[1][0] = 0;
2084
2085   do {
2086     double z = 256 * (2 * (log2f(8 * i) + .6));
2087     mvsadcost[0][i] = (int)z;
2088     mvsadcost[1][i] = (int)z;
2089     mvsadcost[0][-i] = (int)z;
2090     mvsadcost[1][-i] = (int)z;
2091   } while (++i <= MV_MAX);
2092 }
2093
2094 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf,
2095                                 BufferPool *const pool) {
2096   unsigned int i, frame;
2097   VP9_COMP *volatile const cpi = vpx_memalign(32, sizeof(VP9_COMP));
2098   VP9_COMMON *volatile const cm = cpi != NULL ? &cpi->common : NULL;
2099
2100   if (!cm) return NULL;
2101
2102   vp9_zero(*cpi);
2103
2104   if (setjmp(cm->error.jmp)) {
2105     cm->error.setjmp = 0;
2106     vp9_remove_compressor(cpi);
2107     return 0;
2108   }
2109
2110   cm->error.setjmp = 1;
2111   cm->alloc_mi = vp9_enc_alloc_mi;
2112   cm->free_mi = vp9_enc_free_mi;
2113   cm->setup_mi = vp9_enc_setup_mi;
2114
2115   CHECK_MEM_ERROR(cm, cm->fc, (FRAME_CONTEXT *)vpx_calloc(1, sizeof(*cm->fc)));
2116   CHECK_MEM_ERROR(
2117       cm, cm->frame_contexts,
2118       (FRAME_CONTEXT *)vpx_calloc(FRAME_CONTEXTS, sizeof(*cm->frame_contexts)));
2119
2120   cpi->use_svc = 0;
2121   cpi->resize_state = ORIG;
2122   cpi->external_resize = 0;
2123   cpi->resize_avg_qp = 0;
2124   cpi->resize_buffer_underflow = 0;
2125   cpi->use_skin_detection = 0;
2126   cpi->common.buffer_pool = pool;
2127
2128   cpi->force_update_segmentation = 0;
2129
2130   init_config(cpi, oxcf);
2131   vp9_rc_init(&cpi->oxcf, oxcf->pass, &cpi->rc);
2132
2133   cm->current_video_frame = 0;
2134   cpi->partition_search_skippable_frame = 0;
2135   cpi->tile_data = NULL;
2136
2137   realloc_segmentation_maps(cpi);
2138
2139   CHECK_MEM_ERROR(
2140       cm, cpi->skin_map,
2141       vpx_calloc(cm->mi_rows * cm->mi_cols, sizeof(cpi->skin_map[0])));
2142
2143   CHECK_MEM_ERROR(cm, cpi->alt_ref_aq, vp9_alt_ref_aq_create());
2144
2145   CHECK_MEM_ERROR(
2146       cm, cpi->consec_zero_mv,
2147       vpx_calloc(cm->mi_rows * cm->mi_cols, sizeof(*cpi->consec_zero_mv)));
2148
2149   CHECK_MEM_ERROR(cm, cpi->nmvcosts[0],
2150                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[0])));
2151   CHECK_MEM_ERROR(cm, cpi->nmvcosts[1],
2152                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[1])));
2153   CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[0],
2154                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[0])));
2155   CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[1],
2156                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[1])));
2157   CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[0],
2158                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[0])));
2159   CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[1],
2160                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[1])));
2161   CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[0],
2162                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[0])));
2163   CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[1],
2164                   vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[1])));
2165
2166   for (i = 0; i < (sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]));
2167        i++) {
2168     CHECK_MEM_ERROR(
2169         cm, cpi->mbgraph_stats[i].mb_stats,
2170         vpx_calloc(cm->MBs * sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
2171   }
2172
2173 #if CONFIG_FP_MB_STATS
2174   cpi->use_fp_mb_stats = 0;
2175   if (cpi->use_fp_mb_stats) {
2176     // a place holder used to store the first pass mb stats in the first pass
2177     CHECK_MEM_ERROR(cm, cpi->twopass.frame_mb_stats_buf,
2178                     vpx_calloc(cm->MBs * sizeof(uint8_t), 1));
2179   } else {
2180     cpi->twopass.frame_mb_stats_buf = NULL;
2181   }
2182 #endif
2183
2184   cpi->refresh_alt_ref_frame = 0;
2185   cpi->multi_arf_last_grp_enabled = 0;
2186
2187   cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
2188
2189   init_level_info(&cpi->level_info);
2190   init_level_constraint(&cpi->level_constraint);
2191
2192 #if CONFIG_INTERNAL_STATS
2193   cpi->b_calculate_blockiness = 1;
2194   cpi->b_calculate_consistency = 1;
2195   cpi->total_inconsistency = 0;
2196   cpi->psnr.worst = 100.0;
2197   cpi->worst_ssim = 100.0;
2198
2199   cpi->count = 0;
2200   cpi->bytes = 0;
2201
2202   if (cpi->b_calculate_psnr) {
2203     cpi->total_sq_error = 0;
2204     cpi->total_samples = 0;
2205
2206     cpi->totalp_sq_error = 0;
2207     cpi->totalp_samples = 0;
2208
2209     cpi->tot_recode_hits = 0;
2210     cpi->summed_quality = 0;
2211     cpi->summed_weights = 0;
2212     cpi->summedp_quality = 0;
2213     cpi->summedp_weights = 0;
2214   }
2215
2216   cpi->fastssim.worst = 100.0;
2217
2218   cpi->psnrhvs.worst = 100.0;
2219
2220   if (cpi->b_calculate_blockiness) {
2221     cpi->total_blockiness = 0;
2222     cpi->worst_blockiness = 0.0;
2223   }
2224
2225   if (cpi->b_calculate_consistency) {
2226     CHECK_MEM_ERROR(cm, cpi->ssim_vars,
2227                     vpx_malloc(sizeof(*cpi->ssim_vars) * 4 *
2228                                cpi->common.mi_rows * cpi->common.mi_cols));
2229     cpi->worst_consistency = 100.0;
2230   }
2231
2232 #endif
2233
2234   cpi->first_time_stamp_ever = INT64_MAX;
2235
2236   /*********************************************************************
2237    * Warning: Read the comments around 'cal_nmvjointsadcost' and       *
2238    * 'cal_nmvsadcosts' before modifying how these tables are computed. *
2239    *********************************************************************/
2240   cal_nmvjointsadcost(cpi->td.mb.nmvjointsadcost);
2241   cpi->td.mb.nmvcost[0] = &cpi->nmvcosts[0][MV_MAX];
2242   cpi->td.mb.nmvcost[1] = &cpi->nmvcosts[1][MV_MAX];
2243   cpi->td.mb.nmvsadcost[0] = &cpi->nmvsadcosts[0][MV_MAX];
2244   cpi->td.mb.nmvsadcost[1] = &cpi->nmvsadcosts[1][MV_MAX];
2245   cal_nmvsadcosts(cpi->td.mb.nmvsadcost);
2246
2247   cpi->td.mb.nmvcost_hp[0] = &cpi->nmvcosts_hp[0][MV_MAX];
2248   cpi->td.mb.nmvcost_hp[1] = &cpi->nmvcosts_hp[1][MV_MAX];
2249   cpi->td.mb.nmvsadcost_hp[0] = &cpi->nmvsadcosts_hp[0][MV_MAX];
2250   cpi->td.mb.nmvsadcost_hp[1] = &cpi->nmvsadcosts_hp[1][MV_MAX];
2251   cal_nmvsadcosts_hp(cpi->td.mb.nmvsadcost_hp);
2252
2253 #if CONFIG_VP9_TEMPORAL_DENOISING
2254 #ifdef OUTPUT_YUV_DENOISED
2255   yuv_denoised_file = fopen("denoised.yuv", "ab");
2256 #endif
2257 #endif
2258 #ifdef OUTPUT_YUV_SKINMAP
2259   yuv_skinmap_file = fopen("skinmap.yuv", "wb");
2260 #endif
2261 #ifdef OUTPUT_YUV_REC
2262   yuv_rec_file = fopen("rec.yuv", "wb");
2263 #endif
2264 #ifdef OUTPUT_YUV_SVC_SRC
2265   yuv_svc_src[0] = fopen("svc_src_0.yuv", "wb");
2266   yuv_svc_src[1] = fopen("svc_src_1.yuv", "wb");
2267   yuv_svc_src[2] = fopen("svc_src_2.yuv", "wb");
2268 #endif
2269
2270 #if 0
2271   framepsnr = fopen("framepsnr.stt", "a");
2272   kf_list = fopen("kf_list.stt", "w");
2273 #endif
2274
2275   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
2276
2277 #if !CONFIG_REALTIME_ONLY
2278   if (oxcf->pass == 1) {
2279     vp9_init_first_pass(cpi);
2280   } else if (oxcf->pass == 2) {
2281     const size_t packet_sz = sizeof(FIRSTPASS_STATS);
2282     const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
2283
2284     if (cpi->svc.number_spatial_layers > 1 ||
2285         cpi->svc.number_temporal_layers > 1) {
2286       FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
2287       FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = { 0 };
2288       int i;
2289
2290       for (i = 0; i < oxcf->ss_number_layers; ++i) {
2291         FIRSTPASS_STATS *const last_packet_for_layer =
2292             &stats[packets - oxcf->ss_number_layers + i];
2293         const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
2294         const int packets_in_layer = (int)last_packet_for_layer->count + 1;
2295         if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
2296           LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
2297
2298           vpx_free(lc->rc_twopass_stats_in.buf);
2299
2300           lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
2301           CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
2302                           vpx_malloc(lc->rc_twopass_stats_in.sz));
2303           lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
2304           lc->twopass.stats_in = lc->twopass.stats_in_start;
2305           lc->twopass.stats_in_end =
2306               lc->twopass.stats_in_start + packets_in_layer - 1;
2307           stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
2308         }
2309       }
2310
2311       for (i = 0; i < packets; ++i) {
2312         const int layer_id = (int)stats[i].spatial_layer_id;
2313         if (layer_id >= 0 && layer_id < oxcf->ss_number_layers &&
2314             stats_copy[layer_id] != NULL) {
2315           *stats_copy[layer_id] = stats[i];
2316           ++stats_copy[layer_id];
2317         }
2318       }
2319
2320       vp9_init_second_pass_spatial_svc(cpi);
2321     } else {
2322 #if CONFIG_FP_MB_STATS
2323       if (cpi->use_fp_mb_stats) {
2324         const size_t psz = cpi->common.MBs * sizeof(uint8_t);
2325         const int ps = (int)(oxcf->firstpass_mb_stats_in.sz / psz);
2326
2327         cpi->twopass.firstpass_mb_stats.mb_stats_start =
2328             oxcf->firstpass_mb_stats_in.buf;
2329         cpi->twopass.firstpass_mb_stats.mb_stats_end =
2330             cpi->twopass.firstpass_mb_stats.mb_stats_start +
2331             (ps - 1) * cpi->common.MBs * sizeof(uint8_t);
2332       }
2333 #endif
2334
2335       cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
2336       cpi->twopass.stats_in = cpi->twopass.stats_in_start;
2337       cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
2338
2339       vp9_init_second_pass(cpi);
2340     }
2341   }
2342 #endif  // !CONFIG_REALTIME_ONLY
2343
2344   vp9_set_speed_features_framesize_independent(cpi);
2345   vp9_set_speed_features_framesize_dependent(cpi);
2346
2347   if (cpi->sf.enable_tpl_model) {
2348     for (frame = 0; frame < MAX_LAG_BUFFERS; ++frame) {
2349       int mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2350       int mi_rows = mi_cols_aligned_to_sb(cm->mi_rows);
2351
2352       CHECK_MEM_ERROR(cm, cpi->tpl_stats[frame].tpl_stats_ptr,
2353                       vpx_calloc(mi_rows * mi_cols,
2354                                  sizeof(*cpi->tpl_stats[frame].tpl_stats_ptr)));
2355       cpi->tpl_stats[frame].is_valid = 0;
2356       cpi->tpl_stats[frame].width = mi_cols;
2357       cpi->tpl_stats[frame].height = mi_rows;
2358       cpi->tpl_stats[frame].stride = mi_cols;
2359       cpi->tpl_stats[frame].mi_rows = cm->mi_rows;
2360       cpi->tpl_stats[frame].mi_cols = cm->mi_cols;
2361     }
2362   }
2363
2364   // Allocate memory to store variances for a frame.
2365   CHECK_MEM_ERROR(cm, cpi->source_diff_var, vpx_calloc(cm->MBs, sizeof(diff)));
2366   cpi->source_var_thresh = 0;
2367   cpi->frames_till_next_var_check = 0;
2368
2369 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX4DF) \
2370   cpi->fn_ptr[BT].sdf = SDF;                      \
2371   cpi->fn_ptr[BT].sdaf = SDAF;                    \
2372   cpi->fn_ptr[BT].vf = VF;                        \
2373   cpi->fn_ptr[BT].svf = SVF;                      \
2374   cpi->fn_ptr[BT].svaf = SVAF;                    \
2375   cpi->fn_ptr[BT].sdx4df = SDX4DF;
2376
2377   BFP(BLOCK_32X16, vpx_sad32x16, vpx_sad32x16_avg, vpx_variance32x16,
2378       vpx_sub_pixel_variance32x16, vpx_sub_pixel_avg_variance32x16,
2379       vpx_sad32x16x4d)
2380
2381   BFP(BLOCK_16X32, vpx_sad16x32, vpx_sad16x32_avg, vpx_variance16x32,
2382       vpx_sub_pixel_variance16x32, vpx_sub_pixel_avg_variance16x32,
2383       vpx_sad16x32x4d)
2384
2385   BFP(BLOCK_64X32, vpx_sad64x32, vpx_sad64x32_avg, vpx_variance64x32,
2386       vpx_sub_pixel_variance64x32, vpx_sub_pixel_avg_variance64x32,
2387       vpx_sad64x32x4d)
2388
2389   BFP(BLOCK_32X64, vpx_sad32x64, vpx_sad32x64_avg, vpx_variance32x64,
2390       vpx_sub_pixel_variance32x64, vpx_sub_pixel_avg_variance32x64,
2391       vpx_sad32x64x4d)
2392
2393   BFP(BLOCK_32X32, vpx_sad32x32, vpx_sad32x32_avg, vpx_variance32x32,
2394       vpx_sub_pixel_variance32x32, vpx_sub_pixel_avg_variance32x32,
2395       vpx_sad32x32x4d)
2396
2397   BFP(BLOCK_64X64, vpx_sad64x64, vpx_sad64x64_avg, vpx_variance64x64,
2398       vpx_sub_pixel_variance64x64, vpx_sub_pixel_avg_variance64x64,
2399       vpx_sad64x64x4d)
2400
2401   BFP(BLOCK_16X16, vpx_sad16x16, vpx_sad16x16_avg, vpx_variance16x16,
2402       vpx_sub_pixel_variance16x16, vpx_sub_pixel_avg_variance16x16,
2403       vpx_sad16x16x4d)
2404
2405   BFP(BLOCK_16X8, vpx_sad16x8, vpx_sad16x8_avg, vpx_variance16x8,
2406       vpx_sub_pixel_variance16x8, vpx_sub_pixel_avg_variance16x8,
2407       vpx_sad16x8x4d)
2408
2409   BFP(BLOCK_8X16, vpx_sad8x16, vpx_sad8x16_avg, vpx_variance8x16,
2410       vpx_sub_pixel_variance8x16, vpx_sub_pixel_avg_variance8x16,
2411       vpx_sad8x16x4d)
2412
2413   BFP(BLOCK_8X8, vpx_sad8x8, vpx_sad8x8_avg, vpx_variance8x8,
2414       vpx_sub_pixel_variance8x8, vpx_sub_pixel_avg_variance8x8, vpx_sad8x8x4d)
2415
2416   BFP(BLOCK_8X4, vpx_sad8x4, vpx_sad8x4_avg, vpx_variance8x4,
2417       vpx_sub_pixel_variance8x4, vpx_sub_pixel_avg_variance8x4, vpx_sad8x4x4d)
2418
2419   BFP(BLOCK_4X8, vpx_sad4x8, vpx_sad4x8_avg, vpx_variance4x8,
2420       vpx_sub_pixel_variance4x8, vpx_sub_pixel_avg_variance4x8, vpx_sad4x8x4d)
2421
2422   BFP(BLOCK_4X4, vpx_sad4x4, vpx_sad4x4_avg, vpx_variance4x4,
2423       vpx_sub_pixel_variance4x4, vpx_sub_pixel_avg_variance4x4, vpx_sad4x4x4d)
2424
2425 #if CONFIG_VP9_HIGHBITDEPTH
2426   highbd_set_var_fns(cpi);
2427 #endif
2428
2429   /* vp9_init_quantizer() is first called here. Add check in
2430    * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
2431    * called later when needed. This will avoid unnecessary calls of
2432    * vp9_init_quantizer() for every frame.
2433    */
2434   vp9_init_quantizer(cpi);
2435
2436   vp9_loop_filter_init(cm);
2437
2438   cm->error.setjmp = 0;
2439
2440   return cpi;
2441 }
2442
2443 #if CONFIG_INTERNAL_STATS
2444 #define SNPRINT(H, T) snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T))
2445
2446 #define SNPRINT2(H, T, V) \
2447   snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T), (V))
2448 #endif  // CONFIG_INTERNAL_STATS
2449
2450 void vp9_remove_compressor(VP9_COMP *cpi) {
2451   VP9_COMMON *cm;
2452   unsigned int i, frame;
2453   int t;
2454
2455   if (!cpi) return;
2456
2457   cm = &cpi->common;
2458   if (cm->current_video_frame > 0) {
2459 #if CONFIG_INTERNAL_STATS
2460     vpx_clear_system_state();
2461
2462     if (cpi->oxcf.pass != 1) {
2463       char headings[512] = { 0 };
2464       char results[512] = { 0 };
2465       FILE *f = fopen("opsnr.stt", "a");
2466       double time_encoded =
2467           (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
2468           10000000.000;
2469       double total_encode_time =
2470           (cpi->time_receive_data + cpi->time_compress_data) / 1000.000;
2471       const double dr =
2472           (double)cpi->bytes * (double)8 / (double)1000 / time_encoded;
2473       const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
2474       const double target_rate = (double)cpi->oxcf.target_bandwidth / 1000;
2475       const double rate_err = ((100.0 * (dr - target_rate)) / target_rate);
2476
2477       if (cpi->b_calculate_psnr) {
2478         const double total_psnr = vpx_sse_to_psnr(
2479             (double)cpi->total_samples, peak, (double)cpi->total_sq_error);
2480         const double totalp_psnr = vpx_sse_to_psnr(
2481             (double)cpi->totalp_samples, peak, (double)cpi->totalp_sq_error);
2482         const double total_ssim =
2483             100 * pow(cpi->summed_quality / cpi->summed_weights, 8.0);
2484         const double totalp_ssim =
2485             100 * pow(cpi->summedp_quality / cpi->summedp_weights, 8.0);
2486
2487         snprintf(headings, sizeof(headings),
2488                  "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
2489                  "VPXSSIM\tVPSSIMP\tFASTSIM\tPSNRHVS\t"
2490                  "WstPsnr\tWstSsim\tWstFast\tWstHVS\t"
2491                  "AVPsnrY\tAPsnrCb\tAPsnrCr");
2492         snprintf(results, sizeof(results),
2493                  "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2494                  "%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2495                  "%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2496                  "%7.3f\t%7.3f\t%7.3f",
2497                  dr, cpi->psnr.stat[ALL] / cpi->count, total_psnr,
2498                  cpi->psnrp.stat[ALL] / cpi->count, totalp_psnr, total_ssim,
2499                  totalp_ssim, cpi->fastssim.stat[ALL] / cpi->count,
2500                  cpi->psnrhvs.stat[ALL] / cpi->count, cpi->psnr.worst,
2501                  cpi->worst_ssim, cpi->fastssim.worst, cpi->psnrhvs.worst,
2502                  cpi->psnr.stat[Y] / cpi->count, cpi->psnr.stat[U] / cpi->count,
2503                  cpi->psnr.stat[V] / cpi->count);
2504
2505         if (cpi->b_calculate_blockiness) {
2506           SNPRINT(headings, "\t  Block\tWstBlck");
2507           SNPRINT2(results, "\t%7.3f", cpi->total_blockiness / cpi->count);
2508           SNPRINT2(results, "\t%7.3f", cpi->worst_blockiness);
2509         }
2510
2511         if (cpi->b_calculate_consistency) {
2512           double consistency =
2513               vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
2514                               (double)cpi->total_inconsistency);
2515
2516           SNPRINT(headings, "\tConsist\tWstCons");
2517           SNPRINT2(results, "\t%7.3f", consistency);
2518           SNPRINT2(results, "\t%7.3f", cpi->worst_consistency);
2519         }
2520
2521         fprintf(f, "%s\t    Time\tRcErr\tAbsErr\n", headings);
2522         fprintf(f, "%s\t%8.0f\t%7.2f\t%7.2f\n", results, total_encode_time,
2523                 rate_err, fabs(rate_err));
2524       }
2525
2526       fclose(f);
2527     }
2528
2529 #endif
2530
2531 #if 0
2532     {
2533       printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2534       printf("\n_frames recive_data encod_mb_row compress_frame  Total\n");
2535       printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
2536              cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
2537              cpi->time_compress_data / 1000,
2538              (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2539     }
2540 #endif
2541   }
2542
2543 #if CONFIG_VP9_TEMPORAL_DENOISING
2544   vp9_denoiser_free(&(cpi->denoiser));
2545 #endif
2546
2547   for (frame = 0; frame < MAX_LAG_BUFFERS; ++frame) {
2548     vpx_free(cpi->tpl_stats[frame].tpl_stats_ptr);
2549     cpi->tpl_stats[frame].is_valid = 0;
2550   }
2551
2552   for (t = 0; t < cpi->num_workers; ++t) {
2553     VPxWorker *const worker = &cpi->workers[t];
2554     EncWorkerData *const thread_data = &cpi->tile_thr_data[t];
2555
2556     // Deallocate allocated threads.
2557     vpx_get_worker_interface()->end(worker);
2558
2559     // Deallocate allocated thread data.
2560     if (t < cpi->num_workers - 1) {
2561       vpx_free(thread_data->td->counts);
2562       vp9_free_pc_tree(thread_data->td);
2563       vpx_free(thread_data->td);
2564     }
2565   }
2566   vpx_free(cpi->tile_thr_data);
2567   vpx_free(cpi->workers);
2568   vp9_row_mt_mem_dealloc(cpi);
2569
2570   if (cpi->num_workers > 1) {
2571     vp9_loop_filter_dealloc(&cpi->lf_row_sync);
2572     vp9_bitstream_encode_tiles_buffer_dealloc(cpi);
2573   }
2574
2575   vp9_alt_ref_aq_destroy(cpi->alt_ref_aq);
2576
2577   dealloc_compressor_data(cpi);
2578
2579   for (i = 0; i < sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]);
2580        ++i) {
2581     vpx_free(cpi->mbgraph_stats[i].mb_stats);
2582   }
2583
2584 #if CONFIG_FP_MB_STATS
2585   if (cpi->use_fp_mb_stats) {
2586     vpx_free(cpi->twopass.frame_mb_stats_buf);
2587     cpi->twopass.frame_mb_stats_buf = NULL;
2588   }
2589 #endif
2590
2591   vp9_remove_common(cm);
2592   vp9_free_ref_frame_buffers(cm->buffer_pool);
2593 #if CONFIG_VP9_POSTPROC
2594   vp9_free_postproc_buffers(cm);
2595 #endif
2596   vpx_free(cpi);
2597
2598 #if CONFIG_VP9_TEMPORAL_DENOISING
2599 #ifdef OUTPUT_YUV_DENOISED
2600   fclose(yuv_denoised_file);
2601 #endif
2602 #endif
2603 #ifdef OUTPUT_YUV_SKINMAP
2604   fclose(yuv_skinmap_file);
2605 #endif
2606 #ifdef OUTPUT_YUV_REC
2607   fclose(yuv_rec_file);
2608 #endif
2609 #ifdef OUTPUT_YUV_SVC_SRC
2610   fclose(yuv_svc_src[0]);
2611   fclose(yuv_svc_src[1]);
2612   fclose(yuv_svc_src[2]);
2613 #endif
2614
2615 #if 0
2616
2617   if (keyfile)
2618     fclose(keyfile);
2619
2620   if (framepsnr)
2621     fclose(framepsnr);
2622
2623   if (kf_list)
2624     fclose(kf_list);
2625
2626 #endif
2627 }
2628
2629 static void generate_psnr_packet(VP9_COMP *cpi) {
2630   struct vpx_codec_cx_pkt pkt;
2631   int i;
2632   PSNR_STATS psnr;
2633 #if CONFIG_VP9_HIGHBITDEPTH
2634   vpx_calc_highbd_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr,
2635                        cpi->td.mb.e_mbd.bd, cpi->oxcf.input_bit_depth);
2636 #else
2637   vpx_calc_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr);
2638 #endif
2639
2640   for (i = 0; i < 4; ++i) {
2641     pkt.data.psnr.samples[i] = psnr.samples[i];
2642     pkt.data.psnr.sse[i] = psnr.sse[i];
2643     pkt.data.psnr.psnr[i] = psnr.psnr[i];
2644   }
2645   pkt.kind = VPX_CODEC_PSNR_PKT;
2646   if (cpi->use_svc)
2647     cpi->svc
2648         .layer_context[cpi->svc.spatial_layer_id *
2649                        cpi->svc.number_temporal_layers]
2650         .psnr_pkt = pkt.data.psnr;
2651   else
2652     vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2653 }
2654
2655 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
2656   if (ref_frame_flags > 7) return -1;
2657
2658   cpi->ref_frame_flags = ref_frame_flags;
2659   return 0;
2660 }
2661
2662 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
2663   cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
2664   cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
2665   cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
2666   cpi->ext_refresh_frame_flags_pending = 1;
2667 }
2668
2669 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(
2670     VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag) {
2671   MV_REFERENCE_FRAME ref_frame = NONE;
2672   if (ref_frame_flag == VP9_LAST_FLAG)
2673     ref_frame = LAST_FRAME;
2674   else if (ref_frame_flag == VP9_GOLD_FLAG)
2675     ref_frame = GOLDEN_FRAME;
2676   else if (ref_frame_flag == VP9_ALT_FLAG)
2677     ref_frame = ALTREF_FRAME;
2678
2679   return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
2680 }
2681
2682 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2683                            YV12_BUFFER_CONFIG *sd) {
2684   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2685   if (cfg) {
2686     vpx_yv12_copy_frame(cfg, sd);
2687     return 0;
2688   } else {
2689     return -1;
2690   }
2691 }
2692
2693 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2694                           YV12_BUFFER_CONFIG *sd) {
2695   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2696   if (cfg) {
2697     vpx_yv12_copy_frame(sd, cfg);
2698     return 0;
2699   } else {
2700     return -1;
2701   }
2702 }
2703
2704 int vp9_update_entropy(VP9_COMP *cpi, int update) {
2705   cpi->ext_refresh_frame_context = update;
2706   cpi->ext_refresh_frame_context_pending = 1;
2707   return 0;
2708 }
2709
2710 #ifdef OUTPUT_YUV_REC
2711 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2712   YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2713   uint8_t *src = s->y_buffer;
2714   int h = cm->height;
2715
2716 #if CONFIG_VP9_HIGHBITDEPTH
2717   if (s->flags & YV12_FLAG_HIGHBITDEPTH) {
2718     uint16_t *src16 = CONVERT_TO_SHORTPTR(s->y_buffer);
2719
2720     do {
2721       fwrite(src16, s->y_width, 2, yuv_rec_file);
2722       src16 += s->y_stride;
2723     } while (--h);
2724
2725     src16 = CONVERT_TO_SHORTPTR(s->u_buffer);
2726     h = s->uv_height;
2727
2728     do {
2729       fwrite(src16, s->uv_width, 2, yuv_rec_file);
2730       src16 += s->uv_stride;
2731     } while (--h);
2732
2733     src16 = CONVERT_TO_SHORTPTR(s->v_buffer);
2734     h = s->uv_height;
2735
2736     do {
2737       fwrite(src16, s->uv_width, 2, yuv_rec_file);
2738       src16 += s->uv_stride;
2739     } while (--h);
2740
2741     fflush(yuv_rec_file);
2742     return;
2743   }
2744 #endif  // CONFIG_VP9_HIGHBITDEPTH
2745
2746   do {
2747     fwrite(src, s->y_width, 1, yuv_rec_file);
2748     src += s->y_stride;
2749   } while (--h);
2750
2751   src = s->u_buffer;
2752   h = s->uv_height;
2753
2754   do {
2755     fwrite(src, s->uv_width, 1, yuv_rec_file);
2756     src += s->uv_stride;
2757   } while (--h);
2758
2759   src = s->v_buffer;
2760   h = s->uv_height;
2761
2762   do {
2763     fwrite(src, s->uv_width, 1, yuv_rec_file);
2764     src += s->uv_stride;
2765   } while (--h);
2766
2767   fflush(yuv_rec_file);
2768 }
2769 #endif
2770
2771 #if CONFIG_VP9_HIGHBITDEPTH
2772 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2773                                                 YV12_BUFFER_CONFIG *dst,
2774                                                 int bd) {
2775 #else
2776 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2777                                                 YV12_BUFFER_CONFIG *dst) {
2778 #endif  // CONFIG_VP9_HIGHBITDEPTH
2779   // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
2780   int i;
2781   const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2782                                    src->v_buffer };
2783   const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2784   const int src_widths[3] = { src->y_crop_width, src->uv_crop_width,
2785                               src->uv_crop_width };
2786   const int src_heights[3] = { src->y_crop_height, src->uv_crop_height,
2787                                src->uv_crop_height };
2788   uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2789   const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2790   const int dst_widths[3] = { dst->y_crop_width, dst->uv_crop_width,
2791                               dst->uv_crop_width };
2792   const int dst_heights[3] = { dst->y_crop_height, dst->uv_crop_height,
2793                                dst->uv_crop_height };
2794
2795   for (i = 0; i < MAX_MB_PLANE; ++i) {
2796 #if CONFIG_VP9_HIGHBITDEPTH
2797     if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2798       vp9_highbd_resize_plane(srcs[i], src_heights[i], src_widths[i],
2799                               src_strides[i], dsts[i], dst_heights[i],
2800                               dst_widths[i], dst_strides[i], bd);
2801     } else {
2802       vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2803                        dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2804     }
2805 #else
2806     vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2807                      dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2808 #endif  // CONFIG_VP9_HIGHBITDEPTH
2809   }
2810   vpx_extend_frame_borders(dst);
2811 }
2812
2813 #if CONFIG_VP9_HIGHBITDEPTH
2814 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
2815                                    YV12_BUFFER_CONFIG *dst, int bd,
2816                                    INTERP_FILTER filter_type,
2817                                    int phase_scaler) {
2818   const int src_w = src->y_crop_width;
2819   const int src_h = src->y_crop_height;
2820   const int dst_w = dst->y_crop_width;
2821   const int dst_h = dst->y_crop_height;
2822   const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2823                                    src->v_buffer };
2824   const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2825   uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2826   const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2827   const InterpKernel *const kernel = vp9_filter_kernels[filter_type];
2828   int x, y, i;
2829
2830   for (i = 0; i < MAX_MB_PLANE; ++i) {
2831     const int factor = (i == 0 || i == 3 ? 1 : 2);
2832     const int src_stride = src_strides[i];
2833     const int dst_stride = dst_strides[i];
2834     for (y = 0; y < dst_h; y += 16) {
2835       const int y_q4 = y * (16 / factor) * src_h / dst_h + phase_scaler;
2836       for (x = 0; x < dst_w; x += 16) {
2837         const int x_q4 = x * (16 / factor) * src_w / dst_w + phase_scaler;
2838         const uint8_t *src_ptr = srcs[i] +
2839                                  (y / factor) * src_h / dst_h * src_stride +
2840                                  (x / factor) * src_w / dst_w;
2841         uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2842
2843         if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2844           vpx_highbd_convolve8(CONVERT_TO_SHORTPTR(src_ptr), src_stride,
2845                                CONVERT_TO_SHORTPTR(dst_ptr), dst_stride, kernel,
2846                                x_q4 & 0xf, 16 * src_w / dst_w, y_q4 & 0xf,
2847                                16 * src_h / dst_h, 16 / factor, 16 / factor,
2848                                bd);
2849         } else {
2850           vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride, kernel,
2851                         x_q4 & 0xf, 16 * src_w / dst_w, y_q4 & 0xf,
2852                         16 * src_h / dst_h, 16 / factor, 16 / factor);
2853         }
2854       }
2855     }
2856   }
2857
2858   vpx_extend_frame_borders(dst);
2859 }
2860 #endif  // CONFIG_VP9_HIGHBITDEPTH
2861
2862 static int scale_down(VP9_COMP *cpi, int q) {
2863   RATE_CONTROL *const rc = &cpi->rc;
2864   GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2865   int scale = 0;
2866   assert(frame_is_kf_gf_arf(cpi));
2867
2868   if (rc->frame_size_selector == UNSCALED &&
2869       q >= rc->rf_level_maxq[gf_group->rf_level[gf_group->index]]) {
2870     const int max_size_thresh =
2871         (int)(rate_thresh_mult[SCALE_STEP1] *
2872               VPXMAX(rc->this_frame_target, rc->avg_frame_bandwidth));
2873     scale = rc->projected_frame_size > max_size_thresh ? 1 : 0;
2874   }
2875   return scale;
2876 }
2877
2878 static int big_rate_miss_high_threshold(VP9_COMP *cpi) {
2879   const RATE_CONTROL *const rc = &cpi->rc;
2880   int big_miss_high;
2881
2882   if (frame_is_kf_gf_arf(cpi))
2883     big_miss_high = rc->this_frame_target * 3 / 2;
2884   else
2885     big_miss_high = rc->this_frame_target * 2;
2886
2887   return big_miss_high;
2888 }
2889
2890 static int big_rate_miss(VP9_COMP *cpi) {
2891   const RATE_CONTROL *const rc = &cpi->rc;
2892   int big_miss_high;
2893   int big_miss_low;
2894
2895   // Ignore for overlay frames
2896   if (rc->is_src_frame_alt_ref) {
2897     return 0;
2898   } else {
2899     big_miss_low = (rc->this_frame_target / 2);
2900     big_miss_high = big_rate_miss_high_threshold(cpi);
2901
2902     return (rc->projected_frame_size > big_miss_high) ||
2903            (rc->projected_frame_size < big_miss_low);
2904   }
2905 }
2906
2907 // test in two pass for the first
2908 static int two_pass_first_group_inter(VP9_COMP *cpi) {
2909   TWO_PASS *const twopass = &cpi->twopass;
2910   GF_GROUP *const gf_group = &twopass->gf_group;
2911   if ((cpi->oxcf.pass == 2) &&
2912       (gf_group->index == gf_group->first_inter_index)) {
2913     return 1;
2914   } else {
2915     return 0;
2916   }
2917 }
2918
2919 // Function to test for conditions that indicate we should loop
2920 // back and recode a frame.
2921 static int recode_loop_test(VP9_COMP *cpi, int high_limit, int low_limit, int q,
2922                             int maxq, int minq) {
2923   const RATE_CONTROL *const rc = &cpi->rc;
2924   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2925   const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
2926   int force_recode = 0;
2927
2928   if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
2929       big_rate_miss(cpi) || (cpi->sf.recode_loop == ALLOW_RECODE) ||
2930       (two_pass_first_group_inter(cpi) &&
2931        (cpi->sf.recode_loop == ALLOW_RECODE_FIRST)) ||
2932       (frame_is_kfgfarf && (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF))) {
2933     if (frame_is_kfgfarf && (oxcf->resize_mode == RESIZE_DYNAMIC) &&
2934         scale_down(cpi, q)) {
2935       // Code this group at a lower resolution.
2936       cpi->resize_pending = 1;
2937       return 1;
2938     }
2939
2940     // Force recode for extreme overshoot.
2941     if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
2942         (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF &&
2943          rc->projected_frame_size >= big_rate_miss_high_threshold(cpi))) {
2944       return 1;
2945     }
2946
2947     // TODO(agrange) high_limit could be greater than the scale-down threshold.
2948     if ((rc->projected_frame_size > high_limit && q < maxq) ||
2949         (rc->projected_frame_size < low_limit && q > minq)) {
2950       force_recode = 1;
2951     } else if (cpi->oxcf.rc_mode == VPX_CQ) {
2952       // Deal with frame undershoot and whether or not we are
2953       // below the automatically set cq level.
2954       if (q > oxcf->cq_level &&
2955           rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
2956         force_recode = 1;
2957       }
2958     }
2959   }
2960   return force_recode;
2961 }
2962
2963 // This function is used to shift the virtual indices of last reference frames
2964 // as follows:
2965 // LAST_FRAME -> LAST2_FRAME -> LAST3_FRAME
2966 // when the LAST_FRAME is updated.
2967 static INLINE void shift_last_ref_frames(VP9_COMP *cpi) {
2968   int ref_frame;
2969   for (ref_frame = LAST_REF_FRAMES - 1; ref_frame > 0; --ref_frame) {
2970     cpi->ref_fb_idx[ref_frame] = cpi->ref_fb_idx[ref_frame - 1];
2971
2972     // [0] is allocated to the current coded frame. The statistics for the
2973     // reference frames start at [LAST_FRAME], i.e. [1].
2974     if (!cpi->rc.is_src_frame_alt_ref) {
2975       memcpy(cpi->interp_filter_selected[ref_frame + LAST_FRAME],
2976              cpi->interp_filter_selected[ref_frame - 1 + LAST_FRAME],
2977              sizeof(cpi->interp_filter_selected[ref_frame - 1 + LAST_FRAME]));
2978     }
2979   }
2980 }
2981
2982 void update_multi_arf_ref_frames(VP9_COMP *cpi) {
2983   VP9_COMMON *const cm = &cpi->common;
2984   BufferPool *const pool = cm->buffer_pool;
2985
2986   // NOTE: Save the new show frame buffer index for --test-code=warn, i.e.,
2987   //       for the purpose to verify no mismatch between encoder and decoder.
2988   if (cm->show_frame) cpi->last_show_frame_buf_idx = cm->new_fb_idx;
2989
2990   // At this point the new frame has been encoded.
2991   // If any buffer copy / swapping is signaled it should be done here.
2992
2993   if (cm->frame_type == KEY_FRAME) {
2994     int ref_frame;
2995     for (ref_frame = 0; ref_frame < REF_FRAMES; ++ref_frame) {
2996       ref_cnt_fb(pool->frame_bufs,
2997                  &cm->ref_frame_map[cpi->ref_fb_idx[ref_frame]],
2998                  cm->new_fb_idx);
2999     }
3000     return;
3001   }
3002
3003   if (vp9_preserve_existing_gf(cpi)) {
3004     // We have decided to preserve the previously existing golden frame as our
3005     // new ARF frame. However, in the short term in function
3006     // av1_bitstream.c::get_refresh_mask() we left it in the GF slot and, if
3007     // we're updating the GF with the current decoded frame, we save it to the
3008     // ARF slot instead.
3009     // We now have to update the ARF with the current frame and swap gld_fb_idx
3010     // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
3011     // slot and, if we're updating the GF, the current frame becomes the new GF.
3012     int tmp;
3013
3014     ref_cnt_fb(pool->frame_bufs,
3015                &cm->ref_frame_map[cpi->ref_fb_idx[ALTREF_FRAME - 1]],
3016                cm->new_fb_idx);
3017     tmp = cpi->ref_fb_idx[ALTREF_FRAME - 1];
3018     cpi->ref_fb_idx[ALTREF_FRAME - 1] = cpi->ref_fb_idx[GOLDEN_FRAME - 1];
3019     cpi->ref_fb_idx[GOLDEN_FRAME - 1] = tmp;
3020
3021     // We need to modify the mapping accordingly
3022     cpi->arf_map[0] = cpi->ref_fb_idx[ALTREF_FRAME - 1];
3023   } else if (cpi->rc.is_src_frame_ext_arf && cm->show_existing_frame) {
3024     // Deal with the special case for showing existing internal ALTREF_FRAME
3025     // Refresh the LAST_FRAME with the ALTREF_FRAME and retire the LAST3_FRAME
3026     // by updating the virtual indices.
3027     const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3028     const int which_arf = gf_group->arf_ref_idx[gf_group->index];
3029     int tmp;
3030     assert(gf_group->update_type[gf_group->index] == INTNL_OVERLAY_UPDATE);
3031
3032     tmp = cpi->ref_fb_idx[LAST_REF_FRAMES - 1];
3033     shift_last_ref_frames(cpi);
3034
3035     cpi->ref_fb_idx[LAST_FRAME - 1] = cpi->ref_fb_idx[ALTREF2_FRAME - 1];
3036     cpi->ref_fb_idx[ALTREF2_FRAME - 1] = tmp;
3037
3038     // We need to modify the mapping accordingly
3039     cpi->arf_map[which_arf] = cpi->ref_fb_idx[ALTREF2_FRAME - 1];
3040
3041     memcpy(cpi->interp_filter_selected[LAST_FRAME],
3042            cpi->interp_filter_selected[ALTREF2_FRAME],
3043            sizeof(cpi->interp_filter_selected[ALTREF2_FRAME]));
3044   } else { /* For non key/golden frames */
3045     // === ALTREF_FRAME ===
3046     if (cpi->refresh_alt_ref_frame) {
3047       int arf_idx = cpi->ref_fb_idx[ALTREF_FRAME - 1];
3048       int which_arf = 0;
3049       ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
3050
3051       memcpy(cpi->interp_filter_selected[ALTREF_FRAME + which_arf],
3052              cpi->interp_filter_selected[0],
3053              sizeof(cpi->interp_filter_selected[0]));
3054     }
3055
3056     // === GOLDEN_FRAME ===
3057     if (cpi->refresh_golden_frame) {
3058       ref_cnt_fb(pool->frame_bufs,
3059                  &cm->ref_frame_map[cpi->ref_fb_idx[GOLDEN_FRAME - 1]],
3060                  cm->new_fb_idx);
3061
3062       memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
3063              cpi->interp_filter_selected[0],
3064              sizeof(cpi->interp_filter_selected[0]));
3065     }
3066
3067     // === BWDREF_FRAME ===
3068     if (cpi->refresh_bwd_ref_frame) {
3069       ref_cnt_fb(pool->frame_bufs,
3070                  &cm->ref_frame_map[cpi->ref_fb_idx[BWDREF_FRAME - 1]],
3071                  cm->new_fb_idx);
3072
3073       memcpy(cpi->interp_filter_selected[BWDREF_FRAME],
3074              cpi->interp_filter_selected[0],
3075              sizeof(cpi->interp_filter_selected[0]));
3076     }
3077
3078     // === ALTREF2_FRAME ===
3079     if (cpi->refresh_alt2_ref_frame) {
3080       ref_cnt_fb(pool->frame_bufs,
3081                  &cm->ref_frame_map[cpi->ref_fb_idx[ALTREF2_FRAME - 1]],
3082                  cm->new_fb_idx);
3083
3084       memcpy(cpi->interp_filter_selected[ALTREF2_FRAME],
3085              cpi->interp_filter_selected[0],
3086              sizeof(cpi->interp_filter_selected[0]));
3087     }
3088   }
3089
3090   if (cpi->refresh_last_frame) {
3091     // NOTE(zoeliu): We have two layers of mapping (1) from the per-frame
3092     // reference to the reference frame buffer virtual index; and then (2) from
3093     // the virtual index to the reference frame buffer physical index:
3094     //
3095     // LAST_FRAME,      ..., LAST3_FRAME,     ..., ALTREF_FRAME
3096     //      |                     |                     |
3097     //      v                     v                     v
3098     // ref_fb_idx[0],   ..., ref_fb_idx[2],   ..., ref_fb_idx[ALTREF_FRAME-1]
3099     //      |                     |                     |
3100     //      v                     v                     v
3101     // ref_frame_map[], ..., ref_frame_map[], ..., ref_frame_map[]
3102     //
3103     // When refresh_last_frame is set, it is intended to retire LAST3_FRAME,
3104     // have the other 2 LAST reference frames shifted as follows:
3105     // LAST_FRAME -> LAST2_FRAME -> LAST3_FRAME
3106     // , and then have LAST_FRAME refreshed by the newly coded frame.
3107     //
3108     // To fulfill it, the decoder will be notified to execute following 2 steps:
3109     //
3110     // (a) To change ref_frame_map[] and have the virtual index of LAST3_FRAME
3111     //     to point to the newly coded frame, i.e.
3112     //     ref_frame_map[lst_fb_idexes[2]] => new_fb_idx;
3113     //
3114     // (b) To change the 1st layer mapping to have LAST_FRAME mapped to the
3115     //     original virtual index of LAST3_FRAME and have the other mappings
3116     //     shifted as follows:
3117     // LAST_FRAME,      LAST2_FRAME,     LAST3_FRAME
3118     //      |                |                |
3119     //      v                v                v
3120     // ref_fb_idx[2],   ref_fb_idx[0],   ref_fb_idx[1]
3121     int tmp;
3122
3123     ref_cnt_fb(pool->frame_bufs,
3124                &cm->ref_frame_map[cpi->ref_fb_idx[LAST_REF_FRAMES - 1]],
3125                cm->new_fb_idx);
3126
3127     tmp = cpi->ref_fb_idx[LAST_REF_FRAMES - 1];
3128
3129     shift_last_ref_frames(cpi);
3130     cpi->ref_fb_idx[0] = tmp;
3131
3132     assert(cm->show_existing_frame == 0);
3133     memcpy(cpi->interp_filter_selected[LAST_FRAME],
3134            cpi->interp_filter_selected[0],
3135            sizeof(cpi->interp_filter_selected[0]));
3136
3137     if (cpi->rc.is_last_bipred_frame) {
3138       // Refresh the LAST_FRAME with the BWDREF_FRAME and retire the
3139       // LAST3_FRAME by updating the virtual indices.
3140       //
3141       // NOTE: The source frame for BWDREF does not have a holding position as
3142       //       the OVERLAY frame for ALTREF's. Hence, to resolve the reference
3143       //       virtual index reshuffling for BWDREF, the encoder always
3144       //       specifies a LAST_BIPRED right before BWDREF and completes the
3145       //       reshuffling job accordingly.
3146       tmp = cpi->ref_fb_idx[LAST_REF_FRAMES - 1];
3147
3148       shift_last_ref_frames(cpi);
3149       cpi->ref_fb_idx[0] = cpi->ref_fb_idx[BWDREF_FRAME - 1];
3150       cpi->ref_fb_idx[BWDREF_FRAME - 1] = tmp;
3151
3152       memcpy(cpi->interp_filter_selected[LAST_FRAME],
3153              cpi->interp_filter_selected[BWDREF_FRAME],
3154              sizeof(cpi->interp_filter_selected[BWDREF_FRAME]));
3155     }
3156   }
3157
3158   // Assign virtual indexes for LAST_FRAME, GOLDEN_FRAME, and ALTREF_FRAME
3159   cpi->lst_fb_idx = cpi->ref_fb_idx[LAST_FRAME - 1];
3160   cpi->gld_fb_idx = cpi->ref_fb_idx[GOLDEN_FRAME - 1];
3161   cpi->alt_fb_idx = cpi->ref_fb_idx[ALTREF_FRAME - 1];
3162 }
3163
3164 void update_ref_frames(VP9_COMP *cpi) {
3165   VP9_COMMON *const cm = &cpi->common;
3166   BufferPool *const pool = cm->buffer_pool;
3167
3168   // At this point the new frame has been encoded.
3169   // If any buffer copy / swapping is signaled it should be done here.
3170   if (cm->frame_type == KEY_FRAME) {
3171     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
3172                cm->new_fb_idx);
3173     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->alt_fb_idx],
3174                cm->new_fb_idx);
3175   } else if (vp9_preserve_existing_gf(cpi)) {
3176     // We have decided to preserve the previously existing golden frame as our
3177     // new ARF frame. However, in the short term in function
3178     // vp9_get_refresh_mask() we left it in the GF slot and, if
3179     // we're updating the GF with the current decoded frame, we save it to the
3180     // ARF slot instead.
3181     // We now have to update the ARF with the current frame and swap gld_fb_idx
3182     // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
3183     // slot and, if we're updating the GF, the current frame becomes the new GF.
3184     int tmp;
3185
3186     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->alt_fb_idx],
3187                cm->new_fb_idx);
3188
3189     tmp = cpi->alt_fb_idx;
3190     cpi->alt_fb_idx = cpi->gld_fb_idx;
3191     cpi->gld_fb_idx = tmp;
3192   } else { /* For non key/golden frames */
3193     if (cpi->refresh_alt_ref_frame) {
3194       int arf_idx = cpi->alt_fb_idx;
3195       if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
3196         const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3197         arf_idx = gf_group->arf_update_idx[gf_group->index];
3198       }
3199
3200       ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
3201       memcpy(cpi->interp_filter_selected[ALTREF_FRAME],
3202              cpi->interp_filter_selected[0],
3203              sizeof(cpi->interp_filter_selected[0]));
3204     }
3205
3206     if (cpi->refresh_golden_frame) {
3207       ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
3208                  cm->new_fb_idx);
3209       if (!cpi->rc.is_src_frame_alt_ref)
3210         memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
3211                cpi->interp_filter_selected[0],
3212                sizeof(cpi->interp_filter_selected[0]));
3213       else
3214         memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
3215                cpi->interp_filter_selected[ALTREF_FRAME],
3216                sizeof(cpi->interp_filter_selected[ALTREF_FRAME]));
3217     }
3218   }
3219
3220   if (cpi->refresh_last_frame) {
3221     ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
3222                cm->new_fb_idx);
3223     if (!cpi->rc.is_src_frame_alt_ref)
3224       memcpy(cpi->interp_filter_selected[LAST_FRAME],
3225              cpi->interp_filter_selected[0],
3226              sizeof(cpi->interp_filter_selected[0]));
3227   }
3228 }
3229
3230 void vp9_update_reference_frames(VP9_COMP *cpi) {
3231   VP9_COMMON *const cm = &cpi->common;
3232   BufferPool *const pool = cm->buffer_pool;
3233   SVC *const svc = &cpi->svc;
3234
3235   if (cpi->extra_arf_allowed)
3236     update_multi_arf_ref_frames(cpi);
3237   else
3238     update_ref_frames(cpi);
3239
3240 #if CONFIG_VP9_TEMPORAL_DENOISING
3241   if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
3242       cpi->denoiser.denoising_level > kDenLowLow) {
3243     int svc_refresh_denoiser_buffers = 0;
3244     int denoise_svc_second_layer = 0;
3245     FRAME_TYPE frame_type = cm->intra_only ? KEY_FRAME : cm->frame_type;
3246     if (cpi->use_svc) {
3247       int realloc_fail = 0;
3248       const int svc_buf_shift =
3249           svc->number_spatial_layers - svc->spatial_layer_id == 2
3250               ? cpi->denoiser.num_ref_frames
3251               : 0;
3252       int layer =
3253           LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
3254                            svc->number_temporal_layers);
3255       LAYER_CONTEXT *const lc = &svc->layer_context[layer];
3256       svc_refresh_denoiser_buffers =
3257           lc->is_key_frame || svc->spatial_layer_sync[svc->spatial_layer_id];
3258       denoise_svc_second_layer =
3259           svc->number_spatial_layers - svc->spatial_layer_id == 2 ? 1 : 0;
3260       // Check if we need to allocate extra buffers in the denoiser
3261       // for
3262       // refreshed frames.
3263       realloc_fail = vp9_denoiser_realloc_svc(
3264           cm, &cpi->denoiser, svc_buf_shift, cpi->refresh_alt_ref_frame,
3265           cpi->refresh_golden_frame, cpi->refresh_last_frame, cpi->alt_fb_idx,
3266           cpi->gld_fb_idx, cpi->lst_fb_idx);
3267       if (realloc_fail)
3268         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3269                            "Failed to re-allocate denoiser for SVC");
3270     }
3271     vp9_denoiser_update_frame_info(
3272         &cpi->denoiser, *cpi->Source, frame_type, cpi->refresh_alt_ref_frame,
3273         cpi->refresh_golden_frame, cpi->refresh_last_frame, cpi->alt_fb_idx,
3274         cpi->gld_fb_idx, cpi->lst_fb_idx, cpi->resize_pending,
3275         svc_refresh_denoiser_buffers, denoise_svc_second_layer);
3276   }
3277 #endif
3278
3279   if (is_one_pass_cbr_svc(cpi)) {
3280     // Keep track of frame index for each reference frame.
3281     if (cm->frame_type == KEY_FRAME) {
3282       int i;
3283       // On key frame update all reference frame slots.
3284       for (i = 0; i < REF_FRAMES; i++) {
3285         svc->fb_idx_spatial_layer_id[i] = svc->spatial_layer_id;
3286         svc->fb_idx_temporal_layer_id[i] = svc->temporal_layer_id;
3287         // LAST/GOLDEN/ALTREF is already updated above.
3288         if (i != cpi->lst_fb_idx && i != cpi->gld_fb_idx &&
3289             i != cpi->alt_fb_idx)
3290           ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[i], cm->new_fb_idx);
3291       }
3292     } else {
3293       if (cpi->refresh_last_frame) {
3294         svc->fb_idx_spatial_layer_id[cpi->lst_fb_idx] = svc->spatial_layer_id;
3295         svc->fb_idx_temporal_layer_id[cpi->lst_fb_idx] = svc->temporal_layer_id;
3296       }
3297       if (cpi->refresh_golden_frame) {
3298         svc->fb_idx_spatial_layer_id[cpi->gld_fb_idx] = svc->spatial_layer_id;
3299         svc->fb_idx_temporal_layer_id[cpi->gld_fb_idx] = svc->temporal_layer_id;
3300       }
3301       if (cpi->refresh_alt_ref_frame) {
3302         svc->fb_idx_spatial_layer_id[cpi->alt_fb_idx] = svc->spatial_layer_id;
3303         svc->fb_idx_temporal_layer_id[cpi->alt_fb_idx] = svc->temporal_layer_id;
3304       }
3305     }
3306     // Copy flags from encoder to SVC struct.
3307     vp9_copy_flags_ref_update_idx(cpi);
3308     vp9_svc_update_ref_frame_buffer_idx(cpi);
3309   }
3310 }
3311
3312 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
3313   MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
3314   struct loopfilter *lf = &cm->lf;
3315
3316   const int is_reference_frame =
3317       (cm->frame_type == KEY_FRAME || cpi->refresh_last_frame ||
3318        cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame);
3319
3320   if (xd->lossless) {
3321     lf->filter_level = 0;
3322     lf->last_filt_level = 0;
3323   } else {
3324     struct vpx_usec_timer timer;
3325
3326     vpx_clear_system_state();
3327
3328     vpx_usec_timer_start(&timer);
3329
3330     if (!cpi->rc.is_src_frame_alt_ref) {
3331       if ((cpi->common.frame_type == KEY_FRAME) &&
3332           (!cpi->rc.this_key_frame_forced)) {
3333         lf->last_filt_level = 0;
3334       }
3335       vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
3336       lf->last_filt_level = lf->filter_level;
3337     } else {
3338       lf->filter_level = 0;
3339     }
3340
3341     vpx_usec_timer_mark(&timer);
3342     cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3343   }
3344
3345   if (lf->filter_level > 0 && is_reference_frame) {
3346     vp9_build_mask_frame(cm, lf->filter_level, 0);
3347
3348     if (cpi->num_workers > 1)
3349       vp9_loop_filter_frame_mt(cm->frame_to_show, cm, xd->plane,
3350                                lf->filter_level, 0, 0, cpi->workers,
3351                                cpi->num_workers, &cpi->lf_row_sync);
3352     else
3353       vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
3354   }
3355
3356   vpx_extend_frame_inner_borders(cm->frame_to_show);
3357 }
3358
3359 static INLINE void alloc_frame_mvs(VP9_COMMON *const cm, int buffer_idx) {
3360   RefCntBuffer *const new_fb_ptr = &cm->buffer_pool->frame_bufs[buffer_idx];
3361   if (new_fb_ptr->mvs == NULL || new_fb_ptr->mi_rows < cm->mi_rows ||
3362       new_fb_ptr->mi_cols < cm->mi_cols) {
3363     vpx_free(new_fb_ptr->mvs);
3364     CHECK_MEM_ERROR(cm, new_fb_ptr->mvs,
3365                     (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
3366                                          sizeof(*new_fb_ptr->mvs)));
3367     new_fb_ptr->mi_rows = cm->mi_rows;
3368     new_fb_ptr->mi_cols = cm->mi_cols;
3369   }
3370 }
3371
3372 void vp9_scale_references(VP9_COMP *cpi) {
3373   VP9_COMMON *cm = &cpi->common;
3374   MV_REFERENCE_FRAME ref_frame;
3375   const VP9_REFFRAME ref_mask[3] = { VP9_LAST_FLAG, VP9_GOLD_FLAG,
3376                                      VP9_ALT_FLAG };
3377
3378   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3379     // Need to convert from VP9_REFFRAME to index into ref_mask (subtract 1).
3380     if (cpi->ref_frame_flags & ref_mask[ref_frame - 1]) {
3381       BufferPool *const pool = cm->buffer_pool;
3382       const YV12_BUFFER_CONFIG *const ref =
3383           get_ref_frame_buffer(cpi, ref_frame);
3384
3385       if (ref == NULL) {
3386         cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
3387         continue;
3388       }
3389
3390 #if CONFIG_VP9_HIGHBITDEPTH
3391       if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
3392         RefCntBuffer *new_fb_ptr = NULL;
3393         int force_scaling = 0;
3394         int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
3395         if (new_fb == INVALID_IDX) {
3396           new_fb = get_free_fb(cm);
3397           force_scaling = 1;
3398         }
3399         if (new_fb == INVALID_IDX) return;
3400         new_fb_ptr = &pool->frame_bufs[new_fb];
3401         if (force_scaling || new_fb_ptr->buf.y_crop_width != cm->width ||
3402             new_fb_ptr->buf.y_crop_height != cm->height) {
3403           if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
3404                                        cm->subsampling_x, cm->subsampling_y,
3405                                        cm->use_highbitdepth,
3406                                        VP9_ENC_BORDER_IN_PIXELS,
3407                                        cm->byte_alignment, NULL, NULL, NULL))
3408             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3409                                "Failed to allocate frame buffer");
3410           scale_and_extend_frame(ref, &new_fb_ptr->buf, (int)cm->bit_depth,
3411                                  EIGHTTAP, 0);
3412           cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
3413           alloc_frame_mvs(cm, new_fb);
3414         }
3415 #else
3416       if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
3417         RefCntBuffer *new_fb_ptr = NULL;
3418         int force_scaling = 0;
3419         int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
3420         if (new_fb == INVALID_IDX) {
3421           new_fb = get_free_fb(cm);
3422           force_scaling = 1;
3423         }
3424         if (new_fb == INVALID_IDX) return;
3425         new_fb_ptr = &pool->frame_bufs[new_fb];
3426         if (force_scaling || new_fb_ptr->buf.y_crop_width != cm->width ||
3427             new_fb_ptr->buf.y_crop_height != cm->height) {
3428           if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
3429                                        cm->subsampling_x, cm->subsampling_y,
3430                                        VP9_ENC_BORDER_IN_PIXELS,
3431                                        cm->byte_alignment, NULL, NULL, NULL))
3432             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3433                                "Failed to allocate frame buffer");
3434           vp9_scale_and_extend_frame(ref, &new_fb_ptr->buf, EIGHTTAP, 0);
3435           cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
3436           alloc_frame_mvs(cm, new_fb);
3437         }
3438 #endif  // CONFIG_VP9_HIGHBITDEPTH
3439       } else {
3440         int buf_idx;
3441         RefCntBuffer *buf = NULL;
3442         if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
3443           // Check for release of scaled reference.
3444           buf_idx = cpi->scaled_ref_idx[ref_frame - 1];
3445           buf = (buf_idx != INVALID_IDX) ? &pool->frame_bufs[buf_idx] : NULL;
3446           if (buf != NULL) {
3447             --buf->ref_count;
3448             cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
3449           }
3450         }
3451         buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
3452         buf = &pool->frame_bufs[buf_idx];
3453         buf->buf.y_crop_width = ref->y_crop_width;
3454         buf->buf.y_crop_height = ref->y_crop_height;
3455         cpi->scaled_ref_idx[ref_frame - 1] = buf_idx;
3456         ++buf->ref_count;
3457       }
3458     } else {
3459       if (cpi->oxcf.pass != 0 || cpi->use_svc)
3460         cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
3461     }
3462   }
3463 }
3464
3465 static void release_scaled_references(VP9_COMP *cpi) {
3466   VP9_COMMON *cm = &cpi->common;
3467   int i;
3468   if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
3469     // Only release scaled references under certain conditions:
3470     // if reference will be updated, or if scaled reference has same resolution.
3471     int refresh[3];
3472     refresh[0] = (cpi->refresh_last_frame) ? 1 : 0;
3473     refresh[1] = (cpi->refresh_golden_frame) ? 1 : 0;
3474     refresh[2] = (cpi->refresh_alt_ref_frame) ? 1 : 0;
3475     for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
3476       const int idx = cpi->scaled_ref_idx[i - 1];
3477       RefCntBuffer *const buf =
3478           idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[idx] : NULL;
3479       const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, i);
3480       if (buf != NULL &&
3481           (refresh[i - 1] || (buf->buf.y_crop_width == ref->y_crop_width &&
3482                               buf->buf.y_crop_height == ref->y_crop_height))) {
3483         --buf->ref_count;
3484         cpi->scaled_ref_idx[i - 1] = INVALID_IDX;
3485       }
3486     }
3487   } else {
3488     for (i = 0; i < MAX_REF_FRAMES; ++i) {
3489       const int idx = cpi->scaled_ref_idx[i];
3490       RefCntBuffer *const buf =
3491           idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[idx] : NULL;
3492       if (buf != NULL) {
3493         --buf->ref_count;
3494         cpi->scaled_ref_idx[i] = INVALID_IDX;
3495       }
3496     }
3497   }
3498 }
3499
3500 static void full_to_model_count(unsigned int *model_count,
3501                                 unsigned int *full_count) {
3502   int n;
3503   model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
3504   model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
3505   model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
3506   for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
3507     model_count[TWO_TOKEN] += full_count[n];
3508   model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
3509 }
3510
3511 static void full_to_model_counts(vp9_coeff_count_model *model_count,
3512                                  vp9_coeff_count *full_count) {
3513   int i, j, k, l;
3514
3515   for (i = 0; i < PLANE_TYPES; ++i)
3516     for (j = 0; j < REF_TYPES; ++j)
3517       for (k = 0; k < COEF_BANDS; ++k)
3518         for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
3519           full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
3520 }
3521
3522 #if 0 && CONFIG_INTERNAL_STATS
3523 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
3524   VP9_COMMON *const cm = &cpi->common;
3525   FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
3526   int64_t recon_err;
3527
3528   vpx_clear_system_state();
3529
3530 #if CONFIG_VP9_HIGHBITDEPTH
3531   if (cm->use_highbitdepth) {
3532     recon_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3533   } else {
3534     recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3535   }
3536 #else
3537   recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3538 #endif  // CONFIG_VP9_HIGHBITDEPTH
3539
3540
3541   if (cpi->twopass.total_left_stats.coded_error != 0.0) {
3542     double dc_quant_devisor;
3543 #if CONFIG_VP9_HIGHBITDEPTH
3544     switch (cm->bit_depth) {
3545       case VPX_BITS_8:
3546         dc_quant_devisor = 4.0;
3547         break;
3548       case VPX_BITS_10:
3549         dc_quant_devisor = 16.0;
3550         break;
3551       default:
3552         assert(cm->bit_depth == VPX_BITS_12);
3553         dc_quant_devisor = 64.0;
3554         break;
3555     }
3556 #else
3557     dc_quant_devisor = 4.0;
3558 #endif
3559
3560     if (!cm->current_video_frame) {
3561       fprintf(f, "frame, width, height, last ts, last end ts, "
3562           "source_alt_ref_pending, source_alt_ref_active, "
3563           "this_frame_target, projected_frame_size, "
3564           "projected_frame_size / MBs, "
3565           "projected_frame_size - this_frame_target, "
3566           "vbr_bits_off_target, vbr_bits_off_target_fast, "
3567           "twopass.extend_minq, twopass.extend_minq_fast, "
3568           "total_target_vs_actual, "
3569           "starting_buffer_level - bits_off_target, "
3570           "total_actual_bits, base_qindex, q for base_qindex, "
3571           "dc quant, q for active_worst_quality, avg_q, q for oxcf.cq_level, "
3572           "refresh_last_frame, refresh_golden_frame, refresh_alt_ref_frame, "
3573           "frame_type, gfu_boost, "
3574           "twopass.bits_left, "
3575           "twopass.total_left_stats.coded_error, "
3576           "twopass.bits_left / (1 + twopass.total_left_stats.coded_error), "
3577           "tot_recode_hits, recon_err, kf_boost, "
3578           "twopass.kf_zeromotion_pct, twopass.fr_content_type, "
3579           "filter_level, seg.aq_av_offset\n");
3580     }
3581
3582     fprintf(f, "%10u, %d, %d, %10"PRId64", %10"PRId64", %d, %d, %10d, %10d, "
3583         "%10d, %10d, %10"PRId64", %10"PRId64", %5d, %5d, %10"PRId64", "
3584         "%10"PRId64", %10"PRId64", %10d, %7.2lf, %7.2lf, %7.2lf, %7.2lf, "
3585         "%7.2lf, %6d, %6d, %5d, %5d, %5d, %10"PRId64", %10.3lf, %10lf, %8u, "
3586         "%10"PRId64", %10d, %10d, %10d, %10d, %10d\n",
3587         cpi->common.current_video_frame,
3588         cm->width, cm->height,
3589         cpi->last_time_stamp_seen,
3590         cpi->last_end_time_stamp_seen,
3591         cpi->rc.source_alt_ref_pending,
3592         cpi->rc.source_alt_ref_active,
3593         cpi->rc.this_frame_target,
3594         cpi->rc.projected_frame_size,
3595         cpi->rc.projected_frame_size / cpi->common.MBs,
3596         (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
3597         cpi->rc.vbr_bits_off_target,
3598         cpi->rc.vbr_bits_off_target_fast,
3599         cpi->twopass.extend_minq,
3600         cpi->twopass.extend_minq_fast,
3601         cpi->rc.total_target_vs_actual,
3602         (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
3603         cpi->rc.total_actual_bits, cm->base_qindex,
3604         vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth),
3605         (double)vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) /
3606             dc_quant_devisor,
3607         vp9_convert_qindex_to_q(cpi->twopass.active_worst_quality,
3608                                 cm->bit_depth),
3609         cpi->rc.avg_q,
3610         vp9_convert_qindex_to_q(cpi->oxcf.cq_level, cm->bit_depth),
3611         cpi->refresh_last_frame, cpi->refresh_golden_frame,
3612         cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
3613         cpi->twopass.bits_left,
3614         cpi->twopass.total_left_stats.coded_error,
3615         cpi->twopass.bits_left /
3616             (1 + cpi->twopass.total_left_stats.coded_error),
3617         cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
3618         cpi->twopass.kf_zeromotion_pct,
3619         cpi->twopass.fr_content_type,
3620         cm->lf.filter_level,
3621         cm->seg.aq_av_offset);
3622   }
3623   fclose(f);
3624
3625   if (0) {
3626     FILE *const fmodes = fopen("Modes.stt", "a");
3627     int i;
3628
3629     fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
3630             cm->frame_type, cpi->refresh_golden_frame,
3631             cpi->refresh_alt_ref_frame);
3632
3633     for (i = 0; i < MAX_MODES; ++i)
3634       fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
3635
3636     fprintf(fmodes, "\n");
3637
3638     fclose(fmodes);
3639   }
3640 }
3641 #endif
3642
3643 static void set_mv_search_params(VP9_COMP *cpi) {
3644   const VP9_COMMON *const cm = &cpi->common;
3645   const unsigned int max_mv_def = VPXMIN(cm->width, cm->height);
3646
3647   // Default based on max resolution.
3648   cpi->mv_step_param = vp9_init_search_range(max_mv_def);
3649
3650   if (cpi->sf.mv.auto_mv_step_size) {
3651     if (frame_is_intra_only(cm)) {
3652       // Initialize max_mv_magnitude for use in the first INTER frame
3653       // after a key/intra-only frame.
3654       cpi->max_mv_magnitude = max_mv_def;
3655     } else {
3656       if (cm->show_frame) {
3657         // Allow mv_steps to correspond to twice the max mv magnitude found
3658         // in the previous frame, capped by the default max_mv_magnitude based
3659         // on resolution.
3660         cpi->mv_step_param = vp9_init_search_range(
3661             VPXMIN(max_mv_def, 2 * cpi->max_mv_magnitude));
3662       }
3663       cpi->max_mv_magnitude = 0;
3664     }
3665   }
3666 }
3667
3668 static void set_size_independent_vars(VP9_COMP *cpi) {
3669   vp9_set_speed_features_framesize_independent(cpi);
3670   vp9_set_rd_speed_thresholds(cpi);
3671   vp9_set_rd_speed_thresholds_sub8x8(cpi);
3672   cpi->common.interp_filter = cpi->sf.default_interp_filter;
3673 }
3674
3675 static void set_size_dependent_vars(VP9_COMP *cpi, int *q, int *bottom_index,
3676                                     int *top_index) {
3677   VP9_COMMON *const cm = &cpi->common;
3678
3679   // Setup variables that depend on the dimensions of the frame.
3680   vp9_set_speed_features_framesize_dependent(cpi);
3681
3682   // Decide q and q bounds.
3683   *q = vp9_rc_pick_q_and_bounds(cpi, bottom_index, top_index);
3684
3685   if (!frame_is_intra_only(cm)) {
3686     vp9_set_high_precision_mv(cpi, (*q) < HIGH_PRECISION_MV_QTHRESH);
3687   }
3688
3689 #if !CONFIG_REALTIME_ONLY
3690   // Configure experimental use of segmentation for enhanced coding of
3691   // static regions if indicated.
3692   // Only allowed in the second pass of a two pass encode, as it requires
3693   // lagged coding, and if the relevant speed feature flag is set.
3694   if (cpi->oxcf.pass == 2 && cpi->sf.static_segmentation)
3695     configure_static_seg_features(cpi);
3696 #endif  // !CONFIG_REALTIME_ONLY
3697
3698 #if CONFIG_VP9_POSTPROC && !(CONFIG_VP9_TEMPORAL_DENOISING)
3699   if (cpi->oxcf.noise_sensitivity > 0) {
3700     int l = 0;
3701     switch (cpi->oxcf.noise_sensitivity) {
3702       case 1: l = 20; break;
3703       case 2: l = 40; break;
3704       case 3: l = 60; break;
3705       case 4:
3706       case 5: l = 100; break;
3707       case 6: l = 150; break;
3708     }
3709     if (!cpi->common.postproc_state.limits) {
3710       cpi->common.postproc_state.limits =
3711           vpx_calloc(cpi->un_scaled_source->y_width,
3712                      sizeof(*cpi->common.postproc_state.limits));
3713     }
3714     vp9_denoise(cpi->Source, cpi->Source, l, cpi->common.postproc_state.limits);
3715   }
3716 #endif  // CONFIG_VP9_POSTPROC
3717 }
3718
3719 #if CONFIG_VP9_TEMPORAL_DENOISING
3720 static void setup_denoiser_buffer(VP9_COMP *cpi) {
3721   VP9_COMMON *const cm = &cpi->common;
3722   if (cpi->oxcf.noise_sensitivity > 0 &&
3723       !cpi->denoiser.frame_buffer_initialized) {
3724     if (vp9_denoiser_alloc(cm, &cpi->svc, &cpi->denoiser, cpi->use_svc,
3725                            cpi->oxcf.noise_sensitivity, cm->width, cm->height,
3726                            cm->subsampling_x, cm->subsampling_y,
3727 #if CONFIG_VP9_HIGHBITDEPTH
3728                            cm->use_highbitdepth,
3729 #endif
3730                            VP9_ENC_BORDER_IN_PIXELS))
3731       vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3732                          "Failed to allocate denoiser");
3733   }
3734 }
3735 #endif
3736
3737 static void init_motion_estimation(VP9_COMP *cpi) {
3738   int y_stride = cpi->scaled_source.y_stride;
3739
3740   if (cpi->sf.mv.search_method == NSTEP) {
3741     vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
3742   } else if (cpi->sf.mv.search_method == DIAMOND) {
3743     vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
3744   }
3745 }
3746
3747 static void set_frame_size(VP9_COMP *cpi) {
3748   int ref_frame;
3749   VP9_COMMON *const cm = &cpi->common;
3750   VP9EncoderConfig *const oxcf = &cpi->oxcf;
3751   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
3752
3753 #if !CONFIG_REALTIME_ONLY
3754   if (oxcf->pass == 2 && oxcf->rc_mode == VPX_VBR &&
3755       ((oxcf->resize_mode == RESIZE_FIXED && cm->current_video_frame == 0) ||
3756        (oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending))) {
3757     calculate_coded_size(cpi, &oxcf->scaled_frame_width,
3758                          &oxcf->scaled_frame_height);
3759
3760     // There has been a change in frame size.
3761     vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
3762                          oxcf->scaled_frame_height);
3763   }
3764 #endif  // !CONFIG_REALTIME_ONLY
3765
3766   if (oxcf->pass == 0 && oxcf->rc_mode == VPX_CBR && !cpi->use_svc &&
3767       oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending != 0) {
3768     oxcf->scaled_frame_width =
3769         (oxcf->width * cpi->resize_scale_num) / cpi->resize_scale_den;
3770     oxcf->scaled_frame_height =
3771         (oxcf->height * cpi->resize_scale_num) / cpi->resize_scale_den;
3772     // There has been a change in frame size.
3773     vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
3774                          oxcf->scaled_frame_height);
3775
3776     // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3777     set_mv_search_params(cpi);
3778
3779     vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
3780 #if CONFIG_VP9_TEMPORAL_DENOISING
3781     // Reset the denoiser on the resized frame.
3782     if (cpi->oxcf.noise_sensitivity > 0) {
3783       vp9_denoiser_free(&(cpi->denoiser));
3784       setup_denoiser_buffer(cpi);
3785       // Dynamic resize is only triggered for non-SVC, so we can force
3786       // golden frame update here as temporary fix to denoiser.
3787       cpi->refresh_golden_frame = 1;
3788     }
3789 #endif
3790   }
3791
3792   if ((oxcf->pass == 2) && !cpi->use_svc) {
3793     vp9_set_target_rate(cpi);
3794   }
3795
3796   alloc_frame_mvs(cm, cm->new_fb_idx);
3797
3798   // Reset the frame pointers to the current frame size.
3799   if (vpx_realloc_frame_buffer(get_frame_new_buffer(cm), cm->width, cm->height,
3800                                cm->subsampling_x, cm->subsampling_y,
3801 #if CONFIG_VP9_HIGHBITDEPTH
3802                                cm->use_highbitdepth,
3803 #endif
3804                                VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
3805                                NULL, NULL, NULL))
3806     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3807                        "Failed to allocate frame buffer");
3808
3809   alloc_util_frame_buffers(cpi);
3810   init_motion_estimation(cpi);
3811
3812   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3813     RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3814     const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
3815
3816     ref_buf->idx = buf_idx;
3817
3818     if (buf_idx != INVALID_IDX) {
3819       YV12_BUFFER_CONFIG *const buf = &cm->buffer_pool->frame_bufs[buf_idx].buf;
3820       ref_buf->buf = buf;
3821 #if CONFIG_VP9_HIGHBITDEPTH
3822       vp9_setup_scale_factors_for_frame(
3823           &ref_buf->sf, buf->y_crop_width, buf->y_crop_height, cm->width,
3824           cm->height, (buf->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0);
3825 #else
3826       vp9_setup_scale_factors_for_frame(&ref_buf->sf, buf->y_crop_width,
3827                                         buf->y_crop_height, cm->width,
3828                                         cm->height);
3829 #endif  // CONFIG_VP9_HIGHBITDEPTH
3830       if (vp9_is_scaled(&ref_buf->sf)) vpx_extend_frame_borders(buf);
3831     } else {
3832       ref_buf->buf = NULL;
3833     }
3834   }
3835
3836   set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
3837 }
3838
3839 #if CONFIG_CONSISTENT_RECODE
3840 static void save_encode_params(VP9_COMP *cpi) {
3841   VP9_COMMON *const cm = &cpi->common;
3842   const int tile_cols = 1 << cm->log2_tile_cols;
3843   const int tile_rows = 1 << cm->log2_tile_rows;
3844   int tile_col, tile_row;
3845   int i, j;
3846   RD_OPT *rd_opt = &cpi->rd;
3847   for (i = 0; i < MAX_REF_FRAMES; i++) {
3848     for (j = 0; j < REFERENCE_MODES; j++)
3849       rd_opt->prediction_type_threshes_prev[i][j] =
3850           rd_opt->prediction_type_threshes[i][j];
3851
3852     for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
3853       rd_opt->filter_threshes_prev[i][j] = rd_opt->filter_threshes[i][j];
3854   }
3855
3856   if (cpi->tile_data != NULL) {
3857     for (tile_row = 0; tile_row < tile_rows; ++tile_row)
3858       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
3859         TileDataEnc *tile_data =
3860             &cpi->tile_data[tile_row * tile_cols + tile_col];
3861         for (i = 0; i < BLOCK_SIZES; ++i) {
3862           for (j = 0; j < MAX_MODES; ++j) {
3863             tile_data->thresh_freq_fact_prev[i][j] =
3864                 tile_data->thresh_freq_fact[i][j];
3865           }
3866         }
3867       }
3868   }
3869 }
3870 #endif
3871
3872 static int encode_without_recode_loop(VP9_COMP *cpi, size_t *size,
3873                                       uint8_t *dest) {
3874   VP9_COMMON *const cm = &cpi->common;
3875   int q = 0, bottom_index = 0, top_index = 0;
3876   const INTERP_FILTER filter_scaler =
3877       (is_one_pass_cbr_svc(cpi))
3878           ? cpi->svc.downsample_filter_type[cpi->svc.spatial_layer_id]
3879           : EIGHTTAP;
3880   const int phase_scaler =
3881       (is_one_pass_cbr_svc(cpi))
3882           ? cpi->svc.downsample_filter_phase[cpi->svc.spatial_layer_id]
3883           : 0;
3884
3885   // Flag to check if its valid to compute the source sad (used for
3886   // scene detection and for superblock content state in CBR mode).
3887   // The flag may get reset below based on SVC or resizing state.
3888   cpi->compute_source_sad_onepass = cpi->oxcf.mode == REALTIME;
3889
3890   vpx_clear_system_state();
3891
3892   set_frame_size(cpi);
3893
3894   if (is_one_pass_cbr_svc(cpi) &&
3895       cpi->un_scaled_source->y_width == cm->width << 2 &&
3896       cpi->un_scaled_source->y_height == cm->height << 2 &&
3897       cpi->svc.scaled_temp.y_width == cm->width << 1 &&
3898       cpi->svc.scaled_temp.y_height == cm->height << 1) {
3899     // For svc, if it is a 1/4x1/4 downscaling, do a two-stage scaling to take
3900     // advantage of the 1:2 optimized scaler. In the process, the 1/2x1/2
3901     // result will be saved in scaled_temp and might be used later.
3902     const INTERP_FILTER filter_scaler2 = cpi->svc.downsample_filter_type[1];
3903     const int phase_scaler2 = cpi->svc.downsample_filter_phase[1];
3904     cpi->Source = vp9_svc_twostage_scale(
3905         cm, cpi->un_scaled_source, &cpi->scaled_source, &cpi->svc.scaled_temp,
3906         filter_scaler, phase_scaler, filter_scaler2, phase_scaler2);
3907     cpi->svc.scaled_one_half = 1;
3908   } else if (is_one_pass_cbr_svc(cpi) &&
3909              cpi->un_scaled_source->y_width == cm->width << 1 &&
3910              cpi->un_scaled_source->y_height == cm->height << 1 &&
3911              cpi->svc.scaled_one_half) {
3912     // If the spatial layer is 1/2x1/2 and the scaling is already done in the
3913     // two-stage scaling, use the result directly.
3914     cpi->Source = &cpi->svc.scaled_temp;
3915     cpi->svc.scaled_one_half = 0;
3916   } else {
3917     cpi->Source = vp9_scale_if_required(
3918         cm, cpi->un_scaled_source, &cpi->scaled_source, (cpi->oxcf.pass == 0),
3919         filter_scaler, phase_scaler);
3920   }
3921 #ifdef OUTPUT_YUV_SVC_SRC
3922   // Write out at most 3 spatial layers.
3923   if (is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id < 3) {
3924     vpx_write_yuv_frame(yuv_svc_src[cpi->svc.spatial_layer_id], cpi->Source);
3925   }
3926 #endif
3927   // Unfiltered raw source used in metrics calculation if the source
3928   // has been filtered.
3929   if (is_psnr_calc_enabled(cpi)) {
3930 #ifdef ENABLE_KF_DENOISE
3931     if (is_spatial_denoise_enabled(cpi)) {
3932       cpi->raw_source_frame = vp9_scale_if_required(
3933           cm, &cpi->raw_unscaled_source, &cpi->raw_scaled_source,
3934           (cpi->oxcf.pass == 0), EIGHTTAP, phase_scaler);
3935     } else {
3936       cpi->raw_source_frame = cpi->Source;
3937     }
3938 #else
3939     cpi->raw_source_frame = cpi->Source;
3940 #endif
3941   }
3942
3943   if ((cpi->use_svc &&
3944        (cpi->svc.spatial_layer_id < cpi->svc.number_spatial_layers - 1 ||
3945         cpi->svc.temporal_layer_id < cpi->svc.number_temporal_layers - 1 ||
3946         cpi->svc.current_superframe < 1)) ||
3947       cpi->resize_pending || cpi->resize_state || cpi->external_resize ||
3948       cpi->resize_state != ORIG) {
3949     cpi->compute_source_sad_onepass = 0;
3950     if (cpi->content_state_sb_fd != NULL)
3951       memset(cpi->content_state_sb_fd, 0,
3952              (cm->mi_stride >> 3) * ((cm->mi_rows >> 3) + 1) *
3953                  sizeof(*cpi->content_state_sb_fd));
3954   }
3955
3956   // Avoid scaling last_source unless its needed.
3957   // Last source is needed if avg_source_sad() is used, or if
3958   // partition_search_type == SOURCE_VAR_BASED_PARTITION, or if noise
3959   // estimation is enabled.
3960   if (cpi->unscaled_last_source != NULL &&
3961       (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3962        (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_VBR &&
3963         cpi->oxcf.mode == REALTIME && cpi->oxcf.speed >= 5) ||
3964        cpi->sf.partition_search_type == SOURCE_VAR_BASED_PARTITION ||
3965        (cpi->noise_estimate.enabled && !cpi->oxcf.noise_sensitivity) ||
3966        cpi->compute_source_sad_onepass))
3967     cpi->Last_Source = vp9_scale_if_required(
3968         cm, cpi->unscaled_last_source, &cpi->scaled_last_source,
3969         (cpi->oxcf.pass == 0), EIGHTTAP, 0);
3970
3971   if (cpi->Last_Source == NULL ||
3972       cpi->Last_Source->y_width != cpi->Source->y_width ||
3973       cpi->Last_Source->y_height != cpi->Source->y_height)
3974     cpi->compute_source_sad_onepass = 0;
3975
3976   if (frame_is_intra_only(cm) || cpi->resize_pending != 0) {
3977     memset(cpi->consec_zero_mv, 0,
3978            cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
3979   }
3980
3981   vp9_update_noise_estimate(cpi);
3982
3983   // Scene detection is always used for VBR mode or screen-content case.
3984   // For other cases (e.g., CBR mode) use it for 5 <= speed < 8 for now
3985   // (need to check encoding time cost for doing this for speed 8).
3986   cpi->rc.high_source_sad = 0;
3987   cpi->rc.hybrid_intra_scene_change = 0;
3988   cpi->rc.re_encode_maxq_scene_change = 0;
3989   if (cm->show_frame && cpi->oxcf.mode == REALTIME &&
3990       (cpi->oxcf.rc_mode == VPX_VBR ||
3991        cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3992        (cpi->oxcf.speed >= 5 && cpi->oxcf.speed < 8)))
3993     vp9_scene_detection_onepass(cpi);
3994
3995   if (cpi->svc.spatial_layer_id == 0)
3996     cpi->svc.high_source_sad_superframe = cpi->rc.high_source_sad;
3997
3998   // For 1 pass CBR, check if we are dropping this frame.
3999   // Never drop on key frame, if base layer is key for svc,
4000   // on scene change, or if superframe has layer sync.
4001   if (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR &&
4002       !frame_is_intra_only(cm) && !cpi->rc.high_source_sad &&
4003       !cpi->svc.high_source_sad_superframe &&
4004       !cpi->svc.superframe_has_layer_sync &&
4005       (!cpi->use_svc ||
4006        !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)) {
4007     if (vp9_rc_drop_frame(cpi)) return 0;
4008   }
4009
4010   // For 1 pass CBR SVC, only ZEROMV is allowed for spatial reference frame
4011   // when svc->force_zero_mode_spatial_ref = 1. Under those conditions we can
4012   // avoid this frame-level upsampling (for non intra_only frames).
4013   if (frame_is_intra_only(cm) == 0 &&
4014       !(is_one_pass_cbr_svc(cpi) && cpi->svc.force_zero_mode_spatial_ref)) {
4015     vp9_scale_references(cpi);
4016   }
4017
4018   set_size_independent_vars(cpi);
4019   set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
4020
4021   if (cpi->sf.copy_partition_flag) alloc_copy_partition_data(cpi);
4022
4023   if (cpi->sf.svc_use_lowres_part &&
4024       cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2) {
4025     if (cpi->svc.prev_partition_svc == NULL) {
4026       CHECK_MEM_ERROR(
4027           cm, cpi->svc.prev_partition_svc,
4028           (BLOCK_SIZE *)vpx_calloc(cm->mi_stride * cm->mi_rows,
4029                                    sizeof(*cpi->svc.prev_partition_svc)));
4030     }
4031   }
4032
4033   // TODO(jianj): Look into issue of skin detection with high bitdepth.
4034   if (cm->bit_depth == 8 && cpi->oxcf.speed >= 5 && cpi->oxcf.pass == 0 &&
4035       cpi->oxcf.rc_mode == VPX_CBR &&
4036       cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
4037       cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
4038     cpi->use_skin_detection = 1;
4039   }
4040
4041   vp9_set_quantizer(cm, q);
4042   vp9_set_variance_partition_thresholds(cpi, q, 0);
4043
4044   setup_frame(cpi);
4045
4046   suppress_active_map(cpi);
4047
4048   if (cpi->use_svc) {
4049     // On non-zero spatial layer, check for disabling inter-layer
4050     // prediction.
4051     if (cpi->svc.spatial_layer_id > 0) vp9_svc_constrain_inter_layer_pred(cpi);
4052     vp9_svc_assert_constraints_pattern(cpi);
4053   }
4054
4055   // Variance adaptive and in frame q adjustment experiments are mutually
4056   // exclusive.
4057   if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
4058     vp9_vaq_frame_setup(cpi);
4059   } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
4060     vp9_360aq_frame_setup(cpi);
4061   } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
4062     vp9_setup_in_frame_q_adj(cpi);
4063   } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
4064     vp9_cyclic_refresh_setup(cpi);
4065   } else if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ) {
4066     // it may be pretty bad for rate-control,
4067     // and I should handle it somehow
4068     vp9_alt_ref_aq_setup_map(cpi->alt_ref_aq, cpi);
4069   } else if (cpi->roi.enabled && !frame_is_intra_only(cm)) {
4070     apply_roi_map(cpi);
4071   }
4072
4073   apply_active_map(cpi);
4074
4075   vp9_encode_frame(cpi);
4076
4077   // Check if we should drop this frame because of high overshoot.
4078   // Only for frames where high temporal-source SAD is detected.
4079   // For SVC: all spatial layers are checked for re-encoding.
4080   if (cpi->sf.re_encode_overshoot_rt &&
4081       (cpi->rc.high_source_sad ||
4082        (cpi->use_svc && cpi->svc.high_source_sad_superframe))) {
4083     int frame_size = 0;
4084     // Get an estimate of the encoded frame size.
4085     save_coding_context(cpi);
4086     vp9_pack_bitstream(cpi, dest, size);
4087     restore_coding_context(cpi);
4088     frame_size = (int)(*size) << 3;
4089     // Check if encoded frame will overshoot too much, and if so, set the q and
4090     // adjust some rate control parameters, and return to re-encode the frame.
4091     if (vp9_encodedframe_overshoot(cpi, frame_size, &q)) {
4092       vpx_clear_system_state();
4093       vp9_set_quantizer(cm, q);
4094       vp9_set_variance_partition_thresholds(cpi, q, 0);
4095       suppress_active_map(cpi);
4096       // Turn-off cyclic refresh for re-encoded frame.
4097       if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
4098         CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
4099         unsigned char *const seg_map = cpi->segmentation_map;
4100         memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
4101         memset(cr->last_coded_q_map, MAXQ,
4102                cm->mi_rows * cm->mi_cols * sizeof(*cr->last_coded_q_map));
4103         cr->sb_index = 0;
4104         vp9_disable_segmentation(&cm->seg);
4105       }
4106       apply_active_map(cpi);
4107       vp9_encode_frame(cpi);
4108     }
4109   }
4110
4111   // Update some stats from cyclic refresh, and check for golden frame update.
4112   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
4113       !frame_is_intra_only(cm))
4114     vp9_cyclic_refresh_postencode(cpi);
4115
4116   // Update the skip mb flag probabilities based on the distribution
4117   // seen in the last encoder iteration.
4118   // update_base_skip_probs(cpi);
4119   vpx_clear_system_state();
4120   return 1;
4121 }
4122
4123 #define MAX_QSTEP_ADJ 4
4124 static int get_qstep_adj(int rate_excess, int rate_limit) {
4125   int qstep =
4126       rate_limit ? ((rate_excess + rate_limit / 2) / rate_limit) : INT_MAX;
4127   return VPXMIN(qstep, MAX_QSTEP_ADJ);
4128 }
4129
4130 static void encode_with_recode_loop(VP9_COMP *cpi, size_t *size,
4131                                     uint8_t *dest) {
4132   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
4133   VP9_COMMON *const cm = &cpi->common;
4134   RATE_CONTROL *const rc = &cpi->rc;
4135   int bottom_index, top_index;
4136   int loop_count = 0;
4137   int loop_at_this_size = 0;
4138   int loop = 0;
4139   int overshoot_seen = 0;
4140   int undershoot_seen = 0;
4141   int frame_over_shoot_limit;
4142   int frame_under_shoot_limit;
4143   int q = 0, q_low = 0, q_high = 0;
4144   int enable_acl;
4145 #ifdef AGGRESSIVE_VBR
4146   int qrange_adj = 1;
4147 #endif
4148
4149   set_size_independent_vars(cpi);
4150
4151   enable_acl = cpi->sf.allow_acl
4152                    ? (cm->frame_type == KEY_FRAME) || (cm->show_frame == 0)
4153                    : 0;
4154
4155   do {
4156     vpx_clear_system_state();
4157
4158     set_frame_size(cpi);
4159
4160     if (loop_count == 0 || cpi->resize_pending != 0) {
4161       set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
4162
4163 #ifdef AGGRESSIVE_VBR
4164       if (two_pass_first_group_inter(cpi)) {
4165         // Adjustment limits for min and max q
4166         qrange_adj = VPXMAX(1, (top_index - bottom_index) / 2);
4167
4168         bottom_index =
4169             VPXMAX(bottom_index - qrange_adj / 2, oxcf->best_allowed_q);
4170         top_index = VPXMIN(oxcf->worst_allowed_q, top_index + qrange_adj / 2);
4171       }
4172 #endif
4173       // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
4174       set_mv_search_params(cpi);
4175
4176       // Reset the loop state for new frame size.
4177       overshoot_seen = 0;
4178       undershoot_seen = 0;
4179
4180       // Reconfiguration for change in frame size has concluded.
4181       cpi->resize_pending = 0;
4182
4183       q_low = bottom_index;
4184       q_high = top_index;
4185
4186       loop_at_this_size = 0;
4187     }
4188
4189     // Decide frame size bounds first time through.
4190     if (loop_count == 0) {
4191       vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
4192                                        &frame_under_shoot_limit,
4193                                        &frame_over_shoot_limit);
4194     }
4195
4196     cpi->Source =
4197         vp9_scale_if_required(cm, cpi->un_scaled_source, &cpi->scaled_source,
4198                               (oxcf->pass == 0), EIGHTTAP, 0);
4199
4200     // Unfiltered raw source used in metrics calculation if the source
4201     // has been filtered.
4202     if (is_psnr_calc_enabled(cpi)) {
4203 #ifdef ENABLE_KF_DENOISE
4204       if (is_spatial_denoise_enabled(cpi)) {
4205         cpi->raw_source_frame = vp9_scale_if_required(
4206             cm, &cpi->raw_unscaled_source, &cpi->raw_scaled_source,
4207             (oxcf->pass == 0), EIGHTTAP, 0);
4208       } else {
4209         cpi->raw_source_frame = cpi->Source;
4210       }
4211 #else
4212       cpi->raw_source_frame = cpi->Source;
4213 #endif
4214     }
4215
4216     if (cpi->unscaled_last_source != NULL)
4217       cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
4218                                                &cpi->scaled_last_source,
4219                                                (oxcf->pass == 0), EIGHTTAP, 0);
4220
4221     if (frame_is_intra_only(cm) == 0) {
4222       if (loop_count > 0) {
4223         release_scaled_references(cpi);
4224       }
4225       vp9_scale_references(cpi);
4226     }
4227
4228     vp9_set_quantizer(cm, q);
4229
4230     if (loop_count == 0) setup_frame(cpi);
4231
4232     // Variance adaptive and in frame q adjustment experiments are mutually
4233     // exclusive.
4234     if (oxcf->aq_mode == VARIANCE_AQ) {
4235       vp9_vaq_frame_setup(cpi);
4236     } else if (oxcf->aq_mode == EQUATOR360_AQ) {
4237       vp9_360aq_frame_setup(cpi);
4238     } else if (oxcf->aq_mode == COMPLEXITY_AQ) {
4239       vp9_setup_in_frame_q_adj(cpi);
4240     } else if (oxcf->aq_mode == LOOKAHEAD_AQ) {
4241       vp9_alt_ref_aq_setup_map(cpi->alt_ref_aq, cpi);
4242     }
4243
4244     vp9_encode_frame(cpi);
4245
4246     // Update the skip mb flag probabilities based on the distribution
4247     // seen in the last encoder iteration.
4248     // update_base_skip_probs(cpi);
4249
4250     vpx_clear_system_state();
4251
4252     // Dummy pack of the bitstream using up to date stats to get an
4253     // accurate estimate of output frame size to determine if we need
4254     // to recode.
4255     if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
4256       save_coding_context(cpi);
4257       if (!cpi->sf.use_nonrd_pick_mode) vp9_pack_bitstream(cpi, dest, size);
4258
4259       rc->projected_frame_size = (int)(*size) << 3;
4260
4261       if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
4262     }
4263
4264     if (oxcf->rc_mode == VPX_Q) {
4265       loop = 0;
4266     } else {
4267       if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced &&
4268           (rc->projected_frame_size < rc->max_frame_bandwidth)) {
4269         int last_q = q;
4270         int64_t kf_err;
4271
4272         int64_t high_err_target = cpi->ambient_err;
4273         int64_t low_err_target = cpi->ambient_err >> 1;
4274
4275 #if CONFIG_VP9_HIGHBITDEPTH
4276         if (cm->use_highbitdepth) {
4277           kf_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
4278         } else {
4279           kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
4280         }
4281 #else
4282         kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
4283 #endif  // CONFIG_VP9_HIGHBITDEPTH
4284
4285         // Prevent possible divide by zero error below for perfect KF
4286         kf_err += !kf_err;
4287
4288         // The key frame is not good enough or we can afford
4289         // to make it better without undue risk of popping.
4290         if ((kf_err > high_err_target &&
4291              rc->projected_frame_size <= frame_over_shoot_limit) ||
4292             (kf_err > low_err_target &&
4293              rc->projected_frame_size <= frame_under_shoot_limit)) {
4294           // Lower q_high
4295           q_high = q > q_low ? q - 1 : q_low;
4296
4297           // Adjust Q
4298           q = (int)((q * high_err_target) / kf_err);
4299           q = VPXMIN(q, (q_high + q_low) >> 1);
4300         } else if (kf_err < low_err_target &&
4301                    rc->projected_frame_size >= frame_under_shoot_limit) {
4302           // The key frame is much better than the previous frame
4303           // Raise q_low
4304           q_low = q < q_high ? q + 1 : q_high;
4305
4306           // Adjust Q
4307           q = (int)((q * low_err_target) / kf_err);
4308           q = VPXMIN(q, (q_high + q_low + 1) >> 1);
4309         }
4310
4311         // Clamp Q to upper and lower limits:
4312         q = clamp(q, q_low, q_high);
4313
4314         loop = q != last_q;
4315       } else if (recode_loop_test(cpi, frame_over_shoot_limit,
4316                                   frame_under_shoot_limit, q,
4317                                   VPXMAX(q_high, top_index), bottom_index)) {
4318         // Is the projected frame size out of range and are we allowed
4319         // to attempt to recode.
4320         int last_q = q;
4321         int retries = 0;
4322         int qstep;
4323
4324         if (cpi->resize_pending == 1) {
4325           // Change in frame size so go back around the recode loop.
4326           cpi->rc.frame_size_selector =
4327               SCALE_STEP1 - cpi->rc.frame_size_selector;
4328           cpi->rc.next_frame_size_selector = cpi->rc.frame_size_selector;
4329
4330 #if CONFIG_INTERNAL_STATS
4331           ++cpi->tot_recode_hits;
4332 #endif
4333           ++loop_count;
4334           loop = 1;
4335           continue;
4336         }
4337
4338         // Frame size out of permitted range:
4339         // Update correction factor & compute new Q to try...
4340
4341         // Frame is too large
4342         if (rc->projected_frame_size > rc->this_frame_target) {
4343           // Special case if the projected size is > the max allowed.
4344           if ((q == q_high) &&
4345               ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
4346                (rc->projected_frame_size >=
4347                 big_rate_miss_high_threshold(cpi)))) {
4348             int max_rate = VPXMAX(1, VPXMIN(rc->max_frame_bandwidth,
4349                                             big_rate_miss_high_threshold(cpi)));
4350             double q_val_high;
4351             q_val_high = vp9_convert_qindex_to_q(q_high, cm->bit_depth);
4352             q_val_high =
4353                 q_val_high * ((double)rc->projected_frame_size / max_rate);
4354             q_high = vp9_convert_q_to_qindex(q_val_high, cm->bit_depth);
4355             q_high = clamp(q_high, rc->best_quality, rc->worst_quality);
4356           }
4357
4358           // Raise Qlow as to at least the current value
4359           qstep =
4360               get_qstep_adj(rc->projected_frame_size, rc->this_frame_target);
4361           q_low = VPXMIN(q + qstep, q_high);
4362
4363           if (undershoot_seen || loop_at_this_size > 1) {
4364             // Update rate_correction_factor unless
4365             vp9_rc_update_rate_correction_factors(cpi);
4366
4367             q = (q_high + q_low + 1) / 2;
4368           } else {
4369             // Update rate_correction_factor unless
4370             vp9_rc_update_rate_correction_factors(cpi);
4371
4372             q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
4373                                   VPXMAX(q_high, top_index));
4374
4375             while (q < q_low && retries < 10) {
4376               vp9_rc_update_rate_correction_factors(cpi);
4377               q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
4378                                     VPXMAX(q_high, top_index));
4379               retries++;
4380             }
4381           }
4382
4383           overshoot_seen = 1;
4384         } else {
4385           // Frame is too small
4386           qstep =
4387               get_qstep_adj(rc->this_frame_target, rc->projected_frame_size);
4388           q_high = VPXMAX(q - qstep, q_low);
4389
4390           if (overshoot_seen || loop_at_this_size > 1) {
4391             vp9_rc_update_rate_correction_factors(cpi);
4392             q = (q_high + q_low) / 2;
4393           } else {
4394             vp9_rc_update_rate_correction_factors(cpi);
4395             q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
4396                                   VPXMIN(q_low, bottom_index), top_index);
4397             // Special case reset for qlow for constrained quality.
4398             // This should only trigger where there is very substantial
4399             // undershoot on a frame and the auto cq level is above
4400             // the user passsed in value.
4401             if (oxcf->rc_mode == VPX_CQ && q < q_low) {
4402               q_low = q;
4403             }
4404
4405             while (q > q_high && retries < 10) {
4406               vp9_rc_update_rate_correction_factors(cpi);
4407               q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
4408                                     VPXMIN(q_low, bottom_index), top_index);
4409               retries++;
4410             }
4411           }
4412           undershoot_seen = 1;
4413         }
4414
4415         // Clamp Q to upper and lower limits:
4416         q = clamp(q, q_low, q_high);
4417
4418         loop = (q != last_q);
4419       } else {
4420         loop = 0;
4421       }
4422     }
4423
4424     // Special case for overlay frame.
4425     if (rc->is_src_frame_alt_ref &&
4426         rc->projected_frame_size < rc->max_frame_bandwidth)
4427       loop = 0;
4428
4429     if (loop) {
4430       ++loop_count;
4431       ++loop_at_this_size;
4432
4433 #if CONFIG_INTERNAL_STATS
4434       ++cpi->tot_recode_hits;
4435 #endif
4436     }
4437
4438     if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF)
4439       if (loop || !enable_acl) restore_coding_context(cpi);
4440   } while (loop);
4441
4442 #ifdef AGGRESSIVE_VBR
4443   if (two_pass_first_group_inter(cpi)) {
4444     cpi->twopass.active_worst_quality =
4445         VPXMIN(q + qrange_adj, oxcf->worst_allowed_q);
4446   } else if (!frame_is_kf_gf_arf(cpi)) {
4447 #else
4448   if (!frame_is_kf_gf_arf(cpi)) {
4449 #endif
4450     // Have we been forced to adapt Q outside the expected range by an extreme
4451     // rate miss. If so adjust the active maxQ for the subsequent frames.
4452     if (q > cpi->twopass.active_worst_quality) {
4453       cpi->twopass.active_worst_quality = q;
4454     } else if (oxcf->vbr_corpus_complexity && q == q_low &&
4455                rc->projected_frame_size < rc->this_frame_target) {
4456       cpi->twopass.active_worst_quality =
4457           VPXMAX(q, cpi->twopass.active_worst_quality - 1);
4458     }
4459   }
4460
4461   if (enable_acl) {
4462     // Skip recoding, if model diff is below threshold
4463     const int thresh = compute_context_model_thresh(cpi);
4464     const int diff = compute_context_model_diff(cm);
4465     if (diff < thresh) {
4466       vpx_clear_system_state();
4467       restore_coding_context(cpi);
4468       return;
4469     }
4470
4471     vp9_encode_frame(cpi);
4472     vpx_clear_system_state();
4473     restore_coding_context(cpi);
4474     vp9_pack_bitstream(cpi, dest, size);
4475
4476     vp9_encode_frame(cpi);
4477     vpx_clear_system_state();
4478
4479     restore_coding_context(cpi);
4480   }
4481 }
4482
4483 static int get_ref_frame_flags(const VP9_COMP *cpi) {
4484   const int *const map = cpi->common.ref_frame_map;
4485   const int gold_is_last = map[cpi->gld_fb_idx] == map[cpi->lst_fb_idx];
4486   const int alt_is_last = map[cpi->alt_fb_idx] == map[cpi->lst_fb_idx];
4487   const int gold_is_alt = map[cpi->gld_fb_idx] == map[cpi->alt_fb_idx];
4488   int flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
4489
4490   if (gold_is_last) flags &= ~VP9_GOLD_FLAG;
4491
4492   if (cpi->rc.frames_till_gf_update_due == INT_MAX &&
4493       (cpi->svc.number_temporal_layers == 1 &&
4494        cpi->svc.number_spatial_layers == 1))
4495     flags &= ~VP9_GOLD_FLAG;
4496
4497   if (alt_is_last) flags &= ~VP9_ALT_FLAG;
4498
4499   if (gold_is_alt) flags &= ~VP9_ALT_FLAG;
4500
4501   return flags;
4502 }
4503
4504 static void set_ext_overrides(VP9_COMP *cpi) {
4505   // Overrides the defaults with the externally supplied values with
4506   // vp9_update_reference() and vp9_update_entropy() calls
4507   // Note: The overrides are valid only for the next frame passed
4508   // to encode_frame_to_data_rate() function
4509   if (cpi->ext_refresh_frame_context_pending) {
4510     cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
4511     cpi->ext_refresh_frame_context_pending = 0;
4512   }
4513   if (cpi->ext_refresh_frame_flags_pending) {
4514     cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
4515     cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
4516     cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
4517   }
4518 }
4519
4520 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(
4521     VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
4522     YV12_BUFFER_CONFIG *scaled_temp, INTERP_FILTER filter_type,
4523     int phase_scaler, INTERP_FILTER filter_type2, int phase_scaler2) {
4524   if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
4525       cm->mi_rows * MI_SIZE != unscaled->y_height) {
4526 #if CONFIG_VP9_HIGHBITDEPTH
4527     if (cm->bit_depth == VPX_BITS_8) {
4528       vp9_scale_and_extend_frame(unscaled, scaled_temp, filter_type2,
4529                                  phase_scaler2);
4530       vp9_scale_and_extend_frame(scaled_temp, scaled, filter_type,
4531                                  phase_scaler);
4532     } else {
4533       scale_and_extend_frame(unscaled, scaled_temp, (int)cm->bit_depth,
4534                              filter_type2, phase_scaler2);
4535       scale_and_extend_frame(scaled_temp, scaled, (int)cm->bit_depth,
4536                              filter_type, phase_scaler);
4537     }
4538 #else
4539     vp9_scale_and_extend_frame(unscaled, scaled_temp, filter_type2,
4540                                phase_scaler2);
4541     vp9_scale_and_extend_frame(scaled_temp, scaled, filter_type, phase_scaler);
4542 #endif  // CONFIG_VP9_HIGHBITDEPTH
4543     return scaled;
4544   } else {
4545     return unscaled;
4546   }
4547 }
4548
4549 YV12_BUFFER_CONFIG *vp9_scale_if_required(
4550     VP9_COMMON *cm, YV12_BUFFER_CONFIG *unscaled, YV12_BUFFER_CONFIG *scaled,
4551     int use_normative_scaler, INTERP_FILTER filter_type, int phase_scaler) {
4552   if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
4553       cm->mi_rows * MI_SIZE != unscaled->y_height) {
4554 #if CONFIG_VP9_HIGHBITDEPTH
4555     if (use_normative_scaler && unscaled->y_width <= (scaled->y_width << 1) &&
4556         unscaled->y_height <= (scaled->y_height << 1))
4557       if (cm->bit_depth == VPX_BITS_8)
4558         vp9_scale_and_extend_frame(unscaled, scaled, filter_type, phase_scaler);
4559       else
4560         scale_and_extend_frame(unscaled, scaled, (int)cm->bit_depth,
4561                                filter_type, phase_scaler);
4562     else
4563       scale_and_extend_frame_nonnormative(unscaled, scaled, (int)cm->bit_depth);
4564 #else
4565     if (use_normative_scaler && unscaled->y_width <= (scaled->y_width << 1) &&
4566         unscaled->y_height <= (scaled->y_height << 1))
4567       vp9_scale_and_extend_frame(unscaled, scaled, filter_type, phase_scaler);
4568     else
4569       scale_and_extend_frame_nonnormative(unscaled, scaled);
4570 #endif  // CONFIG_VP9_HIGHBITDEPTH
4571     return scaled;
4572   } else {
4573     return unscaled;
4574   }
4575 }
4576
4577 static void set_arf_sign_bias(VP9_COMP *cpi) {
4578   VP9_COMMON *const cm = &cpi->common;
4579   int arf_sign_bias;
4580
4581   if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
4582     const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4583     arf_sign_bias = cpi->rc.source_alt_ref_active &&
4584                     (!cpi->refresh_alt_ref_frame ||
4585                      (gf_group->rf_level[gf_group->index] == GF_ARF_LOW));
4586   } else {
4587     arf_sign_bias =
4588         (cpi->rc.source_alt_ref_active && !cpi->refresh_alt_ref_frame);
4589   }
4590   cm->ref_frame_sign_bias[ALTREF_FRAME] = arf_sign_bias;
4591 }
4592
4593 static int setup_interp_filter_search_mask(VP9_COMP *cpi) {
4594   INTERP_FILTER ifilter;
4595   int ref_total[MAX_REF_FRAMES] = { 0 };
4596   MV_REFERENCE_FRAME ref;
4597   int mask = 0;
4598   if (cpi->common.last_frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame)
4599     return mask;
4600   for (ref = LAST_FRAME; ref <= ALTREF_FRAME; ++ref)
4601     for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter)
4602       ref_total[ref] += cpi->interp_filter_selected[ref][ifilter];
4603
4604   for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter) {
4605     if ((ref_total[LAST_FRAME] &&
4606          cpi->interp_filter_selected[LAST_FRAME][ifilter] == 0) &&
4607         (ref_total[GOLDEN_FRAME] == 0 ||
4608          cpi->interp_filter_selected[GOLDEN_FRAME][ifilter] * 50 <
4609              ref_total[GOLDEN_FRAME]) &&
4610         (ref_total[ALTREF_FRAME] == 0 ||
4611          cpi->interp_filter_selected[ALTREF_FRAME][ifilter] * 50 <
4612              ref_total[ALTREF_FRAME]))
4613       mask |= 1 << ifilter;
4614   }
4615   return mask;
4616 }
4617
4618 #ifdef ENABLE_KF_DENOISE
4619 // Baseline Kernal weights for denoise
4620 static uint8_t dn_kernal_3[9] = { 1, 2, 1, 2, 4, 2, 1, 2, 1 };
4621 static uint8_t dn_kernal_5[25] = { 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 4,
4622                                    2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1 };
4623
4624 static INLINE void add_denoise_point(int centre_val, int data_val, int thresh,
4625                                      uint8_t point_weight, int *sum_val,
4626                                      int *sum_weight) {
4627   if (abs(centre_val - data_val) <= thresh) {
4628     *sum_weight += point_weight;
4629     *sum_val += (int)data_val * (int)point_weight;
4630   }
4631 }
4632
4633 static void spatial_denoise_point(uint8_t *src_ptr, const int stride,
4634                                   const int strength) {
4635   int sum_weight = 0;
4636   int sum_val = 0;
4637   int thresh = strength;
4638   int kernal_size = 5;
4639   int half_k_size = 2;
4640   int i, j;
4641   int max_diff = 0;
4642   uint8_t *tmp_ptr;
4643   uint8_t *kernal_ptr;
4644
4645   // Find the maximum deviation from the source point in the locale.
4646   tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
4647   for (i = 0; i < kernal_size + 2; ++i) {
4648     for (j = 0; j < kernal_size + 2; ++j) {
4649       max_diff = VPXMAX(max_diff, abs((int)*src_ptr - (int)tmp_ptr[j]));
4650     }
4651     tmp_ptr += stride;
4652   }
4653
4654   // Select the kernal size.
4655   if (max_diff > (strength + (strength >> 1))) {
4656     kernal_size = 3;
4657     half_k_size = 1;
4658     thresh = thresh >> 1;
4659   }
4660   kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
4661
4662   // Apply the kernal
4663   tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
4664   for (i = 0; i < kernal_size; ++i) {
4665     for (j = 0; j < kernal_size; ++j) {
4666       add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh, *kernal_ptr,
4667                         &sum_val, &sum_weight);
4668       ++kernal_ptr;
4669     }
4670     tmp_ptr += stride;
4671   }
4672
4673   // Update the source value with the new filtered value
4674   *src_ptr = (uint8_t)((sum_val + (sum_weight >> 1)) / sum_weight);
4675 }
4676
4677 #if CONFIG_VP9_HIGHBITDEPTH
4678 static void highbd_spatial_denoise_point(uint16_t *src_ptr, const int stride,
4679                                          const int strength) {
4680   int sum_weight = 0;
4681   int sum_val = 0;
4682   int thresh = strength;
4683   int kernal_size = 5;
4684   int half_k_size = 2;
4685   int i, j;
4686   int max_diff = 0;
4687   uint16_t *tmp_ptr;
4688   uint8_t *kernal_ptr;
4689
4690   // Find the maximum deviation from the source point in the locale.
4691   tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
4692   for (i = 0; i < kernal_size + 2; ++i) {
4693     for (j = 0; j < kernal_size + 2; ++j) {
4694       max_diff = VPXMAX(max_diff, abs((int)src_ptr - (int)tmp_ptr[j]));
4695     }
4696     tmp_ptr += stride;
4697   }
4698
4699   // Select the kernal size.
4700   if (max_diff > (strength + (strength >> 1))) {
4701     kernal_size = 3;
4702     half_k_size = 1;
4703     thresh = thresh >> 1;
4704   }
4705   kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
4706
4707   // Apply the kernal
4708   tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
4709   for (i = 0; i < kernal_size; ++i) {
4710     for (j = 0; j < kernal_size; ++j) {
4711       add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh, *kernal_ptr,
4712                         &sum_val, &sum_weight);
4713       ++kernal_ptr;
4714     }
4715     tmp_ptr += stride;
4716   }
4717
4718   // Update the source value with the new filtered value
4719   *src_ptr = (uint16_t)((sum_val + (sum_weight >> 1)) / sum_weight);
4720 }
4721 #endif  // CONFIG_VP9_HIGHBITDEPTH
4722
4723 // Apply thresholded spatial noise supression to a given buffer.
4724 static void spatial_denoise_buffer(VP9_COMP *cpi, uint8_t *buffer,
4725                                    const int stride, const int width,
4726                                    const int height, const int strength) {
4727   VP9_COMMON *const cm = &cpi->common;
4728   uint8_t *src_ptr = buffer;
4729   int row;
4730   int col;
4731
4732   for (row = 0; row < height; ++row) {
4733     for (col = 0; col < width; ++col) {
4734 #if CONFIG_VP9_HIGHBITDEPTH
4735       if (cm->use_highbitdepth)
4736         highbd_spatial_denoise_point(CONVERT_TO_SHORTPTR(&src_ptr[col]), stride,
4737                                      strength);
4738       else
4739         spatial_denoise_point(&src_ptr[col], stride, strength);
4740 #else
4741       spatial_denoise_point(&src_ptr[col], stride, strength);
4742 #endif  // CONFIG_VP9_HIGHBITDEPTH
4743     }
4744     src_ptr += stride;
4745   }
4746 }
4747
4748 // Apply thresholded spatial noise supression to source.
4749 static void spatial_denoise_frame(VP9_COMP *cpi) {
4750   YV12_BUFFER_CONFIG *src = cpi->Source;
4751   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
4752   TWO_PASS *const twopass = &cpi->twopass;
4753   VP9_COMMON *const cm = &cpi->common;
4754
4755   // Base the filter strength on the current active max Q.
4756   const int q = (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
4757                                               cm->bit_depth));
4758   int strength =
4759       VPXMAX(oxcf->arnr_strength >> 2, VPXMIN(oxcf->arnr_strength, (q >> 4)));
4760
4761   // Denoise each of Y,U and V buffers.
4762   spatial_denoise_buffer(cpi, src->y_buffer, src->y_stride, src->y_width,
4763                          src->y_height, strength);
4764
4765   strength += (strength >> 1);
4766   spatial_denoise_buffer(cpi, src->u_buffer, src->uv_stride, src->uv_width,
4767                          src->uv_height, strength << 1);
4768
4769   spatial_denoise_buffer(cpi, src->v_buffer, src->uv_stride, src->uv_width,
4770                          src->uv_height, strength << 1);
4771 }
4772 #endif  // ENABLE_KF_DENOISE
4773
4774 static void vp9_try_disable_lookahead_aq(VP9_COMP *cpi, size_t *size,
4775                                          uint8_t *dest) {
4776   if (cpi->common.seg.enabled)
4777     if (ALT_REF_AQ_PROTECT_GAIN) {
4778       size_t nsize = *size;
4779       int overhead;
4780
4781       // TODO(yuryg): optimize this, as
4782       // we don't really need to repack
4783
4784       save_coding_context(cpi);
4785       vp9_disable_segmentation(&cpi->common.seg);
4786       vp9_pack_bitstream(cpi, dest, &nsize);
4787       restore_coding_context(cpi);
4788
4789       overhead = (int)*size - (int)nsize;
4790
4791       if (vp9_alt_ref_aq_disable_if(cpi->alt_ref_aq, overhead, (int)*size))
4792         vp9_encode_frame(cpi);
4793       else
4794         vp9_enable_segmentation(&cpi->common.seg);
4795     }
4796 }
4797
4798 static void encode_frame_to_data_rate(VP9_COMP *cpi, size_t *size,
4799                                       uint8_t *dest,
4800                                       unsigned int *frame_flags) {
4801   VP9_COMMON *const cm = &cpi->common;
4802   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
4803   struct segmentation *const seg = &cm->seg;
4804   TX_SIZE t;
4805
4806   // SVC: skip encoding of enhancement layer if the layer target bandwidth = 0.
4807   if (cpi->use_svc && cpi->svc.spatial_layer_id > 0 &&
4808       cpi->oxcf.target_bandwidth == 0) {
4809     cpi->svc.skip_enhancement_layer = 1;
4810     vp9_rc_postencode_update_drop_frame(cpi);
4811     cpi->ext_refresh_frame_flags_pending = 0;
4812     cpi->last_frame_dropped = 1;
4813     cpi->svc.last_layer_dropped[cpi->svc.spatial_layer_id] = 1;
4814     cpi->svc.drop_spatial_layer[cpi->svc.spatial_layer_id] = 1;
4815     if (cpi->svc.framedrop_mode == LAYER_DROP ||
4816         cpi->svc.drop_spatial_layer[0] == 0) {
4817       // For the case of constrained drop mode where the base is dropped
4818       // (drop_spatial_layer[0] == 1), which means full superframe dropped,
4819       // we don't increment the svc frame counters. In particular temporal
4820       // layer counter (which is incremented in vp9_inc_frame_in_layer())
4821       // won't be incremented, so on a dropped frame we try the same
4822       // temporal_layer_id on next incoming frame. This is to avoid an
4823       // issue with temporal alignement with full superframe dropping.
4824       vp9_inc_frame_in_layer(cpi);
4825     }
4826     return;
4827   }
4828
4829   set_ext_overrides(cpi);
4830   vpx_clear_system_state();
4831
4832 #ifdef ENABLE_KF_DENOISE
4833   // Spatial denoise of key frame.
4834   if (is_spatial_denoise_enabled(cpi)) spatial_denoise_frame(cpi);
4835 #endif
4836
4837   // Set the arf sign bias for this frame.
4838   set_arf_sign_bias(cpi);
4839
4840   // Set default state for segment based loop filter update flags.
4841   cm->lf.mode_ref_delta_update = 0;
4842
4843   if (cpi->oxcf.pass == 2 && cpi->sf.adaptive_interp_filter_search)
4844     cpi->sf.interp_filter_search_mask = setup_interp_filter_search_mask(cpi);
4845
4846   // Set various flags etc to special state if it is a key frame.
4847   if (frame_is_intra_only(cm)) {
4848     // Reset the loop filter deltas and segmentation map.
4849     vp9_reset_segment_features(&cm->seg);
4850
4851     // If segmentation is enabled force a map update for key frames.
4852     if (seg->enabled) {
4853       seg->update_map = 1;
4854       seg->update_data = 1;
4855     }
4856
4857     // The alternate reference frame cannot be active for a key frame.
4858     cpi->rc.source_alt_ref_active = 0;
4859
4860     cm->error_resilient_mode = oxcf->error_resilient_mode;
4861     cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
4862
4863     // By default, encoder assumes decoder can use prev_mi.
4864     if (cm->error_resilient_mode) {
4865       cm->frame_parallel_decoding_mode = 1;
4866       cm->reset_frame_context = 0;
4867       cm->refresh_frame_context = 0;
4868     } else if (cm->intra_only) {
4869       // Only reset the current context.
4870       cm->reset_frame_context = 2;
4871     }
4872   }
4873
4874   vpx_clear_system_state();
4875
4876 #if CONFIG_INTERNAL_STATS
4877   memset(cpi->mode_chosen_counts, 0,
4878          MAX_MODES * sizeof(*cpi->mode_chosen_counts));
4879 #endif
4880 #if CONFIG_CONSISTENT_RECODE
4881   // Backup to ensure consistency between recodes
4882   save_encode_params(cpi);
4883 #endif
4884
4885   if (cpi->sf.recode_loop == DISALLOW_RECODE) {
4886     if (!encode_without_recode_loop(cpi, size, dest)) return;
4887   } else {
4888     encode_with_recode_loop(cpi, size, dest);
4889   }
4890
4891   cpi->last_frame_dropped = 0;
4892   cpi->svc.last_layer_dropped[cpi->svc.spatial_layer_id] = 0;
4893   // Keep track of the frame buffer index updated/refreshed for the
4894   // current encoded TL0 superframe.
4895   if (cpi->svc.temporal_layer_id == 0) {
4896     if (cpi->refresh_last_frame)
4897       cpi->svc.fb_idx_upd_tl0[cpi->svc.spatial_layer_id] = cpi->lst_fb_idx;
4898     else if (cpi->refresh_golden_frame)
4899       cpi->svc.fb_idx_upd_tl0[cpi->svc.spatial_layer_id] = cpi->gld_fb_idx;
4900     else if (cpi->refresh_alt_ref_frame)
4901       cpi->svc.fb_idx_upd_tl0[cpi->svc.spatial_layer_id] = cpi->alt_fb_idx;
4902   }
4903
4904   // Disable segmentation if it decrease rate/distortion ratio
4905   if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ)
4906     vp9_try_disable_lookahead_aq(cpi, size, dest);
4907
4908 #if CONFIG_VP9_TEMPORAL_DENOISING
4909 #ifdef OUTPUT_YUV_DENOISED
4910   if (oxcf->noise_sensitivity > 0 && denoise_svc(cpi)) {
4911     vpx_write_yuv_frame(yuv_denoised_file,
4912                         &cpi->denoiser.running_avg_y[INTRA_FRAME]);
4913   }
4914 #endif
4915 #endif
4916 #ifdef OUTPUT_YUV_SKINMAP
4917   if (cpi->common.current_video_frame > 1) {
4918     vp9_output_skin_map(cpi, yuv_skinmap_file);
4919   }
4920 #endif
4921
4922   // Special case code to reduce pulsing when key frames are forced at a
4923   // fixed interval. Note the reconstruction error if it is the frame before
4924   // the force key frame
4925   if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
4926 #if CONFIG_VP9_HIGHBITDEPTH
4927     if (cm->use_highbitdepth) {
4928       cpi->ambient_err =
4929           vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
4930     } else {
4931       cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
4932     }
4933 #else
4934     cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
4935 #endif  // CONFIG_VP9_HIGHBITDEPTH
4936   }
4937
4938   // If the encoder forced a KEY_FRAME decision
4939   if (cm->frame_type == KEY_FRAME) cpi->refresh_last_frame = 1;
4940
4941   cm->frame_to_show = get_frame_new_buffer(cm);
4942   cm->frame_to_show->color_space = cm->color_space;
4943   cm->frame_to_show->color_range = cm->color_range;
4944   cm->frame_to_show->render_width = cm->render_width;
4945   cm->frame_to_show->render_height = cm->render_height;
4946
4947   // Pick the loop filter level for the frame.
4948   loopfilter_frame(cpi, cm);
4949
4950   // build the bitstream
4951   vp9_pack_bitstream(cpi, dest, size);
4952
4953   if (cm->seg.update_map) update_reference_segmentation_map(cpi);
4954
4955   if (frame_is_intra_only(cm) == 0) {
4956     release_scaled_references(cpi);
4957   }
4958   vp9_update_reference_frames(cpi);
4959
4960   for (t = TX_4X4; t <= TX_32X32; t++)
4961     full_to_model_counts(cpi->td.counts->coef[t],
4962                          cpi->td.rd_counts.coef_counts[t]);
4963
4964   if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
4965     vp9_adapt_coef_probs(cm);
4966
4967   if (!frame_is_intra_only(cm)) {
4968     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
4969       vp9_adapt_mode_probs(cm);
4970       vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
4971     }
4972   }
4973
4974   cpi->ext_refresh_frame_flags_pending = 0;
4975
4976   if (cpi->refresh_golden_frame == 1)
4977     cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
4978   else
4979     cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
4980
4981   if (cpi->refresh_alt_ref_frame == 1)
4982     cpi->frame_flags |= FRAMEFLAGS_ALTREF;
4983   else
4984     cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
4985
4986   cpi->ref_frame_flags = get_ref_frame_flags(cpi);
4987
4988   cm->last_frame_type = cm->frame_type;
4989
4990   vp9_rc_postencode_update(cpi, *size);
4991
4992 #if 0
4993   output_frame_level_debug_stats(cpi);
4994 #endif
4995
4996   if (cm->frame_type == KEY_FRAME) {
4997     // Tell the caller that the frame was coded as a key frame
4998     *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
4999   } else {
5000     *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
5001   }
5002
5003   // Clear the one shot update flags for segmentation map and mode/ref loop
5004   // filter deltas.
5005   cm->seg.update_map = 0;
5006   cm->seg.update_data = 0;
5007   cm->lf.mode_ref_delta_update = 0;
5008
5009   // keep track of the last coded dimensions
5010   cm->last_width = cm->width;
5011   cm->last_height = cm->height;
5012
5013   // reset to normal state now that we are done.
5014   if (!cm->show_existing_frame) cm->last_show_frame = cm->show_frame;
5015
5016   if (cm->show_frame) {
5017     vp9_swap_mi_and_prev_mi(cm);
5018     // Don't increment frame counters if this was an altref buffer
5019     // update not a real frame
5020     ++cm->current_video_frame;
5021     if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
5022   }
5023   cm->prev_frame = cm->cur_frame;
5024
5025   if (cpi->use_svc) {
5026     cpi->svc
5027         .layer_context[cpi->svc.spatial_layer_id *
5028                            cpi->svc.number_temporal_layers +
5029                        cpi->svc.temporal_layer_id]
5030         .last_frame_type = cm->frame_type;
5031     // Reset layer_sync back to 0 for next frame.
5032     cpi->svc.spatial_layer_sync[cpi->svc.spatial_layer_id] = 0;
5033   }
5034
5035   cpi->force_update_segmentation = 0;
5036
5037   if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ)
5038     vp9_alt_ref_aq_unset_all(cpi->alt_ref_aq, cpi);
5039
5040   cpi->svc.previous_frame_is_intra_only = cm->intra_only;
5041   cpi->svc.set_intra_only_frame = 0;
5042 }
5043
5044 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
5045                       unsigned int *frame_flags) {
5046   vp9_rc_get_svc_params(cpi);
5047   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
5048 }
5049
5050 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
5051                         unsigned int *frame_flags) {
5052   if (cpi->oxcf.rc_mode == VPX_CBR) {
5053     vp9_rc_get_one_pass_cbr_params(cpi);
5054   } else {
5055     vp9_rc_get_one_pass_vbr_params(cpi);
5056   }
5057   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
5058 }
5059
5060 #if !CONFIG_REALTIME_ONLY
5061 static void Pass2Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
5062                         unsigned int *frame_flags) {
5063   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
5064   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
5065
5066   vp9_twopass_postencode_update(cpi);
5067 }
5068 #endif  // !CONFIG_REALTIME_ONLY
5069
5070 static void init_ref_frame_bufs(VP9_COMMON *cm) {
5071   int i;
5072   BufferPool *const pool = cm->buffer_pool;
5073   cm->new_fb_idx = INVALID_IDX;
5074   for (i = 0; i < REF_FRAMES; ++i) {
5075     cm->ref_frame_map[i] = INVALID_IDX;
5076     pool->frame_bufs[i].ref_count = 0;
5077   }
5078 }
5079
5080 static void check_initial_width(VP9_COMP *cpi,
5081 #if CONFIG_VP9_HIGHBITDEPTH
5082                                 int use_highbitdepth,
5083 #endif
5084                                 int subsampling_x, int subsampling_y) {
5085   VP9_COMMON *const cm = &cpi->common;
5086
5087   if (!cpi->initial_width ||
5088 #if CONFIG_VP9_HIGHBITDEPTH
5089       cm->use_highbitdepth != use_highbitdepth ||
5090 #endif
5091       cm->subsampling_x != subsampling_x ||
5092       cm->subsampling_y != subsampling_y) {
5093     cm->subsampling_x = subsampling_x;
5094     cm->subsampling_y = subsampling_y;
5095 #if CONFIG_VP9_HIGHBITDEPTH
5096     cm->use_highbitdepth = use_highbitdepth;
5097 #endif
5098
5099     alloc_raw_frame_buffers(cpi);
5100     init_ref_frame_bufs(cm);
5101     alloc_util_frame_buffers(cpi);
5102
5103     init_motion_estimation(cpi);  // TODO(agrange) This can be removed.
5104
5105     cpi->initial_width = cm->width;
5106     cpi->initial_height = cm->height;
5107     cpi->initial_mbs = cm->MBs;
5108   }
5109 }
5110
5111 int vp9_receive_raw_frame(VP9_COMP *cpi, vpx_enc_frame_flags_t frame_flags,
5112                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
5113                           int64_t end_time) {
5114   VP9_COMMON *const cm = &cpi->common;
5115   struct vpx_usec_timer timer;
5116   int res = 0;
5117   const int subsampling_x = sd->subsampling_x;
5118   const int subsampling_y = sd->subsampling_y;
5119 #if CONFIG_VP9_HIGHBITDEPTH
5120   const int use_highbitdepth = (sd->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
5121 #endif
5122
5123 #if CONFIG_VP9_HIGHBITDEPTH
5124   check_initial_width(cpi, use_highbitdepth, subsampling_x, subsampling_y);
5125 #else
5126   check_initial_width(cpi, subsampling_x, subsampling_y);
5127 #endif  // CONFIG_VP9_HIGHBITDEPTH
5128
5129 #if CONFIG_VP9_HIGHBITDEPTH
5130   // Disable denoiser for high bitdepth since vp9_denoiser_filter only works for
5131   // 8 bits.
5132   if (cm->bit_depth > 8) cpi->oxcf.noise_sensitivity = 0;
5133 #endif
5134
5135 #if CONFIG_VP9_TEMPORAL_DENOISING
5136   setup_denoiser_buffer(cpi);
5137 #endif
5138   vpx_usec_timer_start(&timer);
5139
5140   if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
5141 #if CONFIG_VP9_HIGHBITDEPTH
5142                          use_highbitdepth,
5143 #endif  // CONFIG_VP9_HIGHBITDEPTH
5144                          frame_flags))
5145     res = -1;
5146   vpx_usec_timer_mark(&timer);
5147   cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
5148
5149   if ((cm->profile == PROFILE_0 || cm->profile == PROFILE_2) &&
5150       (subsampling_x != 1 || subsampling_y != 1)) {
5151     vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
5152                        "Non-4:2:0 color format requires profile 1 or 3");
5153     res = -1;
5154   }
5155   if ((cm->profile == PROFILE_1 || cm->profile == PROFILE_3) &&
5156       (subsampling_x == 1 && subsampling_y == 1)) {
5157     vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
5158                        "4:2:0 color format requires profile 0 or 2");
5159     res = -1;
5160   }
5161
5162   return res;
5163 }
5164
5165 static int frame_is_reference(const VP9_COMP *cpi) {
5166   const VP9_COMMON *cm = &cpi->common;
5167
5168   return cm->frame_type == KEY_FRAME || cpi->refresh_last_frame ||
5169          cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame ||
5170          cm->refresh_frame_context || cm->lf.mode_ref_delta_update ||
5171          cm->seg.update_map || cm->seg.update_data;
5172 }
5173
5174 static void adjust_frame_rate(VP9_COMP *cpi,
5175                               const struct lookahead_entry *source) {
5176   int64_t this_duration;
5177   int step = 0;
5178
5179   if (source->ts_start == cpi->first_time_stamp_ever) {
5180     this_duration = source->ts_end - source->ts_start;
5181     step = 1;
5182   } else {
5183     int64_t last_duration =
5184         cpi->last_end_time_stamp_seen - cpi->last_time_stamp_seen;
5185
5186     this_duration = source->ts_end - cpi->last_end_time_stamp_seen;
5187
5188     // do a step update if the duration changes by 10%
5189     if (last_duration)
5190       step = (int)((this_duration - last_duration) * 10 / last_duration);
5191   }
5192
5193   if (this_duration) {
5194     if (step) {
5195       vp9_new_framerate(cpi, 10000000.0 / this_duration);
5196     } else {
5197       // Average this frame's rate into the last second's average
5198       // frame rate. If we haven't seen 1 second yet, then average
5199       // over the whole interval seen.
5200       const double interval = VPXMIN(
5201           (double)(source->ts_end - cpi->first_time_stamp_ever), 10000000.0);
5202       double avg_duration = 10000000.0 / cpi->framerate;
5203       avg_duration *= (interval - avg_duration + this_duration);
5204       avg_duration /= interval;
5205
5206       vp9_new_framerate(cpi, 10000000.0 / avg_duration);
5207     }
5208   }
5209   cpi->last_time_stamp_seen = source->ts_start;
5210   cpi->last_end_time_stamp_seen = source->ts_end;
5211 }
5212
5213 // Returns 0 if this is not an alt ref else the offset of the source frame
5214 // used as the arf midpoint.
5215 static int get_arf_src_index(VP9_COMP *cpi) {
5216   RATE_CONTROL *const rc = &cpi->rc;
5217   int arf_src_index = 0;
5218   if (is_altref_enabled(cpi)) {
5219     if (cpi->oxcf.pass == 2) {
5220       const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
5221       if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
5222         arf_src_index = gf_group->arf_src_offset[gf_group->index];
5223       }
5224     } else if (rc->source_alt_ref_pending) {
5225       arf_src_index = rc->frames_till_gf_update_due;
5226     }
5227   }
5228   return arf_src_index;
5229 }
5230
5231 static void check_src_altref(VP9_COMP *cpi,
5232                              const struct lookahead_entry *source) {
5233   RATE_CONTROL *const rc = &cpi->rc;
5234
5235   if (cpi->oxcf.pass == 2) {
5236     const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
5237     rc->is_src_frame_alt_ref =
5238         (gf_group->update_type[gf_group->index] == OVERLAY_UPDATE);
5239   } else {
5240     rc->is_src_frame_alt_ref =
5241         cpi->alt_ref_source && (source == cpi->alt_ref_source);
5242   }
5243
5244   if (rc->is_src_frame_alt_ref) {
5245     // Current frame is an ARF overlay frame.
5246     cpi->alt_ref_source = NULL;
5247
5248     // Don't refresh the last buffer for an ARF overlay frame. It will
5249     // become the GF so preserve last as an alternative prediction option.
5250     cpi->refresh_last_frame = 0;
5251   }
5252 }
5253
5254 #if CONFIG_INTERNAL_STATS
5255 extern double vp9_get_blockiness(const uint8_t *img1, int img1_pitch,
5256                                  const uint8_t *img2, int img2_pitch, int width,
5257                                  int height);
5258
5259 static void adjust_image_stat(double y, double u, double v, double all,
5260                               ImageStat *s) {
5261   s->stat[Y] += y;
5262   s->stat[U] += u;
5263   s->stat[V] += v;
5264   s->stat[ALL] += all;
5265   s->worst = VPXMIN(s->worst, all);
5266 }
5267 #endif  // CONFIG_INTERNAL_STATS
5268
5269 // Adjust the maximum allowable frame size for the target level.
5270 static void level_rc_framerate(VP9_COMP *cpi, int arf_src_index) {
5271   RATE_CONTROL *const rc = &cpi->rc;
5272   LevelConstraint *const ls = &cpi->level_constraint;
5273   VP9_COMMON *const cm = &cpi->common;
5274   const double max_cpb_size = ls->max_cpb_size;
5275   vpx_clear_system_state();
5276   rc->max_frame_bandwidth = VPXMIN(rc->max_frame_bandwidth, ls->max_frame_size);
5277   if (frame_is_intra_only(cm)) {
5278     rc->max_frame_bandwidth =
5279         VPXMIN(rc->max_frame_bandwidth, (int)(max_cpb_size * 0.5));
5280   } else if (arf_src_index > 0) {
5281     rc->max_frame_bandwidth =
5282         VPXMIN(rc->max_frame_bandwidth, (int)(max_cpb_size * 0.4));
5283   } else {
5284     rc->max_frame_bandwidth =
5285         VPXMIN(rc->max_frame_bandwidth, (int)(max_cpb_size * 0.2));
5286   }
5287 }
5288
5289 static void update_level_info(VP9_COMP *cpi, size_t *size, int arf_src_index) {
5290   VP9_COMMON *const cm = &cpi->common;
5291   Vp9LevelInfo *const level_info = &cpi->level_info;
5292   Vp9LevelSpec *const level_spec = &level_info->level_spec;
5293   Vp9LevelStats *const level_stats = &level_info->level_stats;
5294   int i, idx;
5295   uint64_t luma_samples, dur_end;
5296   const uint32_t luma_pic_size = cm->width * cm->height;
5297   const uint32_t luma_pic_breadth = VPXMAX(cm->width, cm->height);
5298   LevelConstraint *const level_constraint = &cpi->level_constraint;
5299   const int8_t level_index = level_constraint->level_index;
5300   double cpb_data_size;
5301
5302   vpx_clear_system_state();
5303
5304   // update level_stats
5305   level_stats->total_compressed_size += *size;
5306   if (cm->show_frame) {
5307     level_stats->total_uncompressed_size +=
5308         luma_pic_size +
5309         2 * (luma_pic_size >> (cm->subsampling_x + cm->subsampling_y));
5310     level_stats->time_encoded =
5311         (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
5312         (double)TICKS_PER_SEC;
5313   }
5314
5315   if (arf_src_index > 0) {
5316     if (!level_stats->seen_first_altref) {
5317       level_stats->seen_first_altref = 1;
5318     } else if (level_stats->frames_since_last_altref <
5319                level_spec->min_altref_distance) {
5320       level_spec->min_altref_distance = level_stats->frames_since_last_altref;
5321     }
5322     level_stats->frames_since_last_altref = 0;
5323   } else {
5324     ++level_stats->frames_since_last_altref;
5325   }
5326
5327   if (level_stats->frame_window_buffer.len < FRAME_WINDOW_SIZE - 1) {
5328     idx = (level_stats->frame_window_buffer.start +
5329            level_stats->frame_window_buffer.len++) %
5330           FRAME_WINDOW_SIZE;
5331   } else {
5332     idx = level_stats->frame_window_buffer.start;
5333     level_stats->frame_window_buffer.start = (idx + 1) % FRAME_WINDOW_SIZE;
5334   }
5335   level_stats->frame_window_buffer.buf[idx].ts = cpi->last_time_stamp_seen;
5336   level_stats->frame_window_buffer.buf[idx].size = (uint32_t)(*size);
5337   level_stats->frame_window_buffer.buf[idx].luma_samples = luma_pic_size;
5338
5339   if (cm->frame_type == KEY_FRAME) {
5340     level_stats->ref_refresh_map = 0;
5341   } else {
5342     int count = 0;
5343     level_stats->ref_refresh_map |= vp9_get_refresh_mask(cpi);
5344     // Also need to consider the case where the encoder refers to a buffer
5345     // that has been implicitly refreshed after encoding a keyframe.
5346     if (!cm->intra_only) {
5347       level_stats->ref_refresh_map |= (1 << cpi->lst_fb_idx);
5348       level_stats->ref_refresh_map |= (1 << cpi->gld_fb_idx);
5349       level_stats->ref_refresh_map |= (1 << cpi->alt_fb_idx);
5350     }
5351     for (i = 0; i < REF_FRAMES; ++i) {
5352       count += (level_stats->ref_refresh_map >> i) & 1;
5353     }
5354     if (count > level_spec->max_ref_frame_buffers) {
5355       level_spec->max_ref_frame_buffers = count;
5356     }
5357   }
5358
5359   // update average_bitrate
5360   level_spec->average_bitrate = (double)level_stats->total_compressed_size /
5361                                 125.0 / level_stats->time_encoded;
5362
5363   // update max_luma_sample_rate
5364   luma_samples = 0;
5365   for (i = 0; i < level_stats->frame_window_buffer.len; ++i) {
5366     idx = (level_stats->frame_window_buffer.start +
5367            level_stats->frame_window_buffer.len - 1 - i) %
5368           FRAME_WINDOW_SIZE;
5369     if (i == 0) {
5370       dur_end = level_stats->frame_window_buffer.buf[idx].ts;
5371     }
5372     if (dur_end - level_stats->frame_window_buffer.buf[idx].ts >=
5373         TICKS_PER_SEC) {
5374       break;
5375     }
5376     luma_samples += level_stats->frame_window_buffer.buf[idx].luma_samples;
5377   }
5378   if (luma_samples > level_spec->max_luma_sample_rate) {
5379     level_spec->max_luma_sample_rate = luma_samples;
5380   }
5381
5382   // update max_cpb_size
5383   cpb_data_size = 0;
5384   for (i = 0; i < CPB_WINDOW_SIZE; ++i) {
5385     if (i >= level_stats->frame_window_buffer.len) break;
5386     idx = (level_stats->frame_window_buffer.start +
5387            level_stats->frame_window_buffer.len - 1 - i) %
5388           FRAME_WINDOW_SIZE;
5389     cpb_data_size += level_stats->frame_window_buffer.buf[idx].size;
5390   }
5391   cpb_data_size = cpb_data_size / 125.0;
5392   if (cpb_data_size > level_spec->max_cpb_size) {
5393     level_spec->max_cpb_size = cpb_data_size;
5394   }
5395
5396   // update max_luma_picture_size
5397   if (luma_pic_size > level_spec->max_luma_picture_size) {
5398     level_spec->max_luma_picture_size = luma_pic_size;
5399   }
5400
5401   // update max_luma_picture_breadth
5402   if (luma_pic_breadth > level_spec->max_luma_picture_breadth) {
5403     level_spec->max_luma_picture_breadth = luma_pic_breadth;
5404   }
5405
5406   // update compression_ratio
5407   level_spec->compression_ratio = (double)level_stats->total_uncompressed_size *
5408                                   cm->bit_depth /
5409                                   level_stats->total_compressed_size / 8.0;
5410
5411   // update max_col_tiles
5412   if (level_spec->max_col_tiles < (1 << cm->log2_tile_cols)) {
5413     level_spec->max_col_tiles = (1 << cm->log2_tile_cols);
5414   }
5415
5416   if (level_index >= 0 && level_constraint->fail_flag == 0) {
5417     if (level_spec->max_luma_picture_size >
5418         vp9_level_defs[level_index].max_luma_picture_size) {
5419       level_constraint->fail_flag |= (1 << LUMA_PIC_SIZE_TOO_LARGE);
5420       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
5421                          "Failed to encode to the target level %d. %s",
5422                          vp9_level_defs[level_index].level,
5423                          level_fail_messages[LUMA_PIC_SIZE_TOO_LARGE]);
5424     }
5425
5426     if (level_spec->max_luma_picture_breadth >
5427         vp9_level_defs[level_index].max_luma_picture_breadth) {
5428       level_constraint->fail_flag |= (1 << LUMA_PIC_BREADTH_TOO_LARGE);
5429       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
5430                          "Failed to encode to the target level %d. %s",
5431                          vp9_level_defs[level_index].level,
5432                          level_fail_messages[LUMA_PIC_BREADTH_TOO_LARGE]);
5433     }
5434
5435     if ((double)level_spec->max_luma_sample_rate >
5436         (double)vp9_level_defs[level_index].max_luma_sample_rate *
5437             (1 + SAMPLE_RATE_GRACE_P)) {
5438       level_constraint->fail_flag |= (1 << LUMA_SAMPLE_RATE_TOO_LARGE);
5439       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
5440                          "Failed to encode to the target level %d. %s",
5441                          vp9_level_defs[level_index].level,
5442                          level_fail_messages[LUMA_SAMPLE_RATE_TOO_LARGE]);
5443     }
5444
5445     if (level_spec->max_col_tiles > vp9_level_defs[level_index].max_col_tiles) {
5446       level_constraint->fail_flag |= (1 << TOO_MANY_COLUMN_TILE);
5447       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
5448                          "Failed to encode to the target level %d. %s",
5449                          vp9_level_defs[level_index].level,
5450                          level_fail_messages[TOO_MANY_COLUMN_TILE]);
5451     }
5452
5453     if (level_spec->min_altref_distance <
5454         vp9_level_defs[level_index].min_altref_distance) {
5455       level_constraint->fail_flag |= (1 << ALTREF_DIST_TOO_SMALL);
5456       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
5457                          "Failed to encode to the target level %d. %s",
5458                          vp9_level_defs[level_index].level,
5459                          level_fail_messages[ALTREF_DIST_TOO_SMALL]);
5460     }
5461
5462     if (level_spec->max_ref_frame_buffers >
5463         vp9_level_defs[level_index].max_ref_frame_buffers) {
5464       level_constraint->fail_flag |= (1 << TOO_MANY_REF_BUFFER);
5465       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
5466                          "Failed to encode to the target level %d. %s",
5467                          vp9_level_defs[level_index].level,
5468                          level_fail_messages[TOO_MANY_REF_BUFFER]);
5469     }
5470
5471     if (level_spec->max_cpb_size > vp9_level_defs[level_index].max_cpb_size) {
5472       level_constraint->fail_flag |= (1 << CPB_TOO_LARGE);
5473       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
5474                          "Failed to encode to the target level %d. %s",
5475                          vp9_level_defs[level_index].level,
5476                          level_fail_messages[CPB_TOO_LARGE]);
5477     }
5478
5479     // Set an upper bound for the next frame size. It will be used in
5480     // level_rc_framerate() before encoding the next frame.
5481     cpb_data_size = 0;
5482     for (i = 0; i < CPB_WINDOW_SIZE - 1; ++i) {
5483       if (i >= level_stats->frame_window_buffer.len) break;
5484       idx = (level_stats->frame_window_buffer.start +
5485              level_stats->frame_window_buffer.len - 1 - i) %
5486             FRAME_WINDOW_SIZE;
5487       cpb_data_size += level_stats->frame_window_buffer.buf[idx].size;
5488     }
5489     cpb_data_size = cpb_data_size / 125.0;
5490     level_constraint->max_frame_size =
5491         (int)((vp9_level_defs[level_index].max_cpb_size - cpb_data_size) *
5492               1000.0);
5493     if (level_stats->frame_window_buffer.len < CPB_WINDOW_SIZE - 1)
5494       level_constraint->max_frame_size >>= 1;
5495   }
5496 }
5497
5498 typedef struct GF_PICTURE {
5499   YV12_BUFFER_CONFIG *frame;
5500   int ref_frame[3];
5501 } GF_PICTURE;
5502
5503 void init_gop_frames(VP9_COMP *cpi, GF_PICTURE *gf_picture,
5504                      const GF_GROUP *gf_group, int *tpl_group_frames) {
5505   int frame_idx, i;
5506   int gld_index = -1;
5507   int alt_index = -1;
5508   int lst_index = -1;
5509   int extend_frame_count = 0;
5510   int pframe_qindex = cpi->tpl_stats[2].base_qindex;
5511
5512   *tpl_group_frames = 0;
5513
5514   // Initialize Golden reference frame.
5515   gf_picture[0].frame = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
5516   for (i = 0; i < 3; ++i) gf_picture[0].ref_frame[i] = -1;
5517   gld_index = 0;
5518   ++*tpl_group_frames;
5519
5520   // Initialize ARF frame
5521   gf_picture[1].frame = cpi->Source;
5522   gf_picture[1].ref_frame[0] = gld_index;
5523   gf_picture[1].ref_frame[1] = lst_index;
5524   gf_picture[1].ref_frame[2] = alt_index;
5525   alt_index = 1;
5526   ++*tpl_group_frames;
5527
5528   // Initialize P frames
5529   for (frame_idx = 2; frame_idx < MAX_LAG_BUFFERS; ++frame_idx) {
5530     struct lookahead_entry *buf =
5531         vp9_lookahead_peek(cpi->lookahead, frame_idx - 2);
5532
5533     if (buf == NULL) break;
5534
5535     gf_picture[frame_idx].frame = &buf->img;
5536     gf_picture[frame_idx].ref_frame[0] = gld_index;
5537     gf_picture[frame_idx].ref_frame[1] = lst_index;
5538     gf_picture[frame_idx].ref_frame[2] = alt_index;
5539
5540     ++*tpl_group_frames;
5541     lst_index = frame_idx;
5542     if (gf_group->update_type[frame_idx] == OVERLAY_UPDATE) break;
5543   }
5544
5545   gld_index = frame_idx;
5546   lst_index = VPXMAX(0, frame_idx - 1);
5547   alt_index = -1;
5548   ++frame_idx;
5549
5550   // Extend two frames outside the current gf group.
5551   for (; frame_idx < MAX_LAG_BUFFERS && extend_frame_count < 2; ++frame_idx) {
5552     struct lookahead_entry *buf =
5553         vp9_lookahead_peek(cpi->lookahead, frame_idx - 2);
5554
5555     if (buf == NULL) break;
5556
5557     cpi->tpl_stats[frame_idx].base_qindex = pframe_qindex;
5558
5559     gf_picture[frame_idx].frame = &buf->img;
5560     gf_picture[frame_idx].ref_frame[0] = gld_index;
5561     gf_picture[frame_idx].ref_frame[1] = lst_index;
5562     gf_picture[frame_idx].ref_frame[2] = alt_index;
5563     lst_index = frame_idx;
5564     ++*tpl_group_frames;
5565     ++extend_frame_count;
5566   }
5567 }
5568
5569 void init_tpl_stats(VP9_COMP *cpi) {
5570   int frame_idx;
5571   for (frame_idx = 0; frame_idx < MAX_LAG_BUFFERS; ++frame_idx) {
5572     TplDepFrame *tpl_frame = &cpi->tpl_stats[frame_idx];
5573     memset(tpl_frame->tpl_stats_ptr, 0,
5574            tpl_frame->height * tpl_frame->width *
5575                sizeof(*tpl_frame->tpl_stats_ptr));
5576     tpl_frame->is_valid = 0;
5577   }
5578 }
5579
5580 uint32_t motion_compensated_prediction(VP9_COMP *cpi, ThreadData *td,
5581                                        uint8_t *cur_frame_buf,
5582                                        uint8_t *ref_frame_buf, int stride,
5583                                        MV *mv, BLOCK_SIZE bsize) {
5584   MACROBLOCK *const x = &td->mb;
5585   MACROBLOCKD *const xd = &x->e_mbd;
5586   MV_SPEED_FEATURES *const mv_sf = &cpi->sf.mv;
5587   const SEARCH_METHODS search_method = HEX;
5588   int step_param;
5589   int sadpb = x->sadperbit16;
5590   uint32_t bestsme = UINT_MAX;
5591   uint32_t distortion;
5592   uint32_t sse;
5593   int cost_list[5];
5594   const MvLimits tmp_mv_limits = x->mv_limits;
5595
5596   MV best_ref_mv1 = { 0, 0 };
5597   MV best_ref_mv1_full; /* full-pixel value of best_ref_mv1 */
5598
5599   best_ref_mv1_full.col = best_ref_mv1.col >> 3;
5600   best_ref_mv1_full.row = best_ref_mv1.row >> 3;
5601
5602   // Setup frame pointers
5603   x->plane[0].src.buf = cur_frame_buf;
5604   x->plane[0].src.stride = stride;
5605   xd->plane[0].pre[0].buf = ref_frame_buf;
5606   xd->plane[0].pre[0].stride = stride;
5607
5608   step_param = mv_sf->reduce_first_step_size;
5609   step_param = VPXMIN(step_param, MAX_MVSEARCH_STEPS - 2);
5610
5611   vp9_set_mv_search_range(&x->mv_limits, &best_ref_mv1);
5612
5613   vp9_full_pixel_search(cpi, x, bsize, &best_ref_mv1_full, step_param,
5614                         search_method, sadpb, cond_cost_list(cpi, cost_list),
5615                         &best_ref_mv1, mv, 0, 0);
5616
5617   /* restore UMV window */
5618   x->mv_limits = tmp_mv_limits;
5619
5620   // Ignore mv costing by sending NULL pointer instead of cost array
5621   bestsme = cpi->find_fractional_mv_step(
5622       x, mv, &best_ref_mv1, cpi->common.allow_high_precision_mv, x->errorperbit,
5623       &cpi->fn_ptr[bsize], 0, mv_sf->subpel_iters_per_step,
5624       cond_cost_list(cpi, cost_list), NULL, NULL, &distortion, &sse, NULL, 0,
5625       0);
5626
5627   return bestsme;
5628 }
5629
5630 int get_overlap_area(int grid_pos_row, int grid_pos_col, int ref_pos_row,
5631                      int ref_pos_col, int block, BLOCK_SIZE bsize) {
5632   int overlap_area;
5633   int width = 0, height = 0;
5634   int bw = 4 << b_width_log2_lookup[bsize];
5635   int bh = 4 << b_height_log2_lookup[bsize];
5636
5637   switch (block) {
5638     case 0:
5639       width = grid_pos_col + bw - ref_pos_col;
5640       height = grid_pos_row + bh - ref_pos_row;
5641       break;
5642     case 1:
5643       width = ref_pos_col + bw - grid_pos_col;
5644       height = grid_pos_row + bh - ref_pos_row;
5645       break;
5646     case 2:
5647       width = grid_pos_col + bw - ref_pos_col;
5648       height = ref_pos_row + bh - grid_pos_row;
5649       break;
5650     case 3:
5651       width = ref_pos_col + bw - grid_pos_col;
5652       height = ref_pos_row + bh - grid_pos_row;
5653       break;
5654     default: assert(0);
5655   }
5656
5657   return overlap_area = width * height;
5658 }
5659
5660 int round_floor(int ref_pos, int bsize_pix) {
5661   int round;
5662   if (ref_pos < 0)
5663     round = -(1 + (-ref_pos - 1) / bsize_pix);
5664   else
5665     round = ref_pos / bsize_pix;
5666
5667   return round;
5668 }
5669
5670 void tpl_model_store(TplDepStats *tpl_stats, int mi_row, int mi_col,
5671                      BLOCK_SIZE bsize, int stride, int64_t intra_cost,
5672                      int64_t inter_cost, int ref_frame_idx, int_mv mv) {
5673   const int mi_height = num_8x8_blocks_high_lookup[bsize];
5674   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
5675   int idx, idy;
5676
5677   intra_cost = intra_cost / (mi_height * mi_width);
5678   inter_cost = inter_cost / (mi_height * mi_width);
5679
5680   intra_cost = VPXMAX(1, intra_cost);
5681   inter_cost = VPXMAX(1, inter_cost);
5682
5683   for (idy = 0; idy < mi_height; ++idy) {
5684     for (idx = 0; idx < mi_width; ++idx) {
5685       TplDepStats *tpl_ptr =
5686           &tpl_stats[(mi_row + idy) * stride + (mi_col + idx)];
5687       tpl_ptr->intra_cost = intra_cost;
5688       tpl_ptr->inter_cost = inter_cost;
5689       tpl_ptr->mc_dep_cost = tpl_ptr->intra_cost + tpl_ptr->mc_flow;
5690       tpl_ptr->ref_frame_index = ref_frame_idx;
5691       tpl_ptr->mv.as_int = mv.as_int;
5692     }
5693   }
5694 }
5695
5696 void tpl_model_update_b(TplDepFrame *tpl_frame, TplDepStats *tpl_stats,
5697                         int mi_row, int mi_col, const BLOCK_SIZE bsize) {
5698   TplDepFrame *ref_tpl_frame = &tpl_frame[tpl_stats->ref_frame_index];
5699   TplDepStats *ref_stats = ref_tpl_frame->tpl_stats_ptr;
5700   MV mv = tpl_stats->mv.as_mv;
5701   int mv_row = mv.row >> 3;
5702   int mv_col = mv.col >> 3;
5703
5704   int ref_pos_row = mi_row * MI_SIZE + mv_row;
5705   int ref_pos_col = mi_col * MI_SIZE + mv_col;
5706
5707   const int bw = 4 << b_width_log2_lookup[bsize];
5708   const int bh = 4 << b_height_log2_lookup[bsize];
5709   const int mi_height = num_8x8_blocks_high_lookup[bsize];
5710   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
5711   const int pix_num = bw * bh;
5712
5713   // top-left on grid block location in pixel
5714   int grid_pos_row_base = round_floor(ref_pos_row, bh) * bh;
5715   int grid_pos_col_base = round_floor(ref_pos_col, bw) * bw;
5716   int block;
5717
5718   for (block = 0; block < 4; ++block) {
5719     int grid_pos_row = grid_pos_row_base + bh * (block >> 1);
5720     int grid_pos_col = grid_pos_col_base + bw * (block & 0x01);
5721
5722     if (grid_pos_row >= 0 && grid_pos_row < ref_tpl_frame->mi_rows * MI_SIZE &&
5723         grid_pos_col >= 0 && grid_pos_col < ref_tpl_frame->mi_cols * MI_SIZE) {
5724       int overlap_area = get_overlap_area(
5725           grid_pos_row, grid_pos_col, ref_pos_row, ref_pos_col, block, bsize);
5726       int ref_mi_row = round_floor(grid_pos_row, bh) * mi_height;
5727       int ref_mi_col = round_floor(grid_pos_col, bw) * mi_width;
5728
5729       int64_t mc_flow = tpl_stats->mc_dep_cost -
5730                         (tpl_stats->mc_dep_cost * tpl_stats->inter_cost) /
5731                             tpl_stats->intra_cost;
5732
5733       int idx, idy;
5734
5735       for (idy = 0; idy < mi_height; ++idy) {
5736         for (idx = 0; idx < mi_width; ++idx) {
5737           TplDepStats *des_stats =
5738               &ref_stats[(ref_mi_row + idy) * ref_tpl_frame->stride +
5739                          (ref_mi_col + idx)];
5740
5741           des_stats->mc_flow += (mc_flow * overlap_area) / pix_num;
5742           des_stats->mc_ref_cost +=
5743               ((tpl_stats->intra_cost - tpl_stats->inter_cost) * overlap_area) /
5744               pix_num;
5745           assert(overlap_area >= 0);
5746         }
5747       }
5748     }
5749   }
5750 }
5751
5752 void tpl_model_update(TplDepFrame *tpl_frame, TplDepStats *tpl_stats,
5753                       int mi_row, int mi_col, const BLOCK_SIZE bsize) {
5754   int idx, idy;
5755   const int mi_height = num_8x8_blocks_high_lookup[bsize];
5756   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
5757
5758   for (idy = 0; idy < mi_height; ++idy) {
5759     for (idx = 0; idx < mi_width; ++idx) {
5760       TplDepStats *tpl_ptr =
5761           &tpl_stats[(mi_row + idy) * tpl_frame->stride + (mi_col + idx)];
5762       tpl_model_update_b(tpl_frame, tpl_ptr, mi_row + idy, mi_col + idx,
5763                          BLOCK_8X8);
5764     }
5765   }
5766 }
5767
5768 void get_quantize_error(MACROBLOCK *x, int plane, tran_low_t *coeff,
5769                         tran_low_t *qcoeff, tran_low_t *dqcoeff,
5770                         TX_SIZE tx_size, int64_t *recon_error, int64_t *sse) {
5771   MACROBLOCKD *const xd = &x->e_mbd;
5772   const struct macroblock_plane *const p = &x->plane[plane];
5773   const struct macroblockd_plane *const pd = &xd->plane[plane];
5774   const scan_order *const scan_order = &vp9_default_scan_orders[tx_size];
5775   uint16_t eob;
5776   int pix_num = 1 << num_pels_log2_lookup[txsize_to_bsize[tx_size]];
5777   const int shift = tx_size == TX_32X32 ? 0 : 2;
5778
5779   vp9_quantize_fp_32x32(coeff, pix_num, x->skip_block, p->round_fp, p->quant_fp,
5780                         qcoeff, dqcoeff, pd->dequant, &eob, scan_order->scan,
5781                         scan_order->iscan);
5782
5783   *recon_error = vp9_block_error(coeff, dqcoeff, pix_num, sse) >> shift;
5784   *recon_error = VPXMAX(*recon_error, 1);
5785
5786   *sse = (*sse) >> shift;
5787   *sse = VPXMAX(*sse, 1);
5788 }
5789
5790 void wht_fwd_txfm(int16_t *src_diff, int bw, tran_low_t *coeff,
5791                   TX_SIZE tx_size) {
5792   switch (tx_size) {
5793     case TX_8X8: vpx_hadamard_8x8(src_diff, bw, coeff); break;
5794     case TX_16X16: vpx_hadamard_16x16(src_diff, bw, coeff); break;
5795     case TX_32X32: vpx_hadamard_32x32(src_diff, bw, coeff); break;
5796     default: assert(0);
5797   }
5798 }
5799
5800 void mc_flow_dispenser(VP9_COMP *cpi, GF_PICTURE *gf_picture, int frame_idx) {
5801   TplDepFrame *tpl_frame = &cpi->tpl_stats[frame_idx];
5802   YV12_BUFFER_CONFIG *this_frame = gf_picture[frame_idx].frame;
5803   YV12_BUFFER_CONFIG *ref_frame[3] = { NULL, NULL, NULL };
5804
5805   VP9_COMMON *cm = &cpi->common;
5806   struct scale_factors sf;
5807   int rdmult, idx;
5808   ThreadData *td = &cpi->td;
5809   MACROBLOCK *x = &td->mb;
5810   MACROBLOCKD *xd = &x->e_mbd;
5811   int mi_row, mi_col;
5812   const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
5813
5814 #if CONFIG_VP9_HIGHBITDEPTH
5815   DECLARE_ALIGNED(16, uint16_t, predictor16[32 * 32 * 3]);
5816   DECLARE_ALIGNED(16, uint8_t, predictor8[32 * 32 * 3]);
5817   uint8_t *predictor;
5818 #else
5819   DECLARE_ALIGNED(16, uint8_t, predictor[32 * 32 * 3]);
5820 #endif
5821   DECLARE_ALIGNED(16, int16_t, src_diff[32 * 32]);
5822   DECLARE_ALIGNED(16, tran_low_t, coeff[32 * 32]);
5823   DECLARE_ALIGNED(16, tran_low_t, qcoeff[32 * 32]);
5824   DECLARE_ALIGNED(16, tran_low_t, dqcoeff[32 * 32]);
5825
5826   MODE_INFO mi_above, mi_left;
5827
5828   const BLOCK_SIZE bsize = BLOCK_32X32;
5829   const TX_SIZE tx_size = max_txsize_lookup[bsize];
5830   const int bw = 4 << b_width_log2_lookup[bsize];
5831   const int bh = 4 << b_height_log2_lookup[bsize];
5832   const int mi_height = num_8x8_blocks_high_lookup[bsize];
5833   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
5834   const int pix_num = bw * bh;
5835   int64_t recon_error, sse;
5836
5837   // Setup scaling factor
5838 #if CONFIG_VP9_HIGHBITDEPTH
5839   vp9_setup_scale_factors_for_frame(
5840       &sf, this_frame->y_crop_width, this_frame->y_crop_height,
5841       this_frame->y_crop_width, this_frame->y_crop_height,
5842       cpi->common.use_highbitdepth);
5843
5844   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
5845     predictor = CONVERT_TO_BYTEPTR(predictor16);
5846   else
5847     predictor = predictor8;
5848 #else
5849   vp9_setup_scale_factors_for_frame(
5850       &sf, this_frame->y_crop_width, this_frame->y_crop_height,
5851       this_frame->y_crop_width, this_frame->y_crop_height);
5852 #endif  // CONFIG_VP9_HIGHBITDEPTH
5853
5854   // Prepare reference frame pointers. If any reference frame slot is
5855   // unavailable, the pointer will be set to Null.
5856   for (idx = 0; idx < 3; ++idx) {
5857     int rf_idx = gf_picture[frame_idx].ref_frame[idx];
5858     if (rf_idx != -1) ref_frame[idx] = gf_picture[rf_idx].frame;
5859   }
5860
5861   xd->mi = cm->mi_grid_visible;
5862   xd->mi[0] = cm->mi;
5863
5864   // Get rd multiplier set up.
5865   rdmult =
5866       (int)vp9_compute_rd_mult_based_on_qindex(cpi, tpl_frame->base_qindex);
5867   if (rdmult < 1) rdmult = 1;
5868   set_error_per_bit(&cpi->td.mb, rdmult);
5869   vp9_initialize_me_consts(cpi, &cpi->td.mb, tpl_frame->base_qindex);
5870
5871   tpl_frame->is_valid = 1;
5872
5873   cm->base_qindex = tpl_frame->base_qindex;
5874   vp9_frame_init_quantizer(cpi);
5875
5876   for (mi_row = 0; mi_row < cm->mi_rows; mi_row += mi_height) {
5877     // Motion estimation row boundary
5878     x->mv_limits.row_min = -((mi_row * MI_SIZE) + (17 - 2 * VP9_INTERP_EXTEND));
5879     x->mv_limits.row_max =
5880         (cm->mi_rows - 1 - mi_row) * MI_SIZE + (17 - 2 * VP9_INTERP_EXTEND);
5881     for (mi_col = 0; mi_col < cm->mi_cols; mi_col += mi_width) {
5882       int mb_y_offset =
5883           mi_row * MI_SIZE * this_frame->y_stride + mi_col * MI_SIZE;
5884       int best_rf_idx = -1;
5885       int_mv best_mv;
5886       int64_t best_inter_cost = INT64_MAX;
5887       int64_t inter_cost;
5888       int rf_idx;
5889
5890       int64_t best_intra_cost = INT64_MAX;
5891       int64_t intra_cost;
5892       PREDICTION_MODE mode;
5893
5894       // Intra prediction search
5895       for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
5896         uint8_t *src, *dst;
5897         int src_stride, dst_stride;
5898
5899         xd->cur_buf = this_frame;
5900
5901         src = this_frame->y_buffer + mb_y_offset;
5902         src_stride = this_frame->y_stride;
5903
5904         dst = &predictor[0];
5905         dst_stride = bw;
5906
5907         xd->mi[0]->sb_type = bsize;
5908         xd->mi[0]->ref_frame[0] = INTRA_FRAME;
5909         xd->mb_to_top_edge = -((mi_row * MI_SIZE) * 8);
5910         xd->mb_to_bottom_edge = ((cm->mi_rows - 1 - mi_row) * MI_SIZE) * 8;
5911         xd->mb_to_left_edge = -((mi_col * MI_SIZE) * 8);
5912         xd->mb_to_right_edge = ((cm->mi_cols - 1 - mi_col) * MI_SIZE) * 8;
5913         xd->above_mi = (mi_row > 0) ? &mi_above : NULL;
5914         xd->left_mi = (mi_col > 0) ? &mi_left : NULL;
5915
5916         vp9_predict_intra_block(xd, b_width_log2_lookup[bsize], tx_size, mode,
5917                                 src, src_stride, dst, dst_stride, 0, 0, 0);
5918
5919         vpx_subtract_block(bh, bw, src_diff, bw, src, src_stride, dst,
5920                            dst_stride);
5921
5922         wht_fwd_txfm(src_diff, bw, coeff, tx_size);
5923
5924         intra_cost = vpx_satd(coeff, pix_num);
5925
5926         if (intra_cost < best_intra_cost) best_intra_cost = intra_cost;
5927       }
5928
5929       // Motion compensated prediction
5930       best_mv.as_int = 0;
5931
5932       (void)mb_y_offset;
5933       // Motion estimation column boundary
5934       x->mv_limits.col_min =
5935           -((mi_col * MI_SIZE) + (17 - 2 * VP9_INTERP_EXTEND));
5936       x->mv_limits.col_max =
5937           ((cm->mi_cols - 1 - mi_col) * MI_SIZE) + (17 - 2 * VP9_INTERP_EXTEND);
5938
5939       for (rf_idx = 0; rf_idx < 3; ++rf_idx) {
5940         int_mv mv;
5941         if (ref_frame[rf_idx] == NULL) continue;
5942
5943         motion_compensated_prediction(cpi, td,
5944                                       this_frame->y_buffer + mb_y_offset,
5945                                       ref_frame[rf_idx]->y_buffer + mb_y_offset,
5946                                       this_frame->y_stride, &mv.as_mv, bsize);
5947
5948         // TODO(jingning): Not yet support high bit-depth in the next three
5949         // steps.
5950 #if CONFIG_VP9_HIGHBITDEPTH
5951         if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
5952           vp9_highbd_build_inter_predictor(
5953               CONVERT_TO_SHORTPTR(ref_frame[rf_idx]->y_buffer + mb_y_offset),
5954               ref_frame[rf_idx]->y_stride, CONVERT_TO_SHORTPTR(&predictor[0]),
5955               bw, &mv.as_mv, &sf, bw, bh, 0, kernel, MV_PRECISION_Q3,
5956               mi_col * MI_SIZE, mi_row * MI_SIZE, xd->bd);
5957           vpx_highbd_subtract_block(
5958               bh, bw, src_diff, bw, this_frame->y_buffer + mb_y_offset,
5959               this_frame->y_stride, &predictor[0], bw, xd->bd);
5960         } else {
5961           vp9_build_inter_predictor(ref_frame[rf_idx]->y_buffer + mb_y_offset,
5962                                     ref_frame[rf_idx]->y_stride, &predictor[0],
5963                                     bw, &mv.as_mv, &sf, bw, bh, 0, kernel,
5964                                     MV_PRECISION_Q3, mi_col * MI_SIZE,
5965                                     mi_row * MI_SIZE);
5966           vpx_subtract_block(bh, bw, src_diff, bw,
5967                              this_frame->y_buffer + mb_y_offset,
5968                              this_frame->y_stride, &predictor[0], bw);
5969         }
5970 #else
5971         vp9_build_inter_predictor(
5972             ref_frame[rf_idx]->y_buffer + mb_y_offset,
5973             ref_frame[rf_idx]->y_stride, &predictor[0], bw, &mv.as_mv, &sf, bw,
5974             bh, 0, kernel, MV_PRECISION_Q3, mi_col * MI_SIZE, mi_row * MI_SIZE);
5975         vpx_subtract_block(bh, bw, src_diff, bw,
5976                            this_frame->y_buffer + mb_y_offset,
5977                            this_frame->y_stride, &predictor[0], bw);
5978 #endif
5979         wht_fwd_txfm(src_diff, bw, coeff, tx_size);
5980
5981         inter_cost = vpx_satd(coeff, pix_num);
5982
5983         if (inter_cost < best_inter_cost) {
5984           best_rf_idx = rf_idx;
5985           best_inter_cost = inter_cost;
5986           best_mv.as_int = mv.as_int;
5987           get_quantize_error(x, 0, coeff, qcoeff, dqcoeff, TX_32X32,
5988                              &recon_error, &sse);
5989         }
5990       }
5991
5992       // Motion flow dependency dispenser.
5993       best_intra_cost = VPXMAX(best_intra_cost, 1);
5994       best_inter_cost = VPXMIN(best_inter_cost, best_intra_cost);
5995
5996       best_intra_cost <<= TPL_DEP_COST_SCALE_LOG2;
5997       best_inter_cost <<= TPL_DEP_COST_SCALE_LOG2;
5998
5999       tpl_model_store(tpl_frame->tpl_stats_ptr, mi_row, mi_col, bsize,
6000                       tpl_frame->stride, best_intra_cost, best_inter_cost,
6001                       gf_picture[frame_idx].ref_frame[best_rf_idx], best_mv);
6002
6003       tpl_model_update(cpi->tpl_stats, tpl_frame->tpl_stats_ptr, mi_row, mi_col,
6004                        bsize);
6005     }
6006   }
6007 }
6008
6009 void setup_tpl_stats(VP9_COMP *cpi) {
6010   GF_PICTURE gf_picture[MAX_LAG_BUFFERS];
6011   const GF_GROUP *gf_group = &cpi->twopass.gf_group;
6012   int tpl_group_frames = 0;
6013   int frame_idx;
6014
6015   // TODO(jingning): Make the model support high bit-depth route.
6016 #if CONFIG_VP9_HIGHBITDEPTH
6017   (void)gf_picture;
6018   (void)gf_group;
6019   (void)tpl_group_frames;
6020   (void)frame_idx;
6021   return;
6022 #endif
6023
6024   init_gop_frames(cpi, gf_picture, gf_group, &tpl_group_frames);
6025
6026   init_tpl_stats(cpi);
6027
6028   // Backward propagation from tpl_group_frames to 1.
6029   for (frame_idx = tpl_group_frames - 1; frame_idx > 0; --frame_idx)
6030     mc_flow_dispenser(cpi, gf_picture, frame_idx);
6031 }
6032
6033 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
6034                             size_t *size, uint8_t *dest, int64_t *time_stamp,
6035                             int64_t *time_end, int flush) {
6036   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
6037   VP9_COMMON *const cm = &cpi->common;
6038   BufferPool *const pool = cm->buffer_pool;
6039   RATE_CONTROL *const rc = &cpi->rc;
6040   struct vpx_usec_timer cmptimer;
6041   YV12_BUFFER_CONFIG *force_src_buffer = NULL;
6042   struct lookahead_entry *last_source = NULL;
6043   struct lookahead_entry *source = NULL;
6044   int arf_src_index;
6045   int i;
6046
6047   if (is_one_pass_cbr_svc(cpi)) {
6048     vp9_one_pass_cbr_svc_start_layer(cpi);
6049   }
6050
6051   vpx_usec_timer_start(&cmptimer);
6052
6053   vp9_set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
6054
6055   // Is multi-arf enabled.
6056   // Note that at the moment multi_arf is only configured for 2 pass VBR and
6057   // will not work properly with svc.
6058   if ((oxcf->pass == 2) && !cpi->use_svc && (cpi->oxcf.enable_auto_arf > 1))
6059     cpi->multi_arf_allowed = 1;
6060   else
6061     cpi->multi_arf_allowed = 0;
6062
6063   // Normal defaults
6064   cm->reset_frame_context = 0;
6065   cm->refresh_frame_context = 1;
6066   if (!is_one_pass_cbr_svc(cpi)) {
6067     cpi->refresh_last_frame = 1;
6068     cpi->refresh_golden_frame = 0;
6069     cpi->refresh_alt_ref_frame = 0;
6070   }
6071
6072   // Should we encode an arf frame.
6073   arf_src_index = get_arf_src_index(cpi);
6074
6075   if (arf_src_index) {
6076     for (i = 0; i <= arf_src_index; ++i) {
6077       struct lookahead_entry *e = vp9_lookahead_peek(cpi->lookahead, i);
6078       // Avoid creating an alt-ref if there's a forced keyframe pending.
6079       if (e == NULL) {
6080         break;
6081       } else if (e->flags == VPX_EFLAG_FORCE_KF) {
6082         arf_src_index = 0;
6083         flush = 1;
6084         break;
6085       }
6086     }
6087   }
6088
6089   if (arf_src_index) {
6090     assert(arf_src_index <= rc->frames_to_key);
6091
6092     if ((source = vp9_lookahead_peek(cpi->lookahead, arf_src_index)) != NULL) {
6093       cpi->alt_ref_source = source;
6094
6095 #if !CONFIG_REALTIME_ONLY
6096       if ((oxcf->mode != REALTIME) && (oxcf->arnr_max_frames > 0) &&
6097           (oxcf->arnr_strength > 0)) {
6098         int bitrate = cpi->rc.avg_frame_bandwidth / 40;
6099         int not_low_bitrate = bitrate > ALT_REF_AQ_LOW_BITRATE_BOUNDARY;
6100
6101         int not_last_frame = (cpi->lookahead->sz - arf_src_index > 1);
6102         not_last_frame |= ALT_REF_AQ_APPLY_TO_LAST_FRAME;
6103
6104         // Produce the filtered ARF frame.
6105         vp9_temporal_filter(cpi, arf_src_index);
6106         vpx_extend_frame_borders(&cpi->alt_ref_buffer);
6107
6108         // for small bitrates segmentation overhead usually
6109         // eats all bitrate gain from enabling delta quantizers
6110         if (cpi->oxcf.alt_ref_aq != 0 && not_low_bitrate && not_last_frame)
6111           vp9_alt_ref_aq_setup_mode(cpi->alt_ref_aq, cpi);
6112
6113         force_src_buffer = &cpi->alt_ref_buffer;
6114       }
6115 #endif
6116       cm->show_frame = 0;
6117       cm->intra_only = 0;
6118       cpi->refresh_alt_ref_frame = 1;
6119       cpi->refresh_golden_frame = 0;
6120       cpi->refresh_last_frame = 0;
6121       rc->is_src_frame_alt_ref = 0;
6122       rc->source_alt_ref_pending = 0;
6123     } else {
6124       rc->source_alt_ref_pending = 0;
6125     }
6126   }
6127
6128   if (!source) {
6129     // Get last frame source.
6130     if (cm->current_video_frame > 0) {
6131       if ((last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
6132         return -1;
6133     }
6134
6135     // Read in the source frame.
6136     if (cpi->use_svc || cpi->svc.set_intra_only_frame)
6137       source = vp9_svc_lookahead_pop(cpi, cpi->lookahead, flush);
6138     else
6139       source = vp9_lookahead_pop(cpi->lookahead, flush);
6140
6141     if (source != NULL) {
6142       cm->show_frame = 1;
6143       cm->intra_only = 0;
6144       // if the flags indicate intra frame, but if the current picture is for
6145       // non-zero spatial layer, it should not be an intra picture.
6146       if ((source->flags & VPX_EFLAG_FORCE_KF) && cpi->use_svc &&
6147           cpi->svc.spatial_layer_id > 0) {
6148         source->flags &= ~(unsigned int)(VPX_EFLAG_FORCE_KF);
6149       }
6150
6151       // Check to see if the frame should be encoded as an arf overlay.
6152       check_src_altref(cpi, source);
6153     }
6154   }
6155
6156   if (source) {
6157     cpi->un_scaled_source = cpi->Source =
6158         force_src_buffer ? force_src_buffer : &source->img;
6159
6160 #ifdef ENABLE_KF_DENOISE
6161     // Copy of raw source for metrics calculation.
6162     if (is_psnr_calc_enabled(cpi))
6163       vp9_copy_and_extend_frame(cpi->Source, &cpi->raw_unscaled_source);
6164 #endif
6165
6166     cpi->unscaled_last_source = last_source != NULL ? &last_source->img : NULL;
6167
6168     *time_stamp = source->ts_start;
6169     *time_end = source->ts_end;
6170     *frame_flags = (source->flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
6171
6172   } else {
6173     *size = 0;
6174 #if !CONFIG_REALTIME_ONLY
6175     if (flush && oxcf->pass == 1 && !cpi->twopass.first_pass_done) {
6176       vp9_end_first_pass(cpi); /* get last stats packet */
6177       cpi->twopass.first_pass_done = 1;
6178     }
6179 #endif  // !CONFIG_REALTIME_ONLY
6180     return -1;
6181   }
6182
6183   if (source->ts_start < cpi->first_time_stamp_ever) {
6184     cpi->first_time_stamp_ever = source->ts_start;
6185     cpi->last_end_time_stamp_seen = source->ts_start;
6186   }
6187
6188   // Clear down mmx registers
6189   vpx_clear_system_state();
6190
6191   // adjust frame rates based on timestamps given
6192   if (cm->show_frame) {
6193     adjust_frame_rate(cpi, source);
6194   }
6195
6196   if (is_one_pass_cbr_svc(cpi)) {
6197     vp9_update_temporal_layer_framerate(cpi);
6198     vp9_restore_layer_context(cpi);
6199   }
6200
6201   // Find a free buffer for the new frame, releasing the reference previously
6202   // held.
6203   if (cm->new_fb_idx != INVALID_IDX) {
6204     --pool->frame_bufs[cm->new_fb_idx].ref_count;
6205   }
6206   cm->new_fb_idx = get_free_fb(cm);
6207
6208   if (cm->new_fb_idx == INVALID_IDX) return -1;
6209
6210   cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx];
6211
6212   if (!cpi->use_svc && cpi->multi_arf_allowed) {
6213     if (cm->frame_type == KEY_FRAME) {
6214       init_buffer_indices(cpi);
6215     } else if (oxcf->pass == 2) {
6216       const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
6217       cpi->alt_fb_idx = gf_group->arf_ref_idx[gf_group->index];
6218     }
6219   }
6220
6221   // Start with a 0 size frame.
6222   *size = 0;
6223
6224   cpi->frame_flags = *frame_flags;
6225
6226 #if !CONFIG_REALTIME_ONLY
6227   if ((oxcf->pass == 2) && !cpi->use_svc) {
6228     vp9_rc_get_second_pass_params(cpi);
6229   } else if (oxcf->pass == 1) {
6230     set_frame_size(cpi);
6231   }
6232 #endif  // !CONFIG_REALTIME_ONLY
6233
6234   if (oxcf->pass != 1 && cpi->level_constraint.level_index >= 0 &&
6235       cpi->level_constraint.fail_flag == 0)
6236     level_rc_framerate(cpi, arf_src_index);
6237
6238   if (cpi->oxcf.pass != 0 || cpi->use_svc || frame_is_intra_only(cm) == 1) {
6239     for (i = 0; i < MAX_REF_FRAMES; ++i) cpi->scaled_ref_idx[i] = INVALID_IDX;
6240   }
6241
6242   if (arf_src_index && cpi->sf.enable_tpl_model) {
6243     vp9_estimate_qp_gop(cpi);
6244     setup_tpl_stats(cpi);
6245   }
6246
6247   cpi->td.mb.fp_src_pred = 0;
6248 #if CONFIG_REALTIME_ONLY
6249   if (cpi->use_svc) {
6250     SvcEncode(cpi, size, dest, frame_flags);
6251   } else {
6252     // One pass encode
6253     Pass0Encode(cpi, size, dest, frame_flags);
6254   }
6255 #else  // !CONFIG_REALTIME_ONLY
6256   if (oxcf->pass == 1 && !cpi->use_svc) {
6257     const int lossless = is_lossless_requested(oxcf);
6258 #if CONFIG_VP9_HIGHBITDEPTH
6259     if (cpi->oxcf.use_highbitdepth)
6260       cpi->td.mb.fwd_txfm4x4 =
6261           lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
6262     else
6263       cpi->td.mb.fwd_txfm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
6264     cpi->td.mb.highbd_inv_txfm_add =
6265         lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
6266 #else
6267     cpi->td.mb.fwd_txfm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
6268 #endif  // CONFIG_VP9_HIGHBITDEPTH
6269     cpi->td.mb.inv_txfm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
6270     vp9_first_pass(cpi, source);
6271   } else if (oxcf->pass == 2 && !cpi->use_svc) {
6272     Pass2Encode(cpi, size, dest, frame_flags);
6273   } else if (cpi->use_svc) {
6274     SvcEncode(cpi, size, dest, frame_flags);
6275   } else {
6276     // One pass encode
6277     Pass0Encode(cpi, size, dest, frame_flags);
6278   }
6279 #endif  // CONFIG_REALTIME_ONLY
6280
6281   if (cm->refresh_frame_context)
6282     cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
6283
6284   // No frame encoded, or frame was dropped, release scaled references.
6285   if ((*size == 0) && (frame_is_intra_only(cm) == 0)) {
6286     release_scaled_references(cpi);
6287   }
6288
6289   if (*size > 0) {
6290     cpi->droppable = !frame_is_reference(cpi);
6291   }
6292
6293   // Save layer specific state.
6294   if (is_one_pass_cbr_svc(cpi) || ((cpi->svc.number_temporal_layers > 1 ||
6295                                     cpi->svc.number_spatial_layers > 1) &&
6296                                    oxcf->pass == 2)) {
6297     vp9_save_layer_context(cpi);
6298   }
6299
6300   vpx_usec_timer_mark(&cmptimer);
6301   cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
6302
6303   // Should we calculate metrics for the frame.
6304   if (is_psnr_calc_enabled(cpi)) generate_psnr_packet(cpi);
6305
6306   if (cpi->keep_level_stats && oxcf->pass != 1)
6307     update_level_info(cpi, size, arf_src_index);
6308
6309 #if CONFIG_INTERNAL_STATS
6310
6311   if (oxcf->pass != 1) {
6312     double samples = 0.0;
6313     cpi->bytes += (int)(*size);
6314
6315     if (cm->show_frame) {
6316       uint32_t bit_depth = 8;
6317       uint32_t in_bit_depth = 8;
6318       cpi->count++;
6319 #if CONFIG_VP9_HIGHBITDEPTH
6320       if (cm->use_highbitdepth) {
6321         in_bit_depth = cpi->oxcf.input_bit_depth;
6322         bit_depth = cm->bit_depth;
6323       }
6324 #endif
6325
6326       if (cpi->b_calculate_psnr) {
6327         YV12_BUFFER_CONFIG *orig = cpi->raw_source_frame;
6328         YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
6329         YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
6330         PSNR_STATS psnr;
6331 #if CONFIG_VP9_HIGHBITDEPTH
6332         vpx_calc_highbd_psnr(orig, recon, &psnr, cpi->td.mb.e_mbd.bd,
6333                              in_bit_depth);
6334 #else
6335         vpx_calc_psnr(orig, recon, &psnr);
6336 #endif  // CONFIG_VP9_HIGHBITDEPTH
6337
6338         adjust_image_stat(psnr.psnr[1], psnr.psnr[2], psnr.psnr[3],
6339                           psnr.psnr[0], &cpi->psnr);
6340         cpi->total_sq_error += psnr.sse[0];
6341         cpi->total_samples += psnr.samples[0];
6342         samples = psnr.samples[0];
6343
6344         {
6345           PSNR_STATS psnr2;
6346           double frame_ssim2 = 0, weight = 0;
6347 #if CONFIG_VP9_POSTPROC
6348           if (vpx_alloc_frame_buffer(
6349                   pp, recon->y_crop_width, recon->y_crop_height,
6350                   cm->subsampling_x, cm->subsampling_y,
6351 #if CONFIG_VP9_HIGHBITDEPTH
6352                   cm->use_highbitdepth,
6353 #endif
6354                   VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment) < 0) {
6355             vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
6356                                "Failed to allocate post processing buffer");
6357           }
6358           {
6359             vp9_ppflags_t ppflags;
6360             ppflags.post_proc_flag = VP9D_DEBLOCK;
6361             ppflags.deblocking_level = 0;  // not used in vp9_post_proc_frame()
6362             ppflags.noise_level = 0;       // not used in vp9_post_proc_frame()
6363             vp9_post_proc_frame(cm, pp, &ppflags);
6364           }
6365 #endif
6366           vpx_clear_system_state();
6367
6368 #if CONFIG_VP9_HIGHBITDEPTH
6369           vpx_calc_highbd_psnr(orig, pp, &psnr2, cpi->td.mb.e_mbd.bd,
6370                                cpi->oxcf.input_bit_depth);
6371 #else
6372           vpx_calc_psnr(orig, pp, &psnr2);
6373 #endif  // CONFIG_VP9_HIGHBITDEPTH
6374
6375           cpi->totalp_sq_error += psnr2.sse[0];
6376           cpi->totalp_samples += psnr2.samples[0];
6377           adjust_image_stat(psnr2.psnr[1], psnr2.psnr[2], psnr2.psnr[3],
6378                             psnr2.psnr[0], &cpi->psnrp);
6379
6380 #if CONFIG_VP9_HIGHBITDEPTH
6381           if (cm->use_highbitdepth) {
6382             frame_ssim2 = vpx_highbd_calc_ssim(orig, recon, &weight, bit_depth,
6383                                                in_bit_depth);
6384           } else {
6385             frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
6386           }
6387 #else
6388           frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
6389 #endif  // CONFIG_VP9_HIGHBITDEPTH
6390
6391           cpi->worst_ssim = VPXMIN(cpi->worst_ssim, frame_ssim2);
6392           cpi->summed_quality += frame_ssim2 * weight;
6393           cpi->summed_weights += weight;
6394
6395 #if CONFIG_VP9_HIGHBITDEPTH
6396           if (cm->use_highbitdepth) {
6397             frame_ssim2 = vpx_highbd_calc_ssim(orig, pp, &weight, bit_depth,
6398                                                in_bit_depth);
6399           } else {
6400             frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
6401           }
6402 #else
6403           frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
6404 #endif  // CONFIG_VP9_HIGHBITDEPTH
6405
6406           cpi->summedp_quality += frame_ssim2 * weight;
6407           cpi->summedp_weights += weight;
6408 #if 0
6409           {
6410             FILE *f = fopen("q_used.stt", "a");
6411             fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
6412                     cpi->common.current_video_frame, y2, u2, v2,
6413                     frame_psnr2, frame_ssim2);
6414             fclose(f);
6415           }
6416 #endif
6417         }
6418       }
6419       if (cpi->b_calculate_blockiness) {
6420 #if CONFIG_VP9_HIGHBITDEPTH
6421         if (!cm->use_highbitdepth)
6422 #endif
6423         {
6424           double frame_blockiness = vp9_get_blockiness(
6425               cpi->Source->y_buffer, cpi->Source->y_stride,
6426               cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
6427               cpi->Source->y_width, cpi->Source->y_height);
6428           cpi->worst_blockiness =
6429               VPXMAX(cpi->worst_blockiness, frame_blockiness);
6430           cpi->total_blockiness += frame_blockiness;
6431         }
6432       }
6433
6434       if (cpi->b_calculate_consistency) {
6435 #if CONFIG_VP9_HIGHBITDEPTH
6436         if (!cm->use_highbitdepth)
6437 #endif
6438         {
6439           double this_inconsistency = vpx_get_ssim_metrics(
6440               cpi->Source->y_buffer, cpi->Source->y_stride,
6441               cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
6442               cpi->Source->y_width, cpi->Source->y_height, cpi->ssim_vars,
6443               &cpi->metrics, 1);
6444
6445           const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
6446           double consistency =
6447               vpx_sse_to_psnr(samples, peak, (double)cpi->total_inconsistency);
6448           if (consistency > 0.0)
6449             cpi->worst_consistency =
6450                 VPXMIN(cpi->worst_consistency, consistency);
6451           cpi->total_inconsistency += this_inconsistency;
6452         }
6453       }
6454
6455       {
6456         double y, u, v, frame_all;
6457         frame_all = vpx_calc_fastssim(cpi->Source, cm->frame_to_show, &y, &u,
6458                                       &v, bit_depth, in_bit_depth);
6459         adjust_image_stat(y, u, v, frame_all, &cpi->fastssim);
6460       }
6461       {
6462         double y, u, v, frame_all;
6463         frame_all = vpx_psnrhvs(cpi->Source, cm->frame_to_show, &y, &u, &v,
6464                                 bit_depth, in_bit_depth);
6465         adjust_image_stat(y, u, v, frame_all, &cpi->psnrhvs);
6466       }
6467     }
6468   }
6469
6470 #endif
6471
6472   if (is_one_pass_cbr_svc(cpi)) {
6473     if (cm->show_frame) {
6474       ++cpi->svc.spatial_layer_to_encode;
6475       if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
6476         cpi->svc.spatial_layer_to_encode = 0;
6477     }
6478   }
6479
6480   vpx_clear_system_state();
6481   return 0;
6482 }
6483
6484 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
6485                               vp9_ppflags_t *flags) {
6486   VP9_COMMON *cm = &cpi->common;
6487 #if !CONFIG_VP9_POSTPROC
6488   (void)flags;
6489 #endif
6490
6491   if (!cm->show_frame) {
6492     return -1;
6493   } else {
6494     int ret;
6495 #if CONFIG_VP9_POSTPROC
6496     ret = vp9_post_proc_frame(cm, dest, flags);
6497 #else
6498     if (cm->frame_to_show) {
6499       *dest = *cm->frame_to_show;
6500       dest->y_width = cm->width;
6501       dest->y_height = cm->height;
6502       dest->uv_width = cm->width >> cm->subsampling_x;
6503       dest->uv_height = cm->height >> cm->subsampling_y;
6504       ret = 0;
6505     } else {
6506       ret = -1;
6507     }
6508 #endif  // !CONFIG_VP9_POSTPROC
6509     vpx_clear_system_state();
6510     return ret;
6511   }
6512 }
6513
6514 int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
6515                           VPX_SCALING vert_mode) {
6516   VP9_COMMON *cm = &cpi->common;
6517   int hr = 0, hs = 0, vr = 0, vs = 0;
6518
6519   if (horiz_mode > ONETWO || vert_mode > ONETWO) return -1;
6520
6521   Scale2Ratio(horiz_mode, &hr, &hs);
6522   Scale2Ratio(vert_mode, &vr, &vs);
6523
6524   // always go to the next whole number
6525   cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
6526   cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
6527   if (cm->current_video_frame) {
6528     assert(cm->width <= cpi->initial_width);
6529     assert(cm->height <= cpi->initial_height);
6530   }
6531
6532   update_frame_size(cpi);
6533
6534   return 0;
6535 }
6536
6537 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
6538                          unsigned int height) {
6539   VP9_COMMON *cm = &cpi->common;
6540 #if CONFIG_VP9_HIGHBITDEPTH
6541   check_initial_width(cpi, cm->use_highbitdepth, 1, 1);
6542 #else
6543   check_initial_width(cpi, 1, 1);
6544 #endif  // CONFIG_VP9_HIGHBITDEPTH
6545
6546 #if CONFIG_VP9_TEMPORAL_DENOISING
6547   setup_denoiser_buffer(cpi);
6548 #endif
6549
6550   if (width) {
6551     cm->width = width;
6552     if (cm->width > cpi->initial_width) {
6553       cm->width = cpi->initial_width;
6554       printf("Warning: Desired width too large, changed to %d\n", cm->width);
6555     }
6556   }
6557
6558   if (height) {
6559     cm->height = height;
6560     if (cm->height > cpi->initial_height) {
6561       cm->height = cpi->initial_height;
6562       printf("Warning: Desired height too large, changed to %d\n", cm->height);
6563     }
6564   }
6565   assert(cm->width <= cpi->initial_width);
6566   assert(cm->height <= cpi->initial_height);
6567
6568   update_frame_size(cpi);
6569
6570   return 0;
6571 }
6572
6573 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
6574   cpi->use_svc = use_svc;
6575   return;
6576 }
6577
6578 int vp9_get_quantizer(VP9_COMP *cpi) { return cpi->common.base_qindex; }
6579
6580 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags) {
6581   if (flags &
6582       (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF)) {
6583     int ref = 7;
6584
6585     if (flags & VP8_EFLAG_NO_REF_LAST) ref ^= VP9_LAST_FLAG;
6586
6587     if (flags & VP8_EFLAG_NO_REF_GF) ref ^= VP9_GOLD_FLAG;
6588
6589     if (flags & VP8_EFLAG_NO_REF_ARF) ref ^= VP9_ALT_FLAG;
6590
6591     vp9_use_as_reference(cpi, ref);
6592   }
6593
6594   if (flags &
6595       (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF |
6596        VP8_EFLAG_FORCE_GF | VP8_EFLAG_FORCE_ARF)) {
6597     int upd = 7;
6598
6599     if (flags & VP8_EFLAG_NO_UPD_LAST) upd ^= VP9_LAST_FLAG;
6600
6601     if (flags & VP8_EFLAG_NO_UPD_GF) upd ^= VP9_GOLD_FLAG;
6602
6603     if (flags & VP8_EFLAG_NO_UPD_ARF) upd ^= VP9_ALT_FLAG;
6604
6605     vp9_update_reference(cpi, upd);
6606   }
6607
6608   if (flags & VP8_EFLAG_NO_UPD_ENTROPY) {
6609     vp9_update_entropy(cpi, 0);
6610   }
6611 }
6612
6613 void vp9_set_row_mt(VP9_COMP *cpi) {
6614   // Enable row based multi-threading for supported modes of encoding
6615   cpi->row_mt = 0;
6616   if (((cpi->oxcf.mode == GOOD || cpi->oxcf.mode == BEST) &&
6617        cpi->oxcf.speed < 5 && cpi->oxcf.pass == 1) &&
6618       cpi->oxcf.row_mt && !cpi->use_svc)
6619     cpi->row_mt = 1;
6620
6621   if (cpi->oxcf.mode == GOOD && cpi->oxcf.speed < 5 &&
6622       (cpi->oxcf.pass == 0 || cpi->oxcf.pass == 2) && cpi->oxcf.row_mt &&
6623       !cpi->use_svc)
6624     cpi->row_mt = 1;
6625
6626   // In realtime mode, enable row based multi-threading for all the speed levels
6627   // where non-rd path is used.
6628   if (cpi->oxcf.mode == REALTIME && cpi->oxcf.speed >= 5 && cpi->oxcf.row_mt) {
6629     cpi->row_mt = 1;
6630   }
6631
6632   if (cpi->row_mt)
6633     cpi->row_mt_bit_exact = 1;
6634   else
6635     cpi->row_mt_bit_exact = 0;
6636 }