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