]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_onyx_if.c
0ac9d5f054d9c975632a2f6145b3c91de99ef082
[libvpx] / vp9 / encoder / vp9_onyx_if.c
1 /*
2  * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <math.h>
12 #include <stdio.h>
13 #include <limits.h>
14
15 #include "./vpx_config.h"
16 #include "./vpx_scale_rtcd.h"
17 #include "vpx/internal/vpx_psnr.h"
18 #include "vpx_ports/vpx_timer.h"
19
20 #include "vp9/common/vp9_alloccommon.h"
21 #include "vp9/common/vp9_filter.h"
22 #include "vp9/common/vp9_idct.h"
23 #if CONFIG_VP9_POSTPROC
24 #include "vp9/common/vp9_postproc.h"
25 #endif
26 #include "vp9/common/vp9_reconinter.h"
27 #include "vp9/common/vp9_systemdependent.h"
28 #include "vp9/common/vp9_tile_common.h"
29
30 #include "vp9/encoder/vp9_aq_complexity.h"
31 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
32 #include "vp9/encoder/vp9_aq_variance.h"
33 #include "vp9/encoder/vp9_bitstream.h"
34 #include "vp9/encoder/vp9_encodeframe.h"
35 #include "vp9/encoder/vp9_encodemv.h"
36 #include "vp9/encoder/vp9_firstpass.h"
37 #include "vp9/encoder/vp9_mbgraph.h"
38 #include "vp9/encoder/vp9_onyx_int.h"
39 #include "vp9/encoder/vp9_picklpf.h"
40 #include "vp9/encoder/vp9_ratectrl.h"
41 #include "vp9/encoder/vp9_rdopt.h"
42 #include "vp9/encoder/vp9_segmentation.h"
43 #include "vp9/encoder/vp9_speed_features.h"
44 #if CONFIG_INTERNAL_STATS
45 #include "vp9/encoder/vp9_ssim.h"
46 #endif
47 #include "vp9/encoder/vp9_temporal_filter.h"
48 #include "vp9/encoder/vp9_resize.h"
49 #include "vp9/encoder/vp9_svc_layercontext.h"
50
51 void vp9_coef_tree_initialize();
52
53 #define DEFAULT_INTERP_FILTER SWITCHABLE
54
55 #define SHARP_FILTER_QTHRESH 0          /* Q threshold for 8-tap sharp filter */
56
57 #define ALTREF_HIGH_PRECISION_MV 1      // Whether to use high precision mv
58                                          //  for altref computation.
59 #define HIGH_PRECISION_MV_QTHRESH 200   // Q threshold for high precision
60                                          // mv. Choose a very high value for
61                                          // now so that HIGH_PRECISION is always
62                                          // chosen.
63
64 // Max rate target for 1080P and below encodes under normal circumstances
65 // (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
66 #define MAX_MB_RATE 250
67 #define MAXRATE_1080P 2025000
68
69 // #define OUTPUT_YUV_REC
70
71 #ifdef OUTPUT_YUV_SRC
72 FILE *yuv_file;
73 #endif
74 #ifdef OUTPUT_YUV_REC
75 FILE *yuv_rec_file;
76 #endif
77
78 #if 0
79 FILE *framepsnr;
80 FILE *kf_list;
81 FILE *keyfile;
82 #endif
83
84 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
85   switch (mode) {
86     case NORMAL:
87       *hr = 1;
88       *hs = 1;
89       break;
90     case FOURFIVE:
91       *hr = 4;
92       *hs = 5;
93       break;
94     case THREEFIVE:
95       *hr = 3;
96       *hs = 5;
97     break;
98     case ONETWO:
99       *hr = 1;
100       *hs = 2;
101     break;
102     default:
103       *hr = 1;
104       *hs = 1;
105        assert(0);
106       break;
107   }
108 }
109
110 static void set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
111   MACROBLOCK *const mb = &cpi->mb;
112   cpi->common.allow_high_precision_mv = allow_high_precision_mv;
113   if (cpi->common.allow_high_precision_mv) {
114     mb->mvcost = mb->nmvcost_hp;
115     mb->mvsadcost = mb->nmvsadcost_hp;
116   } else {
117     mb->mvcost = mb->nmvcost;
118     mb->mvsadcost = mb->nmvsadcost;
119   }
120 }
121
122 static void setup_key_frame(VP9_COMP *cpi) {
123   vp9_setup_past_independence(&cpi->common);
124
125   // All buffers are implicitly updated on key frames.
126   cpi->refresh_golden_frame = 1;
127   cpi->refresh_alt_ref_frame = 1;
128 }
129
130 static void setup_inter_frame(VP9_COMMON *cm) {
131   if (cm->error_resilient_mode || cm->intra_only)
132     vp9_setup_past_independence(cm);
133
134   assert(cm->frame_context_idx < FRAME_CONTEXTS);
135   cm->fc = cm->frame_contexts[cm->frame_context_idx];
136 }
137
138 void vp9_initialize_enc() {
139   static int init_done = 0;
140
141   if (!init_done) {
142     vp9_init_neighbors();
143     vp9_init_quant_tables();
144
145     vp9_coef_tree_initialize();
146     vp9_tokenize_initialize();
147     vp9_init_me_luts();
148     vp9_rc_init_minq_luts();
149     vp9_entropy_mv_init();
150     vp9_entropy_mode_init();
151     init_done = 1;
152   }
153 }
154
155 static void dealloc_compressor_data(VP9_COMP *cpi) {
156   VP9_COMMON *const cm = &cpi->common;
157   int i;
158
159   // Delete sementation map
160   vpx_free(cpi->segmentation_map);
161   cpi->segmentation_map = NULL;
162   vpx_free(cm->last_frame_seg_map);
163   cm->last_frame_seg_map = NULL;
164   vpx_free(cpi->coding_context.last_frame_seg_map_copy);
165   cpi->coding_context.last_frame_seg_map_copy = NULL;
166
167   vpx_free(cpi->complexity_map);
168   cpi->complexity_map = NULL;
169
170   vp9_cyclic_refresh_free(cpi->cyclic_refresh);
171   cpi->cyclic_refresh = NULL;
172
173   vpx_free(cpi->active_map);
174   cpi->active_map = NULL;
175
176   vp9_free_frame_buffers(cm);
177
178   vp9_free_frame_buffer(&cpi->last_frame_uf);
179   vp9_free_frame_buffer(&cpi->scaled_source);
180   vp9_free_frame_buffer(&cpi->scaled_last_source);
181   vp9_free_frame_buffer(&cpi->alt_ref_buffer);
182   vp9_lookahead_destroy(cpi->lookahead);
183
184   vpx_free(cpi->tok);
185   cpi->tok = 0;
186
187   // Activity mask based per mb zbin adjustments
188   vpx_free(cpi->mb_activity_map);
189   cpi->mb_activity_map = 0;
190   vpx_free(cpi->mb_norm_activity_map);
191   cpi->mb_norm_activity_map = 0;
192
193   for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
194     LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
195     vpx_free(lc->rc_twopass_stats_in.buf);
196     lc->rc_twopass_stats_in.buf = NULL;
197     lc->rc_twopass_stats_in.sz = 0;
198   }
199 }
200
201 static void save_coding_context(VP9_COMP *cpi) {
202   CODING_CONTEXT *const cc = &cpi->coding_context;
203   VP9_COMMON *cm = &cpi->common;
204
205   // Stores a snapshot of key state variables which can subsequently be
206   // restored with a call to vp9_restore_coding_context. These functions are
207   // intended for use in a re-code loop in vp9_compress_frame where the
208   // quantizer value is adjusted between loop iterations.
209   vp9_copy(cc->nmvjointcost,  cpi->mb.nmvjointcost);
210   vp9_copy(cc->nmvcosts,  cpi->mb.nmvcosts);
211   vp9_copy(cc->nmvcosts_hp,  cpi->mb.nmvcosts_hp);
212
213   vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
214
215   vpx_memcpy(cpi->coding_context.last_frame_seg_map_copy,
216              cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
217
218   vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
219   vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
220
221   cc->fc = cm->fc;
222 }
223
224 static void restore_coding_context(VP9_COMP *cpi) {
225   CODING_CONTEXT *const cc = &cpi->coding_context;
226   VP9_COMMON *cm = &cpi->common;
227
228   // Restore key state variables to the snapshot state stored in the
229   // previous call to vp9_save_coding_context.
230   vp9_copy(cpi->mb.nmvjointcost, cc->nmvjointcost);
231   vp9_copy(cpi->mb.nmvcosts, cc->nmvcosts);
232   vp9_copy(cpi->mb.nmvcosts_hp, cc->nmvcosts_hp);
233
234   vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
235
236   vpx_memcpy(cm->last_frame_seg_map,
237              cpi->coding_context.last_frame_seg_map_copy,
238              (cm->mi_rows * cm->mi_cols));
239
240   vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
241   vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
242
243   cm->fc = cc->fc;
244 }
245
246 static void configure_static_seg_features(VP9_COMP *cpi) {
247   VP9_COMMON *const cm = &cpi->common;
248   const RATE_CONTROL *const rc = &cpi->rc;
249   struct segmentation *const seg = &cm->seg;
250
251   int high_q = (int)(rc->avg_q > 48.0);
252   int qi_delta;
253
254   // Disable and clear down for KF
255   if (cm->frame_type == KEY_FRAME) {
256     // Clear down the global segmentation map
257     vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
258     seg->update_map = 0;
259     seg->update_data = 0;
260     cpi->static_mb_pct = 0;
261
262     // Disable segmentation
263     vp9_disable_segmentation(seg);
264
265     // Clear down the segment features.
266     vp9_clearall_segfeatures(seg);
267   } else if (cpi->refresh_alt_ref_frame) {
268     // If this is an alt ref frame
269     // Clear down the global segmentation map
270     vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
271     seg->update_map = 0;
272     seg->update_data = 0;
273     cpi->static_mb_pct = 0;
274
275     // Disable segmentation and individual segment features by default
276     vp9_disable_segmentation(seg);
277     vp9_clearall_segfeatures(seg);
278
279     // Scan frames from current to arf frame.
280     // This function re-enables segmentation if appropriate.
281     vp9_update_mbgraph_stats(cpi);
282
283     // If segmentation was enabled set those features needed for the
284     // arf itself.
285     if (seg->enabled) {
286       seg->update_map = 1;
287       seg->update_data = 1;
288
289       qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875);
290       vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
291       vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
292
293       vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
294       vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
295
296       // Where relevant assume segment data is delta data
297       seg->abs_delta = SEGMENT_DELTADATA;
298     }
299   } else if (seg->enabled) {
300     // All other frames if segmentation has been enabled
301
302     // First normal frame in a valid gf or alt ref group
303     if (rc->frames_since_golden == 0) {
304       // Set up segment features for normal frames in an arf group
305       if (rc->source_alt_ref_active) {
306         seg->update_map = 0;
307         seg->update_data = 1;
308         seg->abs_delta = SEGMENT_DELTADATA;
309
310         qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125);
311         vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
312         vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
313
314         vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
315         vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
316
317         // Segment coding disabled for compred testing
318         if (high_q || (cpi->static_mb_pct == 100)) {
319           vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
320           vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
321           vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
322         }
323       } else {
324         // Disable segmentation and clear down features if alt ref
325         // is not active for this group
326
327         vp9_disable_segmentation(seg);
328
329         vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
330
331         seg->update_map = 0;
332         seg->update_data = 0;
333
334         vp9_clearall_segfeatures(seg);
335       }
336     } else if (rc->is_src_frame_alt_ref) {
337       // Special case where we are coding over the top of a previous
338       // alt ref frame.
339       // Segment coding disabled for compred testing
340
341       // Enable ref frame features for segment 0 as well
342       vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
343       vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
344
345       // All mbs should use ALTREF_FRAME
346       vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
347       vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
348       vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
349       vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
350
351       // Skip all MBs if high Q (0,0 mv and skip coeffs)
352       if (high_q) {
353         vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
354         vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
355       }
356       // Enable data update
357       seg->update_data = 1;
358     } else {
359       // All other frames.
360
361       // No updates.. leave things as they are.
362       seg->update_map = 0;
363       seg->update_data = 0;
364     }
365   }
366 }
367
368 static void update_reference_segmentation_map(VP9_COMP *cpi) {
369   VP9_COMMON *const cm = &cpi->common;
370   MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
371   uint8_t *cache_ptr = cm->last_frame_seg_map;
372   int row, col;
373
374   for (row = 0; row < cm->mi_rows; row++) {
375     MODE_INFO **mi_8x8 = mi_8x8_ptr;
376     uint8_t *cache = cache_ptr;
377     for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
378       cache[0] = mi_8x8[0]->mbmi.segment_id;
379     mi_8x8_ptr += cm->mi_stride;
380     cache_ptr += cm->mi_cols;
381   }
382 }
383 static int is_slowest_mode(int mode) {
384   return (mode == MODE_SECONDPASS_BEST || mode == MODE_BESTQUALITY);
385 }
386
387 static void set_rd_speed_thresholds(VP9_COMP *cpi) {
388   int i;
389
390   // Set baseline threshold values
391   for (i = 0; i < MAX_MODES; ++i)
392   cpi->rd_thresh_mult[i] = is_slowest_mode(cpi->oxcf.mode) ? -500 : 0;
393
394   cpi->rd_thresh_mult[THR_NEARESTMV] = 0;
395   cpi->rd_thresh_mult[THR_NEARESTG] = 0;
396   cpi->rd_thresh_mult[THR_NEARESTA] = 0;
397
398   cpi->rd_thresh_mult[THR_DC] += 1000;
399
400   cpi->rd_thresh_mult[THR_NEWMV] += 1000;
401   cpi->rd_thresh_mult[THR_NEWA] += 1000;
402   cpi->rd_thresh_mult[THR_NEWG] += 1000;
403
404   cpi->rd_thresh_mult[THR_NEARMV] += 1000;
405   cpi->rd_thresh_mult[THR_NEARA] += 1000;
406   cpi->rd_thresh_mult[THR_COMP_NEARESTLA] += 1000;
407   cpi->rd_thresh_mult[THR_COMP_NEARESTGA] += 1000;
408
409   cpi->rd_thresh_mult[THR_TM] += 1000;
410
411   cpi->rd_thresh_mult[THR_COMP_NEARLA] += 1500;
412   cpi->rd_thresh_mult[THR_COMP_NEWLA] += 2000;
413   cpi->rd_thresh_mult[THR_NEARG] += 1000;
414   cpi->rd_thresh_mult[THR_COMP_NEARGA] += 1500;
415   cpi->rd_thresh_mult[THR_COMP_NEWGA] += 2000;
416
417   cpi->rd_thresh_mult[THR_ZEROMV] += 2000;
418   cpi->rd_thresh_mult[THR_ZEROG] += 2000;
419   cpi->rd_thresh_mult[THR_ZEROA] += 2000;
420   cpi->rd_thresh_mult[THR_COMP_ZEROLA] += 2500;
421   cpi->rd_thresh_mult[THR_COMP_ZEROGA] += 2500;
422
423   cpi->rd_thresh_mult[THR_H_PRED] += 2000;
424   cpi->rd_thresh_mult[THR_V_PRED] += 2000;
425   cpi->rd_thresh_mult[THR_D45_PRED ] += 2500;
426   cpi->rd_thresh_mult[THR_D135_PRED] += 2500;
427   cpi->rd_thresh_mult[THR_D117_PRED] += 2500;
428   cpi->rd_thresh_mult[THR_D153_PRED] += 2500;
429   cpi->rd_thresh_mult[THR_D207_PRED] += 2500;
430   cpi->rd_thresh_mult[THR_D63_PRED] += 2500;
431
432   /* disable frame modes if flags not set */
433   if (!(cpi->ref_frame_flags & VP9_LAST_FLAG)) {
434     cpi->rd_thresh_mult[THR_NEWMV    ] = INT_MAX;
435     cpi->rd_thresh_mult[THR_NEARESTMV] = INT_MAX;
436     cpi->rd_thresh_mult[THR_ZEROMV   ] = INT_MAX;
437     cpi->rd_thresh_mult[THR_NEARMV   ] = INT_MAX;
438   }
439   if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
440     cpi->rd_thresh_mult[THR_NEARESTG ] = INT_MAX;
441     cpi->rd_thresh_mult[THR_ZEROG    ] = INT_MAX;
442     cpi->rd_thresh_mult[THR_NEARG    ] = INT_MAX;
443     cpi->rd_thresh_mult[THR_NEWG     ] = INT_MAX;
444   }
445   if (!(cpi->ref_frame_flags & VP9_ALT_FLAG)) {
446     cpi->rd_thresh_mult[THR_NEARESTA ] = INT_MAX;
447     cpi->rd_thresh_mult[THR_ZEROA    ] = INT_MAX;
448     cpi->rd_thresh_mult[THR_NEARA    ] = INT_MAX;
449     cpi->rd_thresh_mult[THR_NEWA     ] = INT_MAX;
450   }
451
452   if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
453       (VP9_LAST_FLAG | VP9_ALT_FLAG)) {
454     cpi->rd_thresh_mult[THR_COMP_ZEROLA   ] = INT_MAX;
455     cpi->rd_thresh_mult[THR_COMP_NEARESTLA] = INT_MAX;
456     cpi->rd_thresh_mult[THR_COMP_NEARLA   ] = INT_MAX;
457     cpi->rd_thresh_mult[THR_COMP_NEWLA    ] = INT_MAX;
458   }
459   if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
460       (VP9_GOLD_FLAG | VP9_ALT_FLAG)) {
461     cpi->rd_thresh_mult[THR_COMP_ZEROGA   ] = INT_MAX;
462     cpi->rd_thresh_mult[THR_COMP_NEARESTGA] = INT_MAX;
463     cpi->rd_thresh_mult[THR_COMP_NEARGA   ] = INT_MAX;
464     cpi->rd_thresh_mult[THR_COMP_NEWGA    ] = INT_MAX;
465   }
466 }
467
468 static void set_rd_speed_thresholds_sub8x8(VP9_COMP *cpi) {
469   const SPEED_FEATURES *const sf = &cpi->sf;
470   int i;
471
472   for (i = 0; i < MAX_REFS; ++i)
473     cpi->rd_thresh_mult_sub8x8[i] = is_slowest_mode(cpi->oxcf.mode)  ? -500 : 0;
474
475   cpi->rd_thresh_mult_sub8x8[THR_LAST] += 2500;
476   cpi->rd_thresh_mult_sub8x8[THR_GOLD] += 2500;
477   cpi->rd_thresh_mult_sub8x8[THR_ALTR] += 2500;
478   cpi->rd_thresh_mult_sub8x8[THR_INTRA] += 2500;
479   cpi->rd_thresh_mult_sub8x8[THR_COMP_LA] += 4500;
480   cpi->rd_thresh_mult_sub8x8[THR_COMP_GA] += 4500;
481
482   // Check for masked out split cases.
483   for (i = 0; i < MAX_REFS; i++)
484     if (sf->disable_split_mask & (1 << i))
485       cpi->rd_thresh_mult_sub8x8[i] = INT_MAX;
486
487   // disable mode test if frame flag is not set
488   if (!(cpi->ref_frame_flags & VP9_LAST_FLAG))
489     cpi->rd_thresh_mult_sub8x8[THR_LAST] = INT_MAX;
490   if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG))
491     cpi->rd_thresh_mult_sub8x8[THR_GOLD] = INT_MAX;
492   if (!(cpi->ref_frame_flags & VP9_ALT_FLAG))
493     cpi->rd_thresh_mult_sub8x8[THR_ALTR] = INT_MAX;
494   if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
495       (VP9_LAST_FLAG | VP9_ALT_FLAG))
496     cpi->rd_thresh_mult_sub8x8[THR_COMP_LA] = INT_MAX;
497   if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
498       (VP9_GOLD_FLAG | VP9_ALT_FLAG))
499     cpi->rd_thresh_mult_sub8x8[THR_COMP_GA] = INT_MAX;
500 }
501
502 static void set_speed_features(VP9_COMP *cpi) {
503 #if CONFIG_INTERNAL_STATS
504   int i;
505   for (i = 0; i < MAX_MODES; ++i)
506     cpi->mode_chosen_counts[i] = 0;
507 #endif
508
509   vp9_set_speed_features(cpi);
510
511   // Set rd thresholds based on mode and speed setting
512   set_rd_speed_thresholds(cpi);
513   set_rd_speed_thresholds_sub8x8(cpi);
514
515   cpi->mb.fwd_txm4x4 = vp9_fdct4x4;
516   if (cpi->oxcf.lossless || cpi->mb.e_mbd.lossless) {
517     cpi->mb.fwd_txm4x4 = vp9_fwht4x4;
518   }
519 }
520
521 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
522   VP9_COMMON *cm = &cpi->common;
523   const VP9_CONFIG *oxcf = &cpi->oxcf;
524
525   cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
526                                       cm->subsampling_x, cm->subsampling_y,
527                                       oxcf->lag_in_frames);
528   if (!cpi->lookahead)
529     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
530                        "Failed to allocate lag buffers");
531
532   if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
533                                oxcf->width, oxcf->height,
534                                cm->subsampling_x, cm->subsampling_y,
535                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
536     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
537                        "Failed to allocate altref buffer");
538 }
539
540 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
541   VP9_COMMON *cm = &cpi->common;
542
543   if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
544     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
545                        "Failed to allocate frame buffers");
546
547   if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
548                              cm->width, cm->height,
549                              cm->subsampling_x, cm->subsampling_y,
550                              VP9_ENC_BORDER_IN_PIXELS))
551     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
552                        "Failed to allocate last frame buffer");
553
554   if (vp9_alloc_frame_buffer(&cpi->scaled_source,
555                              cm->width, cm->height,
556                              cm->subsampling_x, cm->subsampling_y,
557                              VP9_ENC_BORDER_IN_PIXELS))
558     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
559                        "Failed to allocate scaled source buffer");
560
561   if (vp9_alloc_frame_buffer(&cpi->scaled_last_source,
562                              cm->width, cm->height,
563                              cm->subsampling_x, cm->subsampling_y,
564                              VP9_ENC_BORDER_IN_PIXELS))
565     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
566                        "Failed to allocate scaled last source buffer");
567
568   vpx_free(cpi->tok);
569
570   {
571     unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
572
573     CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
574   }
575
576   vpx_free(cpi->mb_activity_map);
577   CHECK_MEM_ERROR(cm, cpi->mb_activity_map,
578                   vpx_calloc(sizeof(unsigned int),
579                              cm->mb_rows * cm->mb_cols));
580
581   vpx_free(cpi->mb_norm_activity_map);
582   CHECK_MEM_ERROR(cm, cpi->mb_norm_activity_map,
583                   vpx_calloc(sizeof(unsigned int),
584                              cm->mb_rows * cm->mb_cols));
585 }
586
587
588 static void update_frame_size(VP9_COMP *cpi) {
589   VP9_COMMON *const cm = &cpi->common;
590   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
591
592   vp9_update_frame_size(cm);
593
594   // Update size of buffers local to this frame
595   if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
596                                cm->width, cm->height,
597                                cm->subsampling_x, cm->subsampling_y,
598                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
599     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
600                        "Failed to reallocate last frame buffer");
601
602   if (vp9_realloc_frame_buffer(&cpi->scaled_source,
603                                cm->width, cm->height,
604                                cm->subsampling_x, cm->subsampling_y,
605                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
606     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
607                        "Failed to reallocate scaled source buffer");
608
609   if (vp9_realloc_frame_buffer(&cpi->scaled_last_source,
610                                cm->width, cm->height,
611                                cm->subsampling_x, cm->subsampling_y,
612                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
613     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
614                        "Failed to reallocate scaled last source buffer");
615
616   {
617     int y_stride = cpi->scaled_source.y_stride;
618
619     if (cpi->sf.search_method == NSTEP) {
620       vp9_init3smotion_compensation(&cpi->mb, y_stride);
621     } else if (cpi->sf.search_method == DIAMOND) {
622       vp9_init_dsmotion_compensation(&cpi->mb, y_stride);
623     }
624   }
625
626   init_macroblockd(cm, xd);
627 }
628
629 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
630   VP9_COMMON *const cm = &cpi->common;
631   RATE_CONTROL *const rc = &cpi->rc;
632   VP9_CONFIG *const oxcf = &cpi->oxcf;
633   int vbr_max_bits;
634
635   oxcf->framerate = framerate < 0.1 ? 30 : framerate;
636   cpi->output_framerate = cpi->oxcf.framerate;
637   rc->av_per_frame_bandwidth = (int)(oxcf->target_bandwidth /
638                                      cpi->output_framerate);
639   rc->min_frame_bandwidth = (int)(rc->av_per_frame_bandwidth *
640                                   oxcf->two_pass_vbrmin_section / 100);
641
642   rc->min_frame_bandwidth = MAX(rc->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
643
644   // A maximum bitrate for a frame is defined.
645   // The baseline for this aligns with HW implementations that
646   // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
647   // per 16x16 MB (averaged over a frame). However this limit is extended if
648   // a very high rate is given on the command line or the the rate cannnot
649   // be acheived because of a user specificed max q (e.g. when the user
650   // specifies lossless encode.
651   //
652   vbr_max_bits = (int)(((int64_t)rc->av_per_frame_bandwidth *
653       oxcf->two_pass_vbrmax_section) / 100);
654   rc->max_frame_bandwidth = MAX(MAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P),
655                                 vbr_max_bits);
656
657   // Set Maximum gf/arf interval
658   rc->max_gf_interval = 16;
659
660   // Extended interval for genuinely static scenes
661   rc->static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
662
663   // Special conditions when alt ref frame enabled in lagged compress mode
664   if (oxcf->play_alternate && oxcf->lag_in_frames) {
665     if (rc->max_gf_interval > oxcf->lag_in_frames - 1)
666       rc->max_gf_interval = oxcf->lag_in_frames - 1;
667
668     if (rc->static_scene_max_gf_interval > oxcf->lag_in_frames - 1)
669       rc->static_scene_max_gf_interval = oxcf->lag_in_frames - 1;
670   }
671
672   if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
673     rc->max_gf_interval = rc->static_scene_max_gf_interval;
674 }
675
676 int64_t vp9_rescale(int64_t val, int64_t num, int denom) {
677   int64_t llnum = num;
678   int64_t llden = denom;
679   int64_t llval = val;
680
681   return (llval * llnum / llden);
682 }
683
684 static void set_tile_limits(VP9_COMP *cpi) {
685   VP9_COMMON *const cm = &cpi->common;
686
687   int min_log2_tile_cols, max_log2_tile_cols;
688   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
689
690   cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
691                              min_log2_tile_cols, max_log2_tile_cols);
692   cm->log2_tile_rows = cpi->oxcf.tile_rows;
693 }
694
695 static void init_config(struct VP9_COMP *cpi, VP9_CONFIG *oxcf) {
696   VP9_COMMON *const cm = &cpi->common;
697   int i;
698
699   cpi->oxcf = *oxcf;
700
701   cm->profile = oxcf->profile;
702   cm->bit_depth = oxcf->bit_depth;
703
704   cm->width = oxcf->width;
705   cm->height = oxcf->height;
706   cm->subsampling_x = 0;
707   cm->subsampling_y = 0;
708   vp9_alloc_compressor_data(cpi);
709
710   // Spatial scalability.
711   cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
712   // Temporal scalability.
713   cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
714
715   if ((cpi->svc.number_temporal_layers > 1 &&
716       cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) ||
717       (cpi->svc.number_spatial_layers > 1 &&
718       cpi->oxcf.mode == MODE_SECONDPASS_BEST)) {
719     vp9_init_layer_context(cpi);
720   }
721
722   // change includes all joint functionality
723   vp9_change_config(cpi, oxcf);
724
725   cpi->static_mb_pct = 0;
726
727   cpi->lst_fb_idx = 0;
728   cpi->gld_fb_idx = 1;
729   cpi->alt_fb_idx = 2;
730
731   set_tile_limits(cpi);
732
733   cpi->fixed_divide[0] = 0;
734   for (i = 1; i < 512; i++)
735     cpi->fixed_divide[i] = 0x80000 / i;
736 }
737
738 void vp9_change_config(struct VP9_COMP *cpi, const VP9_CONFIG *oxcf) {
739   VP9_COMMON *const cm = &cpi->common;
740   RATE_CONTROL *const rc = &cpi->rc;
741
742   if (cm->profile != oxcf->profile)
743     cm->profile = oxcf->profile;
744   cm->bit_depth = oxcf->bit_depth;
745
746   if (cm->profile <= PROFILE_1)
747     assert(cm->bit_depth == BITS_8);
748   else
749     assert(cm->bit_depth > BITS_8);
750
751   cpi->oxcf = *oxcf;
752
753   if (cpi->oxcf.cpu_used == -6)
754     cpi->oxcf.play_alternate = 0;
755
756   switch (cpi->oxcf.mode) {
757       // Real time and one pass deprecated in test code base
758     case MODE_GOODQUALITY:
759       cpi->pass = 0;
760       cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
761       break;
762
763     case MODE_BESTQUALITY:
764       cpi->pass = 0;
765       break;
766
767     case MODE_FIRSTPASS:
768       cpi->pass = 1;
769       break;
770
771     case MODE_SECONDPASS:
772       cpi->pass = 2;
773       cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
774       break;
775
776     case MODE_SECONDPASS_BEST:
777       cpi->pass = 2;
778       break;
779
780     case MODE_REALTIME:
781       cpi->pass = 0;
782       break;
783   }
784
785   cpi->oxcf.lossless = oxcf->lossless;
786   if (cpi->oxcf.lossless) {
787     // In lossless mode, make sure right quantizer range and correct transform
788     // is set.
789     cpi->oxcf.worst_allowed_q = 0;
790     cpi->oxcf.best_allowed_q = 0;
791     cpi->mb.e_mbd.itxm_add = vp9_iwht4x4_add;
792   } else {
793     cpi->mb.e_mbd.itxm_add = vp9_idct4x4_add;
794   }
795   rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
796   cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
797
798   cpi->refresh_golden_frame = 0;
799   cpi->refresh_last_frame = 1;
800   cm->refresh_frame_context = 1;
801   cm->reset_frame_context = 0;
802
803   vp9_reset_segment_features(&cm->seg);
804   set_high_precision_mv(cpi, 0);
805
806   {
807     int i;
808
809     for (i = 0; i < MAX_SEGMENTS; i++)
810       cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
811   }
812   cpi->encode_breakout = cpi->oxcf.encode_breakout;
813
814   // local file playback mode == really big buffer
815   if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
816     cpi->oxcf.starting_buffer_level   = 60000;
817     cpi->oxcf.optimal_buffer_level    = 60000;
818     cpi->oxcf.maximum_buffer_size     = 240000;
819   }
820
821   // Convert target bandwidth from Kbit/s to Bit/s
822   cpi->oxcf.target_bandwidth       *= 1000;
823
824   cpi->oxcf.starting_buffer_level =
825       vp9_rescale(cpi->oxcf.starting_buffer_level,
826                   cpi->oxcf.target_bandwidth, 1000);
827
828   // Set or reset optimal and maximum buffer levels.
829   if (cpi->oxcf.optimal_buffer_level == 0)
830     cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
831   else
832     cpi->oxcf.optimal_buffer_level =
833         vp9_rescale(cpi->oxcf.optimal_buffer_level,
834                     cpi->oxcf.target_bandwidth, 1000);
835
836   if (cpi->oxcf.maximum_buffer_size == 0)
837     cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
838   else
839     cpi->oxcf.maximum_buffer_size =
840         vp9_rescale(cpi->oxcf.maximum_buffer_size,
841                     cpi->oxcf.target_bandwidth, 1000);
842   // Under a configuration change, where maximum_buffer_size may change,
843   // keep buffer level clipped to the maximum allowed buffer size.
844   rc->bits_off_target = MIN(rc->bits_off_target, cpi->oxcf.maximum_buffer_size);
845   rc->buffer_level = MIN(rc->buffer_level, cpi->oxcf.maximum_buffer_size);
846
847   // Set up frame rate and related parameters rate control values.
848   vp9_new_framerate(cpi, cpi->oxcf.framerate);
849
850   // Set absolute upper and lower quality limits
851   rc->worst_quality = cpi->oxcf.worst_allowed_q;
852   rc->best_quality = cpi->oxcf.best_allowed_q;
853
854   // active values should only be modified if out of new range
855
856   cpi->cq_target_quality = cpi->oxcf.cq_level;
857
858   cm->interp_filter = DEFAULT_INTERP_FILTER;
859
860   cm->display_width = cpi->oxcf.width;
861   cm->display_height = cpi->oxcf.height;
862
863   // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
864   cpi->oxcf.sharpness = MIN(7, cpi->oxcf.sharpness);
865
866   cpi->common.lf.sharpness_level = cpi->oxcf.sharpness;
867
868   if (cpi->initial_width) {
869     // Increasing the size of the frame beyond the first seen frame, or some
870     // otherwise signaled maximum size, is not supported.
871     // TODO(jkoleszar): exit gracefully.
872     assert(cm->width <= cpi->initial_width);
873     assert(cm->height <= cpi->initial_height);
874   }
875   update_frame_size(cpi);
876
877   if ((cpi->svc.number_temporal_layers > 1 &&
878       cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) ||
879       (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2)) {
880     vp9_update_layer_context_change_config(cpi,
881                                            (int)cpi->oxcf.target_bandwidth);
882   }
883
884   cpi->speed = abs(cpi->oxcf.cpu_used);
885
886   // Limit on lag buffers as these are not currently dynamically allocated.
887   if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS)
888     cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
889
890 #if CONFIG_MULTIPLE_ARF
891   vp9_zero(cpi->alt_ref_source);
892 #else
893   cpi->alt_ref_source = NULL;
894 #endif
895   rc->is_src_frame_alt_ref = 0;
896
897 #if 0
898   // Experimental RD Code
899   cpi->frame_distortion = 0;
900   cpi->last_frame_distortion = 0;
901 #endif
902
903   set_tile_limits(cpi);
904
905   cpi->ext_refresh_frame_flags_pending = 0;
906   cpi->ext_refresh_frame_context_pending = 0;
907 }
908
909 #define M_LOG2_E 0.693147180559945309417
910 #define log2f(x) (log (x) / (float) M_LOG2_E)
911
912 static void cal_nmvjointsadcost(int *mvjointsadcost) {
913   mvjointsadcost[0] = 600;
914   mvjointsadcost[1] = 300;
915   mvjointsadcost[2] = 300;
916   mvjointsadcost[3] = 300;
917 }
918
919 static void cal_nmvsadcosts(int *mvsadcost[2]) {
920   int i = 1;
921
922   mvsadcost[0][0] = 0;
923   mvsadcost[1][0] = 0;
924
925   do {
926     double z = 256 * (2 * (log2f(8 * i) + .6));
927     mvsadcost[0][i] = (int)z;
928     mvsadcost[1][i] = (int)z;
929     mvsadcost[0][-i] = (int)z;
930     mvsadcost[1][-i] = (int)z;
931   } while (++i <= MV_MAX);
932 }
933
934 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
935   int i = 1;
936
937   mvsadcost[0][0] = 0;
938   mvsadcost[1][0] = 0;
939
940   do {
941     double z = 256 * (2 * (log2f(8 * i) + .6));
942     mvsadcost[0][i] = (int)z;
943     mvsadcost[1][i] = (int)z;
944     mvsadcost[0][-i] = (int)z;
945     mvsadcost[1][-i] = (int)z;
946   } while (++i <= MV_MAX);
947 }
948
949 static void alloc_mode_context(VP9_COMMON *cm, int num_4x4_blk,
950                                PICK_MODE_CONTEXT *ctx) {
951   int num_pix = num_4x4_blk << 4;
952   int i, k;
953   ctx->num_4x4_blk = num_4x4_blk;
954
955   CHECK_MEM_ERROR(cm, ctx->zcoeff_blk,
956                   vpx_calloc(num_4x4_blk, sizeof(uint8_t)));
957   for (i = 0; i < MAX_MB_PLANE; ++i) {
958     for (k = 0; k < 3; ++k) {
959       CHECK_MEM_ERROR(cm, ctx->coeff[i][k],
960                       vpx_memalign(16, num_pix * sizeof(int16_t)));
961       CHECK_MEM_ERROR(cm, ctx->qcoeff[i][k],
962                       vpx_memalign(16, num_pix * sizeof(int16_t)));
963       CHECK_MEM_ERROR(cm, ctx->dqcoeff[i][k],
964                       vpx_memalign(16, num_pix * sizeof(int16_t)));
965       CHECK_MEM_ERROR(cm, ctx->eobs[i][k],
966                       vpx_memalign(16, num_pix * sizeof(uint16_t)));
967       ctx->coeff_pbuf[i][k]   = ctx->coeff[i][k];
968       ctx->qcoeff_pbuf[i][k]  = ctx->qcoeff[i][k];
969       ctx->dqcoeff_pbuf[i][k] = ctx->dqcoeff[i][k];
970       ctx->eobs_pbuf[i][k]    = ctx->eobs[i][k];
971     }
972   }
973 }
974
975 static void free_mode_context(PICK_MODE_CONTEXT *ctx) {
976   int i, k;
977   vpx_free(ctx->zcoeff_blk);
978   ctx->zcoeff_blk = 0;
979   for (i = 0; i < MAX_MB_PLANE; ++i) {
980     for (k = 0; k < 3; ++k) {
981       vpx_free(ctx->coeff[i][k]);
982       ctx->coeff[i][k] = 0;
983       vpx_free(ctx->qcoeff[i][k]);
984       ctx->qcoeff[i][k] = 0;
985       vpx_free(ctx->dqcoeff[i][k]);
986       ctx->dqcoeff[i][k] = 0;
987       vpx_free(ctx->eobs[i][k]);
988       ctx->eobs[i][k] = 0;
989     }
990   }
991 }
992
993 static void init_pick_mode_context(VP9_COMP *cpi) {
994   int i;
995   VP9_COMMON *const cm = &cpi->common;
996   MACROBLOCK *const x  = &cpi->mb;
997
998   for (i = 0; i < BLOCK_SIZES; ++i) {
999     const int num_4x4_w = num_4x4_blocks_wide_lookup[i];
1000     const int num_4x4_h = num_4x4_blocks_high_lookup[i];
1001     const int num_4x4_blk = MAX(4, num_4x4_w * num_4x4_h);
1002     if (i < BLOCK_16X16) {
1003       for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1004         for (x->mb_index = 0; x->mb_index < 4; ++x->mb_index) {
1005           for (x->b_index = 0; x->b_index < 16 / num_4x4_blk; ++x->b_index) {
1006             PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1007             alloc_mode_context(cm, num_4x4_blk, ctx);
1008           }
1009         }
1010       }
1011     } else if (i < BLOCK_32X32) {
1012       for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1013         for (x->mb_index = 0; x->mb_index < 64 / num_4x4_blk; ++x->mb_index) {
1014           PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1015           ctx->num_4x4_blk = num_4x4_blk;
1016           alloc_mode_context(cm, num_4x4_blk, ctx);
1017         }
1018       }
1019     } else if (i < BLOCK_64X64) {
1020       for (x->sb_index = 0; x->sb_index < 256 / num_4x4_blk; ++x->sb_index) {
1021         PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1022         ctx->num_4x4_blk = num_4x4_blk;
1023         alloc_mode_context(cm, num_4x4_blk, ctx);
1024       }
1025     } else {
1026       PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1027       ctx->num_4x4_blk = num_4x4_blk;
1028       alloc_mode_context(cm, num_4x4_blk, ctx);
1029     }
1030   }
1031 }
1032
1033 static void free_pick_mode_context(MACROBLOCK *x) {
1034   int i;
1035
1036   for (i = 0; i < BLOCK_SIZES; ++i) {
1037     const int num_4x4_w = num_4x4_blocks_wide_lookup[i];
1038     const int num_4x4_h = num_4x4_blocks_high_lookup[i];
1039     const int num_4x4_blk = MAX(4, num_4x4_w * num_4x4_h);
1040     if (i < BLOCK_16X16) {
1041       for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1042         for (x->mb_index = 0; x->mb_index < 4; ++x->mb_index) {
1043           for (x->b_index = 0; x->b_index < 16 / num_4x4_blk; ++x->b_index) {
1044             PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1045             free_mode_context(ctx);
1046           }
1047         }
1048       }
1049     } else if (i < BLOCK_32X32) {
1050       for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1051         for (x->mb_index = 0; x->mb_index < 64 / num_4x4_blk; ++x->mb_index) {
1052           PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1053           free_mode_context(ctx);
1054         }
1055       }
1056     } else if (i < BLOCK_64X64) {
1057       for (x->sb_index = 0; x->sb_index < 256 / num_4x4_blk; ++x->sb_index) {
1058         PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1059         free_mode_context(ctx);
1060       }
1061     } else {
1062       PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1063       free_mode_context(ctx);
1064     }
1065   }
1066 }
1067
1068 VP9_COMP *vp9_create_compressor(VP9_CONFIG *oxcf) {
1069   int i, j;
1070   VP9_COMP *const cpi = vpx_memalign(32, sizeof(VP9_COMP));
1071   VP9_COMMON *const cm = cpi != NULL ? &cpi->common : NULL;
1072
1073   if (!cm)
1074     return NULL;
1075
1076   vp9_zero(*cpi);
1077
1078   if (setjmp(cm->error.jmp)) {
1079     cm->error.setjmp = 0;
1080     vp9_remove_compressor(cpi);
1081     return 0;
1082   }
1083
1084   cm->error.setjmp = 1;
1085
1086   CHECK_MEM_ERROR(cm, cpi->mb.ss, vpx_calloc(sizeof(search_site),
1087                                              (MAX_MVSEARCH_STEPS * 8) + 1));
1088
1089   vp9_rtcd();
1090
1091   cpi->use_svc = 0;
1092
1093   init_config(cpi, oxcf);
1094   vp9_rc_init(&cpi->oxcf, cpi->pass, &cpi->rc);
1095   init_pick_mode_context(cpi);
1096
1097   cm->current_video_frame = 0;
1098
1099   // Set reference frame sign bias for ALTREF frame to 1 (for now)
1100   cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
1101
1102   cpi->gold_is_last = 0;
1103   cpi->alt_is_last = 0;
1104   cpi->gold_is_alt = 0;
1105
1106   // Create the encoder segmentation map and set all entries to 0
1107   CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1108                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1109
1110   // Create a complexity map used for rd adjustment
1111   CHECK_MEM_ERROR(cm, cpi->complexity_map,
1112                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1113
1114   // Create a map used for cyclic background refresh.
1115   CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
1116                   vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
1117
1118   // And a place holder structure is the coding context
1119   // for use if we want to save and restore it
1120   CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1121                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1122
1123   CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
1124   vpx_memset(cpi->active_map, 1, cm->MBs);
1125   cpi->active_map_enabled = 0;
1126
1127   for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1128                    sizeof(cpi->mbgraph_stats[0])); i++) {
1129     CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1130                     vpx_calloc(cm->MBs *
1131                                sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1132   }
1133
1134   /*Initialize the feed-forward activity masking.*/
1135   cpi->activity_avg = 90 << 12;
1136   cpi->key_frame_frequency = cpi->oxcf.key_freq;
1137   cpi->refresh_alt_ref_frame = 0;
1138
1139 #if CONFIG_MULTIPLE_ARF
1140   // Turn multiple ARF usage on/off. This is a quick hack for the initial test
1141   // version. It should eventually be set via the codec API.
1142   cpi->multi_arf_enabled = 1;
1143
1144   if (cpi->multi_arf_enabled) {
1145     cpi->sequence_number = 0;
1146     cpi->frame_coding_order_period = 0;
1147     vp9_zero(cpi->frame_coding_order);
1148     vp9_zero(cpi->arf_buffer_idx);
1149   }
1150 #endif
1151
1152   cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1153 #if CONFIG_INTERNAL_STATS
1154   cpi->b_calculate_ssimg = 0;
1155
1156   cpi->count = 0;
1157   cpi->bytes = 0;
1158
1159   if (cpi->b_calculate_psnr) {
1160     cpi->total_y = 0.0;
1161     cpi->total_u = 0.0;
1162     cpi->total_v = 0.0;
1163     cpi->total = 0.0;
1164     cpi->total_sq_error = 0;
1165     cpi->total_samples = 0;
1166
1167     cpi->totalp_y = 0.0;
1168     cpi->totalp_u = 0.0;
1169     cpi->totalp_v = 0.0;
1170     cpi->totalp = 0.0;
1171     cpi->totalp_sq_error = 0;
1172     cpi->totalp_samples = 0;
1173
1174     cpi->tot_recode_hits = 0;
1175     cpi->summed_quality = 0;
1176     cpi->summed_weights = 0;
1177     cpi->summedp_quality = 0;
1178     cpi->summedp_weights = 0;
1179   }
1180
1181   if (cpi->b_calculate_ssimg) {
1182     cpi->total_ssimg_y = 0;
1183     cpi->total_ssimg_u = 0;
1184     cpi->total_ssimg_v = 0;
1185     cpi->total_ssimg_all = 0;
1186   }
1187
1188 #endif
1189
1190   cpi->first_time_stamp_ever = INT64_MAX;
1191
1192   cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
1193   cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
1194   cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
1195   cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
1196   cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
1197   cal_nmvsadcosts(cpi->mb.nmvsadcost);
1198
1199   cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
1200   cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
1201   cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
1202   cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
1203   cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
1204
1205 #ifdef OUTPUT_YUV_SRC
1206   yuv_file = fopen("bd.yuv", "ab");
1207 #endif
1208 #ifdef OUTPUT_YUV_REC
1209   yuv_rec_file = fopen("rec.yuv", "wb");
1210 #endif
1211
1212 #if 0
1213   framepsnr = fopen("framepsnr.stt", "a");
1214   kf_list = fopen("kf_list.stt", "w");
1215 #endif
1216
1217   cpi->output_pkt_list = oxcf->output_pkt_list;
1218
1219   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
1220
1221   if (cpi->pass == 1) {
1222     vp9_init_first_pass(cpi);
1223   } else if (cpi->pass == 2) {
1224     const size_t packet_sz = sizeof(FIRSTPASS_STATS);
1225     const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1226
1227     if (cpi->svc.number_spatial_layers > 1
1228         && cpi->svc.number_temporal_layers == 1) {
1229       FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
1230       FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = {0};
1231       int i;
1232
1233       for (i = 0; i < oxcf->ss_number_layers; ++i) {
1234         FIRSTPASS_STATS *const last_packet_for_layer =
1235             &stats[packets - oxcf->ss_number_layers + i];
1236         const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
1237         const int packets_in_layer = (int)last_packet_for_layer->count + 1;
1238         if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
1239           LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
1240
1241           vpx_free(lc->rc_twopass_stats_in.buf);
1242
1243           lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
1244           CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
1245                           vpx_malloc(lc->rc_twopass_stats_in.sz));
1246           lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
1247           lc->twopass.stats_in = lc->twopass.stats_in_start;
1248           lc->twopass.stats_in_end = lc->twopass.stats_in_start
1249                                      + packets_in_layer - 1;
1250           stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
1251         }
1252       }
1253
1254       for (i = 0; i < packets; ++i) {
1255         const int layer_id = (int)stats[i].spatial_layer_id;
1256         if (layer_id >= 0 && layer_id < oxcf->ss_number_layers
1257             && stats_copy[layer_id] != NULL) {
1258           *stats_copy[layer_id] = stats[i];
1259           ++stats_copy[layer_id];
1260         }
1261       }
1262
1263       vp9_init_second_pass_spatial_svc(cpi);
1264     } else {
1265       cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1266       cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1267       cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
1268
1269       vp9_init_second_pass(cpi);
1270     }
1271   }
1272
1273   set_speed_features(cpi);
1274
1275   // Default rd threshold factors for mode selection
1276   for (i = 0; i < BLOCK_SIZES; ++i) {
1277     for (j = 0; j < MAX_MODES; ++j)
1278       cpi->rd_thresh_freq_fact[i][j] = 32;
1279     for (j = 0; j < MAX_REFS; ++j)
1280       cpi->rd_thresh_freq_sub8x8[i][j] = 32;
1281   }
1282
1283 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SVFHH, SVFHV, SVFHHV, \
1284             SDX3F, SDX8F, SDX4DF)\
1285     cpi->fn_ptr[BT].sdf            = SDF; \
1286     cpi->fn_ptr[BT].sdaf           = SDAF; \
1287     cpi->fn_ptr[BT].vf             = VF; \
1288     cpi->fn_ptr[BT].svf            = SVF; \
1289     cpi->fn_ptr[BT].svaf           = SVAF; \
1290     cpi->fn_ptr[BT].svf_halfpix_h  = SVFHH; \
1291     cpi->fn_ptr[BT].svf_halfpix_v  = SVFHV; \
1292     cpi->fn_ptr[BT].svf_halfpix_hv = SVFHHV; \
1293     cpi->fn_ptr[BT].sdx3f          = SDX3F; \
1294     cpi->fn_ptr[BT].sdx8f          = SDX8F; \
1295     cpi->fn_ptr[BT].sdx4df         = SDX4DF;
1296
1297   BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
1298       vp9_variance32x16, vp9_sub_pixel_variance32x16,
1299       vp9_sub_pixel_avg_variance32x16, NULL, NULL,
1300       NULL, NULL, NULL,
1301       vp9_sad32x16x4d)
1302
1303   BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
1304       vp9_variance16x32, vp9_sub_pixel_variance16x32,
1305       vp9_sub_pixel_avg_variance16x32, NULL, NULL,
1306       NULL, NULL, NULL,
1307       vp9_sad16x32x4d)
1308
1309   BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
1310       vp9_variance64x32, vp9_sub_pixel_variance64x32,
1311       vp9_sub_pixel_avg_variance64x32, NULL, NULL,
1312       NULL, NULL, NULL,
1313       vp9_sad64x32x4d)
1314
1315   BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
1316       vp9_variance32x64, vp9_sub_pixel_variance32x64,
1317       vp9_sub_pixel_avg_variance32x64, NULL, NULL,
1318       NULL, NULL, NULL,
1319       vp9_sad32x64x4d)
1320
1321   BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
1322       vp9_variance32x32, vp9_sub_pixel_variance32x32,
1323       vp9_sub_pixel_avg_variance32x32, vp9_variance_halfpixvar32x32_h,
1324       vp9_variance_halfpixvar32x32_v,
1325       vp9_variance_halfpixvar32x32_hv, vp9_sad32x32x3, vp9_sad32x32x8,
1326       vp9_sad32x32x4d)
1327
1328   BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
1329       vp9_variance64x64, vp9_sub_pixel_variance64x64,
1330       vp9_sub_pixel_avg_variance64x64, vp9_variance_halfpixvar64x64_h,
1331       vp9_variance_halfpixvar64x64_v,
1332       vp9_variance_halfpixvar64x64_hv, vp9_sad64x64x3, vp9_sad64x64x8,
1333       vp9_sad64x64x4d)
1334
1335   BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
1336       vp9_variance16x16, vp9_sub_pixel_variance16x16,
1337       vp9_sub_pixel_avg_variance16x16, vp9_variance_halfpixvar16x16_h,
1338       vp9_variance_halfpixvar16x16_v,
1339       vp9_variance_halfpixvar16x16_hv, vp9_sad16x16x3, vp9_sad16x16x8,
1340       vp9_sad16x16x4d)
1341
1342   BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
1343       vp9_variance16x8, vp9_sub_pixel_variance16x8,
1344       vp9_sub_pixel_avg_variance16x8, NULL, NULL, NULL,
1345       vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
1346
1347   BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
1348       vp9_variance8x16, vp9_sub_pixel_variance8x16,
1349       vp9_sub_pixel_avg_variance8x16, NULL, NULL, NULL,
1350       vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
1351
1352   BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1353       vp9_variance8x8, vp9_sub_pixel_variance8x8,
1354       vp9_sub_pixel_avg_variance8x8, NULL, NULL, NULL,
1355       vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1356
1357   BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1358       vp9_variance8x4, vp9_sub_pixel_variance8x4,
1359       vp9_sub_pixel_avg_variance8x4, NULL, NULL,
1360       NULL, NULL, vp9_sad8x4x8,
1361       vp9_sad8x4x4d)
1362
1363   BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1364       vp9_variance4x8, vp9_sub_pixel_variance4x8,
1365       vp9_sub_pixel_avg_variance4x8, NULL, NULL,
1366       NULL, NULL, vp9_sad4x8x8,
1367       vp9_sad4x8x4d)
1368
1369   BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1370       vp9_variance4x4, vp9_sub_pixel_variance4x4,
1371       vp9_sub_pixel_avg_variance4x4, NULL, NULL, NULL,
1372       vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1373
1374   cpi->full_search_sad = vp9_full_search_sad;
1375   cpi->diamond_search_sad = vp9_diamond_search_sad;
1376   cpi->refining_search_sad = vp9_refining_search_sad;
1377
1378   /* vp9_init_quantizer() is first called here. Add check in
1379    * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1380    * called later when needed. This will avoid unnecessary calls of
1381    * vp9_init_quantizer() for every frame.
1382    */
1383   vp9_init_quantizer(cpi);
1384
1385   vp9_loop_filter_init(cm);
1386
1387   cm->error.setjmp = 0;
1388
1389   vp9_zero(cpi->common.counts.uv_mode);
1390
1391 #ifdef MODE_TEST_HIT_STATS
1392   vp9_zero(cpi->mode_test_hits);
1393 #endif
1394
1395   return cpi;
1396 }
1397
1398 void vp9_remove_compressor(VP9_COMP *cpi) {
1399   int i;
1400
1401   if (!cpi)
1402     return;
1403
1404   if (cpi && (cpi->common.current_video_frame > 0)) {
1405 #if CONFIG_INTERNAL_STATS
1406
1407     vp9_clear_system_state();
1408
1409     // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1410     if (cpi->pass != 1) {
1411       FILE *f = fopen("opsnr.stt", "a");
1412       double time_encoded = (cpi->last_end_time_stamp_seen
1413                              - cpi->first_time_stamp_ever) / 10000000.000;
1414       double total_encode_time = (cpi->time_receive_data +
1415                                   cpi->time_compress_data)   / 1000.000;
1416       double dr = (double)cpi->bytes * (double) 8 / (double)1000
1417                   / time_encoded;
1418
1419       if (cpi->b_calculate_psnr) {
1420         const double total_psnr =
1421             vpx_sse_to_psnr((double)cpi->total_samples, 255.0,
1422                             (double)cpi->total_sq_error);
1423         const double totalp_psnr =
1424             vpx_sse_to_psnr((double)cpi->totalp_samples, 255.0,
1425                             (double)cpi->totalp_sq_error);
1426         const double total_ssim = 100 * pow(cpi->summed_quality /
1427                                                 cpi->summed_weights, 8.0);
1428         const double totalp_ssim = 100 * pow(cpi->summedp_quality /
1429                                                 cpi->summedp_weights, 8.0);
1430
1431         fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1432                 "VPXSSIM\tVPSSIMP\t  Time(ms)\n");
1433         fprintf(f, "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%8.0f\n",
1434                 dr, cpi->total / cpi->count, total_psnr,
1435                 cpi->totalp / cpi->count, totalp_psnr, total_ssim, totalp_ssim,
1436                 total_encode_time);
1437       }
1438
1439       if (cpi->b_calculate_ssimg) {
1440         fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t  Time(ms)\n");
1441         fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1442                 cpi->total_ssimg_y / cpi->count,
1443                 cpi->total_ssimg_u / cpi->count,
1444                 cpi->total_ssimg_v / cpi->count,
1445                 cpi->total_ssimg_all / cpi->count, total_encode_time);
1446       }
1447
1448       fclose(f);
1449     }
1450
1451 #endif
1452
1453 #ifdef MODE_TEST_HIT_STATS
1454     if (cpi->pass != 1) {
1455       double norm_per_pixel_mode_tests = 0;
1456       double norm_counts[BLOCK_SIZES];
1457       int i;
1458       int sb64_per_frame;
1459       int norm_factors[BLOCK_SIZES] =
1460         {256, 128, 128, 64, 32, 32, 16, 8, 8, 4, 2, 2, 1};
1461       FILE *f = fopen("mode_hit_stats.stt", "a");
1462
1463       // On average, how many mode tests do we do
1464       for (i = 0; i < BLOCK_SIZES; ++i) {
1465         norm_counts[i] = (double)cpi->mode_test_hits[i] /
1466                          (double)norm_factors[i];
1467         norm_per_pixel_mode_tests += norm_counts[i];
1468       }
1469       // Convert to a number per 64x64 and per frame
1470       sb64_per_frame = ((cpi->common.height + 63) / 64) *
1471                        ((cpi->common.width + 63) / 64);
1472       norm_per_pixel_mode_tests =
1473         norm_per_pixel_mode_tests /
1474         (double)(cpi->common.current_video_frame * sb64_per_frame);
1475
1476       fprintf(f, "%6.4f\n", norm_per_pixel_mode_tests);
1477       fclose(f);
1478     }
1479 #endif
1480
1481 #if 0
1482     {
1483       printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1484       printf("\n_frames recive_data encod_mb_row compress_frame  Total\n");
1485       printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1486              cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1487              cpi->time_compress_data / 1000,
1488              (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1489     }
1490 #endif
1491   }
1492
1493   free_pick_mode_context(&cpi->mb);
1494   dealloc_compressor_data(cpi);
1495   vpx_free(cpi->mb.ss);
1496   vpx_free(cpi->tok);
1497
1498   for (i = 0; i < sizeof(cpi->mbgraph_stats) /
1499                   sizeof(cpi->mbgraph_stats[0]); ++i) {
1500     vpx_free(cpi->mbgraph_stats[i].mb_stats);
1501   }
1502
1503   vp9_remove_common(&cpi->common);
1504   vpx_free(cpi);
1505
1506 #ifdef OUTPUT_YUV_SRC
1507   fclose(yuv_file);
1508 #endif
1509 #ifdef OUTPUT_YUV_REC
1510   fclose(yuv_rec_file);
1511 #endif
1512
1513 #if 0
1514
1515   if (keyfile)
1516     fclose(keyfile);
1517
1518   if (framepsnr)
1519     fclose(framepsnr);
1520
1521   if (kf_list)
1522     fclose(kf_list);
1523
1524 #endif
1525 }
1526 static int64_t get_sse(const uint8_t *a, int a_stride,
1527                        const uint8_t *b, int b_stride,
1528                        int width, int height) {
1529   const int dw = width % 16;
1530   const int dh = height % 16;
1531   int64_t total_sse = 0;
1532   unsigned int sse = 0;
1533   int sum = 0;
1534   int x, y;
1535
1536   if (dw > 0) {
1537     variance(&a[width - dw], a_stride, &b[width - dw], b_stride,
1538              dw, height, &sse, &sum);
1539     total_sse += sse;
1540   }
1541
1542   if (dh > 0) {
1543     variance(&a[(height - dh) * a_stride], a_stride,
1544              &b[(height - dh) * b_stride], b_stride,
1545              width - dw, dh, &sse, &sum);
1546     total_sse += sse;
1547   }
1548
1549   for (y = 0; y < height / 16; ++y) {
1550     const uint8_t *pa = a;
1551     const uint8_t *pb = b;
1552     for (x = 0; x < width / 16; ++x) {
1553       vp9_mse16x16(pa, a_stride, pb, b_stride, &sse);
1554       total_sse += sse;
1555
1556       pa += 16;
1557       pb += 16;
1558     }
1559
1560     a += 16 * a_stride;
1561     b += 16 * b_stride;
1562   }
1563
1564   return total_sse;
1565 }
1566
1567 typedef struct {
1568   double psnr[4];       // total/y/u/v
1569   uint64_t sse[4];      // total/y/u/v
1570   uint32_t samples[4];  // total/y/u/v
1571 } PSNR_STATS;
1572
1573 static void calc_psnr(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b,
1574                       PSNR_STATS *psnr) {
1575   const int widths[3]        = {a->y_width,  a->uv_width,  a->uv_width };
1576   const int heights[3]       = {a->y_height, a->uv_height, a->uv_height};
1577   const uint8_t *a_planes[3] = {a->y_buffer, a->u_buffer,  a->v_buffer };
1578   const int a_strides[3]     = {a->y_stride, a->uv_stride, a->uv_stride};
1579   const uint8_t *b_planes[3] = {b->y_buffer, b->u_buffer,  b->v_buffer };
1580   const int b_strides[3]     = {b->y_stride, b->uv_stride, b->uv_stride};
1581   int i;
1582   uint64_t total_sse = 0;
1583   uint32_t total_samples = 0;
1584
1585   for (i = 0; i < 3; ++i) {
1586     const int w = widths[i];
1587     const int h = heights[i];
1588     const uint32_t samples = w * h;
1589     const uint64_t sse = get_sse(a_planes[i], a_strides[i],
1590                                  b_planes[i], b_strides[i],
1591                                  w, h);
1592     psnr->sse[1 + i] = sse;
1593     psnr->samples[1 + i] = samples;
1594     psnr->psnr[1 + i] = vpx_sse_to_psnr(samples, 255.0, (double)sse);
1595
1596     total_sse += sse;
1597     total_samples += samples;
1598   }
1599
1600   psnr->sse[0] = total_sse;
1601   psnr->samples[0] = total_samples;
1602   psnr->psnr[0] = vpx_sse_to_psnr((double)total_samples, 255.0,
1603                                   (double)total_sse);
1604 }
1605
1606 static void generate_psnr_packet(VP9_COMP *cpi) {
1607   struct vpx_codec_cx_pkt pkt;
1608   int i;
1609   PSNR_STATS psnr;
1610   calc_psnr(cpi->Source, cpi->common.frame_to_show, &psnr);
1611   for (i = 0; i < 4; ++i) {
1612     pkt.data.psnr.samples[i] = psnr.samples[i];
1613     pkt.data.psnr.sse[i] = psnr.sse[i];
1614     pkt.data.psnr.psnr[i] = psnr.psnr[i];
1615   }
1616   pkt.kind = VPX_CODEC_PSNR_PKT;
1617   vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
1618 }
1619
1620 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
1621   if (ref_frame_flags > 7)
1622     return -1;
1623
1624   cpi->ref_frame_flags = ref_frame_flags;
1625   return 0;
1626 }
1627
1628 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
1629   cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
1630   cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
1631   cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
1632   cpi->ext_refresh_frame_flags_pending = 1;
1633 }
1634
1635 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
1636                                 VP9_REFFRAME ref_frame_flag) {
1637   MV_REFERENCE_FRAME ref_frame = NONE;
1638   if (ref_frame_flag == VP9_LAST_FLAG)
1639     ref_frame = LAST_FRAME;
1640   else if (ref_frame_flag == VP9_GOLD_FLAG)
1641     ref_frame = GOLDEN_FRAME;
1642   else if (ref_frame_flag == VP9_ALT_FLAG)
1643     ref_frame = ALTREF_FRAME;
1644
1645   return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
1646 }
1647
1648 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1649                            YV12_BUFFER_CONFIG *sd) {
1650   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1651   if (cfg) {
1652     vp8_yv12_copy_frame(cfg, sd);
1653     return 0;
1654   } else {
1655     return -1;
1656   }
1657 }
1658
1659 int vp9_get_reference_enc(VP9_COMP *cpi, int index, YV12_BUFFER_CONFIG **fb) {
1660   VP9_COMMON *cm = &cpi->common;
1661
1662   if (index < 0 || index >= REF_FRAMES)
1663     return -1;
1664
1665   *fb = &cm->frame_bufs[cm->ref_frame_map[index]].buf;
1666   return 0;
1667 }
1668
1669 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1670                           YV12_BUFFER_CONFIG *sd) {
1671   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1672   if (cfg) {
1673     vp8_yv12_copy_frame(sd, cfg);
1674     return 0;
1675   } else {
1676     return -1;
1677   }
1678 }
1679
1680 int vp9_update_entropy(VP9_COMP * cpi, int update) {
1681   cpi->ext_refresh_frame_context = update;
1682   cpi->ext_refresh_frame_context_pending = 1;
1683   return 0;
1684 }
1685
1686
1687 #ifdef OUTPUT_YUV_SRC
1688 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s) {
1689   uint8_t *src = s->y_buffer;
1690   int h = s->y_height;
1691
1692   do {
1693     fwrite(src, s->y_width, 1,  yuv_file);
1694     src += s->y_stride;
1695   } while (--h);
1696
1697   src = s->u_buffer;
1698   h = s->uv_height;
1699
1700   do {
1701     fwrite(src, s->uv_width, 1,  yuv_file);
1702     src += s->uv_stride;
1703   } while (--h);
1704
1705   src = s->v_buffer;
1706   h = s->uv_height;
1707
1708   do {
1709     fwrite(src, s->uv_width, 1, yuv_file);
1710     src += s->uv_stride;
1711   } while (--h);
1712 }
1713 #endif
1714
1715 #ifdef OUTPUT_YUV_REC
1716 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
1717   YV12_BUFFER_CONFIG *s = cm->frame_to_show;
1718   uint8_t *src = s->y_buffer;
1719   int h = cm->height;
1720
1721   do {
1722     fwrite(src, s->y_width, 1,  yuv_rec_file);
1723     src += s->y_stride;
1724   } while (--h);
1725
1726   src = s->u_buffer;
1727   h = s->uv_height;
1728
1729   do {
1730     fwrite(src, s->uv_width, 1,  yuv_rec_file);
1731     src += s->uv_stride;
1732   } while (--h);
1733
1734   src = s->v_buffer;
1735   h = s->uv_height;
1736
1737   do {
1738     fwrite(src, s->uv_width, 1, yuv_rec_file);
1739     src += s->uv_stride;
1740   } while (--h);
1741
1742 #if CONFIG_ALPHA
1743   if (s->alpha_buffer) {
1744     src = s->alpha_buffer;
1745     h = s->alpha_height;
1746     do {
1747       fwrite(src, s->alpha_width, 1,  yuv_rec_file);
1748       src += s->alpha_stride;
1749     } while (--h);
1750   }
1751 #endif
1752
1753   fflush(yuv_rec_file);
1754 }
1755 #endif
1756
1757 static void scale_and_extend_frame_nonnormative(YV12_BUFFER_CONFIG *src_fb,
1758                                                 YV12_BUFFER_CONFIG *dst_fb) {
1759   const int in_w = src_fb->y_crop_width;
1760   const int in_h = src_fb->y_crop_height;
1761   const int out_w = dst_fb->y_crop_width;
1762   const int out_h = dst_fb->y_crop_height;
1763   const int in_w_uv = src_fb->uv_crop_width;
1764   const int in_h_uv = src_fb->uv_crop_height;
1765   const int out_w_uv = dst_fb->uv_crop_width;
1766   const int out_h_uv = dst_fb->uv_crop_height;
1767   int i;
1768
1769   uint8_t *srcs[4] = {src_fb->y_buffer, src_fb->u_buffer, src_fb->v_buffer,
1770     src_fb->alpha_buffer};
1771   int src_strides[4] = {src_fb->y_stride, src_fb->uv_stride, src_fb->uv_stride,
1772     src_fb->alpha_stride};
1773
1774   uint8_t *dsts[4] = {dst_fb->y_buffer, dst_fb->u_buffer, dst_fb->v_buffer,
1775     dst_fb->alpha_buffer};
1776   int dst_strides[4] = {dst_fb->y_stride, dst_fb->uv_stride, dst_fb->uv_stride,
1777     dst_fb->alpha_stride};
1778
1779   for (i = 0; i < MAX_MB_PLANE; ++i) {
1780     if (i == 0 || i == 3) {
1781       // Y and alpha planes
1782       vp9_resize_plane(srcs[i], in_h, in_w, src_strides[i],
1783                        dsts[i], out_h, out_w, dst_strides[i]);
1784     } else {
1785       // Chroma planes
1786       vp9_resize_plane(srcs[i], in_h_uv, in_w_uv, src_strides[i],
1787                        dsts[i], out_h_uv, out_w_uv, dst_strides[i]);
1788     }
1789   }
1790   vp8_yv12_extend_frame_borders(dst_fb);
1791 }
1792
1793 static void scale_and_extend_frame(YV12_BUFFER_CONFIG *src_fb,
1794                                    YV12_BUFFER_CONFIG *dst_fb) {
1795   const int in_w = src_fb->y_crop_width;
1796   const int in_h = src_fb->y_crop_height;
1797   const int out_w = dst_fb->y_crop_width;
1798   const int out_h = dst_fb->y_crop_height;
1799   int x, y, i;
1800
1801   uint8_t *srcs[4] = {src_fb->y_buffer, src_fb->u_buffer, src_fb->v_buffer,
1802                       src_fb->alpha_buffer};
1803   int src_strides[4] = {src_fb->y_stride, src_fb->uv_stride, src_fb->uv_stride,
1804                         src_fb->alpha_stride};
1805
1806   uint8_t *dsts[4] = {dst_fb->y_buffer, dst_fb->u_buffer, dst_fb->v_buffer,
1807                       dst_fb->alpha_buffer};
1808   int dst_strides[4] = {dst_fb->y_stride, dst_fb->uv_stride, dst_fb->uv_stride,
1809                         dst_fb->alpha_stride};
1810
1811   for (y = 0; y < out_h; y += 16) {
1812     for (x = 0; x < out_w; x += 16) {
1813       for (i = 0; i < MAX_MB_PLANE; ++i) {
1814         const int factor = (i == 0 || i == 3 ? 1 : 2);
1815         const int x_q4 = x * (16 / factor) * in_w / out_w;
1816         const int y_q4 = y * (16 / factor) * in_h / out_h;
1817         const int src_stride = src_strides[i];
1818         const int dst_stride = dst_strides[i];
1819         uint8_t *src = srcs[i] + y / factor * in_h / out_h * src_stride +
1820                                  x / factor * in_w / out_w;
1821         uint8_t *dst = dsts[i] + y / factor * dst_stride + x / factor;
1822
1823         vp9_convolve8(src, src_stride, dst, dst_stride,
1824                       vp9_sub_pel_filters_8[x_q4 & 0xf], 16 * in_w / out_w,
1825                       vp9_sub_pel_filters_8[y_q4 & 0xf], 16 * in_h / out_h,
1826                       16 / factor, 16 / factor);
1827       }
1828     }
1829   }
1830
1831   vp8_yv12_extend_frame_borders(dst_fb);
1832 }
1833
1834 static int find_fp_qindex() {
1835   int i;
1836
1837   for (i = 0; i < QINDEX_RANGE; i++) {
1838     if (vp9_convert_qindex_to_q(i) >= 30.0) {
1839       break;
1840     }
1841   }
1842
1843   if (i == QINDEX_RANGE)
1844     i--;
1845
1846   return i;
1847 }
1848
1849 #define WRITE_RECON_BUFFER 0
1850 #if WRITE_RECON_BUFFER
1851 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
1852   FILE *yframe;
1853   int i;
1854   char filename[255];
1855
1856   snprintf(filename, sizeof(filename), "cx\\y%04d.raw", this_frame);
1857   yframe = fopen(filename, "wb");
1858
1859   for (i = 0; i < frame->y_height; i++)
1860     fwrite(frame->y_buffer + i * frame->y_stride,
1861            frame->y_width, 1, yframe);
1862
1863   fclose(yframe);
1864   snprintf(filename, sizeof(filename), "cx\\u%04d.raw", this_frame);
1865   yframe = fopen(filename, "wb");
1866
1867   for (i = 0; i < frame->uv_height; i++)
1868     fwrite(frame->u_buffer + i * frame->uv_stride,
1869            frame->uv_width, 1, yframe);
1870
1871   fclose(yframe);
1872   snprintf(filename, sizeof(filename), "cx\\v%04d.raw", this_frame);
1873   yframe = fopen(filename, "wb");
1874
1875   for (i = 0; i < frame->uv_height; i++)
1876     fwrite(frame->v_buffer + i * frame->uv_stride,
1877            frame->uv_width, 1, yframe);
1878
1879   fclose(yframe);
1880 }
1881 #endif
1882
1883 // Function to test for conditions that indicate we should loop
1884 // back and recode a frame.
1885 static int recode_loop_test(const VP9_COMP *cpi,
1886                             int high_limit, int low_limit,
1887                             int q, int maxq, int minq) {
1888   const VP9_COMMON *const cm = &cpi->common;
1889   const RATE_CONTROL *const rc = &cpi->rc;
1890   int force_recode = 0;
1891
1892   // Special case trap if maximum allowed frame size exceeded.
1893   if (rc->projected_frame_size > rc->max_frame_bandwidth) {
1894     force_recode = 1;
1895
1896   // Is frame recode allowed.
1897   // Yes if either recode mode 1 is selected or mode 2 is selected
1898   // and the frame is a key frame, golden frame or alt_ref_frame
1899   } else if ((cpi->sf.recode_loop == ALLOW_RECODE) ||
1900              ((cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF) &&
1901               (cm->frame_type == KEY_FRAME ||
1902                cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1903     // General over and under shoot tests
1904     if ((rc->projected_frame_size > high_limit && q < maxq) ||
1905         (rc->projected_frame_size < low_limit && q > minq)) {
1906       force_recode = 1;
1907     } else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
1908       // Deal with frame undershoot and whether or not we are
1909       // below the automatically set cq level.
1910       if (q > cpi->cq_target_quality &&
1911           rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
1912         force_recode = 1;
1913       }
1914     }
1915   }
1916   return force_recode;
1917 }
1918
1919 void vp9_update_reference_frames(VP9_COMP *cpi) {
1920   VP9_COMMON * const cm = &cpi->common;
1921
1922   // At this point the new frame has been encoded.
1923   // If any buffer copy / swapping is signaled it should be done here.
1924   if (cm->frame_type == KEY_FRAME) {
1925     ref_cnt_fb(cm->frame_bufs,
1926                &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1927     ref_cnt_fb(cm->frame_bufs,
1928                &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1929   }
1930 #if CONFIG_MULTIPLE_ARF
1931   else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
1932       !cpi->refresh_alt_ref_frame) {
1933 #else
1934   else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
1935            !cpi->use_svc) {
1936 #endif
1937     /* Preserve the previously existing golden frame and update the frame in
1938      * the alt ref slot instead. This is highly specific to the current use of
1939      * alt-ref as a forward reference, and this needs to be generalized as
1940      * other uses are implemented (like RTC/temporal scaling)
1941      *
1942      * The update to the buffer in the alt ref slot was signaled in
1943      * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
1944      * as the golden frame next time.
1945      */
1946     int tmp;
1947
1948     ref_cnt_fb(cm->frame_bufs,
1949                &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1950
1951     tmp = cpi->alt_fb_idx;
1952     cpi->alt_fb_idx = cpi->gld_fb_idx;
1953     cpi->gld_fb_idx = tmp;
1954   }  else { /* For non key/golden frames */
1955     if (cpi->refresh_alt_ref_frame) {
1956       int arf_idx = cpi->alt_fb_idx;
1957 #if CONFIG_MULTIPLE_ARF
1958       if (cpi->multi_arf_enabled) {
1959         arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
1960       }
1961 #endif
1962       ref_cnt_fb(cm->frame_bufs,
1963                  &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
1964     }
1965
1966     if (cpi->refresh_golden_frame) {
1967       ref_cnt_fb(cm->frame_bufs,
1968                  &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1969     }
1970   }
1971
1972   if (cpi->refresh_last_frame) {
1973     ref_cnt_fb(cm->frame_bufs,
1974                &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
1975   }
1976 }
1977
1978 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
1979   MACROBLOCKD *xd = &cpi->mb.e_mbd;
1980   struct loopfilter *lf = &cm->lf;
1981   if (xd->lossless) {
1982       lf->filter_level = 0;
1983   } else {
1984     struct vpx_usec_timer timer;
1985
1986     vp9_clear_system_state();
1987
1988     vpx_usec_timer_start(&timer);
1989
1990     vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
1991
1992     vpx_usec_timer_mark(&timer);
1993     cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
1994   }
1995
1996   if (lf->filter_level > 0) {
1997     vp9_loop_filter_frame(cm, xd, lf->filter_level, 0, 0);
1998   }
1999
2000   vp9_extend_frame_inner_borders(cm->frame_to_show);
2001 }
2002
2003 void vp9_scale_references(VP9_COMP *cpi) {
2004   VP9_COMMON *cm = &cpi->common;
2005   MV_REFERENCE_FRAME ref_frame;
2006
2007   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2008     const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
2009     YV12_BUFFER_CONFIG *const ref = &cm->frame_bufs[idx].buf;
2010
2011     if (ref->y_crop_width != cm->width ||
2012         ref->y_crop_height != cm->height) {
2013       const int new_fb = get_free_fb(cm);
2014       vp9_realloc_frame_buffer(&cm->frame_bufs[new_fb].buf,
2015                                cm->width, cm->height,
2016                                cm->subsampling_x, cm->subsampling_y,
2017                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
2018       scale_and_extend_frame(ref, &cm->frame_bufs[new_fb].buf);
2019       cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2020     } else {
2021       cpi->scaled_ref_idx[ref_frame - 1] = idx;
2022       cm->frame_bufs[idx].ref_count++;
2023     }
2024   }
2025 }
2026
2027 static void release_scaled_references(VP9_COMP *cpi) {
2028   VP9_COMMON *cm = &cpi->common;
2029   int i;
2030
2031   for (i = 0; i < 3; i++)
2032     cm->frame_bufs[cpi->scaled_ref_idx[i]].ref_count--;
2033 }
2034
2035 static void full_to_model_count(unsigned int *model_count,
2036                                 unsigned int *full_count) {
2037   int n;
2038   model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2039   model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2040   model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2041   for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
2042     model_count[TWO_TOKEN] += full_count[n];
2043   model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
2044 }
2045
2046 static void full_to_model_counts(vp9_coeff_count_model *model_count,
2047                                  vp9_coeff_count *full_count) {
2048   int i, j, k, l;
2049
2050   for (i = 0; i < PLANE_TYPES; ++i)
2051     for (j = 0; j < REF_TYPES; ++j)
2052       for (k = 0; k < COEF_BANDS; ++k)
2053         for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
2054           full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2055 }
2056
2057 #if 0 && CONFIG_INTERNAL_STATS
2058 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2059   VP9_COMMON *const cm = &cpi->common;
2060   FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2061   int recon_err;
2062
2063   vp9_clear_system_state();
2064
2065   recon_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2066
2067   if (cpi->twopass.total_left_stats.coded_error != 0.0)
2068     fprintf(f, "%10u %10d %10d %10d %10d %10d "
2069         "%10"PRId64" %10"PRId64" %10d "
2070         "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
2071         "%6d %6d %5d %5d %5d "
2072         "%10"PRId64" %10.3lf"
2073         "%10lf %8u %10d %10d %10d\n",
2074         cpi->common.current_video_frame, cpi->rc.this_frame_target,
2075         cpi->rc.projected_frame_size,
2076         cpi->rc.projected_frame_size / cpi->common.MBs,
2077         (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2078         cpi->rc.total_target_vs_actual,
2079         (cpi->oxcf.starting_buffer_level - cpi->rc.bits_off_target),
2080         cpi->rc.total_actual_bits, cm->base_qindex,
2081         vp9_convert_qindex_to_q(cm->base_qindex),
2082         (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
2083         cpi->rc.avg_q,
2084         vp9_convert_qindex_to_q(cpi->rc.ni_av_qi),
2085         vp9_convert_qindex_to_q(cpi->cq_target_quality),
2086         cpi->refresh_last_frame, cpi->refresh_golden_frame,
2087         cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2088         cpi->twopass.bits_left,
2089         cpi->twopass.total_left_stats.coded_error,
2090         cpi->twopass.bits_left /
2091             (1 + cpi->twopass.total_left_stats.coded_error),
2092         cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2093         cpi->twopass.kf_zeromotion_pct);
2094
2095   fclose(f);
2096
2097   if (0) {
2098     FILE *const fmodes = fopen("Modes.stt", "a");
2099     int i;
2100
2101     fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2102             cm->frame_type, cpi->refresh_golden_frame,
2103             cpi->refresh_alt_ref_frame);
2104
2105     for (i = 0; i < MAX_MODES; ++i)
2106       fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2107
2108     fprintf(fmodes, "\n");
2109
2110     fclose(fmodes);
2111   }
2112 }
2113 #endif
2114
2115 static void encode_without_recode_loop(VP9_COMP *cpi,
2116                                        size_t *size,
2117                                        uint8_t *dest,
2118                                        int q) {
2119   VP9_COMMON *const cm = &cpi->common;
2120   vp9_clear_system_state();
2121   vp9_set_quantizer(cm, q);
2122
2123   // Set up entropy context depending on frame type. The decoder mandates
2124   // the use of the default context, index 0, for keyframes and inter
2125   // frames where the error_resilient_mode or intra_only flag is set. For
2126   // other inter-frames the encoder currently uses only two contexts;
2127   // context 1 for ALTREF frames and context 0 for the others.
2128   if (cm->frame_type == KEY_FRAME) {
2129     setup_key_frame(cpi);
2130   } else {
2131     if (!cm->intra_only && !cm->error_resilient_mode && !cpi->use_svc)
2132       cm->frame_context_idx = cpi->refresh_alt_ref_frame;
2133
2134     setup_inter_frame(cm);
2135   }
2136   // Variance adaptive and in frame q adjustment experiments are mutually
2137   // exclusive.
2138   if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2139     vp9_vaq_frame_setup(cpi);
2140   } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
2141     vp9_setup_in_frame_q_adj(cpi);
2142   } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
2143     vp9_cyclic_refresh_setup(cpi);
2144   }
2145   // transform / motion compensation build reconstruction frame
2146   vp9_encode_frame(cpi);
2147
2148   // Update the skip mb flag probabilities based on the distribution
2149   // seen in the last encoder iteration.
2150   // update_base_skip_probs(cpi);
2151   vp9_clear_system_state();
2152 }
2153
2154 static void encode_with_recode_loop(VP9_COMP *cpi,
2155                                     size_t *size,
2156                                     uint8_t *dest,
2157                                     int q,
2158                                     int bottom_index,
2159                                     int top_index) {
2160   VP9_COMMON *const cm = &cpi->common;
2161   RATE_CONTROL *const rc = &cpi->rc;
2162   int loop_count = 0;
2163   int loop = 0;
2164   int overshoot_seen = 0;
2165   int undershoot_seen = 0;
2166   int q_low = bottom_index, q_high = top_index;
2167   int frame_over_shoot_limit;
2168   int frame_under_shoot_limit;
2169
2170   // Decide frame size bounds
2171   vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
2172                                    &frame_under_shoot_limit,
2173                                    &frame_over_shoot_limit);
2174
2175   do {
2176     vp9_clear_system_state();
2177
2178     vp9_set_quantizer(cm, q);
2179
2180     if (loop_count == 0) {
2181       // Set up entropy context depending on frame type. The decoder mandates
2182       // the use of the default context, index 0, for keyframes and inter
2183       // frames where the error_resilient_mode or intra_only flag is set. For
2184       // other inter-frames the encoder currently uses only two contexts;
2185       // context 1 for ALTREF frames and context 0 for the others.
2186       if (cm->frame_type == KEY_FRAME) {
2187         setup_key_frame(cpi);
2188       } else {
2189         if (!cm->intra_only && !cm->error_resilient_mode && !cpi->use_svc)
2190           cpi->common.frame_context_idx = cpi->refresh_alt_ref_frame;
2191
2192         setup_inter_frame(cm);
2193       }
2194     }
2195
2196     // Variance adaptive and in frame q adjustment experiments are mutually
2197     // exclusive.
2198     if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2199       vp9_vaq_frame_setup(cpi);
2200     } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
2201       vp9_setup_in_frame_q_adj(cpi);
2202     }
2203
2204     // transform / motion compensation build reconstruction frame
2205     vp9_encode_frame(cpi);
2206
2207     // Update the skip mb flag probabilities based on the distribution
2208     // seen in the last encoder iteration.
2209     // update_base_skip_probs(cpi);
2210
2211     vp9_clear_system_state();
2212
2213     // Dummy pack of the bitstream using up to date stats to get an
2214     // accurate estimate of output frame size to determine if we need
2215     // to recode.
2216     if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
2217       save_coding_context(cpi);
2218       cpi->dummy_packing = 1;
2219       if (!cpi->sf.use_nonrd_pick_mode)
2220         vp9_pack_bitstream(cpi, dest, size);
2221
2222       rc->projected_frame_size = (int)(*size) << 3;
2223       restore_coding_context(cpi);
2224
2225       if (frame_over_shoot_limit == 0)
2226         frame_over_shoot_limit = 1;
2227     }
2228
2229     if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2230       loop = 0;
2231     } else {
2232       if ((cm->frame_type == KEY_FRAME) &&
2233            rc->this_key_frame_forced &&
2234            (rc->projected_frame_size < rc->max_frame_bandwidth)) {
2235         int last_q = q;
2236         int kf_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2237
2238         int high_err_target = cpi->ambient_err;
2239         int low_err_target = cpi->ambient_err >> 1;
2240
2241         // Prevent possible divide by zero error below for perfect KF
2242         kf_err += !kf_err;
2243
2244         // The key frame is not good enough or we can afford
2245         // to make it better without undue risk of popping.
2246         if ((kf_err > high_err_target &&
2247              rc->projected_frame_size <= frame_over_shoot_limit) ||
2248             (kf_err > low_err_target &&
2249              rc->projected_frame_size <= frame_under_shoot_limit)) {
2250           // Lower q_high
2251           q_high = q > q_low ? q - 1 : q_low;
2252
2253           // Adjust Q
2254           q = (q * high_err_target) / kf_err;
2255           q = MIN(q, (q_high + q_low) >> 1);
2256         } else if (kf_err < low_err_target &&
2257                    rc->projected_frame_size >= frame_under_shoot_limit) {
2258           // The key frame is much better than the previous frame
2259           // Raise q_low
2260           q_low = q < q_high ? q + 1 : q_high;
2261
2262           // Adjust Q
2263           q = (q * low_err_target) / kf_err;
2264           q = MIN(q, (q_high + q_low + 1) >> 1);
2265         }
2266
2267         // Clamp Q to upper and lower limits:
2268         q = clamp(q, q_low, q_high);
2269
2270         loop = q != last_q;
2271       } else if (recode_loop_test(
2272           cpi, frame_over_shoot_limit, frame_under_shoot_limit,
2273           q, MAX(q_high, top_index), bottom_index)) {
2274         // Is the projected frame size out of range and are we allowed
2275         // to attempt to recode.
2276         int last_q = q;
2277         int retries = 0;
2278
2279         // Frame size out of permitted range:
2280         // Update correction factor & compute new Q to try...
2281
2282         // Frame is too large
2283         if (rc->projected_frame_size > rc->this_frame_target) {
2284           // Special case if the projected size is > the max allowed.
2285           if (rc->projected_frame_size >= rc->max_frame_bandwidth)
2286             q_high = rc->worst_quality;
2287
2288           // Raise Qlow as to at least the current value
2289           q_low = q < q_high ? q + 1 : q_high;
2290
2291           if (undershoot_seen || loop_count > 1) {
2292             // Update rate_correction_factor unless
2293             vp9_rc_update_rate_correction_factors(cpi, 1);
2294
2295             q = (q_high + q_low + 1) / 2;
2296           } else {
2297             // Update rate_correction_factor unless
2298             vp9_rc_update_rate_correction_factors(cpi, 0);
2299
2300             q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
2301                                    bottom_index, MAX(q_high, top_index));
2302
2303             while (q < q_low && retries < 10) {
2304               vp9_rc_update_rate_correction_factors(cpi, 0);
2305               q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
2306                                      bottom_index, MAX(q_high, top_index));
2307               retries++;
2308             }
2309           }
2310
2311           overshoot_seen = 1;
2312         } else {
2313           // Frame is too small
2314           q_high = q > q_low ? q - 1 : q_low;
2315
2316           if (overshoot_seen || loop_count > 1) {
2317             vp9_rc_update_rate_correction_factors(cpi, 1);
2318             q = (q_high + q_low) / 2;
2319           } else {
2320             vp9_rc_update_rate_correction_factors(cpi, 0);
2321             q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
2322                                    bottom_index, top_index);
2323             // Special case reset for qlow for constrained quality.
2324             // This should only trigger where there is very substantial
2325             // undershoot on a frame and the auto cq level is above
2326             // the user passsed in value.
2327             if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY &&
2328                 q < q_low) {
2329               q_low = q;
2330             }
2331
2332             while (q > q_high && retries < 10) {
2333               vp9_rc_update_rate_correction_factors(cpi, 0);
2334               q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
2335                                      bottom_index, top_index);
2336               retries++;
2337             }
2338           }
2339
2340           undershoot_seen = 1;
2341         }
2342
2343         // Clamp Q to upper and lower limits:
2344         q = clamp(q, q_low, q_high);
2345
2346         loop = q != last_q;
2347       } else {
2348         loop = 0;
2349       }
2350     }
2351
2352     // Special case for overlay frame.
2353     if (rc->is_src_frame_alt_ref &&
2354         rc->projected_frame_size < rc->max_frame_bandwidth)
2355       loop = 0;
2356
2357     if (loop) {
2358       loop_count++;
2359
2360 #if CONFIG_INTERNAL_STATS
2361       cpi->tot_recode_hits++;
2362 #endif
2363     }
2364   } while (loop);
2365 }
2366
2367 static void get_ref_frame_flags(VP9_COMP *cpi) {
2368   if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
2369     cpi->gold_is_last = 1;
2370   else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
2371     cpi->gold_is_last = 0;
2372
2373   if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
2374     cpi->alt_is_last = 1;
2375   else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
2376     cpi->alt_is_last = 0;
2377
2378   if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
2379     cpi->gold_is_alt = 1;
2380   else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
2381     cpi->gold_is_alt = 0;
2382
2383   cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
2384
2385   if (cpi->gold_is_last)
2386     cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
2387
2388   if (cpi->rc.frames_till_gf_update_due == INT_MAX)
2389     cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
2390
2391   if (cpi->alt_is_last)
2392     cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
2393
2394   if (cpi->gold_is_alt)
2395     cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
2396 }
2397
2398 static void set_ext_overrides(VP9_COMP *cpi) {
2399   // Overrides the defaults with the externally supplied values with
2400   // vp9_update_reference() and vp9_update_entropy() calls
2401   // Note: The overrides are valid only for the next frame passed
2402   // to encode_frame_to_data_rate() function
2403   if (cpi->ext_refresh_frame_context_pending) {
2404     cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
2405     cpi->ext_refresh_frame_context_pending = 0;
2406   }
2407   if (cpi->ext_refresh_frame_flags_pending) {
2408     cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
2409     cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
2410     cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
2411     cpi->ext_refresh_frame_flags_pending = 0;
2412   }
2413 }
2414
2415 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2416                                       size_t *size,
2417                                       uint8_t *dest,
2418                                       unsigned int *frame_flags) {
2419   VP9_COMMON *const cm = &cpi->common;
2420   TX_SIZE t;
2421   int q;
2422   int top_index;
2423   int bottom_index;
2424
2425   const SPEED_FEATURES *const sf = &cpi->sf;
2426   const unsigned int max_mv_def = MIN(cm->width, cm->height);
2427   struct segmentation *const seg = &cm->seg;
2428
2429   set_ext_overrides(cpi);
2430
2431   /* Scale the source buffer, if required. */
2432   if (cm->mi_cols * MI_SIZE != cpi->un_scaled_source->y_width ||
2433       cm->mi_rows * MI_SIZE != cpi->un_scaled_source->y_height) {
2434     scale_and_extend_frame_nonnormative(cpi->un_scaled_source,
2435                                         &cpi->scaled_source);
2436     cpi->Source = &cpi->scaled_source;
2437   } else {
2438     cpi->Source = cpi->un_scaled_source;
2439   }
2440
2441   // Scale the last source buffer, if required.
2442   if (cpi->unscaled_last_source != NULL) {
2443     if (cm->mi_cols * MI_SIZE != cpi->unscaled_last_source->y_width ||
2444         cm->mi_rows * MI_SIZE != cpi->unscaled_last_source->y_height) {
2445       scale_and_extend_frame_nonnormative(cpi->unscaled_last_source,
2446                                           &cpi->scaled_last_source);
2447       cpi->Last_Source = &cpi->scaled_last_source;
2448     } else {
2449       cpi->Last_Source = cpi->unscaled_last_source;
2450     }
2451   }
2452
2453   vp9_scale_references(cpi);
2454
2455   vp9_clear_system_state();
2456
2457   // Enable or disable mode based tweaking of the zbin.
2458   // For 2 pass only used where GF/ARF prediction quality
2459   // is above a threshold.
2460   cpi->zbin_mode_boost = 0;
2461   cpi->zbin_mode_boost_enabled = 0;
2462
2463   // Current default encoder behavior for the altref sign bias.
2464   cm->ref_frame_sign_bias[ALTREF_FRAME] = cpi->rc.source_alt_ref_active;
2465
2466   // Set default state for segment based loop filter update flags.
2467   cm->lf.mode_ref_delta_update = 0;
2468
2469   // Initialize cpi->mv_step_param to default based on max resolution.
2470   cpi->mv_step_param = vp9_init_search_range(cpi, max_mv_def);
2471   // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2472   if (sf->auto_mv_step_size) {
2473     if (frame_is_intra_only(cm)) {
2474       // Initialize max_mv_magnitude for use in the first INTER frame
2475       // after a key/intra-only frame.
2476       cpi->max_mv_magnitude = max_mv_def;
2477     } else {
2478       if (cm->show_frame)
2479         // Allow mv_steps to correspond to twice the max mv magnitude found
2480         // in the previous frame, capped by the default max_mv_magnitude based
2481         // on resolution.
2482         cpi->mv_step_param = vp9_init_search_range(cpi, MIN(max_mv_def, 2 *
2483                                  cpi->max_mv_magnitude));
2484       cpi->max_mv_magnitude = 0;
2485     }
2486   }
2487
2488   // Set various flags etc to special state if it is a key frame.
2489   if (frame_is_intra_only(cm)) {
2490     setup_key_frame(cpi);
2491     // Reset the loop filter deltas and segmentation map.
2492     vp9_reset_segment_features(&cm->seg);
2493
2494     // If segmentation is enabled force a map update for key frames.
2495     if (seg->enabled) {
2496       seg->update_map = 1;
2497       seg->update_data = 1;
2498     }
2499
2500     // The alternate reference frame cannot be active for a key frame.
2501     cpi->rc.source_alt_ref_active = 0;
2502
2503     cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2504     cm->frame_parallel_decoding_mode =
2505       (cpi->oxcf.frame_parallel_decoding_mode != 0);
2506
2507     // By default, encoder assumes decoder can use prev_mi.
2508     cm->coding_use_prev_mi = 1;
2509     if (cm->error_resilient_mode) {
2510       cm->coding_use_prev_mi = 0;
2511       cm->frame_parallel_decoding_mode = 1;
2512       cm->reset_frame_context = 0;
2513       cm->refresh_frame_context = 0;
2514     } else if (cm->intra_only) {
2515       // Only reset the current context.
2516       cm->reset_frame_context = 2;
2517     }
2518   }
2519
2520   // Configure experimental use of segmentation for enhanced coding of
2521   // static regions if indicated.
2522   // Only allowed in second pass of two pass (as requires lagged coding)
2523   // and if the relevant speed feature flag is set.
2524   if (cpi->pass == 2 && cpi->sf.static_segmentation)
2525     configure_static_seg_features(cpi);
2526
2527   // For 1 pass CBR, check if we are dropping this frame.
2528   // Never drop on key frame.
2529   if (cpi->pass == 0 &&
2530       cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
2531       cm->frame_type != KEY_FRAME) {
2532     if (vp9_rc_drop_frame(cpi)) {
2533       vp9_rc_postencode_update_drop_frame(cpi);
2534       ++cm->current_video_frame;
2535       return;
2536     }
2537   }
2538
2539   vp9_clear_system_state();
2540
2541   vp9_zero(cpi->rd_tx_select_threshes);
2542
2543 #if CONFIG_VP9_POSTPROC
2544   if (cpi->oxcf.noise_sensitivity > 0) {
2545     int l = 0;
2546     switch (cpi->oxcf.noise_sensitivity) {
2547       case 1:
2548         l = 20;
2549         break;
2550       case 2:
2551         l = 40;
2552         break;
2553       case 3:
2554         l = 60;
2555         break;
2556       case 4:
2557       case 5:
2558         l = 100;
2559         break;
2560       case 6:
2561         l = 150;
2562         break;
2563     }
2564     vp9_denoise(cpi->Source, cpi->Source, l);
2565   }
2566 #endif
2567
2568 #ifdef OUTPUT_YUV_SRC
2569   vp9_write_yuv_frame(cpi->Source);
2570 #endif
2571
2572   set_speed_features(cpi);
2573
2574   // Decide q and q bounds.
2575   q = vp9_rc_pick_q_and_bounds(cpi, &bottom_index, &top_index);
2576
2577   if (!frame_is_intra_only(cm)) {
2578     cm->interp_filter = DEFAULT_INTERP_FILTER;
2579     /* TODO: Decide this more intelligently */
2580     set_high_precision_mv(cpi, q < HIGH_PRECISION_MV_QTHRESH);
2581   }
2582
2583   if (cpi->sf.recode_loop == DISALLOW_RECODE) {
2584     encode_without_recode_loop(cpi, size, dest, q);
2585   } else {
2586     encode_with_recode_loop(cpi, size, dest, q, bottom_index, top_index);
2587   }
2588
2589   // Special case code to reduce pulsing when key frames are forced at a
2590   // fixed interval. Note the reconstruction error if it is the frame before
2591   // the force key frame
2592   if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
2593     cpi->ambient_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2594   }
2595
2596   // If the encoder forced a KEY_FRAME decision
2597   if (cm->frame_type == KEY_FRAME)
2598     cpi->refresh_last_frame = 1;
2599
2600   cm->frame_to_show = get_frame_new_buffer(cm);
2601
2602 #if WRITE_RECON_BUFFER
2603   if (cm->show_frame)
2604     write_cx_frame_to_file(cm->frame_to_show,
2605                            cm->current_video_frame);
2606   else
2607     write_cx_frame_to_file(cm->frame_to_show,
2608                            cm->current_video_frame + 1000);
2609 #endif
2610
2611   // Pick the loop filter level for the frame.
2612   loopfilter_frame(cpi, cm);
2613
2614 #if WRITE_RECON_BUFFER
2615   if (cm->show_frame)
2616     write_cx_frame_to_file(cm->frame_to_show,
2617                            cm->current_video_frame + 2000);
2618   else
2619     write_cx_frame_to_file(cm->frame_to_show,
2620                            cm->current_video_frame + 3000);
2621 #endif
2622
2623   // build the bitstream
2624   cpi->dummy_packing = 0;
2625   vp9_pack_bitstream(cpi, dest, size);
2626
2627   if (cm->seg.update_map)
2628     update_reference_segmentation_map(cpi);
2629
2630   release_scaled_references(cpi);
2631   vp9_update_reference_frames(cpi);
2632
2633   for (t = TX_4X4; t <= TX_32X32; t++)
2634     full_to_model_counts(cm->counts.coef[t], cpi->coef_counts[t]);
2635
2636   if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
2637     vp9_adapt_coef_probs(cm);
2638
2639   if (!frame_is_intra_only(cm)) {
2640     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2641       vp9_adapt_mode_probs(cm);
2642       vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2643     }
2644   }
2645
2646 #if 0
2647   output_frame_level_debug_stats(cpi);
2648 #endif
2649   if (cpi->refresh_golden_frame == 1)
2650     cm->frame_flags |= FRAMEFLAGS_GOLDEN;
2651   else
2652     cm->frame_flags &= ~FRAMEFLAGS_GOLDEN;
2653
2654   if (cpi->refresh_alt_ref_frame == 1)
2655     cm->frame_flags |= FRAMEFLAGS_ALTREF;
2656   else
2657     cm->frame_flags &= ~FRAMEFLAGS_ALTREF;
2658
2659   get_ref_frame_flags(cpi);
2660
2661   vp9_rc_postencode_update(cpi, *size);
2662
2663   if (cm->frame_type == KEY_FRAME) {
2664     // Tell the caller that the frame was coded as a key frame
2665     *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
2666
2667 #if CONFIG_MULTIPLE_ARF
2668     // Reset the sequence number.
2669     if (cpi->multi_arf_enabled) {
2670       cpi->sequence_number = 0;
2671       cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
2672       cpi->new_frame_coding_order_period = -1;
2673     }
2674 #endif
2675   } else {
2676     *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
2677
2678 #if CONFIG_MULTIPLE_ARF
2679     /* Increment position in the coded frame sequence. */
2680     if (cpi->multi_arf_enabled) {
2681       ++cpi->sequence_number;
2682       if (cpi->sequence_number >= cpi->frame_coding_order_period) {
2683         cpi->sequence_number = 0;
2684         cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
2685         cpi->new_frame_coding_order_period = -1;
2686       }
2687       cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
2688       assert(cpi->this_frame_weight >= 0);
2689     }
2690 #endif
2691   }
2692
2693   // Clear the one shot update flags for segmentation map and mode/ref loop
2694   // filter deltas.
2695   cm->seg.update_map = 0;
2696   cm->seg.update_data = 0;
2697   cm->lf.mode_ref_delta_update = 0;
2698
2699   // keep track of the last coded dimensions
2700   cm->last_width = cm->width;
2701   cm->last_height = cm->height;
2702
2703   // reset to normal state now that we are done.
2704   if (!cm->show_existing_frame)
2705     cm->last_show_frame = cm->show_frame;
2706
2707   if (cm->show_frame) {
2708     vp9_swap_mi_and_prev_mi(cm);
2709
2710     // Don't increment frame counters if this was an altref buffer
2711     // update not a real frame
2712     ++cm->current_video_frame;
2713     if (cpi->use_svc)
2714       vp9_inc_frame_in_layer(&cpi->svc);
2715   }
2716 }
2717
2718 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2719                       unsigned int *frame_flags) {
2720   vp9_rc_get_svc_params(cpi);
2721   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2722 }
2723
2724 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2725                         unsigned int *frame_flags) {
2726   if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
2727     vp9_rc_get_one_pass_cbr_params(cpi);
2728   } else {
2729     vp9_rc_get_one_pass_vbr_params(cpi);
2730   }
2731   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2732 }
2733
2734 static void Pass1Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2735                         unsigned int *frame_flags) {
2736   (void) size;
2737   (void) dest;
2738   (void) frame_flags;
2739
2740   vp9_rc_get_first_pass_params(cpi);
2741   vp9_set_quantizer(&cpi->common, find_fp_qindex());
2742   vp9_first_pass(cpi);
2743 }
2744
2745 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
2746                         uint8_t *dest, unsigned int *frame_flags) {
2747   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
2748
2749   vp9_rc_get_second_pass_params(cpi);
2750   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2751
2752   vp9_twopass_postencode_update(cpi);
2753 }
2754
2755 static void check_initial_width(VP9_COMP *cpi, int subsampling_x,
2756                                 int subsampling_y) {
2757   VP9_COMMON *const cm = &cpi->common;
2758
2759   if (!cpi->initial_width) {
2760     cm->subsampling_x = subsampling_x;
2761     cm->subsampling_y = subsampling_y;
2762     alloc_raw_frame_buffers(cpi);
2763     cpi->initial_width = cm->width;
2764     cpi->initial_height = cm->height;
2765   }
2766 }
2767
2768
2769 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
2770                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
2771                           int64_t end_time) {
2772   VP9_COMMON *cm = &cpi->common;
2773   struct vpx_usec_timer timer;
2774   int res = 0;
2775   const int subsampling_x = sd->uv_width  < sd->y_width;
2776   const int subsampling_y = sd->uv_height < sd->y_height;
2777
2778   check_initial_width(cpi, subsampling_x, subsampling_y);
2779   vpx_usec_timer_start(&timer);
2780   if (vp9_lookahead_push(cpi->lookahead,
2781                          sd, time_stamp, end_time, frame_flags))
2782     res = -1;
2783   vpx_usec_timer_mark(&timer);
2784   cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
2785
2786   if (cm->profile == PROFILE_0 && (subsampling_x != 1 || subsampling_y != 1)) {
2787     vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
2788                        "Non-4:2:0 color space requires profile >= 1");
2789     res = -1;
2790   }
2791
2792   return res;
2793 }
2794
2795
2796 static int frame_is_reference(const VP9_COMP *cpi) {
2797   const VP9_COMMON *cm = &cpi->common;
2798
2799   return cm->frame_type == KEY_FRAME ||
2800          cpi->refresh_last_frame ||
2801          cpi->refresh_golden_frame ||
2802          cpi->refresh_alt_ref_frame ||
2803          cm->refresh_frame_context ||
2804          cm->lf.mode_ref_delta_update ||
2805          cm->seg.update_map ||
2806          cm->seg.update_data;
2807 }
2808
2809 #if CONFIG_MULTIPLE_ARF
2810 int is_next_frame_arf(VP9_COMP *cpi) {
2811   // Negative entry in frame_coding_order indicates an ARF at this position.
2812   return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
2813 }
2814 #endif
2815
2816 void adjust_frame_rate(VP9_COMP *cpi) {
2817   int64_t this_duration;
2818   int step = 0;
2819
2820   if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
2821     this_duration = cpi->source->ts_end - cpi->source->ts_start;
2822     step = 1;
2823   } else {
2824     int64_t last_duration = cpi->last_end_time_stamp_seen
2825         - cpi->last_time_stamp_seen;
2826
2827     this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
2828
2829     // do a step update if the duration changes by 10%
2830     if (last_duration)
2831       step = (int)((this_duration - last_duration) * 10 / last_duration);
2832   }
2833
2834   if (this_duration) {
2835     if (step) {
2836       vp9_new_framerate(cpi, 10000000.0 / this_duration);
2837     } else {
2838       // Average this frame's rate into the last second's average
2839       // frame rate. If we haven't seen 1 second yet, then average
2840       // over the whole interval seen.
2841       const double interval = MIN((double)(cpi->source->ts_end
2842                                    - cpi->first_time_stamp_ever), 10000000.0);
2843       double avg_duration = 10000000.0 / cpi->oxcf.framerate;
2844       avg_duration *= (interval - avg_duration + this_duration);
2845       avg_duration /= interval;
2846
2847       vp9_new_framerate(cpi, 10000000.0 / avg_duration);
2848     }
2849   }
2850   cpi->last_time_stamp_seen = cpi->source->ts_start;
2851   cpi->last_end_time_stamp_seen = cpi->source->ts_end;
2852 }
2853
2854 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
2855                             size_t *size, uint8_t *dest,
2856                             int64_t *time_stamp, int64_t *time_end, int flush) {
2857   VP9_COMMON *const cm = &cpi->common;
2858   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
2859   RATE_CONTROL *const rc = &cpi->rc;
2860   struct vpx_usec_timer  cmptimer;
2861   YV12_BUFFER_CONFIG *force_src_buffer = NULL;
2862   MV_REFERENCE_FRAME ref_frame;
2863
2864   if (!cpi)
2865     return -1;
2866
2867   if (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2) {
2868     vp9_restore_layer_context(cpi);
2869   }
2870
2871   vpx_usec_timer_start(&cmptimer);
2872
2873   cpi->source = NULL;
2874   cpi->last_source = NULL;
2875
2876   set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
2877
2878   // Normal defaults
2879   cm->reset_frame_context = 0;
2880   cm->refresh_frame_context = 1;
2881   cpi->refresh_last_frame = 1;
2882   cpi->refresh_golden_frame = 0;
2883   cpi->refresh_alt_ref_frame = 0;
2884
2885   // Should we code an alternate reference frame.
2886   if (cpi->oxcf.play_alternate && rc->source_alt_ref_pending) {
2887     int frames_to_arf;
2888
2889 #if CONFIG_MULTIPLE_ARF
2890     assert(!cpi->multi_arf_enabled ||
2891            cpi->frame_coding_order[cpi->sequence_number] < 0);
2892
2893     if (cpi->multi_arf_enabled && (cpi->pass == 2))
2894       frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
2895           - cpi->next_frame_in_order;
2896     else
2897 #endif
2898       frames_to_arf = rc->frames_till_gf_update_due;
2899
2900     assert(frames_to_arf <= rc->frames_to_key);
2901
2902     if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
2903 #if CONFIG_MULTIPLE_ARF
2904       cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
2905 #else
2906       cpi->alt_ref_source = cpi->source;
2907 #endif
2908
2909       if (cpi->oxcf.arnr_max_frames > 0) {
2910         // Produce the filtered ARF frame.
2911         // TODO(agrange) merge these two functions.
2912         vp9_configure_arnr_filter(cpi, frames_to_arf, rc->gfu_boost);
2913         vp9_temporal_filter_prepare(cpi, frames_to_arf);
2914         vp9_extend_frame_borders(&cpi->alt_ref_buffer);
2915         force_src_buffer = &cpi->alt_ref_buffer;
2916       }
2917
2918       cm->show_frame = 0;
2919       cpi->refresh_alt_ref_frame = 1;
2920       cpi->refresh_golden_frame = 0;
2921       cpi->refresh_last_frame = 0;
2922       rc->is_src_frame_alt_ref = 0;
2923
2924 #if CONFIG_MULTIPLE_ARF
2925       if (!cpi->multi_arf_enabled)
2926 #endif
2927         rc->source_alt_ref_pending = 0;
2928     } else {
2929       rc->source_alt_ref_pending = 0;
2930     }
2931   }
2932
2933   if (!cpi->source) {
2934 #if CONFIG_MULTIPLE_ARF
2935     int i;
2936 #endif
2937
2938     // Get last frame source.
2939     if (cm->current_video_frame > 0) {
2940       if ((cpi->last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
2941         return -1;
2942     }
2943
2944     if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
2945       cm->show_frame = 1;
2946       cm->intra_only = 0;
2947
2948 #if CONFIG_MULTIPLE_ARF
2949       // Is this frame the ARF overlay.
2950       rc->is_src_frame_alt_ref = 0;
2951       for (i = 0; i < cpi->arf_buffered; ++i) {
2952         if (cpi->source == cpi->alt_ref_source[i]) {
2953           rc->is_src_frame_alt_ref = 1;
2954           cpi->refresh_golden_frame = 1;
2955           break;
2956         }
2957       }
2958 #else
2959       rc->is_src_frame_alt_ref = cpi->alt_ref_source &&
2960                                  (cpi->source == cpi->alt_ref_source);
2961 #endif
2962       if (rc->is_src_frame_alt_ref) {
2963         // Current frame is an ARF overlay frame.
2964 #if CONFIG_MULTIPLE_ARF
2965         cpi->alt_ref_source[i] = NULL;
2966 #else
2967         cpi->alt_ref_source = NULL;
2968 #endif
2969         // Don't refresh the last buffer for an ARF overlay frame. It will
2970         // become the GF so preserve last as an alternative prediction option.
2971         cpi->refresh_last_frame = 0;
2972       }
2973 #if CONFIG_MULTIPLE_ARF
2974       ++cpi->next_frame_in_order;
2975 #endif
2976     }
2977   }
2978
2979   if (cpi->source) {
2980     cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
2981                                                            : &cpi->source->img;
2982
2983   if (cpi->last_source != NULL) {
2984     cpi->unscaled_last_source = &cpi->last_source->img;
2985   } else {
2986     cpi->unscaled_last_source = NULL;
2987   }
2988
2989     *time_stamp = cpi->source->ts_start;
2990     *time_end = cpi->source->ts_end;
2991     *frame_flags = cpi->source->flags;
2992
2993 #if CONFIG_MULTIPLE_ARF
2994     if (cm->frame_type != KEY_FRAME && cpi->pass == 2)
2995       rc->source_alt_ref_pending = is_next_frame_arf(cpi);
2996 #endif
2997   } else {
2998     *size = 0;
2999     if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
3000       vp9_end_first_pass(cpi);    /* get last stats packet */
3001       cpi->twopass.first_pass_done = 1;
3002     }
3003     return -1;
3004   }
3005
3006   if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
3007     cpi->first_time_stamp_ever = cpi->source->ts_start;
3008     cpi->last_end_time_stamp_seen = cpi->source->ts_start;
3009   }
3010
3011   // adjust frame rates based on timestamps given
3012   if (cm->show_frame) {
3013     adjust_frame_rate(cpi);
3014   }
3015
3016   if (cpi->svc.number_temporal_layers > 1 &&
3017       cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
3018     vp9_update_temporal_layer_framerate(cpi);
3019     vp9_restore_layer_context(cpi);
3020   }
3021
3022   // start with a 0 size frame
3023   *size = 0;
3024
3025   // Clear down mmx registers
3026   vp9_clear_system_state();
3027
3028   /* find a free buffer for the new frame, releasing the reference previously
3029    * held.
3030    */
3031   cm->frame_bufs[cm->new_fb_idx].ref_count--;
3032   cm->new_fb_idx = get_free_fb(cm);
3033
3034 #if CONFIG_MULTIPLE_ARF
3035   /* Set up the correct ARF frame. */
3036   if (cpi->refresh_alt_ref_frame) {
3037     ++cpi->arf_buffered;
3038   }
3039   if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
3040       (cpi->pass == 2)) {
3041     cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
3042   }
3043 #endif
3044
3045   cm->frame_flags = *frame_flags;
3046
3047   // Reset the frame pointers to the current frame size
3048   vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
3049                            cm->width, cm->height,
3050                            cm->subsampling_x, cm->subsampling_y,
3051                            VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
3052
3053   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3054     const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
3055     YV12_BUFFER_CONFIG *const buf = &cm->frame_bufs[idx].buf;
3056     RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3057     ref_buf->buf = buf;
3058     ref_buf->idx = idx;
3059     vp9_setup_scale_factors_for_frame(&ref_buf->sf,
3060                                       buf->y_crop_width, buf->y_crop_height,
3061                                       cm->width, cm->height);
3062
3063     if (vp9_is_scaled(&ref_buf->sf))
3064       vp9_extend_frame_borders(buf);
3065   }
3066
3067   set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
3068
3069   if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3070     vp9_vaq_init();
3071   }
3072
3073   if (cpi->pass == 1 &&
3074       (!cpi->use_svc || cpi->svc.number_temporal_layers == 1)) {
3075     Pass1Encode(cpi, size, dest, frame_flags);
3076   } else if (cpi->pass == 2 &&
3077       (!cpi->use_svc || cpi->svc.number_temporal_layers == 1)) {
3078     Pass2Encode(cpi, size, dest, frame_flags);
3079   } else if (cpi->use_svc) {
3080     SvcEncode(cpi, size, dest, frame_flags);
3081   } else {
3082     // One pass encode
3083     Pass0Encode(cpi, size, dest, frame_flags);
3084   }
3085
3086   if (cm->refresh_frame_context)
3087     cm->frame_contexts[cm->frame_context_idx] = cm->fc;
3088
3089   // Frame was dropped, release scaled references.
3090   if (*size == 0) {
3091     release_scaled_references(cpi);
3092   }
3093
3094   if (*size > 0) {
3095     cpi->droppable = !frame_is_reference(cpi);
3096   }
3097
3098   // Save layer specific state.
3099   if ((cpi->svc.number_temporal_layers > 1 &&
3100       cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) ||
3101       (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2)) {
3102     vp9_save_layer_context(cpi);
3103   }
3104
3105   vpx_usec_timer_mark(&cmptimer);
3106   cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
3107
3108   if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
3109     generate_psnr_packet(cpi);
3110
3111 #if CONFIG_INTERNAL_STATS
3112
3113   if (cpi->pass != 1) {
3114     cpi->bytes += (int)(*size);
3115
3116     if (cm->show_frame) {
3117       cpi->count++;
3118
3119       if (cpi->b_calculate_psnr) {
3120         YV12_BUFFER_CONFIG *orig = cpi->Source;
3121         YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
3122         YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
3123         PSNR_STATS psnr;
3124         calc_psnr(orig, recon, &psnr);
3125
3126         cpi->total += psnr.psnr[0];
3127         cpi->total_y += psnr.psnr[1];
3128         cpi->total_u += psnr.psnr[2];
3129         cpi->total_v += psnr.psnr[3];
3130         cpi->total_sq_error += psnr.sse[0];
3131         cpi->total_samples += psnr.samples[0];
3132
3133         {
3134           PSNR_STATS psnr2;
3135           double frame_ssim2 = 0, weight = 0;
3136 #if CONFIG_VP9_POSTPROC
3137           vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
3138                       cm->lf.filter_level * 10 / 6);
3139 #endif
3140           vp9_clear_system_state();
3141
3142           calc_psnr(orig, pp, &psnr2);
3143
3144           cpi->totalp += psnr2.psnr[0];
3145           cpi->totalp_y += psnr2.psnr[1];
3146           cpi->totalp_u += psnr2.psnr[2];
3147           cpi->totalp_v += psnr2.psnr[3];
3148           cpi->totalp_sq_error += psnr2.sse[0];
3149           cpi->totalp_samples += psnr2.samples[0];
3150
3151           frame_ssim2 = vp9_calc_ssim(orig, recon, 1, &weight);
3152
3153           cpi->summed_quality += frame_ssim2 * weight;
3154           cpi->summed_weights += weight;
3155
3156           frame_ssim2 = vp9_calc_ssim(orig, &cm->post_proc_buffer, 1, &weight);
3157
3158           cpi->summedp_quality += frame_ssim2 * weight;
3159           cpi->summedp_weights += weight;
3160 #if 0
3161           {
3162             FILE *f = fopen("q_used.stt", "a");
3163             fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
3164                     cpi->common.current_video_frame, y2, u2, v2,
3165                     frame_psnr2, frame_ssim2);
3166             fclose(f);
3167           }
3168 #endif
3169         }
3170       }
3171
3172       if (cpi->b_calculate_ssimg) {
3173         double y, u, v, frame_all;
3174         frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u, &v);
3175         cpi->total_ssimg_y += y;
3176         cpi->total_ssimg_u += u;
3177         cpi->total_ssimg_v += v;
3178         cpi->total_ssimg_all += frame_all;
3179       }
3180     }
3181   }
3182
3183 #endif
3184   return 0;
3185 }
3186
3187 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
3188                               vp9_ppflags_t *flags) {
3189   VP9_COMMON *cm = &cpi->common;
3190
3191   if (!cm->show_frame) {
3192     return -1;
3193   } else {
3194     int ret;
3195 #if CONFIG_VP9_POSTPROC
3196     ret = vp9_post_proc_frame(cm, dest, flags);
3197 #else
3198
3199     if (cm->frame_to_show) {
3200       *dest = *cm->frame_to_show;
3201       dest->y_width = cm->width;
3202       dest->y_height = cm->height;
3203       dest->uv_width = cm->width >> cm->subsampling_x;
3204       dest->uv_height = cm->height >> cm->subsampling_y;
3205       ret = 0;
3206     } else {
3207       ret = -1;
3208     }
3209
3210 #endif  // !CONFIG_VP9_POSTPROC
3211     vp9_clear_system_state();
3212     return ret;
3213   }
3214 }
3215
3216 int vp9_set_roimap(VP9_COMP *cpi, unsigned char *map, unsigned int rows,
3217                    unsigned int cols, int delta_q[MAX_SEGMENTS],
3218                    int delta_lf[MAX_SEGMENTS],
3219                    unsigned int threshold[MAX_SEGMENTS]) {
3220   signed char feature_data[SEG_LVL_MAX][MAX_SEGMENTS];
3221   struct segmentation *seg = &cpi->common.seg;
3222   int i;
3223
3224   if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
3225     return -1;
3226
3227   if (!map) {
3228     vp9_disable_segmentation(seg);
3229     return 0;
3230   }
3231
3232   // Set the segmentation Map
3233   vp9_set_segmentation_map(cpi, map);
3234
3235   // Activate segmentation.
3236   vp9_enable_segmentation(seg);
3237
3238   // Set up the quant, LF and breakout threshold segment data
3239   for (i = 0; i < MAX_SEGMENTS; i++) {
3240     feature_data[SEG_LVL_ALT_Q][i] = delta_q[i];
3241     feature_data[SEG_LVL_ALT_LF][i] = delta_lf[i];
3242     cpi->segment_encode_breakout[i] = threshold[i];
3243   }
3244
3245   // Enable the loop and quant changes in the feature mask
3246   for (i = 0; i < MAX_SEGMENTS; i++) {
3247     if (delta_q[i])
3248       vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
3249     else
3250       vp9_disable_segfeature(seg, i, SEG_LVL_ALT_Q);
3251
3252     if (delta_lf[i])
3253       vp9_enable_segfeature(seg, i, SEG_LVL_ALT_LF);
3254     else
3255       vp9_disable_segfeature(seg, i, SEG_LVL_ALT_LF);
3256   }
3257
3258   // Initialize the feature data structure
3259   // SEGMENT_DELTADATA    0, SEGMENT_ABSDATA      1
3260   vp9_set_segment_data(seg, &feature_data[0][0], SEGMENT_DELTADATA);
3261
3262   return 0;
3263 }
3264
3265 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *map,
3266                        unsigned int rows, unsigned int cols) {
3267   if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
3268     if (map) {
3269       vpx_memcpy(cpi->active_map, map, rows * cols);
3270       cpi->active_map_enabled = 1;
3271     } else {
3272       cpi->active_map_enabled = 0;
3273     }
3274
3275     return 0;
3276   } else {
3277     // cpi->active_map_enabled = 0;
3278     return -1;
3279   }
3280 }
3281
3282 int vp9_set_internal_size(VP9_COMP *cpi,
3283                           VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
3284   VP9_COMMON *cm = &cpi->common;
3285   int hr = 0, hs = 0, vr = 0, vs = 0;
3286
3287   if (horiz_mode > ONETWO || vert_mode > ONETWO)
3288     return -1;
3289
3290   Scale2Ratio(horiz_mode, &hr, &hs);
3291   Scale2Ratio(vert_mode, &vr, &vs);
3292
3293   // always go to the next whole number
3294   cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
3295   cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
3296
3297   assert(cm->width <= cpi->initial_width);
3298   assert(cm->height <= cpi->initial_height);
3299   update_frame_size(cpi);
3300   return 0;
3301 }
3302
3303 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
3304                          unsigned int height) {
3305   VP9_COMMON *cm = &cpi->common;
3306
3307   check_initial_width(cpi, 1, 1);
3308
3309   if (width) {
3310     cm->width = width;
3311     if (cm->width * 5 < cpi->initial_width) {
3312       cm->width = cpi->initial_width / 5 + 1;
3313       printf("Warning: Desired width too small, changed to %d\n", cm->width);
3314     }
3315     if (cm->width > cpi->initial_width) {
3316       cm->width = cpi->initial_width;
3317       printf("Warning: Desired width too large, changed to %d\n", cm->width);
3318     }
3319   }
3320
3321   if (height) {
3322     cm->height = height;
3323     if (cm->height * 5 < cpi->initial_height) {
3324       cm->height = cpi->initial_height / 5 + 1;
3325       printf("Warning: Desired height too small, changed to %d\n", cm->height);
3326     }
3327     if (cm->height > cpi->initial_height) {
3328       cm->height = cpi->initial_height;
3329       printf("Warning: Desired height too large, changed to %d\n", cm->height);
3330     }
3331   }
3332
3333   assert(cm->width <= cpi->initial_width);
3334   assert(cm->height <= cpi->initial_height);
3335   update_frame_size(cpi);
3336   return 0;
3337 }
3338
3339 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
3340   cpi->use_svc = use_svc;
3341   return;
3342 }
3343
3344 int vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b) {
3345   assert(a->y_crop_width == b->y_crop_width);
3346   assert(a->y_crop_height == b->y_crop_height);
3347
3348   return (int)get_sse(a->y_buffer, a->y_stride, b->y_buffer, b->y_stride,
3349                       a->y_crop_width, a->y_crop_height);
3350 }
3351
3352
3353 int vp9_get_quantizer(VP9_COMP *cpi) {
3354   return cpi->common.base_qindex;
3355 }