]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_encoder.c
Merge "Remove unused vp9_init_quant_tables function"
[libvpx] / vp9 / encoder / vp9_encoder.c
1 /*
2  * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <math.h>
12 #include <stdio.h>
13 #include <limits.h>
14
15 #include "./vpx_config.h"
16 #include "./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_context_tree.h"
35 #include "vp9/encoder/vp9_encodeframe.h"
36 #include "vp9/encoder/vp9_encodemv.h"
37 #include "vp9/encoder/vp9_firstpass.h"
38 #include "vp9/encoder/vp9_mbgraph.h"
39 #include "vp9/encoder/vp9_encoder.h"
40 #include "vp9/encoder/vp9_picklpf.h"
41 #include "vp9/encoder/vp9_ratectrl.h"
42 #include "vp9/encoder/vp9_rdopt.h"
43 #include "vp9/encoder/vp9_segmentation.h"
44 #include "vp9/encoder/vp9_speed_features.h"
45 #if CONFIG_INTERNAL_STATS
46 #include "vp9/encoder/vp9_ssim.h"
47 #endif
48 #include "vp9/encoder/vp9_temporal_filter.h"
49 #include "vp9/encoder/vp9_resize.h"
50 #include "vp9/encoder/vp9_svc_layercontext.h"
51
52 void vp9_coef_tree_initialize();
53
54 #define DEFAULT_INTERP_FILTER SWITCHABLE
55
56 #define SHARP_FILTER_QTHRESH 0          /* Q threshold for 8-tap sharp filter */
57
58 #define ALTREF_HIGH_PRECISION_MV 1      // Whether to use high precision mv
59                                          //  for altref computation.
60 #define HIGH_PRECISION_MV_QTHRESH 200   // Q threshold for high precision
61                                          // mv. Choose a very high value for
62                                          // now so that HIGH_PRECISION is always
63                                          // chosen.
64
65 // #define OUTPUT_YUV_REC
66
67 #ifdef OUTPUT_YUV_DENOISED
68 FILE *yuv_denoised_file;
69 #endif
70 #ifdef OUTPUT_YUV_SRC
71 FILE *yuv_file;
72 #endif
73 #ifdef OUTPUT_YUV_REC
74 FILE *yuv_rec_file;
75 #endif
76
77 #if 0
78 FILE *framepsnr;
79 FILE *kf_list;
80 FILE *keyfile;
81 #endif
82
83 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
84   switch (mode) {
85     case NORMAL:
86       *hr = 1;
87       *hs = 1;
88       break;
89     case FOURFIVE:
90       *hr = 4;
91       *hs = 5;
92       break;
93     case THREEFIVE:
94       *hr = 3;
95       *hs = 5;
96     break;
97     case ONETWO:
98       *hr = 1;
99       *hs = 2;
100     break;
101     default:
102       *hr = 1;
103       *hs = 1;
104        assert(0);
105       break;
106   }
107 }
108
109 static void set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
110   MACROBLOCK *const mb = &cpi->mb;
111   cpi->common.allow_high_precision_mv = allow_high_precision_mv;
112   if (cpi->common.allow_high_precision_mv) {
113     mb->mvcost = mb->nmvcost_hp;
114     mb->mvsadcost = mb->nmvsadcost_hp;
115   } else {
116     mb->mvcost = mb->nmvcost;
117     mb->mvsadcost = mb->nmvsadcost;
118   }
119 }
120
121 static void setup_frame(VP9_COMP *cpi) {
122   VP9_COMMON *const cm = &cpi->common;
123   // Set up entropy context depending on frame type. The decoder mandates
124   // the use of the default context, index 0, for keyframes and inter
125   // frames where the error_resilient_mode or intra_only flag is set. For
126   // other inter-frames the encoder currently uses only two contexts;
127   // context 1 for ALTREF frames and context 0 for the others.
128   if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
129     vp9_setup_past_independence(cm);
130   } else {
131     if (!cpi->use_svc)
132       cm->frame_context_idx = cpi->refresh_alt_ref_frame;
133   }
134
135   if (cm->frame_type == KEY_FRAME) {
136     cpi->refresh_golden_frame = 1;
137     cpi->refresh_alt_ref_frame = 1;
138   } else {
139     cm->fc = cm->frame_contexts[cm->frame_context_idx];
140   }
141 }
142
143 void vp9_initialize_enc() {
144   static int init_done = 0;
145
146   if (!init_done) {
147     vp9_init_neighbors();
148     vp9_coef_tree_initialize();
149     vp9_tokenize_initialize();
150     vp9_init_me_luts();
151     vp9_rc_init_minq_luts();
152     vp9_entropy_mv_init();
153     vp9_entropy_mode_init();
154     vp9_temporal_filter_init();
155     init_done = 1;
156   }
157 }
158
159 static void dealloc_compressor_data(VP9_COMP *cpi) {
160   VP9_COMMON *const cm = &cpi->common;
161   int i;
162
163   // Delete sementation map
164   vpx_free(cpi->segmentation_map);
165   cpi->segmentation_map = NULL;
166   vpx_free(cm->last_frame_seg_map);
167   cm->last_frame_seg_map = NULL;
168   vpx_free(cpi->coding_context.last_frame_seg_map_copy);
169   cpi->coding_context.last_frame_seg_map_copy = NULL;
170
171   vpx_free(cpi->complexity_map);
172   cpi->complexity_map = NULL;
173
174   vp9_cyclic_refresh_free(cpi->cyclic_refresh);
175   cpi->cyclic_refresh = NULL;
176
177   vpx_free(cpi->active_map);
178   cpi->active_map = NULL;
179
180   vp9_free_frame_buffers(cm);
181
182   vp9_free_frame_buffer(&cpi->last_frame_uf);
183   vp9_free_frame_buffer(&cpi->scaled_source);
184   vp9_free_frame_buffer(&cpi->scaled_last_source);
185   vp9_free_frame_buffer(&cpi->alt_ref_buffer);
186   vp9_lookahead_destroy(cpi->lookahead);
187
188   vpx_free(cpi->tok);
189   cpi->tok = 0;
190
191   vp9_free_pc_tree(cpi);
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
384
385 static void set_speed_features(VP9_COMP *cpi) {
386 #if CONFIG_INTERNAL_STATS
387   int i;
388   for (i = 0; i < MAX_MODES; ++i)
389     cpi->mode_chosen_counts[i] = 0;
390 #endif
391
392   vp9_set_speed_features(cpi);
393
394   // Set rd thresholds based on mode and speed setting
395   vp9_set_rd_speed_thresholds(cpi);
396   vp9_set_rd_speed_thresholds_sub8x8(cpi);
397 }
398
399 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
400   VP9_COMMON *cm = &cpi->common;
401   const VP9EncoderConfig *oxcf = &cpi->oxcf;
402
403   cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
404                                       cm->subsampling_x, cm->subsampling_y,
405                                       oxcf->lag_in_frames);
406   if (!cpi->lookahead)
407     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
408                        "Failed to allocate lag buffers");
409
410   if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
411                                oxcf->width, oxcf->height,
412                                cm->subsampling_x, cm->subsampling_y,
413                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
414     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
415                        "Failed to allocate altref buffer");
416 }
417
418 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
419   VP9_COMMON *cm = &cpi->common;
420
421   if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
422     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
423                        "Failed to allocate frame buffers");
424
425   if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
426                              cm->width, cm->height,
427                              cm->subsampling_x, cm->subsampling_y,
428                              VP9_ENC_BORDER_IN_PIXELS))
429     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
430                        "Failed to allocate last frame buffer");
431
432   if (vp9_alloc_frame_buffer(&cpi->scaled_source,
433                              cm->width, cm->height,
434                              cm->subsampling_x, cm->subsampling_y,
435                              VP9_ENC_BORDER_IN_PIXELS))
436     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
437                        "Failed to allocate scaled source buffer");
438
439   if (vp9_alloc_frame_buffer(&cpi->scaled_last_source,
440                              cm->width, cm->height,
441                              cm->subsampling_x, cm->subsampling_y,
442                              VP9_ENC_BORDER_IN_PIXELS))
443     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
444                        "Failed to allocate scaled last source buffer");
445
446   vpx_free(cpi->tok);
447
448   {
449     unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
450
451     CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
452   }
453
454   vp9_setup_pc_tree(&cpi->common, cpi);
455 }
456
457 static void update_frame_size(VP9_COMP *cpi) {
458   VP9_COMMON *const cm = &cpi->common;
459   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
460
461   vp9_update_frame_size(cm);
462
463   // Update size of buffers local to this frame
464   if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
465                                cm->width, cm->height,
466                                cm->subsampling_x, cm->subsampling_y,
467                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
468     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
469                        "Failed to reallocate last frame buffer");
470
471   if (vp9_realloc_frame_buffer(&cpi->scaled_source,
472                                cm->width, cm->height,
473                                cm->subsampling_x, cm->subsampling_y,
474                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
475     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
476                        "Failed to reallocate scaled source buffer");
477
478   if (vp9_realloc_frame_buffer(&cpi->scaled_last_source,
479                                cm->width, cm->height,
480                                cm->subsampling_x, cm->subsampling_y,
481                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
482     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
483                        "Failed to reallocate scaled last source buffer");
484
485   {
486     int y_stride = cpi->scaled_source.y_stride;
487
488     if (cpi->sf.mv.search_method == NSTEP) {
489       vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
490     } else if (cpi->sf.mv.search_method == DIAMOND) {
491       vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
492     }
493   }
494
495   init_macroblockd(cm, xd);
496 }
497
498 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
499   cpi->oxcf.framerate = framerate < 0.1 ? 30 : framerate;
500   vp9_rc_update_framerate(cpi);
501 }
502
503 int64_t vp9_rescale(int64_t val, int64_t num, int denom) {
504   int64_t llnum = num;
505   int64_t llden = denom;
506   int64_t llval = val;
507
508   return (llval * llnum / llden);
509 }
510
511 static void set_tile_limits(VP9_COMP *cpi) {
512   VP9_COMMON *const cm = &cpi->common;
513
514   int min_log2_tile_cols, max_log2_tile_cols;
515   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
516
517   cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
518                              min_log2_tile_cols, max_log2_tile_cols);
519   cm->log2_tile_rows = cpi->oxcf.tile_rows;
520 }
521
522 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
523   VP9_COMMON *const cm = &cpi->common;
524
525   cpi->oxcf = *oxcf;
526
527   cm->profile = oxcf->profile;
528   cm->bit_depth = oxcf->bit_depth;
529
530   cm->width = oxcf->width;
531   cm->height = oxcf->height;
532   cm->subsampling_x = 0;
533   cm->subsampling_y = 0;
534   vp9_alloc_compressor_data(cpi);
535
536   // Spatial scalability.
537   cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
538   // Temporal scalability.
539   cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
540
541   if ((cpi->svc.number_temporal_layers > 1 &&
542       cpi->oxcf.rc_mode == VPX_CBR) ||
543       (cpi->svc.number_spatial_layers > 1 &&
544       cpi->oxcf.mode == TWO_PASS_SECOND_BEST)) {
545     vp9_init_layer_context(cpi);
546   }
547
548   // change includes all joint functionality
549   vp9_change_config(cpi, oxcf);
550
551   cpi->static_mb_pct = 0;
552
553   cpi->lst_fb_idx = 0;
554   cpi->gld_fb_idx = 1;
555   cpi->alt_fb_idx = 2;
556
557   set_tile_limits(cpi);
558 }
559
560 static int get_pass(MODE mode) {
561   switch (mode) {
562     case REALTIME:
563     case ONE_PASS_GOOD:
564     case ONE_PASS_BEST:
565       return 0;
566
567     case TWO_PASS_FIRST:
568       return 1;
569
570     case TWO_PASS_SECOND_GOOD:
571     case TWO_PASS_SECOND_BEST:
572       return 2;
573   }
574   return -1;
575 }
576
577 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
578   VP9_COMMON *const cm = &cpi->common;
579   RATE_CONTROL *const rc = &cpi->rc;
580
581   if (cm->profile != oxcf->profile)
582     cm->profile = oxcf->profile;
583   cm->bit_depth = oxcf->bit_depth;
584
585   if (cm->profile <= PROFILE_1)
586     assert(cm->bit_depth == BITS_8);
587   else
588     assert(cm->bit_depth > BITS_8);
589
590   cpi->oxcf = *oxcf;
591   cpi->pass = get_pass(cpi->oxcf.mode);
592
593   rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
594   cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
595
596   cpi->refresh_golden_frame = 0;
597   cpi->refresh_last_frame = 1;
598   cm->refresh_frame_context = 1;
599   cm->reset_frame_context = 0;
600
601   vp9_reset_segment_features(&cm->seg);
602   set_high_precision_mv(cpi, 0);
603
604   {
605     int i;
606
607     for (i = 0; i < MAX_SEGMENTS; i++)
608       cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
609   }
610   cpi->encode_breakout = cpi->oxcf.encode_breakout;
611
612   // local file playback mode == really big buffer
613   if (cpi->oxcf.rc_mode == VPX_VBR) {
614     cpi->oxcf.starting_buffer_level_ms = 60000;
615     cpi->oxcf.optimal_buffer_level_ms = 60000;
616     cpi->oxcf.maximum_buffer_size_ms = 240000;
617   }
618
619   rc->starting_buffer_level = vp9_rescale(cpi->oxcf.starting_buffer_level_ms,
620                                           cpi->oxcf.target_bandwidth, 1000);
621
622   // Set or reset optimal and maximum buffer levels.
623   if (cpi->oxcf.optimal_buffer_level_ms == 0)
624     rc->optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
625   else
626     rc->optimal_buffer_level = vp9_rescale(cpi->oxcf.optimal_buffer_level_ms,
627                                            cpi->oxcf.target_bandwidth, 1000);
628
629   if (cpi->oxcf.maximum_buffer_size_ms == 0)
630     rc->maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
631   else
632     rc->maximum_buffer_size = vp9_rescale(cpi->oxcf.maximum_buffer_size_ms,
633                                           cpi->oxcf.target_bandwidth, 1000);
634   // Under a configuration change, where maximum_buffer_size may change,
635   // keep buffer level clipped to the maximum allowed buffer size.
636   rc->bits_off_target = MIN(rc->bits_off_target, rc->maximum_buffer_size);
637   rc->buffer_level = MIN(rc->buffer_level, rc->maximum_buffer_size);
638
639   // Set up frame rate and related parameters rate control values.
640   vp9_new_framerate(cpi, cpi->oxcf.framerate);
641
642   // Set absolute upper and lower quality limits
643   rc->worst_quality = cpi->oxcf.worst_allowed_q;
644   rc->best_quality = cpi->oxcf.best_allowed_q;
645
646   cm->interp_filter = DEFAULT_INTERP_FILTER;
647
648   cm->display_width = cpi->oxcf.width;
649   cm->display_height = cpi->oxcf.height;
650
651   if (cpi->initial_width) {
652     // Increasing the size of the frame beyond the first seen frame, or some
653     // otherwise signaled maximum size, is not supported.
654     // TODO(jkoleszar): exit gracefully.
655     assert(cm->width <= cpi->initial_width);
656     assert(cm->height <= cpi->initial_height);
657   }
658   update_frame_size(cpi);
659
660   if ((cpi->svc.number_temporal_layers > 1 &&
661       cpi->oxcf.rc_mode == VPX_CBR) ||
662       (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2)) {
663     vp9_update_layer_context_change_config(cpi,
664                                            (int)cpi->oxcf.target_bandwidth);
665   }
666
667 #if CONFIG_MULTIPLE_ARF
668   vp9_zero(cpi->alt_ref_source);
669 #else
670   cpi->alt_ref_source = NULL;
671 #endif
672   rc->is_src_frame_alt_ref = 0;
673
674 #if 0
675   // Experimental RD Code
676   cpi->frame_distortion = 0;
677   cpi->last_frame_distortion = 0;
678 #endif
679
680   set_tile_limits(cpi);
681
682   cpi->ext_refresh_frame_flags_pending = 0;
683   cpi->ext_refresh_frame_context_pending = 0;
684
685 #if CONFIG_DENOISING
686   vp9_denoiser_alloc(&(cpi->denoiser), cm->width, cm->height,
687                      // TODO(tkopp) An unrelated bug causes
688                      // cm->subsampling_{x,y} to be uninitialized at this point
689                      // in execution. For now we assume YUV-420, which is x/y
690                      // subsampling of 1.
691                      1, 1,
692                      // cm->subsampling_x, cm->subsampling_y,
693                      VP9_ENC_BORDER_IN_PIXELS);
694 #endif
695 }
696
697 #ifndef M_LOG2_E
698 #define M_LOG2_E 0.693147180559945309417
699 #endif
700 #define log2f(x) (log (x) / (float) M_LOG2_E)
701
702 static void cal_nmvjointsadcost(int *mvjointsadcost) {
703   mvjointsadcost[0] = 600;
704   mvjointsadcost[1] = 300;
705   mvjointsadcost[2] = 300;
706   mvjointsadcost[3] = 300;
707 }
708
709 static void cal_nmvsadcosts(int *mvsadcost[2]) {
710   int i = 1;
711
712   mvsadcost[0][0] = 0;
713   mvsadcost[1][0] = 0;
714
715   do {
716     double z = 256 * (2 * (log2f(8 * i) + .6));
717     mvsadcost[0][i] = (int)z;
718     mvsadcost[1][i] = (int)z;
719     mvsadcost[0][-i] = (int)z;
720     mvsadcost[1][-i] = (int)z;
721   } while (++i <= MV_MAX);
722 }
723
724 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
725   int i = 1;
726
727   mvsadcost[0][0] = 0;
728   mvsadcost[1][0] = 0;
729
730   do {
731     double z = 256 * (2 * (log2f(8 * i) + .6));
732     mvsadcost[0][i] = (int)z;
733     mvsadcost[1][i] = (int)z;
734     mvsadcost[0][-i] = (int)z;
735     mvsadcost[1][-i] = (int)z;
736   } while (++i <= MV_MAX);
737 }
738
739
740 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf) {
741   unsigned int i, j;
742   VP9_COMP *const cpi = vpx_memalign(32, sizeof(VP9_COMP));
743   VP9_COMMON *const cm = cpi != NULL ? &cpi->common : NULL;
744
745   if (!cm)
746     return NULL;
747
748   vp9_zero(*cpi);
749
750   if (setjmp(cm->error.jmp)) {
751     cm->error.setjmp = 0;
752     vp9_remove_compressor(cpi);
753     return 0;
754   }
755
756   cm->error.setjmp = 1;
757
758   vp9_rtcd();
759
760   cpi->use_svc = 0;
761
762   init_config(cpi, oxcf);
763   vp9_rc_init(&cpi->oxcf, cpi->pass, &cpi->rc);
764
765   cm->current_video_frame = 0;
766
767   // Set reference frame sign bias for ALTREF frame to 1 (for now)
768   cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
769
770   cpi->gold_is_last = 0;
771   cpi->alt_is_last = 0;
772   cpi->gold_is_alt = 0;
773
774   // Create the encoder segmentation map and set all entries to 0
775   CHECK_MEM_ERROR(cm, cpi->segmentation_map,
776                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
777
778   // Create a complexity map used for rd adjustment
779   CHECK_MEM_ERROR(cm, cpi->complexity_map,
780                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
781
782   // Create a map used for cyclic background refresh.
783   CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
784                   vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
785
786   // And a place holder structure is the coding context
787   // for use if we want to save and restore it
788   CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
789                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
790
791   CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
792   vpx_memset(cpi->active_map, 1, cm->MBs);
793   cpi->active_map_enabled = 0;
794
795   for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
796                    sizeof(cpi->mbgraph_stats[0])); i++) {
797     CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
798                     vpx_calloc(cm->MBs *
799                                sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
800   }
801
802   cpi->refresh_alt_ref_frame = 0;
803
804 #if CONFIG_MULTIPLE_ARF
805   // Turn multiple ARF usage on/off. This is a quick hack for the initial test
806   // version. It should eventually be set via the codec API.
807   cpi->multi_arf_enabled = 1;
808
809   if (cpi->multi_arf_enabled) {
810     cpi->sequence_number = 0;
811     cpi->frame_coding_order_period = 0;
812     vp9_zero(cpi->frame_coding_order);
813     vp9_zero(cpi->arf_buffer_idx);
814   }
815 #endif
816
817   cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
818 #if CONFIG_INTERNAL_STATS
819   cpi->b_calculate_ssimg = 0;
820
821   cpi->count = 0;
822   cpi->bytes = 0;
823
824   if (cpi->b_calculate_psnr) {
825     cpi->total_y = 0.0;
826     cpi->total_u = 0.0;
827     cpi->total_v = 0.0;
828     cpi->total = 0.0;
829     cpi->total_sq_error = 0;
830     cpi->total_samples = 0;
831
832     cpi->totalp_y = 0.0;
833     cpi->totalp_u = 0.0;
834     cpi->totalp_v = 0.0;
835     cpi->totalp = 0.0;
836     cpi->totalp_sq_error = 0;
837     cpi->totalp_samples = 0;
838
839     cpi->tot_recode_hits = 0;
840     cpi->summed_quality = 0;
841     cpi->summed_weights = 0;
842     cpi->summedp_quality = 0;
843     cpi->summedp_weights = 0;
844   }
845
846   if (cpi->b_calculate_ssimg) {
847     cpi->total_ssimg_y = 0;
848     cpi->total_ssimg_u = 0;
849     cpi->total_ssimg_v = 0;
850     cpi->total_ssimg_all = 0;
851   }
852
853 #endif
854
855   cpi->first_time_stamp_ever = INT64_MAX;
856
857   cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
858   cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
859   cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
860   cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
861   cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
862   cal_nmvsadcosts(cpi->mb.nmvsadcost);
863
864   cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
865   cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
866   cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
867   cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
868   cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
869
870 #ifdef OUTPUT_YUV_DENOISED
871   yuv_denoised_file = fopen("denoised.yuv", "ab");
872 #endif
873 #ifdef OUTPUT_YUV_SRC
874   yuv_file = fopen("bd.yuv", "ab");
875 #endif
876 #ifdef OUTPUT_YUV_REC
877   yuv_rec_file = fopen("rec.yuv", "wb");
878 #endif
879
880 #if 0
881   framepsnr = fopen("framepsnr.stt", "a");
882   kf_list = fopen("kf_list.stt", "w");
883 #endif
884
885   cpi->output_pkt_list = oxcf->output_pkt_list;
886
887   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
888
889   if (cpi->pass == 1) {
890     vp9_init_first_pass(cpi);
891   } else if (cpi->pass == 2) {
892     const size_t packet_sz = sizeof(FIRSTPASS_STATS);
893     const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
894
895     if (cpi->svc.number_spatial_layers > 1
896         && cpi->svc.number_temporal_layers == 1) {
897       FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
898       FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = {0};
899       int i;
900
901       for (i = 0; i < oxcf->ss_number_layers; ++i) {
902         FIRSTPASS_STATS *const last_packet_for_layer =
903             &stats[packets - oxcf->ss_number_layers + i];
904         const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
905         const int packets_in_layer = (int)last_packet_for_layer->count + 1;
906         if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
907           LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
908
909           vpx_free(lc->rc_twopass_stats_in.buf);
910
911           lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
912           CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
913                           vpx_malloc(lc->rc_twopass_stats_in.sz));
914           lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
915           lc->twopass.stats_in = lc->twopass.stats_in_start;
916           lc->twopass.stats_in_end = lc->twopass.stats_in_start
917                                      + packets_in_layer - 1;
918           stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
919         }
920       }
921
922       for (i = 0; i < packets; ++i) {
923         const int layer_id = (int)stats[i].spatial_layer_id;
924         if (layer_id >= 0 && layer_id < oxcf->ss_number_layers
925             && stats_copy[layer_id] != NULL) {
926           *stats_copy[layer_id] = stats[i];
927           ++stats_copy[layer_id];
928         }
929       }
930
931       vp9_init_second_pass_spatial_svc(cpi);
932     } else {
933       cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
934       cpi->twopass.stats_in = cpi->twopass.stats_in_start;
935       cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
936
937       vp9_init_second_pass(cpi);
938     }
939   }
940
941   set_speed_features(cpi);
942
943   // Default rd threshold factors for mode selection
944   for (i = 0; i < BLOCK_SIZES; ++i) {
945     for (j = 0; j < MAX_MODES; ++j)
946       cpi->rd.thresh_freq_fact[i][j] = 32;
947   }
948
949 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF)\
950     cpi->fn_ptr[BT].sdf            = SDF; \
951     cpi->fn_ptr[BT].sdaf           = SDAF; \
952     cpi->fn_ptr[BT].vf             = VF; \
953     cpi->fn_ptr[BT].svf            = SVF; \
954     cpi->fn_ptr[BT].svaf           = SVAF; \
955     cpi->fn_ptr[BT].sdx3f          = SDX3F; \
956     cpi->fn_ptr[BT].sdx8f          = SDX8F; \
957     cpi->fn_ptr[BT].sdx4df         = SDX4DF;
958
959   BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
960       vp9_variance32x16, vp9_sub_pixel_variance32x16,
961       vp9_sub_pixel_avg_variance32x16, NULL, NULL, vp9_sad32x16x4d)
962
963   BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
964       vp9_variance16x32, vp9_sub_pixel_variance16x32,
965       vp9_sub_pixel_avg_variance16x32, NULL, NULL, vp9_sad16x32x4d)
966
967   BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
968       vp9_variance64x32, vp9_sub_pixel_variance64x32,
969       vp9_sub_pixel_avg_variance64x32, NULL, NULL, vp9_sad64x32x4d)
970
971   BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
972       vp9_variance32x64, vp9_sub_pixel_variance32x64,
973       vp9_sub_pixel_avg_variance32x64, NULL, NULL, vp9_sad32x64x4d)
974
975   BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
976       vp9_variance32x32, vp9_sub_pixel_variance32x32,
977       vp9_sub_pixel_avg_variance32x32, vp9_sad32x32x3, vp9_sad32x32x8,
978       vp9_sad32x32x4d)
979
980   BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
981       vp9_variance64x64, vp9_sub_pixel_variance64x64,
982       vp9_sub_pixel_avg_variance64x64, vp9_sad64x64x3, vp9_sad64x64x8,
983       vp9_sad64x64x4d)
984
985   BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
986       vp9_variance16x16, vp9_sub_pixel_variance16x16,
987       vp9_sub_pixel_avg_variance16x16, vp9_sad16x16x3, vp9_sad16x16x8,
988       vp9_sad16x16x4d)
989
990   BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
991       vp9_variance16x8, vp9_sub_pixel_variance16x8,
992       vp9_sub_pixel_avg_variance16x8,
993       vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
994
995   BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
996       vp9_variance8x16, vp9_sub_pixel_variance8x16,
997       vp9_sub_pixel_avg_variance8x16,
998       vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
999
1000   BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1001       vp9_variance8x8, vp9_sub_pixel_variance8x8,
1002       vp9_sub_pixel_avg_variance8x8,
1003       vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1004
1005   BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1006       vp9_variance8x4, vp9_sub_pixel_variance8x4,
1007       vp9_sub_pixel_avg_variance8x4, NULL, vp9_sad8x4x8, vp9_sad8x4x4d)
1008
1009   BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1010       vp9_variance4x8, vp9_sub_pixel_variance4x8,
1011       vp9_sub_pixel_avg_variance4x8, NULL, vp9_sad4x8x8, vp9_sad4x8x4d)
1012
1013   BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1014       vp9_variance4x4, vp9_sub_pixel_variance4x4,
1015       vp9_sub_pixel_avg_variance4x4,
1016       vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1017
1018   cpi->full_search_sad = vp9_full_search_sad;
1019   cpi->diamond_search_sad = vp9_diamond_search_sad;
1020   cpi->refining_search_sad = vp9_refining_search_sad;
1021
1022   /* vp9_init_quantizer() is first called here. Add check in
1023    * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1024    * called later when needed. This will avoid unnecessary calls of
1025    * vp9_init_quantizer() for every frame.
1026    */
1027   vp9_init_quantizer(cpi);
1028
1029   vp9_loop_filter_init(cm);
1030
1031   cm->error.setjmp = 0;
1032
1033   return cpi;
1034 }
1035
1036 void vp9_remove_compressor(VP9_COMP *cpi) {
1037   unsigned int i;
1038
1039   if (!cpi)
1040     return;
1041
1042   if (cpi && (cpi->common.current_video_frame > 0)) {
1043 #if CONFIG_INTERNAL_STATS
1044
1045     vp9_clear_system_state();
1046
1047     // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1048     if (cpi->pass != 1) {
1049       FILE *f = fopen("opsnr.stt", "a");
1050       double time_encoded = (cpi->last_end_time_stamp_seen
1051                              - cpi->first_time_stamp_ever) / 10000000.000;
1052       double total_encode_time = (cpi->time_receive_data +
1053                                   cpi->time_compress_data)   / 1000.000;
1054       double dr = (double)cpi->bytes * (double) 8 / (double)1000
1055                   / time_encoded;
1056
1057       if (cpi->b_calculate_psnr) {
1058         const double total_psnr =
1059             vpx_sse_to_psnr((double)cpi->total_samples, 255.0,
1060                             (double)cpi->total_sq_error);
1061         const double totalp_psnr =
1062             vpx_sse_to_psnr((double)cpi->totalp_samples, 255.0,
1063                             (double)cpi->totalp_sq_error);
1064         const double total_ssim = 100 * pow(cpi->summed_quality /
1065                                                 cpi->summed_weights, 8.0);
1066         const double totalp_ssim = 100 * pow(cpi->summedp_quality /
1067                                                 cpi->summedp_weights, 8.0);
1068
1069         fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1070                 "VPXSSIM\tVPSSIMP\t  Time(ms)\n");
1071         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",
1072                 dr, cpi->total / cpi->count, total_psnr,
1073                 cpi->totalp / cpi->count, totalp_psnr, total_ssim, totalp_ssim,
1074                 total_encode_time);
1075       }
1076
1077       if (cpi->b_calculate_ssimg) {
1078         fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t  Time(ms)\n");
1079         fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1080                 cpi->total_ssimg_y / cpi->count,
1081                 cpi->total_ssimg_u / cpi->count,
1082                 cpi->total_ssimg_v / cpi->count,
1083                 cpi->total_ssimg_all / cpi->count, total_encode_time);
1084       }
1085
1086       fclose(f);
1087     }
1088
1089 #endif
1090
1091 #if 0
1092     {
1093       printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1094       printf("\n_frames recive_data encod_mb_row compress_frame  Total\n");
1095       printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1096              cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1097              cpi->time_compress_data / 1000,
1098              (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1099     }
1100 #endif
1101   }
1102
1103 #if CONFIG_DENOISING
1104   vp9_denoiser_free(&(cpi->denoiser));
1105 #endif
1106
1107   dealloc_compressor_data(cpi);
1108   vpx_free(cpi->tok);
1109
1110   for (i = 0; i < sizeof(cpi->mbgraph_stats) /
1111                   sizeof(cpi->mbgraph_stats[0]); ++i) {
1112     vpx_free(cpi->mbgraph_stats[i].mb_stats);
1113   }
1114
1115   vp9_remove_common(&cpi->common);
1116   vpx_free(cpi);
1117
1118 #ifdef OUTPUT_YUV_DENOISED
1119   fclose(yuv_denoised_file);
1120 #endif
1121 #ifdef OUTPUT_YUV_SRC
1122   fclose(yuv_file);
1123 #endif
1124 #ifdef OUTPUT_YUV_REC
1125   fclose(yuv_rec_file);
1126 #endif
1127
1128 #if 0
1129
1130   if (keyfile)
1131     fclose(keyfile);
1132
1133   if (framepsnr)
1134     fclose(framepsnr);
1135
1136   if (kf_list)
1137     fclose(kf_list);
1138
1139 #endif
1140 }
1141 static int64_t get_sse(const uint8_t *a, int a_stride,
1142                        const uint8_t *b, int b_stride,
1143                        int width, int height) {
1144   const int dw = width % 16;
1145   const int dh = height % 16;
1146   int64_t total_sse = 0;
1147   unsigned int sse = 0;
1148   int sum = 0;
1149   int x, y;
1150
1151   if (dw > 0) {
1152     variance(&a[width - dw], a_stride, &b[width - dw], b_stride,
1153              dw, height, &sse, &sum);
1154     total_sse += sse;
1155   }
1156
1157   if (dh > 0) {
1158     variance(&a[(height - dh) * a_stride], a_stride,
1159              &b[(height - dh) * b_stride], b_stride,
1160              width - dw, dh, &sse, &sum);
1161     total_sse += sse;
1162   }
1163
1164   for (y = 0; y < height / 16; ++y) {
1165     const uint8_t *pa = a;
1166     const uint8_t *pb = b;
1167     for (x = 0; x < width / 16; ++x) {
1168       vp9_mse16x16(pa, a_stride, pb, b_stride, &sse);
1169       total_sse += sse;
1170
1171       pa += 16;
1172       pb += 16;
1173     }
1174
1175     a += 16 * a_stride;
1176     b += 16 * b_stride;
1177   }
1178
1179   return total_sse;
1180 }
1181
1182 typedef struct {
1183   double psnr[4];       // total/y/u/v
1184   uint64_t sse[4];      // total/y/u/v
1185   uint32_t samples[4];  // total/y/u/v
1186 } PSNR_STATS;
1187
1188 static void calc_psnr(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b,
1189                       PSNR_STATS *psnr) {
1190   const int widths[3]        = {a->y_width,  a->uv_width,  a->uv_width };
1191   const int heights[3]       = {a->y_height, a->uv_height, a->uv_height};
1192   const uint8_t *a_planes[3] = {a->y_buffer, a->u_buffer,  a->v_buffer };
1193   const int a_strides[3]     = {a->y_stride, a->uv_stride, a->uv_stride};
1194   const uint8_t *b_planes[3] = {b->y_buffer, b->u_buffer,  b->v_buffer };
1195   const int b_strides[3]     = {b->y_stride, b->uv_stride, b->uv_stride};
1196   int i;
1197   uint64_t total_sse = 0;
1198   uint32_t total_samples = 0;
1199
1200   for (i = 0; i < 3; ++i) {
1201     const int w = widths[i];
1202     const int h = heights[i];
1203     const uint32_t samples = w * h;
1204     const uint64_t sse = get_sse(a_planes[i], a_strides[i],
1205                                  b_planes[i], b_strides[i],
1206                                  w, h);
1207     psnr->sse[1 + i] = sse;
1208     psnr->samples[1 + i] = samples;
1209     psnr->psnr[1 + i] = vpx_sse_to_psnr(samples, 255.0, (double)sse);
1210
1211     total_sse += sse;
1212     total_samples += samples;
1213   }
1214
1215   psnr->sse[0] = total_sse;
1216   psnr->samples[0] = total_samples;
1217   psnr->psnr[0] = vpx_sse_to_psnr((double)total_samples, 255.0,
1218                                   (double)total_sse);
1219 }
1220
1221 static void generate_psnr_packet(VP9_COMP *cpi) {
1222   struct vpx_codec_cx_pkt pkt;
1223   int i;
1224   PSNR_STATS psnr;
1225   calc_psnr(cpi->Source, cpi->common.frame_to_show, &psnr);
1226   for (i = 0; i < 4; ++i) {
1227     pkt.data.psnr.samples[i] = psnr.samples[i];
1228     pkt.data.psnr.sse[i] = psnr.sse[i];
1229     pkt.data.psnr.psnr[i] = psnr.psnr[i];
1230   }
1231   pkt.kind = VPX_CODEC_PSNR_PKT;
1232   vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
1233 }
1234
1235 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
1236   if (ref_frame_flags > 7)
1237     return -1;
1238
1239   cpi->ref_frame_flags = ref_frame_flags;
1240   return 0;
1241 }
1242
1243 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
1244   cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
1245   cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
1246   cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
1247   cpi->ext_refresh_frame_flags_pending = 1;
1248 }
1249
1250 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
1251                                 VP9_REFFRAME ref_frame_flag) {
1252   MV_REFERENCE_FRAME ref_frame = NONE;
1253   if (ref_frame_flag == VP9_LAST_FLAG)
1254     ref_frame = LAST_FRAME;
1255   else if (ref_frame_flag == VP9_GOLD_FLAG)
1256     ref_frame = GOLDEN_FRAME;
1257   else if (ref_frame_flag == VP9_ALT_FLAG)
1258     ref_frame = ALTREF_FRAME;
1259
1260   return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
1261 }
1262
1263 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1264                            YV12_BUFFER_CONFIG *sd) {
1265   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1266   if (cfg) {
1267     vp8_yv12_copy_frame(cfg, sd);
1268     return 0;
1269   } else {
1270     return -1;
1271   }
1272 }
1273
1274 int vp9_get_reference_enc(VP9_COMP *cpi, int index, YV12_BUFFER_CONFIG **fb) {
1275   VP9_COMMON *cm = &cpi->common;
1276
1277   if (index < 0 || index >= REF_FRAMES)
1278     return -1;
1279
1280   *fb = &cm->frame_bufs[cm->ref_frame_map[index]].buf;
1281   return 0;
1282 }
1283
1284 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1285                           YV12_BUFFER_CONFIG *sd) {
1286   YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1287   if (cfg) {
1288     vp8_yv12_copy_frame(sd, cfg);
1289     return 0;
1290   } else {
1291     return -1;
1292   }
1293 }
1294
1295 int vp9_update_entropy(VP9_COMP * cpi, int update) {
1296   cpi->ext_refresh_frame_context = update;
1297   cpi->ext_refresh_frame_context_pending = 1;
1298   return 0;
1299 }
1300
1301
1302 #if defined(OUTPUT_YUV_SRC) || defined(OUTPUT_YUV_DENOISED)
1303 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s, FILE *f) {
1304   uint8_t *src = s->y_buffer;
1305   int h = s->y_height;
1306
1307   do {
1308     fwrite(src, s->y_width, 1, f);
1309     src += s->y_stride;
1310   } while (--h);
1311
1312   src = s->u_buffer;
1313   h = s->uv_height;
1314
1315   do {
1316     fwrite(src, s->uv_width, 1, f);
1317     src += s->uv_stride;
1318   } while (--h);
1319
1320   src = s->v_buffer;
1321   h = s->uv_height;
1322
1323   do {
1324     fwrite(src, s->uv_width, 1, f);
1325     src += s->uv_stride;
1326   } while (--h);
1327 }
1328 #endif
1329
1330 #ifdef OUTPUT_YUV_REC
1331 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
1332   YV12_BUFFER_CONFIG *s = cm->frame_to_show;
1333   uint8_t *src = s->y_buffer;
1334   int h = cm->height;
1335
1336   do {
1337     fwrite(src, s->y_width, 1,  yuv_rec_file);
1338     src += s->y_stride;
1339   } while (--h);
1340
1341   src = s->u_buffer;
1342   h = s->uv_height;
1343
1344   do {
1345     fwrite(src, s->uv_width, 1,  yuv_rec_file);
1346     src += s->uv_stride;
1347   } while (--h);
1348
1349   src = s->v_buffer;
1350   h = s->uv_height;
1351
1352   do {
1353     fwrite(src, s->uv_width, 1, yuv_rec_file);
1354     src += s->uv_stride;
1355   } while (--h);
1356
1357 #if CONFIG_ALPHA
1358   if (s->alpha_buffer) {
1359     src = s->alpha_buffer;
1360     h = s->alpha_height;
1361     do {
1362       fwrite(src, s->alpha_width, 1,  yuv_rec_file);
1363       src += s->alpha_stride;
1364     } while (--h);
1365   }
1366 #endif
1367
1368   fflush(yuv_rec_file);
1369 }
1370 #endif
1371
1372 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
1373                                                 YV12_BUFFER_CONFIG *dst) {
1374   // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
1375   int i;
1376   const uint8_t *const srcs[4] = {src->y_buffer, src->u_buffer, src->v_buffer,
1377                                   src->alpha_buffer};
1378   const int src_strides[4] = {src->y_stride, src->uv_stride, src->uv_stride,
1379                               src->alpha_stride};
1380   const int src_widths[4] = {src->y_crop_width, src->uv_crop_width,
1381                              src->uv_crop_width, src->y_crop_width};
1382   const int src_heights[4] = {src->y_crop_height, src->uv_crop_height,
1383                               src->uv_crop_height, src->y_crop_height};
1384   uint8_t *const dsts[4] = {dst->y_buffer, dst->u_buffer, dst->v_buffer,
1385                             dst->alpha_buffer};
1386   const int dst_strides[4] = {dst->y_stride, dst->uv_stride, dst->uv_stride,
1387                               dst->alpha_stride};
1388   const int dst_widths[4] = {dst->y_crop_width, dst->uv_crop_width,
1389                              dst->uv_crop_width, dst->y_crop_width};
1390   const int dst_heights[4] = {dst->y_crop_height, dst->uv_crop_height,
1391                               dst->uv_crop_height, dst->y_crop_height};
1392
1393   for (i = 0; i < MAX_MB_PLANE; ++i)
1394     vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
1395                      dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
1396
1397   // TODO(hkuang): Call C version explicitly
1398   // as neon version only expand border size 32.
1399   vp8_yv12_extend_frame_borders_c(dst);
1400 }
1401
1402 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
1403                                    YV12_BUFFER_CONFIG *dst) {
1404   const int src_w = src->y_crop_width;
1405   const int src_h = src->y_crop_height;
1406   const int dst_w = dst->y_crop_width;
1407   const int dst_h = dst->y_crop_height;
1408   const uint8_t *const srcs[4] = {src->y_buffer, src->u_buffer, src->v_buffer,
1409                                   src->alpha_buffer};
1410   const int src_strides[4] = {src->y_stride, src->uv_stride, src->uv_stride,
1411                               src->alpha_stride};
1412   uint8_t *const dsts[4] = {dst->y_buffer, dst->u_buffer, dst->v_buffer,
1413                             dst->alpha_buffer};
1414   const int dst_strides[4] = {dst->y_stride, dst->uv_stride, dst->uv_stride,
1415                               dst->alpha_stride};
1416   const InterpKernel *const kernel = vp9_get_interp_kernel(EIGHTTAP);
1417   int x, y, i;
1418
1419   for (y = 0; y < dst_h; y += 16) {
1420     for (x = 0; x < dst_w; x += 16) {
1421       for (i = 0; i < MAX_MB_PLANE; ++i) {
1422         const int factor = (i == 0 || i == 3 ? 1 : 2);
1423         const int x_q4 = x * (16 / factor) * src_w / dst_w;
1424         const int y_q4 = y * (16 / factor) * src_h / dst_h;
1425         const int src_stride = src_strides[i];
1426         const int dst_stride = dst_strides[i];
1427         const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
1428                                      src_stride + (x / factor) * src_w / dst_w;
1429         uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
1430
1431         vp9_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
1432                       kernel[x_q4 & 0xf], 16 * src_w / dst_w,
1433                       kernel[y_q4 & 0xf], 16 * src_h / dst_h,
1434                       16 / factor, 16 / factor);
1435       }
1436     }
1437   }
1438
1439   // TODO(hkuang): Call C version explicitly
1440   // as neon version only expand border size 32.
1441   vp8_yv12_extend_frame_borders_c(dst);
1442 }
1443
1444 #define WRITE_RECON_BUFFER 0
1445 #if WRITE_RECON_BUFFER
1446 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
1447   FILE *yframe;
1448   int i;
1449   char filename[255];
1450
1451   snprintf(filename, sizeof(filename), "cx\\y%04d.raw", this_frame);
1452   yframe = fopen(filename, "wb");
1453
1454   for (i = 0; i < frame->y_height; i++)
1455     fwrite(frame->y_buffer + i * frame->y_stride,
1456            frame->y_width, 1, yframe);
1457
1458   fclose(yframe);
1459   snprintf(filename, sizeof(filename), "cx\\u%04d.raw", this_frame);
1460   yframe = fopen(filename, "wb");
1461
1462   for (i = 0; i < frame->uv_height; i++)
1463     fwrite(frame->u_buffer + i * frame->uv_stride,
1464            frame->uv_width, 1, yframe);
1465
1466   fclose(yframe);
1467   snprintf(filename, sizeof(filename), "cx\\v%04d.raw", this_frame);
1468   yframe = fopen(filename, "wb");
1469
1470   for (i = 0; i < frame->uv_height; i++)
1471     fwrite(frame->v_buffer + i * frame->uv_stride,
1472            frame->uv_width, 1, yframe);
1473
1474   fclose(yframe);
1475 }
1476 #endif
1477
1478 // Function to test for conditions that indicate we should loop
1479 // back and recode a frame.
1480 static int recode_loop_test(const VP9_COMP *cpi,
1481                             int high_limit, int low_limit,
1482                             int q, int maxq, int minq) {
1483   const VP9_COMMON *const cm = &cpi->common;
1484   const RATE_CONTROL *const rc = &cpi->rc;
1485   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1486   int force_recode = 0;
1487
1488   // Special case trap if maximum allowed frame size exceeded.
1489   if (rc->projected_frame_size > rc->max_frame_bandwidth) {
1490     force_recode = 1;
1491
1492   // Is frame recode allowed.
1493   // Yes if either recode mode 1 is selected or mode 2 is selected
1494   // and the frame is a key frame, golden frame or alt_ref_frame
1495   } else if ((cpi->sf.recode_loop == ALLOW_RECODE) ||
1496              ((cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF) &&
1497               (cm->frame_type == KEY_FRAME ||
1498                cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1499     // General over and under shoot tests
1500     if ((rc->projected_frame_size > high_limit && q < maxq) ||
1501         (rc->projected_frame_size < low_limit && q > minq)) {
1502       force_recode = 1;
1503     } else if (cpi->oxcf.rc_mode == VPX_CQ) {
1504       // Deal with frame undershoot and whether or not we are
1505       // below the automatically set cq level.
1506       if (q > oxcf->cq_level &&
1507           rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
1508         force_recode = 1;
1509       }
1510     }
1511   }
1512   return force_recode;
1513 }
1514
1515 void vp9_update_reference_frames(VP9_COMP *cpi) {
1516   VP9_COMMON * const cm = &cpi->common;
1517
1518   // At this point the new frame has been encoded.
1519   // If any buffer copy / swapping is signaled it should be done here.
1520   if (cm->frame_type == KEY_FRAME) {
1521     ref_cnt_fb(cm->frame_bufs,
1522                &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1523     ref_cnt_fb(cm->frame_bufs,
1524                &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1525   }
1526 #if CONFIG_MULTIPLE_ARF
1527   else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
1528       !cpi->refresh_alt_ref_frame) {
1529 #else
1530   else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
1531            !cpi->use_svc) {
1532 #endif
1533     /* Preserve the previously existing golden frame and update the frame in
1534      * the alt ref slot instead. This is highly specific to the current use of
1535      * alt-ref as a forward reference, and this needs to be generalized as
1536      * other uses are implemented (like RTC/temporal scaling)
1537      *
1538      * The update to the buffer in the alt ref slot was signaled in
1539      * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
1540      * as the golden frame next time.
1541      */
1542     int tmp;
1543
1544     ref_cnt_fb(cm->frame_bufs,
1545                &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1546
1547     tmp = cpi->alt_fb_idx;
1548     cpi->alt_fb_idx = cpi->gld_fb_idx;
1549     cpi->gld_fb_idx = tmp;
1550   }  else { /* For non key/golden frames */
1551     if (cpi->refresh_alt_ref_frame) {
1552       int arf_idx = cpi->alt_fb_idx;
1553 #if CONFIG_MULTIPLE_ARF
1554       if (cpi->multi_arf_enabled) {
1555         arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
1556       }
1557 #endif
1558       ref_cnt_fb(cm->frame_bufs,
1559                  &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
1560     }
1561
1562     if (cpi->refresh_golden_frame) {
1563       ref_cnt_fb(cm->frame_bufs,
1564                  &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1565     }
1566   }
1567
1568   if (cpi->refresh_last_frame) {
1569     ref_cnt_fb(cm->frame_bufs,
1570                &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
1571   }
1572 #if CONFIG_DENOISING
1573   vp9_denoiser_update_frame_info(&cpi->denoiser,
1574                                 *cpi->Source,
1575                                 cpi->common.frame_type,
1576                                 cpi->refresh_alt_ref_frame,
1577                                 cpi->refresh_golden_frame,
1578                                 cpi->refresh_last_frame);
1579 #endif
1580 }
1581
1582 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
1583   MACROBLOCKD *xd = &cpi->mb.e_mbd;
1584   struct loopfilter *lf = &cm->lf;
1585   if (xd->lossless) {
1586       lf->filter_level = 0;
1587   } else {
1588     struct vpx_usec_timer timer;
1589
1590     vp9_clear_system_state();
1591
1592     vpx_usec_timer_start(&timer);
1593
1594     vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
1595
1596     vpx_usec_timer_mark(&timer);
1597     cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
1598   }
1599
1600   if (lf->filter_level > 0) {
1601     vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
1602   }
1603
1604   vp9_extend_frame_inner_borders(cm->frame_to_show);
1605 }
1606
1607 void vp9_scale_references(VP9_COMP *cpi) {
1608   VP9_COMMON *cm = &cpi->common;
1609   MV_REFERENCE_FRAME ref_frame;
1610
1611   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1612     const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
1613     const YV12_BUFFER_CONFIG *const ref = &cm->frame_bufs[idx].buf;
1614
1615     if (ref->y_crop_width != cm->width ||
1616         ref->y_crop_height != cm->height) {
1617       const int new_fb = get_free_fb(cm);
1618       vp9_realloc_frame_buffer(&cm->frame_bufs[new_fb].buf,
1619                                cm->width, cm->height,
1620                                cm->subsampling_x, cm->subsampling_y,
1621                                VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
1622       scale_and_extend_frame(ref, &cm->frame_bufs[new_fb].buf);
1623       cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
1624     } else {
1625       cpi->scaled_ref_idx[ref_frame - 1] = idx;
1626       cm->frame_bufs[idx].ref_count++;
1627     }
1628   }
1629 }
1630
1631 static void release_scaled_references(VP9_COMP *cpi) {
1632   VP9_COMMON *cm = &cpi->common;
1633   int i;
1634
1635   for (i = 0; i < 3; i++)
1636     cm->frame_bufs[cpi->scaled_ref_idx[i]].ref_count--;
1637 }
1638
1639 static void full_to_model_count(unsigned int *model_count,
1640                                 unsigned int *full_count) {
1641   int n;
1642   model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
1643   model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
1644   model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
1645   for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
1646     model_count[TWO_TOKEN] += full_count[n];
1647   model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
1648 }
1649
1650 static void full_to_model_counts(vp9_coeff_count_model *model_count,
1651                                  vp9_coeff_count *full_count) {
1652   int i, j, k, l;
1653
1654   for (i = 0; i < PLANE_TYPES; ++i)
1655     for (j = 0; j < REF_TYPES; ++j)
1656       for (k = 0; k < COEF_BANDS; ++k)
1657         for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1658           full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
1659 }
1660
1661 #if 0 && CONFIG_INTERNAL_STATS
1662 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
1663   VP9_COMMON *const cm = &cpi->common;
1664   FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
1665   int recon_err;
1666
1667   vp9_clear_system_state();
1668
1669   recon_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
1670
1671   if (cpi->twopass.total_left_stats.coded_error != 0.0)
1672     fprintf(f, "%10u %10d %10d %10d %10d"
1673         "%10"PRId64" %10"PRId64" %10"PRId64" %10"PRId64" %10d "
1674         "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
1675         "%6d %6d %5d %5d %5d "
1676         "%10"PRId64" %10.3lf"
1677         "%10lf %8u %10d %10d %10d\n",
1678         cpi->common.current_video_frame, cpi->rc.this_frame_target,
1679         cpi->rc.projected_frame_size,
1680         cpi->rc.projected_frame_size / cpi->common.MBs,
1681         (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
1682         cpi->rc.vbr_bits_off_target,
1683         cpi->rc.total_target_vs_actual,
1684         (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
1685         cpi->rc.total_actual_bits, cm->base_qindex,
1686         vp9_convert_qindex_to_q(cm->base_qindex),
1687         (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
1688         cpi->rc.avg_q,
1689         vp9_convert_qindex_to_q(cpi->rc.ni_av_qi),
1690         vp9_convert_qindex_to_q(cpi->oxcf.cq_level),
1691         cpi->refresh_last_frame, cpi->refresh_golden_frame,
1692         cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
1693         cpi->twopass.bits_left,
1694         cpi->twopass.total_left_stats.coded_error,
1695         cpi->twopass.bits_left /
1696             (1 + cpi->twopass.total_left_stats.coded_error),
1697         cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
1698         cpi->twopass.kf_zeromotion_pct);
1699
1700   fclose(f);
1701
1702   if (0) {
1703     FILE *const fmodes = fopen("Modes.stt", "a");
1704     int i;
1705
1706     fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
1707             cm->frame_type, cpi->refresh_golden_frame,
1708             cpi->refresh_alt_ref_frame);
1709
1710     for (i = 0; i < MAX_MODES; ++i)
1711       fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
1712
1713     fprintf(fmodes, "\n");
1714
1715     fclose(fmodes);
1716   }
1717 }
1718 #endif
1719
1720 static void encode_without_recode_loop(VP9_COMP *cpi,
1721                                        int q) {
1722   VP9_COMMON *const cm = &cpi->common;
1723   vp9_clear_system_state();
1724   vp9_set_quantizer(cm, q);
1725   setup_frame(cpi);
1726   // Variance adaptive and in frame q adjustment experiments are mutually
1727   // exclusive.
1728   if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
1729     vp9_vaq_frame_setup(cpi);
1730   } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1731     vp9_setup_in_frame_q_adj(cpi);
1732   } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1733     vp9_cyclic_refresh_setup(cpi);
1734   }
1735   // transform / motion compensation build reconstruction frame
1736   vp9_encode_frame(cpi);
1737
1738   // Update the skip mb flag probabilities based on the distribution
1739   // seen in the last encoder iteration.
1740   // update_base_skip_probs(cpi);
1741   vp9_clear_system_state();
1742 }
1743
1744 static void encode_with_recode_loop(VP9_COMP *cpi,
1745                                     size_t *size,
1746                                     uint8_t *dest,
1747                                     int q,
1748                                     int bottom_index,
1749                                     int top_index) {
1750   VP9_COMMON *const cm = &cpi->common;
1751   RATE_CONTROL *const rc = &cpi->rc;
1752   int loop_count = 0;
1753   int loop = 0;
1754   int overshoot_seen = 0;
1755   int undershoot_seen = 0;
1756   int q_low = bottom_index, q_high = top_index;
1757   int frame_over_shoot_limit;
1758   int frame_under_shoot_limit;
1759
1760   // Decide frame size bounds
1761   vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
1762                                    &frame_under_shoot_limit,
1763                                    &frame_over_shoot_limit);
1764
1765   do {
1766     vp9_clear_system_state();
1767
1768     vp9_set_quantizer(cm, q);
1769
1770     if (loop_count == 0)
1771       setup_frame(cpi);
1772
1773     // Variance adaptive and in frame q adjustment experiments are mutually
1774     // exclusive.
1775     if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
1776       vp9_vaq_frame_setup(cpi);
1777     } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1778       vp9_setup_in_frame_q_adj(cpi);
1779     }
1780
1781     // transform / motion compensation build reconstruction frame
1782     vp9_encode_frame(cpi);
1783
1784     // Update the skip mb flag probabilities based on the distribution
1785     // seen in the last encoder iteration.
1786     // update_base_skip_probs(cpi);
1787
1788     vp9_clear_system_state();
1789
1790     // Dummy pack of the bitstream using up to date stats to get an
1791     // accurate estimate of output frame size to determine if we need
1792     // to recode.
1793     if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
1794       save_coding_context(cpi);
1795       cpi->dummy_packing = 1;
1796       if (!cpi->sf.use_nonrd_pick_mode)
1797         vp9_pack_bitstream(cpi, dest, size);
1798
1799       rc->projected_frame_size = (int)(*size) << 3;
1800       restore_coding_context(cpi);
1801
1802       if (frame_over_shoot_limit == 0)
1803         frame_over_shoot_limit = 1;
1804     }
1805
1806     if (cpi->oxcf.rc_mode == VPX_Q) {
1807       loop = 0;
1808     } else {
1809       if ((cm->frame_type == KEY_FRAME) &&
1810            rc->this_key_frame_forced &&
1811            (rc->projected_frame_size < rc->max_frame_bandwidth)) {
1812         int last_q = q;
1813         int kf_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
1814
1815         int high_err_target = cpi->ambient_err;
1816         int low_err_target = cpi->ambient_err >> 1;
1817
1818         // Prevent possible divide by zero error below for perfect KF
1819         kf_err += !kf_err;
1820
1821         // The key frame is not good enough or we can afford
1822         // to make it better without undue risk of popping.
1823         if ((kf_err > high_err_target &&
1824              rc->projected_frame_size <= frame_over_shoot_limit) ||
1825             (kf_err > low_err_target &&
1826              rc->projected_frame_size <= frame_under_shoot_limit)) {
1827           // Lower q_high
1828           q_high = q > q_low ? q - 1 : q_low;
1829
1830           // Adjust Q
1831           q = (q * high_err_target) / kf_err;
1832           q = MIN(q, (q_high + q_low) >> 1);
1833         } else if (kf_err < low_err_target &&
1834                    rc->projected_frame_size >= frame_under_shoot_limit) {
1835           // The key frame is much better than the previous frame
1836           // Raise q_low
1837           q_low = q < q_high ? q + 1 : q_high;
1838
1839           // Adjust Q
1840           q = (q * low_err_target) / kf_err;
1841           q = MIN(q, (q_high + q_low + 1) >> 1);
1842         }
1843
1844         // Clamp Q to upper and lower limits:
1845         q = clamp(q, q_low, q_high);
1846
1847         loop = q != last_q;
1848       } else if (recode_loop_test(
1849           cpi, frame_over_shoot_limit, frame_under_shoot_limit,
1850           q, MAX(q_high, top_index), bottom_index)) {
1851         // Is the projected frame size out of range and are we allowed
1852         // to attempt to recode.
1853         int last_q = q;
1854         int retries = 0;
1855
1856         // Frame size out of permitted range:
1857         // Update correction factor & compute new Q to try...
1858
1859         // Frame is too large
1860         if (rc->projected_frame_size > rc->this_frame_target) {
1861           // Special case if the projected size is > the max allowed.
1862           if (rc->projected_frame_size >= rc->max_frame_bandwidth)
1863             q_high = rc->worst_quality;
1864
1865           // Raise Qlow as to at least the current value
1866           q_low = q < q_high ? q + 1 : q_high;
1867
1868           if (undershoot_seen || loop_count > 1) {
1869             // Update rate_correction_factor unless
1870             vp9_rc_update_rate_correction_factors(cpi, 1);
1871
1872             q = (q_high + q_low + 1) / 2;
1873           } else {
1874             // Update rate_correction_factor unless
1875             vp9_rc_update_rate_correction_factors(cpi, 0);
1876
1877             q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1878                                    bottom_index, MAX(q_high, top_index));
1879
1880             while (q < q_low && retries < 10) {
1881               vp9_rc_update_rate_correction_factors(cpi, 0);
1882               q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1883                                      bottom_index, MAX(q_high, top_index));
1884               retries++;
1885             }
1886           }
1887
1888           overshoot_seen = 1;
1889         } else {
1890           // Frame is too small
1891           q_high = q > q_low ? q - 1 : q_low;
1892
1893           if (overshoot_seen || loop_count > 1) {
1894             vp9_rc_update_rate_correction_factors(cpi, 1);
1895             q = (q_high + q_low) / 2;
1896           } else {
1897             vp9_rc_update_rate_correction_factors(cpi, 0);
1898             q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1899                                    bottom_index, top_index);
1900             // Special case reset for qlow for constrained quality.
1901             // This should only trigger where there is very substantial
1902             // undershoot on a frame and the auto cq level is above
1903             // the user passsed in value.
1904             if (cpi->oxcf.rc_mode == VPX_CQ &&
1905                 q < q_low) {
1906               q_low = q;
1907             }
1908
1909             while (q > q_high && retries < 10) {
1910               vp9_rc_update_rate_correction_factors(cpi, 0);
1911               q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1912                                      bottom_index, top_index);
1913               retries++;
1914             }
1915           }
1916
1917           undershoot_seen = 1;
1918         }
1919
1920         // Clamp Q to upper and lower limits:
1921         q = clamp(q, q_low, q_high);
1922
1923         loop = q != last_q;
1924       } else {
1925         loop = 0;
1926       }
1927     }
1928
1929     // Special case for overlay frame.
1930     if (rc->is_src_frame_alt_ref &&
1931         rc->projected_frame_size < rc->max_frame_bandwidth)
1932       loop = 0;
1933
1934     if (loop) {
1935       loop_count++;
1936
1937 #if CONFIG_INTERNAL_STATS
1938       cpi->tot_recode_hits++;
1939 #endif
1940     }
1941   } while (loop);
1942 }
1943
1944 static void get_ref_frame_flags(VP9_COMP *cpi) {
1945   if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
1946     cpi->gold_is_last = 1;
1947   else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
1948     cpi->gold_is_last = 0;
1949
1950   if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
1951     cpi->alt_is_last = 1;
1952   else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
1953     cpi->alt_is_last = 0;
1954
1955   if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
1956     cpi->gold_is_alt = 1;
1957   else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
1958     cpi->gold_is_alt = 0;
1959
1960   cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1961
1962   if (cpi->gold_is_last)
1963     cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
1964
1965   if (cpi->rc.frames_till_gf_update_due == INT_MAX)
1966     cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
1967
1968   if (cpi->alt_is_last)
1969     cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
1970
1971   if (cpi->gold_is_alt)
1972     cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
1973 }
1974
1975 static void set_ext_overrides(VP9_COMP *cpi) {
1976   // Overrides the defaults with the externally supplied values with
1977   // vp9_update_reference() and vp9_update_entropy() calls
1978   // Note: The overrides are valid only for the next frame passed
1979   // to encode_frame_to_data_rate() function
1980   if (cpi->ext_refresh_frame_context_pending) {
1981     cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
1982     cpi->ext_refresh_frame_context_pending = 0;
1983   }
1984   if (cpi->ext_refresh_frame_flags_pending) {
1985     cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
1986     cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
1987     cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
1988     cpi->ext_refresh_frame_flags_pending = 0;
1989   }
1990 }
1991
1992 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
1993                                           YV12_BUFFER_CONFIG *unscaled,
1994                                           YV12_BUFFER_CONFIG *scaled) {
1995   if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
1996       cm->mi_rows * MI_SIZE != unscaled->y_height) {
1997     scale_and_extend_frame_nonnormative(unscaled, scaled);
1998     return scaled;
1999   } else {
2000     return unscaled;
2001   }
2002 }
2003
2004 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2005                                       size_t *size,
2006                                       uint8_t *dest,
2007                                       unsigned int *frame_flags) {
2008   VP9_COMMON *const cm = &cpi->common;
2009   TX_SIZE t;
2010   int q;
2011   int top_index;
2012   int bottom_index;
2013
2014   const SPEED_FEATURES *const sf = &cpi->sf;
2015   const unsigned int max_mv_def = MIN(cm->width, cm->height);
2016   struct segmentation *const seg = &cm->seg;
2017   set_ext_overrides(cpi);
2018
2019   cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
2020                                       &cpi->scaled_source);
2021
2022   if (cpi->unscaled_last_source != NULL)
2023     cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
2024                                              &cpi->scaled_last_source);
2025
2026   vp9_scale_references(cpi);
2027
2028   vp9_clear_system_state();
2029
2030   // Enable or disable mode based tweaking of the zbin.
2031   // For 2 pass only used where GF/ARF prediction quality
2032   // is above a threshold.
2033   cpi->zbin_mode_boost = 0;
2034   cpi->zbin_mode_boost_enabled = 0;
2035
2036   // Current default encoder behavior for the altref sign bias.
2037   cm->ref_frame_sign_bias[ALTREF_FRAME] = cpi->rc.source_alt_ref_active;
2038
2039   // Set default state for segment based loop filter update flags.
2040   cm->lf.mode_ref_delta_update = 0;
2041
2042   // Initialize cpi->mv_step_param to default based on max resolution.
2043   cpi->mv_step_param = vp9_init_search_range(sf, max_mv_def);
2044   // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2045   if (sf->mv.auto_mv_step_size) {
2046     if (frame_is_intra_only(cm)) {
2047       // Initialize max_mv_magnitude for use in the first INTER frame
2048       // after a key/intra-only frame.
2049       cpi->max_mv_magnitude = max_mv_def;
2050     } else {
2051       if (cm->show_frame)
2052         // Allow mv_steps to correspond to twice the max mv magnitude found
2053         // in the previous frame, capped by the default max_mv_magnitude based
2054         // on resolution.
2055         cpi->mv_step_param = vp9_init_search_range(sf, MIN(max_mv_def, 2 *
2056                                  cpi->max_mv_magnitude));
2057       cpi->max_mv_magnitude = 0;
2058     }
2059   }
2060
2061   // Set various flags etc to special state if it is a key frame.
2062   if (frame_is_intra_only(cm)) {
2063     // Reset the loop filter deltas and segmentation map.
2064     vp9_reset_segment_features(&cm->seg);
2065
2066     // If segmentation is enabled force a map update for key frames.
2067     if (seg->enabled) {
2068       seg->update_map = 1;
2069       seg->update_data = 1;
2070     }
2071
2072     // The alternate reference frame cannot be active for a key frame.
2073     cpi->rc.source_alt_ref_active = 0;
2074
2075     cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2076     cm->frame_parallel_decoding_mode =
2077       (cpi->oxcf.frame_parallel_decoding_mode != 0);
2078
2079     // By default, encoder assumes decoder can use prev_mi.
2080     cm->coding_use_prev_mi = 1;
2081     if (cm->error_resilient_mode) {
2082       cm->coding_use_prev_mi = 0;
2083       cm->frame_parallel_decoding_mode = 1;
2084       cm->reset_frame_context = 0;
2085       cm->refresh_frame_context = 0;
2086     } else if (cm->intra_only) {
2087       // Only reset the current context.
2088       cm->reset_frame_context = 2;
2089     }
2090   }
2091
2092   // Configure experimental use of segmentation for enhanced coding of
2093   // static regions if indicated.
2094   // Only allowed in second pass of two pass (as requires lagged coding)
2095   // and if the relevant speed feature flag is set.
2096   if (cpi->pass == 2 && cpi->sf.static_segmentation)
2097     configure_static_seg_features(cpi);
2098
2099   // For 1 pass CBR, check if we are dropping this frame.
2100   // Never drop on key frame.
2101   if (cpi->pass == 0 &&
2102       cpi->oxcf.rc_mode == VPX_CBR &&
2103       cm->frame_type != KEY_FRAME) {
2104     if (vp9_rc_drop_frame(cpi)) {
2105       vp9_rc_postencode_update_drop_frame(cpi);
2106       ++cm->current_video_frame;
2107       return;
2108     }
2109   }
2110
2111   vp9_clear_system_state();
2112
2113 #if CONFIG_VP9_POSTPROC
2114   if (cpi->oxcf.noise_sensitivity > 0) {
2115     int l = 0;
2116     switch (cpi->oxcf.noise_sensitivity) {
2117       case 1:
2118         l = 20;
2119         break;
2120       case 2:
2121         l = 40;
2122         break;
2123       case 3:
2124         l = 60;
2125         break;
2126       case 4:
2127       case 5:
2128         l = 100;
2129         break;
2130       case 6:
2131         l = 150;
2132         break;
2133     }
2134     vp9_denoise(cpi->Source, cpi->Source, l);
2135   }
2136 #endif
2137
2138 #ifdef OUTPUT_YUV_DENOISED
2139   vp9_write_yuv_frame(&cpi->denoiser.running_avg_y[INTRA_FRAME],
2140                       yuv_denoised_file);
2141 #endif
2142 #ifdef OUTPUT_YUV_SRC
2143   vp9_write_yuv_frame(cpi->Source, yuv_file);
2144 #endif
2145
2146   set_speed_features(cpi);
2147
2148   // Decide q and q bounds.
2149   q = vp9_rc_pick_q_and_bounds(cpi, &bottom_index, &top_index);
2150
2151   if (!frame_is_intra_only(cm)) {
2152     cm->interp_filter = DEFAULT_INTERP_FILTER;
2153     /* TODO: Decide this more intelligently */
2154     set_high_precision_mv(cpi, q < HIGH_PRECISION_MV_QTHRESH);
2155   }
2156
2157   if (cpi->sf.recode_loop == DISALLOW_RECODE) {
2158     encode_without_recode_loop(cpi, q);
2159   } else {
2160     encode_with_recode_loop(cpi, size, dest, q, bottom_index, top_index);
2161   }
2162
2163   // Special case code to reduce pulsing when key frames are forced at a
2164   // fixed interval. Note the reconstruction error if it is the frame before
2165   // the force key frame
2166   if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
2167     cpi->ambient_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2168   }
2169
2170   // If the encoder forced a KEY_FRAME decision
2171   if (cm->frame_type == KEY_FRAME)
2172     cpi->refresh_last_frame = 1;
2173
2174   cm->frame_to_show = get_frame_new_buffer(cm);
2175
2176 #if WRITE_RECON_BUFFER
2177   if (cm->show_frame)
2178     write_cx_frame_to_file(cm->frame_to_show,
2179                            cm->current_video_frame);
2180   else
2181     write_cx_frame_to_file(cm->frame_to_show,
2182                            cm->current_video_frame + 1000);
2183 #endif
2184
2185   // Pick the loop filter level for the frame.
2186   loopfilter_frame(cpi, cm);
2187
2188 #if WRITE_RECON_BUFFER
2189   if (cm->show_frame)
2190     write_cx_frame_to_file(cm->frame_to_show,
2191                            cm->current_video_frame + 2000);
2192   else
2193     write_cx_frame_to_file(cm->frame_to_show,
2194                            cm->current_video_frame + 3000);
2195 #endif
2196
2197   // build the bitstream
2198   cpi->dummy_packing = 0;
2199   vp9_pack_bitstream(cpi, dest, size);
2200
2201   if (cm->seg.update_map)
2202     update_reference_segmentation_map(cpi);
2203
2204   release_scaled_references(cpi);
2205   vp9_update_reference_frames(cpi);
2206
2207   for (t = TX_4X4; t <= TX_32X32; t++)
2208     full_to_model_counts(cm->counts.coef[t], cpi->coef_counts[t]);
2209
2210   if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
2211     vp9_adapt_coef_probs(cm);
2212
2213   if (!frame_is_intra_only(cm)) {
2214     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2215       vp9_adapt_mode_probs(cm);
2216       vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2217     }
2218   }
2219
2220   if (cpi->refresh_golden_frame == 1)
2221     cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
2222   else
2223     cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
2224
2225   if (cpi->refresh_alt_ref_frame == 1)
2226     cpi->frame_flags |= FRAMEFLAGS_ALTREF;
2227   else
2228     cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
2229
2230   get_ref_frame_flags(cpi);
2231
2232   cm->last_frame_type = cm->frame_type;
2233   vp9_rc_postencode_update(cpi, *size);
2234
2235 #if 0
2236   output_frame_level_debug_stats(cpi);
2237 #endif
2238
2239   if (cm->frame_type == KEY_FRAME) {
2240     // Tell the caller that the frame was coded as a key frame
2241     *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
2242
2243 #if CONFIG_MULTIPLE_ARF
2244     // Reset the sequence number.
2245     if (cpi->multi_arf_enabled) {
2246       cpi->sequence_number = 0;
2247       cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
2248       cpi->new_frame_coding_order_period = -1;
2249     }
2250 #endif
2251   } else {
2252     *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
2253
2254 #if CONFIG_MULTIPLE_ARF
2255     /* Increment position in the coded frame sequence. */
2256     if (cpi->multi_arf_enabled) {
2257       ++cpi->sequence_number;
2258       if (cpi->sequence_number >= cpi->frame_coding_order_period) {
2259         cpi->sequence_number = 0;
2260         cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
2261         cpi->new_frame_coding_order_period = -1;
2262       }
2263       cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
2264       assert(cpi->this_frame_weight >= 0);
2265     }
2266 #endif
2267   }
2268
2269   // Clear the one shot update flags for segmentation map and mode/ref loop
2270   // filter deltas.
2271   cm->seg.update_map = 0;
2272   cm->seg.update_data = 0;
2273   cm->lf.mode_ref_delta_update = 0;
2274
2275   // keep track of the last coded dimensions
2276   cm->last_width = cm->width;
2277   cm->last_height = cm->height;
2278
2279   // reset to normal state now that we are done.
2280   if (!cm->show_existing_frame)
2281     cm->last_show_frame = cm->show_frame;
2282
2283   if (cm->show_frame) {
2284     vp9_swap_mi_and_prev_mi(cm);
2285
2286     // Don't increment frame counters if this was an altref buffer
2287     // update not a real frame
2288     ++cm->current_video_frame;
2289     if (cpi->use_svc)
2290       vp9_inc_frame_in_layer(&cpi->svc);
2291   }
2292 }
2293
2294 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2295                       unsigned int *frame_flags) {
2296   vp9_rc_get_svc_params(cpi);
2297   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2298 }
2299
2300 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2301                         unsigned int *frame_flags) {
2302   if (cpi->oxcf.rc_mode == VPX_CBR) {
2303     vp9_rc_get_one_pass_cbr_params(cpi);
2304   } else {
2305     vp9_rc_get_one_pass_vbr_params(cpi);
2306   }
2307   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2308 }
2309
2310 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
2311                         uint8_t *dest, unsigned int *frame_flags) {
2312   cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
2313
2314   vp9_rc_get_second_pass_params(cpi);
2315   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2316
2317   vp9_twopass_postencode_update(cpi);
2318 }
2319
2320 static void check_initial_width(VP9_COMP *cpi, int subsampling_x,
2321                                 int subsampling_y) {
2322   VP9_COMMON *const cm = &cpi->common;
2323
2324   if (!cpi->initial_width) {
2325     cm->subsampling_x = subsampling_x;
2326     cm->subsampling_y = subsampling_y;
2327     alloc_raw_frame_buffers(cpi);
2328     cpi->initial_width = cm->width;
2329     cpi->initial_height = cm->height;
2330   }
2331 }
2332
2333
2334 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
2335                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
2336                           int64_t end_time) {
2337   VP9_COMMON *cm = &cpi->common;
2338   struct vpx_usec_timer timer;
2339   int res = 0;
2340   const int subsampling_x = sd->uv_width  < sd->y_width;
2341   const int subsampling_y = sd->uv_height < sd->y_height;
2342
2343   check_initial_width(cpi, subsampling_x, subsampling_y);
2344   vpx_usec_timer_start(&timer);
2345   if (vp9_lookahead_push(cpi->lookahead,
2346                          sd, time_stamp, end_time, frame_flags))
2347     res = -1;
2348   vpx_usec_timer_mark(&timer);
2349   cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
2350
2351   if (cm->profile == PROFILE_0 && (subsampling_x != 1 || subsampling_y != 1)) {
2352     vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
2353                        "Non-4:2:0 color space requires profile >= 1");
2354     res = -1;
2355   }
2356
2357   return res;
2358 }
2359
2360
2361 static int frame_is_reference(const VP9_COMP *cpi) {
2362   const VP9_COMMON *cm = &cpi->common;
2363
2364   return cm->frame_type == KEY_FRAME ||
2365          cpi->refresh_last_frame ||
2366          cpi->refresh_golden_frame ||
2367          cpi->refresh_alt_ref_frame ||
2368          cm->refresh_frame_context ||
2369          cm->lf.mode_ref_delta_update ||
2370          cm->seg.update_map ||
2371          cm->seg.update_data;
2372 }
2373
2374 #if CONFIG_MULTIPLE_ARF
2375 int is_next_frame_arf(VP9_COMP *cpi) {
2376   // Negative entry in frame_coding_order indicates an ARF at this position.
2377   return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
2378 }
2379 #endif
2380
2381 void adjust_frame_rate(VP9_COMP *cpi) {
2382   int64_t this_duration;
2383   int step = 0;
2384
2385   if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
2386     this_duration = cpi->source->ts_end - cpi->source->ts_start;
2387     step = 1;
2388   } else {
2389     int64_t last_duration = cpi->last_end_time_stamp_seen
2390         - cpi->last_time_stamp_seen;
2391
2392     this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
2393
2394     // do a step update if the duration changes by 10%
2395     if (last_duration)
2396       step = (int)((this_duration - last_duration) * 10 / last_duration);
2397   }
2398
2399   if (this_duration) {
2400     if (step) {
2401       vp9_new_framerate(cpi, 10000000.0 / this_duration);
2402     } else {
2403       // Average this frame's rate into the last second's average
2404       // frame rate. If we haven't seen 1 second yet, then average
2405       // over the whole interval seen.
2406       const double interval = MIN((double)(cpi->source->ts_end
2407                                    - cpi->first_time_stamp_ever), 10000000.0);
2408       double avg_duration = 10000000.0 / cpi->oxcf.framerate;
2409       avg_duration *= (interval - avg_duration + this_duration);
2410       avg_duration /= interval;
2411
2412       vp9_new_framerate(cpi, 10000000.0 / avg_duration);
2413     }
2414   }
2415   cpi->last_time_stamp_seen = cpi->source->ts_start;
2416   cpi->last_end_time_stamp_seen = cpi->source->ts_end;
2417 }
2418
2419 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
2420                             size_t *size, uint8_t *dest,
2421                             int64_t *time_stamp, int64_t *time_end, int flush) {
2422   VP9_COMMON *const cm = &cpi->common;
2423   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
2424   RATE_CONTROL *const rc = &cpi->rc;
2425   struct vpx_usec_timer  cmptimer;
2426   YV12_BUFFER_CONFIG *force_src_buffer = NULL;
2427   MV_REFERENCE_FRAME ref_frame;
2428
2429   if (!cpi)
2430     return -1;
2431
2432   if (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2) {
2433     vp9_restore_layer_context(cpi);
2434   }
2435
2436   vpx_usec_timer_start(&cmptimer);
2437
2438   cpi->source = NULL;
2439   cpi->last_source = NULL;
2440
2441   set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
2442
2443   // Normal defaults
2444   cm->reset_frame_context = 0;
2445   cm->refresh_frame_context = 1;
2446   cpi->refresh_last_frame = 1;
2447   cpi->refresh_golden_frame = 0;
2448   cpi->refresh_alt_ref_frame = 0;
2449
2450   // Should we code an alternate reference frame.
2451   if (is_altref_enabled(&cpi->oxcf) && rc->source_alt_ref_pending) {
2452     int frames_to_arf;
2453
2454 #if CONFIG_MULTIPLE_ARF
2455     assert(!cpi->multi_arf_enabled ||
2456            cpi->frame_coding_order[cpi->sequence_number] < 0);
2457
2458     if (cpi->multi_arf_enabled && (cpi->pass == 2))
2459       frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
2460           - cpi->next_frame_in_order;
2461     else
2462 #endif
2463       frames_to_arf = rc->frames_till_gf_update_due;
2464
2465     assert(frames_to_arf <= rc->frames_to_key);
2466
2467     if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
2468 #if CONFIG_MULTIPLE_ARF
2469       cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
2470 #else
2471       cpi->alt_ref_source = cpi->source;
2472 #endif
2473
2474       if (cpi->oxcf.arnr_max_frames > 0) {
2475         // Produce the filtered ARF frame.
2476         // TODO(agrange) merge these two functions.
2477         vp9_configure_arnr_filter(cpi, frames_to_arf, rc->gfu_boost);
2478         vp9_temporal_filter_prepare(cpi, frames_to_arf);
2479         vp9_extend_frame_borders(&cpi->alt_ref_buffer);
2480         force_src_buffer = &cpi->alt_ref_buffer;
2481       }
2482
2483       cm->show_frame = 0;
2484       cpi->refresh_alt_ref_frame = 1;
2485       cpi->refresh_golden_frame = 0;
2486       cpi->refresh_last_frame = 0;
2487       rc->is_src_frame_alt_ref = 0;
2488
2489 #if CONFIG_MULTIPLE_ARF
2490       if (!cpi->multi_arf_enabled)
2491 #endif
2492         rc->source_alt_ref_pending = 0;
2493     } else {
2494       rc->source_alt_ref_pending = 0;
2495     }
2496   }
2497
2498   if (!cpi->source) {
2499 #if CONFIG_MULTIPLE_ARF
2500     int i;
2501 #endif
2502
2503     // Get last frame source.
2504     if (cm->current_video_frame > 0) {
2505       if ((cpi->last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
2506         return -1;
2507     }
2508
2509     if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
2510       cm->show_frame = 1;
2511       cm->intra_only = 0;
2512
2513 #if CONFIG_MULTIPLE_ARF
2514       // Is this frame the ARF overlay.
2515       rc->is_src_frame_alt_ref = 0;
2516       for (i = 0; i < cpi->arf_buffered; ++i) {
2517         if (cpi->source == cpi->alt_ref_source[i]) {
2518           rc->is_src_frame_alt_ref = 1;
2519           cpi->refresh_golden_frame = 1;
2520           break;
2521         }
2522       }
2523 #else
2524       rc->is_src_frame_alt_ref = cpi->alt_ref_source &&
2525                                  (cpi->source == cpi->alt_ref_source);
2526 #endif
2527       if (rc->is_src_frame_alt_ref) {
2528         // Current frame is an ARF overlay frame.
2529 #if CONFIG_MULTIPLE_ARF
2530         cpi->alt_ref_source[i] = NULL;
2531 #else
2532         cpi->alt_ref_source = NULL;
2533 #endif
2534         // Don't refresh the last buffer for an ARF overlay frame. It will
2535         // become the GF so preserve last as an alternative prediction option.
2536         cpi->refresh_last_frame = 0;
2537       }
2538 #if CONFIG_MULTIPLE_ARF
2539       ++cpi->next_frame_in_order;
2540 #endif
2541     }
2542   }
2543
2544   if (cpi->source) {
2545     cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
2546                                                            : &cpi->source->img;
2547
2548   if (cpi->last_source != NULL) {
2549     cpi->unscaled_last_source = &cpi->last_source->img;
2550   } else {
2551     cpi->unscaled_last_source = NULL;
2552   }
2553
2554     *time_stamp = cpi->source->ts_start;
2555     *time_end = cpi->source->ts_end;
2556     *frame_flags = cpi->source->flags;
2557
2558 #if CONFIG_MULTIPLE_ARF
2559     if (cm->frame_type != KEY_FRAME && cpi->pass == 2)
2560       rc->source_alt_ref_pending = is_next_frame_arf(cpi);
2561 #endif
2562   } else {
2563     *size = 0;
2564     if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
2565       vp9_end_first_pass(cpi);    /* get last stats packet */
2566       cpi->twopass.first_pass_done = 1;
2567     }
2568     return -1;
2569   }
2570
2571   if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
2572     cpi->first_time_stamp_ever = cpi->source->ts_start;
2573     cpi->last_end_time_stamp_seen = cpi->source->ts_start;
2574   }
2575
2576   // adjust frame rates based on timestamps given
2577   if (cm->show_frame) {
2578     adjust_frame_rate(cpi);
2579   }
2580
2581   if (cpi->svc.number_temporal_layers > 1 &&
2582       cpi->oxcf.rc_mode == VPX_CBR) {
2583     vp9_update_temporal_layer_framerate(cpi);
2584     vp9_restore_layer_context(cpi);
2585   }
2586
2587   // start with a 0 size frame
2588   *size = 0;
2589
2590   // Clear down mmx registers
2591   vp9_clear_system_state();
2592
2593   /* find a free buffer for the new frame, releasing the reference previously
2594    * held.
2595    */
2596   cm->frame_bufs[cm->new_fb_idx].ref_count--;
2597   cm->new_fb_idx = get_free_fb(cm);
2598
2599 #if CONFIG_MULTIPLE_ARF
2600   /* Set up the correct ARF frame. */
2601   if (cpi->refresh_alt_ref_frame) {
2602     ++cpi->arf_buffered;
2603   }
2604   if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
2605       (cpi->pass == 2)) {
2606     cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
2607   }
2608 #endif
2609
2610   cpi->frame_flags = *frame_flags;
2611
2612   if (cpi->pass == 2 &&
2613       cm->current_video_frame == 0 &&
2614       cpi->oxcf.allow_spatial_resampling &&
2615       cpi->oxcf.rc_mode == VPX_VBR) {
2616     // Internal scaling is triggered on the first frame.
2617     vp9_set_size_literal(cpi, cpi->oxcf.scaled_frame_width,
2618                          cpi->oxcf.scaled_frame_height);
2619   }
2620
2621   // Reset the frame pointers to the current frame size
2622   vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
2623                            cm->width, cm->height,
2624                            cm->subsampling_x, cm->subsampling_y,
2625                            VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
2626
2627   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2628     const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
2629     YV12_BUFFER_CONFIG *const buf = &cm->frame_bufs[idx].buf;
2630     RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
2631     ref_buf->buf = buf;
2632     ref_buf->idx = idx;
2633     vp9_setup_scale_factors_for_frame(&ref_buf->sf,
2634                                       buf->y_crop_width, buf->y_crop_height,
2635                                       cm->width, cm->height);
2636
2637     if (vp9_is_scaled(&ref_buf->sf))
2638       vp9_extend_frame_borders(buf);
2639   }
2640
2641   set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
2642
2643   if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2644     vp9_vaq_init();
2645   }
2646
2647   if (cpi->pass == 1 &&
2648       (!cpi->use_svc || cpi->svc.number_temporal_layers == 1)) {
2649     const int lossless = is_lossless_requested(&cpi->oxcf);
2650     cpi->mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vp9_fdct4x4;
2651     cpi->mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
2652     vp9_first_pass(cpi);
2653   } else if (cpi->pass == 2 &&
2654       (!cpi->use_svc || cpi->svc.number_temporal_layers == 1)) {
2655     Pass2Encode(cpi, size, dest, frame_flags);
2656   } else if (cpi->use_svc) {
2657     SvcEncode(cpi, size, dest, frame_flags);
2658   } else {
2659     // One pass encode
2660     Pass0Encode(cpi, size, dest, frame_flags);
2661   }
2662
2663   if (cm->refresh_frame_context)
2664     cm->frame_contexts[cm->frame_context_idx] = cm->fc;
2665
2666   // Frame was dropped, release scaled references.
2667   if (*size == 0) {
2668     release_scaled_references(cpi);
2669   }
2670
2671   if (*size > 0) {
2672     cpi->droppable = !frame_is_reference(cpi);
2673   }
2674
2675   // Save layer specific state.
2676   if ((cpi->svc.number_temporal_layers > 1 &&
2677       cpi->oxcf.rc_mode == VPX_CBR) ||
2678       (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2)) {
2679     vp9_save_layer_context(cpi);
2680   }
2681
2682   vpx_usec_timer_mark(&cmptimer);
2683   cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
2684
2685   if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
2686     generate_psnr_packet(cpi);
2687
2688 #if CONFIG_INTERNAL_STATS
2689
2690   if (cpi->pass != 1) {
2691     cpi->bytes += (int)(*size);
2692
2693     if (cm->show_frame) {
2694       cpi->count++;
2695
2696       if (cpi->b_calculate_psnr) {
2697         YV12_BUFFER_CONFIG *orig = cpi->Source;
2698         YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2699         YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
2700         PSNR_STATS psnr;
2701         calc_psnr(orig, recon, &psnr);
2702
2703         cpi->total += psnr.psnr[0];
2704         cpi->total_y += psnr.psnr[1];
2705         cpi->total_u += psnr.psnr[2];
2706         cpi->total_v += psnr.psnr[3];
2707         cpi->total_sq_error += psnr.sse[0];
2708         cpi->total_samples += psnr.samples[0];
2709
2710         {
2711           PSNR_STATS psnr2;
2712           double frame_ssim2 = 0, weight = 0;
2713 #if CONFIG_VP9_POSTPROC
2714           vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
2715                       cm->lf.filter_level * 10 / 6);
2716 #endif
2717           vp9_clear_system_state();
2718
2719           calc_psnr(orig, pp, &psnr2);
2720
2721           cpi->totalp += psnr2.psnr[0];
2722           cpi->totalp_y += psnr2.psnr[1];
2723           cpi->totalp_u += psnr2.psnr[2];
2724           cpi->totalp_v += psnr2.psnr[3];
2725           cpi->totalp_sq_error += psnr2.sse[0];
2726           cpi->totalp_samples += psnr2.samples[0];
2727
2728           frame_ssim2 = vp9_calc_ssim(orig, recon, 1, &weight);
2729
2730           cpi->summed_quality += frame_ssim2 * weight;
2731           cpi->summed_weights += weight;
2732
2733           frame_ssim2 = vp9_calc_ssim(orig, &cm->post_proc_buffer, 1, &weight);
2734
2735           cpi->summedp_quality += frame_ssim2 * weight;
2736           cpi->summedp_weights += weight;
2737 #if 0
2738           {
2739             FILE *f = fopen("q_used.stt", "a");
2740             fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
2741                     cpi->common.current_video_frame, y2, u2, v2,
2742                     frame_psnr2, frame_ssim2);
2743             fclose(f);
2744           }
2745 #endif
2746         }
2747       }
2748
2749       if (cpi->b_calculate_ssimg) {
2750         double y, u, v, frame_all;
2751         frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u, &v);
2752         cpi->total_ssimg_y += y;
2753         cpi->total_ssimg_u += u;
2754         cpi->total_ssimg_v += v;
2755         cpi->total_ssimg_all += frame_all;
2756       }
2757     }
2758   }
2759
2760 #endif
2761   return 0;
2762 }
2763
2764 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
2765                               vp9_ppflags_t *flags) {
2766   VP9_COMMON *cm = &cpi->common;
2767 #if !CONFIG_VP9_POSTPROC
2768   (void)flags;
2769 #endif
2770
2771   if (!cm->show_frame) {
2772     return -1;
2773   } else {
2774     int ret;
2775 #if CONFIG_VP9_POSTPROC
2776     ret = vp9_post_proc_frame(cm, dest, flags);
2777 #else
2778     if (cm->frame_to_show) {
2779       *dest = *cm->frame_to_show;
2780       dest->y_width = cm->width;
2781       dest->y_height = cm->height;
2782       dest->uv_width = cm->width >> cm->subsampling_x;
2783       dest->uv_height = cm->height >> cm->subsampling_y;
2784       ret = 0;
2785     } else {
2786       ret = -1;
2787     }
2788 #endif  // !CONFIG_VP9_POSTPROC
2789     vp9_clear_system_state();
2790     return ret;
2791   }
2792 }
2793
2794 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *map, int rows, int cols) {
2795   if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
2796     if (map) {
2797       vpx_memcpy(cpi->active_map, map, rows * cols);
2798       cpi->active_map_enabled = 1;
2799     } else {
2800       cpi->active_map_enabled = 0;
2801     }
2802
2803     return 0;
2804   } else {
2805     // cpi->active_map_enabled = 0;
2806     return -1;
2807   }
2808 }
2809
2810 int vp9_set_internal_size(VP9_COMP *cpi,
2811                           VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
2812   VP9_COMMON *cm = &cpi->common;
2813   int hr = 0, hs = 0, vr = 0, vs = 0;
2814
2815   if (horiz_mode > ONETWO || vert_mode > ONETWO)
2816     return -1;
2817
2818   Scale2Ratio(horiz_mode, &hr, &hs);
2819   Scale2Ratio(vert_mode, &vr, &vs);
2820
2821   // always go to the next whole number
2822   cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
2823   cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
2824
2825   assert(cm->width <= cpi->initial_width);
2826   assert(cm->height <= cpi->initial_height);
2827   update_frame_size(cpi);
2828   return 0;
2829 }
2830
2831 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
2832                          unsigned int height) {
2833   VP9_COMMON *cm = &cpi->common;
2834
2835   check_initial_width(cpi, 1, 1);
2836
2837   if (width) {
2838     cm->width = width;
2839     if (cm->width * 5 < cpi->initial_width) {
2840       cm->width = cpi->initial_width / 5 + 1;
2841       printf("Warning: Desired width too small, changed to %d\n", cm->width);
2842     }
2843     if (cm->width > cpi->initial_width) {
2844       cm->width = cpi->initial_width;
2845       printf("Warning: Desired width too large, changed to %d\n", cm->width);
2846     }
2847   }
2848
2849   if (height) {
2850     cm->height = height;
2851     if (cm->height * 5 < cpi->initial_height) {
2852       cm->height = cpi->initial_height / 5 + 1;
2853       printf("Warning: Desired height too small, changed to %d\n", cm->height);
2854     }
2855     if (cm->height > cpi->initial_height) {
2856       cm->height = cpi->initial_height;
2857       printf("Warning: Desired height too large, changed to %d\n", cm->height);
2858     }
2859   }
2860
2861   assert(cm->width <= cpi->initial_width);
2862   assert(cm->height <= cpi->initial_height);
2863   update_frame_size(cpi);
2864   return 0;
2865 }
2866
2867 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
2868   cpi->use_svc = use_svc;
2869   return;
2870 }
2871
2872 int vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b) {
2873   assert(a->y_crop_width == b->y_crop_width);
2874   assert(a->y_crop_height == b->y_crop_height);
2875
2876   return (int)get_sse(a->y_buffer, a->y_stride, b->y_buffer, b->y_stride,
2877                       a->y_crop_width, a->y_crop_height);
2878 }
2879
2880
2881 int vp9_get_quantizer(VP9_COMP *cpi) {
2882   return cpi->common.base_qindex;
2883 }