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