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