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