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