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