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