]> granicus.if.org Git - libvpx/blob - vp8/encoder/onyx_if.c
Revert "vp8: Move loopfilter synchronization to end of encode_frame call."
[libvpx] / vp8 / encoder / onyx_if.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include "vpx_config.h"
12 #include "./vpx_scale_rtcd.h"
13 #include "./vpx_dsp_rtcd.h"
14 #include "./vp8_rtcd.h"
15 #include "vp8/common/onyxc_int.h"
16 #include "vp8/common/blockd.h"
17 #include "onyx_int.h"
18 #include "vp8/common/systemdependent.h"
19 #include "vp8/encoder/quantize.h"
20 #include "vp8/common/alloccommon.h"
21 #include "mcomp.h"
22 #include "firstpass.h"
23 #include "vpx_dsp/psnr.h"
24 #include "vpx_scale/vpx_scale.h"
25 #include "vp8/common/extend.h"
26 #include "ratectrl.h"
27 #include "vp8/common/quant_common.h"
28 #include "segmentation.h"
29 #if CONFIG_POSTPROC
30 #include "vp8/common/postproc.h"
31 #endif
32 #include "vpx_mem/vpx_mem.h"
33 #include "vp8/common/reconintra.h"
34 #include "vp8/common/swapyv12buffer.h"
35 #include "vp8/common/threading.h"
36 #include "vpx_ports/vpx_timer.h"
37 #if ARCH_ARM
38 #include "vpx_ports/arm.h"
39 #endif
40 #if CONFIG_MULTI_RES_ENCODING
41 #include "mr_dissim.h"
42 #endif
43 #include "encodeframe.h"
44
45 #include <math.h>
46 #include <stdio.h>
47 #include <limits.h>
48
49 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
50 extern int vp8_update_coef_context(VP8_COMP *cpi);
51 extern void vp8_update_coef_probs(VP8_COMP *cpi);
52 #endif
53
54 extern void vp8cx_pick_filter_level_fast(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
55 extern void vp8cx_set_alt_lf_level(VP8_COMP *cpi, int filt_val);
56 extern void vp8cx_pick_filter_level(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi);
57
58 extern void vp8_deblock_frame(YV12_BUFFER_CONFIG *source,
59                               YV12_BUFFER_CONFIG *post, int filt_lvl,
60                               int low_var_thresh, int flag);
61 extern void print_parms(VP8_CONFIG *ocf, char *filenam);
62 extern unsigned int vp8_get_processor_freq();
63 extern void print_tree_update_probs();
64 extern int vp8cx_create_encoder_threads(VP8_COMP *cpi);
65 extern void vp8cx_remove_encoder_threads(VP8_COMP *cpi);
66
67 int vp8_estimate_entropy_savings(VP8_COMP *cpi);
68
69 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest);
70
71 extern void vp8_temporal_filter_prepare_c(VP8_COMP *cpi, int distance);
72
73 static void set_default_lf_deltas(VP8_COMP *cpi);
74
75 extern const int vp8_gf_interval_table[101];
76
77 #if CONFIG_INTERNAL_STATS
78 #include "math.h"
79 #include "vpx_dsp/ssim.h"
80 #endif
81
82 #ifdef OUTPUT_YUV_SRC
83 FILE *yuv_file;
84 #endif
85 #ifdef OUTPUT_YUV_DENOISED
86 FILE *yuv_denoised_file;
87 #endif
88
89 #if 0
90 FILE *framepsnr;
91 FILE *kf_list;
92 FILE *keyfile;
93 #endif
94
95 #if 0
96 extern int skip_true_count;
97 extern int skip_false_count;
98 #endif
99
100 #ifdef VP8_ENTROPY_STATS
101 extern int intra_mode_stats[10][10][10];
102 #endif
103
104 #ifdef SPEEDSTATS
105 unsigned int frames_at_speed[16] = { 0, 0, 0, 0, 0, 0, 0, 0,
106                                      0, 0, 0, 0, 0, 0, 0, 0 };
107 unsigned int tot_pm = 0;
108 unsigned int cnt_pm = 0;
109 unsigned int tot_ef = 0;
110 unsigned int cnt_ef = 0;
111 #endif
112
113 #ifdef MODE_STATS
114 extern unsigned __int64 Sectionbits[50];
115 extern int y_modes[5];
116 extern int uv_modes[4];
117 extern int b_modes[10];
118
119 extern int inter_y_modes[10];
120 extern int inter_uv_modes[4];
121 extern unsigned int inter_b_modes[15];
122 #endif
123
124 extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
125
126 extern const int qrounding_factors[129];
127 extern const int qzbin_factors[129];
128 extern void vp8cx_init_quantizer(VP8_COMP *cpi);
129 extern const int vp8cx_base_skip_false_prob[128];
130
131 /* Tables relating active max Q to active min Q */
132 static const unsigned char kf_low_motion_minq[QINDEX_RANGE] = {
133   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
134   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
135   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,
136   1,  1,  1,  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  4,  4,  4,  5,  5,  5,
137   5,  5,  6,  6,  6,  6,  7,  7,  8,  8,  8,  8,  9,  9,  10, 10, 10, 10, 11,
138   11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
139   17, 17, 18, 18, 18, 18, 19, 20, 20, 21, 21, 22, 23, 23
140 };
141 static const unsigned char kf_high_motion_minq[QINDEX_RANGE] = {
142   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
143   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,
144   1,  1,  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  5,
145   5,  5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  8,  8,  8,  8,  9,  9,  10, 10,
146   10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16,
147   16, 16, 16, 17, 17, 18, 18, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21,
148   22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28, 29, 30
149 };
150 static const unsigned char gf_low_motion_minq[QINDEX_RANGE] = {
151   0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  3,  3,  3,
152   3,  4,  4,  4,  4,  5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,
153   8,  8,  9,  9,  9,  9,  10, 10, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
154   15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24,
155   25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34,
156   34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 44,
157   45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58
158 };
159 static const unsigned char gf_mid_motion_minq[QINDEX_RANGE] = {
160   0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  2,  2,  3,  3,  3,  4,  4,  4,  5,
161   5,  5,  6,  6,  6,  7,  7,  7,  8,  8,  8,  9,  9,  9,  10, 10, 10, 10, 11,
162   11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18,
163   18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
164   28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37,
165   37, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50,
166   51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64
167 };
168 static const unsigned char gf_high_motion_minq[QINDEX_RANGE] = {
169   0,  0,  0,  0,  1,  1,  1,  1,  1,  2,  2,  2,  3,  3,  3,  4,  4,  4,  5,
170   5,  5,  6,  6,  6,  7,  7,  7,  8,  8,  8,  9,  9,  9,  10, 10, 10, 11, 11,
171   12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21,
172   21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30,
173   31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40,
174   40, 41, 41, 42, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
175   57, 58, 59, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80
176 };
177 static const unsigned char inter_minq[QINDEX_RANGE] = {
178   0,  0,  1,  1,  2,  3,  3,  4,  4,  5,  6,  6,  7,  8,  8,  9,  9,  10, 11,
179   11, 12, 13, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23, 24,
180   24, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
181   39, 39, 40, 41, 42, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 50, 51, 52, 53,
182   54, 55, 55, 56, 57, 58, 59, 60, 60, 61, 62, 63, 64, 65, 66, 67, 67, 68, 69,
183   70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 86,
184   87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100
185 };
186
187 #ifdef PACKET_TESTING
188 extern FILE *vpxlogc;
189 #endif
190
191 static void save_layer_context(VP8_COMP *cpi) {
192   LAYER_CONTEXT *lc = &cpi->layer_context[cpi->current_layer];
193
194   /* Save layer dependent coding state */
195   lc->target_bandwidth = cpi->target_bandwidth;
196   lc->starting_buffer_level = cpi->oxcf.starting_buffer_level;
197   lc->optimal_buffer_level = cpi->oxcf.optimal_buffer_level;
198   lc->maximum_buffer_size = cpi->oxcf.maximum_buffer_size;
199   lc->starting_buffer_level_in_ms = cpi->oxcf.starting_buffer_level_in_ms;
200   lc->optimal_buffer_level_in_ms = cpi->oxcf.optimal_buffer_level_in_ms;
201   lc->maximum_buffer_size_in_ms = cpi->oxcf.maximum_buffer_size_in_ms;
202   lc->buffer_level = cpi->buffer_level;
203   lc->bits_off_target = cpi->bits_off_target;
204   lc->total_actual_bits = cpi->total_actual_bits;
205   lc->worst_quality = cpi->worst_quality;
206   lc->active_worst_quality = cpi->active_worst_quality;
207   lc->best_quality = cpi->best_quality;
208   lc->active_best_quality = cpi->active_best_quality;
209   lc->ni_av_qi = cpi->ni_av_qi;
210   lc->ni_tot_qi = cpi->ni_tot_qi;
211   lc->ni_frames = cpi->ni_frames;
212   lc->avg_frame_qindex = cpi->avg_frame_qindex;
213   lc->rate_correction_factor = cpi->rate_correction_factor;
214   lc->key_frame_rate_correction_factor = cpi->key_frame_rate_correction_factor;
215   lc->gf_rate_correction_factor = cpi->gf_rate_correction_factor;
216   lc->zbin_over_quant = cpi->mb.zbin_over_quant;
217   lc->inter_frame_target = cpi->inter_frame_target;
218   lc->total_byte_count = cpi->total_byte_count;
219   lc->filter_level = cpi->common.filter_level;
220
221   lc->last_frame_percent_intra = cpi->last_frame_percent_intra;
222
223   memcpy(lc->count_mb_ref_frame_usage, cpi->mb.count_mb_ref_frame_usage,
224          sizeof(cpi->mb.count_mb_ref_frame_usage));
225 }
226
227 static void restore_layer_context(VP8_COMP *cpi, const int layer) {
228   LAYER_CONTEXT *lc = &cpi->layer_context[layer];
229
230   /* Restore layer dependent coding state */
231   cpi->current_layer = layer;
232   cpi->target_bandwidth = lc->target_bandwidth;
233   cpi->oxcf.target_bandwidth = lc->target_bandwidth;
234   cpi->oxcf.starting_buffer_level = lc->starting_buffer_level;
235   cpi->oxcf.optimal_buffer_level = lc->optimal_buffer_level;
236   cpi->oxcf.maximum_buffer_size = lc->maximum_buffer_size;
237   cpi->oxcf.starting_buffer_level_in_ms = lc->starting_buffer_level_in_ms;
238   cpi->oxcf.optimal_buffer_level_in_ms = lc->optimal_buffer_level_in_ms;
239   cpi->oxcf.maximum_buffer_size_in_ms = lc->maximum_buffer_size_in_ms;
240   cpi->buffer_level = lc->buffer_level;
241   cpi->bits_off_target = lc->bits_off_target;
242   cpi->total_actual_bits = lc->total_actual_bits;
243   cpi->active_worst_quality = lc->active_worst_quality;
244   cpi->active_best_quality = lc->active_best_quality;
245   cpi->ni_av_qi = lc->ni_av_qi;
246   cpi->ni_tot_qi = lc->ni_tot_qi;
247   cpi->ni_frames = lc->ni_frames;
248   cpi->avg_frame_qindex = lc->avg_frame_qindex;
249   cpi->rate_correction_factor = lc->rate_correction_factor;
250   cpi->key_frame_rate_correction_factor = lc->key_frame_rate_correction_factor;
251   cpi->gf_rate_correction_factor = lc->gf_rate_correction_factor;
252   cpi->mb.zbin_over_quant = lc->zbin_over_quant;
253   cpi->inter_frame_target = lc->inter_frame_target;
254   cpi->total_byte_count = lc->total_byte_count;
255   cpi->common.filter_level = lc->filter_level;
256
257   cpi->last_frame_percent_intra = lc->last_frame_percent_intra;
258
259   memcpy(cpi->mb.count_mb_ref_frame_usage, lc->count_mb_ref_frame_usage,
260          sizeof(cpi->mb.count_mb_ref_frame_usage));
261 }
262
263 static int rescale(int val, int num, int denom) {
264   int64_t llnum = num;
265   int64_t llden = denom;
266   int64_t llval = val;
267
268   return (int)(llval * llnum / llden);
269 }
270
271 static void init_temporal_layer_context(VP8_COMP *cpi, VP8_CONFIG *oxcf,
272                                         const int layer,
273                                         double prev_layer_framerate) {
274   LAYER_CONTEXT *lc = &cpi->layer_context[layer];
275
276   lc->framerate = cpi->output_framerate / cpi->oxcf.rate_decimator[layer];
277   lc->target_bandwidth = cpi->oxcf.target_bitrate[layer] * 1000;
278
279   lc->starting_buffer_level_in_ms = oxcf->starting_buffer_level;
280   lc->optimal_buffer_level_in_ms = oxcf->optimal_buffer_level;
281   lc->maximum_buffer_size_in_ms = oxcf->maximum_buffer_size;
282
283   lc->starting_buffer_level =
284       rescale((int)(oxcf->starting_buffer_level), lc->target_bandwidth, 1000);
285
286   if (oxcf->optimal_buffer_level == 0) {
287     lc->optimal_buffer_level = lc->target_bandwidth / 8;
288   } else {
289     lc->optimal_buffer_level =
290         rescale((int)(oxcf->optimal_buffer_level), lc->target_bandwidth, 1000);
291   }
292
293   if (oxcf->maximum_buffer_size == 0) {
294     lc->maximum_buffer_size = lc->target_bandwidth / 8;
295   } else {
296     lc->maximum_buffer_size =
297         rescale((int)(oxcf->maximum_buffer_size), lc->target_bandwidth, 1000);
298   }
299
300   /* Work out the average size of a frame within this layer */
301   if (layer > 0) {
302     lc->avg_frame_size_for_layer =
303         (int)((cpi->oxcf.target_bitrate[layer] -
304                cpi->oxcf.target_bitrate[layer - 1]) *
305               1000 / (lc->framerate - prev_layer_framerate));
306   }
307
308   lc->active_worst_quality = cpi->oxcf.worst_allowed_q;
309   lc->active_best_quality = cpi->oxcf.best_allowed_q;
310   lc->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
311
312   lc->buffer_level = lc->starting_buffer_level;
313   lc->bits_off_target = lc->starting_buffer_level;
314
315   lc->total_actual_bits = 0;
316   lc->ni_av_qi = 0;
317   lc->ni_tot_qi = 0;
318   lc->ni_frames = 0;
319   lc->rate_correction_factor = 1.0;
320   lc->key_frame_rate_correction_factor = 1.0;
321   lc->gf_rate_correction_factor = 1.0;
322   lc->inter_frame_target = 0;
323 }
324
325 // Upon a run-time change in temporal layers, reset the layer context parameters
326 // for any "new" layers. For "existing" layers, let them inherit the parameters
327 // from the previous layer state (at the same layer #). In future we may want
328 // to better map the previous layer state(s) to the "new" ones.
329 static void reset_temporal_layer_change(VP8_COMP *cpi, VP8_CONFIG *oxcf,
330                                         const int prev_num_layers) {
331   int i;
332   double prev_layer_framerate = 0;
333   const int curr_num_layers = cpi->oxcf.number_of_layers;
334   // If the previous state was 1 layer, get current layer context from cpi.
335   // We need this to set the layer context for the new layers below.
336   if (prev_num_layers == 1) {
337     cpi->current_layer = 0;
338     save_layer_context(cpi);
339   }
340   for (i = 0; i < curr_num_layers; ++i) {
341     LAYER_CONTEXT *lc = &cpi->layer_context[i];
342     if (i >= prev_num_layers) {
343       init_temporal_layer_context(cpi, oxcf, i, prev_layer_framerate);
344     }
345     // The initial buffer levels are set based on their starting levels.
346     // We could set the buffer levels based on the previous state (normalized
347     // properly by the layer bandwidths) but we would need to keep track of
348     // the previous set of layer bandwidths (i.e., target_bitrate[i])
349     // before the layer change. For now, reset to the starting levels.
350     lc->buffer_level =
351         cpi->oxcf.starting_buffer_level_in_ms * cpi->oxcf.target_bitrate[i];
352     lc->bits_off_target = lc->buffer_level;
353     // TDOD(marpan): Should we set the rate_correction_factor and
354     // active_worst/best_quality to values derived from the previous layer
355     // state (to smooth-out quality dips/rate fluctuation at transition)?
356
357     // We need to treat the 1 layer case separately: oxcf.target_bitrate[i]
358     // is not set for 1 layer, and the restore_layer_context/save_context()
359     // are not called in the encoding loop, so we need to call it here to
360     // pass the layer context state to |cpi|.
361     if (curr_num_layers == 1) {
362       lc->target_bandwidth = cpi->oxcf.target_bandwidth;
363       lc->buffer_level =
364           cpi->oxcf.starting_buffer_level_in_ms * lc->target_bandwidth / 1000;
365       lc->bits_off_target = lc->buffer_level;
366       restore_layer_context(cpi, 0);
367     }
368     prev_layer_framerate = cpi->output_framerate / cpi->oxcf.rate_decimator[i];
369   }
370 }
371
372 static void setup_features(VP8_COMP *cpi) {
373   // If segmentation enabled set the update flags
374   if (cpi->mb.e_mbd.segmentation_enabled) {
375     cpi->mb.e_mbd.update_mb_segmentation_map = 1;
376     cpi->mb.e_mbd.update_mb_segmentation_data = 1;
377   } else {
378     cpi->mb.e_mbd.update_mb_segmentation_map = 0;
379     cpi->mb.e_mbd.update_mb_segmentation_data = 0;
380   }
381
382   cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
383   cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
384   memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
385   memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
386   memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0,
387          sizeof(cpi->mb.e_mbd.ref_lf_deltas));
388   memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0,
389          sizeof(cpi->mb.e_mbd.mode_lf_deltas));
390
391   set_default_lf_deltas(cpi);
392 }
393
394 static void dealloc_raw_frame_buffers(VP8_COMP *cpi);
395
396 void vp8_initialize_enc(void) {
397   static volatile int init_done = 0;
398
399   if (!init_done) {
400     vpx_dsp_rtcd();
401     vp8_init_intra_predictors();
402     init_done = 1;
403   }
404 }
405
406 static void dealloc_compressor_data(VP8_COMP *cpi) {
407   vpx_free(cpi->tplist);
408   cpi->tplist = NULL;
409
410   /* Delete last frame MV storage buffers */
411   vpx_free(cpi->lfmv);
412   cpi->lfmv = 0;
413
414   vpx_free(cpi->lf_ref_frame_sign_bias);
415   cpi->lf_ref_frame_sign_bias = 0;
416
417   vpx_free(cpi->lf_ref_frame);
418   cpi->lf_ref_frame = 0;
419
420   /* Delete sementation map */
421   vpx_free(cpi->segmentation_map);
422   cpi->segmentation_map = 0;
423
424   vpx_free(cpi->active_map);
425   cpi->active_map = 0;
426
427   vp8_de_alloc_frame_buffers(&cpi->common);
428
429   vp8_yv12_de_alloc_frame_buffer(&cpi->pick_lf_lvl_frame);
430   vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
431   dealloc_raw_frame_buffers(cpi);
432
433   vpx_free(cpi->tok);
434   cpi->tok = 0;
435
436   /* Structure used to monitor GF usage */
437   vpx_free(cpi->gf_active_flags);
438   cpi->gf_active_flags = 0;
439
440   /* Activity mask based per mb zbin adjustments */
441   vpx_free(cpi->mb_activity_map);
442   cpi->mb_activity_map = 0;
443
444   vpx_free(cpi->mb.pip);
445   cpi->mb.pip = 0;
446
447 #if CONFIG_MULTITHREAD
448   vpx_free(cpi->mt_current_mb_col);
449   cpi->mt_current_mb_col = NULL;
450 #endif
451 }
452
453 static void enable_segmentation(VP8_COMP *cpi) {
454   /* Set the appropriate feature bit */
455   cpi->mb.e_mbd.segmentation_enabled = 1;
456   cpi->mb.e_mbd.update_mb_segmentation_map = 1;
457   cpi->mb.e_mbd.update_mb_segmentation_data = 1;
458 }
459 static void disable_segmentation(VP8_COMP *cpi) {
460   /* Clear the appropriate feature bit */
461   cpi->mb.e_mbd.segmentation_enabled = 0;
462 }
463
464 /* Valid values for a segment are 0 to 3
465  * Segmentation map is arrange as [Rows][Columns]
466  */
467 static void set_segmentation_map(VP8_COMP *cpi,
468                                  unsigned char *segmentation_map) {
469   /* Copy in the new segmentation map */
470   memcpy(cpi->segmentation_map, segmentation_map,
471          (cpi->common.mb_rows * cpi->common.mb_cols));
472
473   /* Signal that the map should be updated. */
474   cpi->mb.e_mbd.update_mb_segmentation_map = 1;
475   cpi->mb.e_mbd.update_mb_segmentation_data = 1;
476 }
477
478 /* The values given for each segment can be either deltas (from the default
479  * value chosen for the frame) or absolute values.
480  *
481  * Valid range for abs values is:
482  *    (0-127 for MB_LVL_ALT_Q), (0-63 for SEGMENT_ALT_LF)
483  * Valid range for delta values are:
484  *    (+/-127 for MB_LVL_ALT_Q), (+/-63 for SEGMENT_ALT_LF)
485  *
486  * abs_delta = SEGMENT_DELTADATA (deltas)
487  * abs_delta = SEGMENT_ABSDATA (use the absolute values given).
488  *
489  */
490 static void set_segment_data(VP8_COMP *cpi, signed char *feature_data,
491                              unsigned char abs_delta) {
492   cpi->mb.e_mbd.mb_segement_abs_delta = abs_delta;
493   memcpy(cpi->segment_feature_data, feature_data,
494          sizeof(cpi->segment_feature_data));
495 }
496
497 /* A simple function to cyclically refresh the background at a lower Q */
498 static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment) {
499   unsigned char *seg_map = cpi->segmentation_map;
500   signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
501   int i;
502   int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
503   int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
504
505   cpi->cyclic_refresh_q = Q / 2;
506
507   if (cpi->oxcf.screen_content_mode) {
508     // Modify quality ramp-up based on Q. Above some Q level, increase the
509     // number of blocks to be refreshed, and reduce it below the thredhold.
510     // Turn-off under certain conditions (i.e., away from key frame, and if
511     // we are at good quality (low Q) and most of the blocks were
512     // skipped-encoded
513     // in previous frame.
514     int qp_thresh = (cpi->oxcf.screen_content_mode == 2) ? 80 : 100;
515     if (Q >= qp_thresh) {
516       cpi->cyclic_refresh_mode_max_mbs_perframe =
517           (cpi->common.mb_rows * cpi->common.mb_cols) / 10;
518     } else if (cpi->frames_since_key > 250 && Q < 20 &&
519                cpi->mb.skip_true_count > (int)(0.95 * mbs_in_frame)) {
520       cpi->cyclic_refresh_mode_max_mbs_perframe = 0;
521     } else {
522       cpi->cyclic_refresh_mode_max_mbs_perframe =
523           (cpi->common.mb_rows * cpi->common.mb_cols) / 20;
524     }
525     block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
526   }
527
528   // Set every macroblock to be eligible for update.
529   // For key frame this will reset seg map to 0.
530   memset(cpi->segmentation_map, 0, mbs_in_frame);
531
532   if (cpi->common.frame_type != KEY_FRAME && block_count > 0) {
533     /* Cycle through the macro_block rows */
534     /* MB loop to set local segmentation map */
535     i = cpi->cyclic_refresh_mode_index;
536     assert(i < mbs_in_frame);
537     do {
538       /* If the MB is as a candidate for clean up then mark it for
539        * possible boost/refresh (segment 1) The segment id may get
540        * reset to 0 later if the MB gets coded anything other than
541        * last frame 0,0 as only (last frame 0,0) MBs are eligable for
542        * refresh : that is to say Mbs likely to be background blocks.
543        */
544       if (cpi->cyclic_refresh_map[i] == 0) {
545         seg_map[i] = 1;
546         block_count--;
547       } else if (cpi->cyclic_refresh_map[i] < 0) {
548         cpi->cyclic_refresh_map[i]++;
549       }
550
551       i++;
552       if (i == mbs_in_frame) i = 0;
553
554     } while (block_count && i != cpi->cyclic_refresh_mode_index);
555
556     cpi->cyclic_refresh_mode_index = i;
557
558 #if CONFIG_TEMPORAL_DENOISING
559     if (cpi->oxcf.noise_sensitivity > 0) {
560       if (cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive &&
561           Q < (int)cpi->denoiser.denoise_pars.qp_thresh &&
562           (cpi->frames_since_key >
563            2 * cpi->denoiser.denoise_pars.consec_zerolast)) {
564         // Under aggressive denoising, use segmentation to turn off loop
565         // filter below some qp thresh. The filter is reduced for all
566         // blocks that have been encoded as ZEROMV LAST x frames in a row,
567         // where x is set by cpi->denoiser.denoise_pars.consec_zerolast.
568         // This is to avoid "dot" artifacts that can occur from repeated
569         // loop filtering on noisy input source.
570         cpi->cyclic_refresh_q = Q;
571         // lf_adjustment = -MAX_LOOP_FILTER;
572         lf_adjustment = -40;
573         for (i = 0; i < mbs_in_frame; ++i) {
574           seg_map[i] = (cpi->consec_zero_last[i] >
575                         cpi->denoiser.denoise_pars.consec_zerolast)
576                            ? 1
577                            : 0;
578         }
579       }
580     }
581 #endif
582   }
583
584   /* Activate segmentation. */
585   cpi->mb.e_mbd.update_mb_segmentation_map = 1;
586   cpi->mb.e_mbd.update_mb_segmentation_data = 1;
587   enable_segmentation(cpi);
588
589   /* Set up the quant segment data */
590   feature_data[MB_LVL_ALT_Q][0] = 0;
591   feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
592   feature_data[MB_LVL_ALT_Q][2] = 0;
593   feature_data[MB_LVL_ALT_Q][3] = 0;
594
595   /* Set up the loop segment data */
596   feature_data[MB_LVL_ALT_LF][0] = 0;
597   feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
598   feature_data[MB_LVL_ALT_LF][2] = 0;
599   feature_data[MB_LVL_ALT_LF][3] = 0;
600
601   /* Initialise the feature data structure */
602   set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
603 }
604
605 static void set_default_lf_deltas(VP8_COMP *cpi) {
606   cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
607   cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
608
609   memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
610   memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
611
612   /* Test of ref frame deltas */
613   cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
614   cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
615   cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
616   cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
617
618   cpi->mb.e_mbd.mode_lf_deltas[0] = 4; /* BPRED */
619
620   if (cpi->oxcf.Mode == MODE_REALTIME) {
621     cpi->mb.e_mbd.mode_lf_deltas[1] = -12; /* Zero */
622   } else {
623     cpi->mb.e_mbd.mode_lf_deltas[1] = -2; /* Zero */
624   }
625
626   cpi->mb.e_mbd.mode_lf_deltas[2] = 2; /* New mv */
627   cpi->mb.e_mbd.mode_lf_deltas[3] = 4; /* Split mv */
628 }
629
630 /* Convenience macros for mapping speed and mode into a continuous
631  * range
632  */
633 #define GOOD(x) (x + 1)
634 #define RT(x) (x + 7)
635
636 static int speed_map(int speed, const int *map) {
637   int res;
638
639   do {
640     res = *map++;
641   } while (speed >= *map++);
642   return res;
643 }
644
645 static const int thresh_mult_map_znn[] = {
646   /* map common to zero, nearest, and near */
647   0, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(2), 2000, INT_MAX
648 };
649
650 static const int thresh_mult_map_vhpred[] = { 1000, GOOD(2), 1500,    GOOD(3),
651                                               2000, RT(0),   1000,    RT(1),
652                                               2000, RT(7),   INT_MAX, INT_MAX };
653
654 static const int thresh_mult_map_bpred[] = { 2000,    GOOD(0), 2500, GOOD(2),
655                                              5000,    GOOD(3), 7500, RT(0),
656                                              2500,    RT(1),   5000, RT(6),
657                                              INT_MAX, INT_MAX };
658
659 static const int thresh_mult_map_tm[] = { 1000,    GOOD(2), 1500, GOOD(3),
660                                           2000,    RT(0),   0,    RT(1),
661                                           1000,    RT(2),   2000, RT(7),
662                                           INT_MAX, INT_MAX };
663
664 static const int thresh_mult_map_new1[] = { 1000,  GOOD(2), 2000,
665                                             RT(0), 2000,    INT_MAX };
666
667 static const int thresh_mult_map_new2[] = { 1000, GOOD(2), 2000, GOOD(3),
668                                             2500, GOOD(5), 4000, RT(0),
669                                             2000, RT(2),   2500, RT(5),
670                                             4000, INT_MAX };
671
672 static const int thresh_mult_map_split1[] = {
673   2500,  GOOD(0), 1700,  GOOD(2), 10000, GOOD(3), 25000, GOOD(4), INT_MAX,
674   RT(0), 5000,    RT(1), 10000,   RT(2), 25000,   RT(3), INT_MAX, INT_MAX
675 };
676
677 static const int thresh_mult_map_split2[] = {
678   5000,  GOOD(0), 4500,  GOOD(2), 20000, GOOD(3), 50000, GOOD(4), INT_MAX,
679   RT(0), 10000,   RT(1), 20000,   RT(2), 50000,   RT(3), INT_MAX, INT_MAX
680 };
681
682 static const int mode_check_freq_map_zn2[] = {
683   /* {zero,nearest}{2,3} */
684   0, RT(10), 1 << 1, RT(11), 1 << 2, RT(12), 1 << 3, INT_MAX
685 };
686
687 static const int mode_check_freq_map_vhbpred[] = {
688   0, GOOD(5), 2, RT(0), 0, RT(3), 2, RT(5), 4, INT_MAX
689 };
690
691 static const int mode_check_freq_map_near2[] = {
692   0,      GOOD(5), 2,      RT(0),  0,      RT(3),  2,
693   RT(10), 1 << 2,  RT(11), 1 << 3, RT(12), 1 << 4, INT_MAX
694 };
695
696 static const int mode_check_freq_map_new1[] = {
697   0, RT(10), 1 << 1, RT(11), 1 << 2, RT(12), 1 << 3, INT_MAX
698 };
699
700 static const int mode_check_freq_map_new2[] = { 0,      GOOD(5), 4,      RT(0),
701                                                 0,      RT(3),   4,      RT(10),
702                                                 1 << 3, RT(11),  1 << 4, RT(12),
703                                                 1 << 5, INT_MAX };
704
705 static const int mode_check_freq_map_split1[] = {
706   0, GOOD(2), 2, GOOD(3), 7, RT(1), 2, RT(2), 7, INT_MAX
707 };
708
709 static const int mode_check_freq_map_split2[] = {
710   0, GOOD(1), 2, GOOD(2), 4, GOOD(3), 15, RT(1), 4, RT(2), 15, INT_MAX
711 };
712
713 void vp8_set_speed_features(VP8_COMP *cpi) {
714   SPEED_FEATURES *sf = &cpi->sf;
715   int Mode = cpi->compressor_speed;
716   int Speed = cpi->Speed;
717   int i;
718   VP8_COMMON *cm = &cpi->common;
719   int last_improved_quant = sf->improved_quant;
720   int ref_frames;
721
722   /* Initialise default mode frequency sampling variables */
723   for (i = 0; i < MAX_MODES; ++i) {
724     cpi->mode_check_freq[i] = 0;
725   }
726
727   cpi->mb.mbs_tested_so_far = 0;
728   cpi->mb.mbs_zero_last_dot_suppress = 0;
729
730   /* best quality defaults */
731   sf->RD = 1;
732   sf->search_method = NSTEP;
733   sf->improved_quant = 1;
734   sf->improved_dct = 1;
735   sf->auto_filter = 1;
736   sf->recode_loop = 1;
737   sf->quarter_pixel_search = 1;
738   sf->half_pixel_search = 1;
739   sf->iterative_sub_pixel = 1;
740   sf->optimize_coefficients = 1;
741   sf->use_fastquant_for_pick = 0;
742   sf->no_skip_block4x4_search = 1;
743
744   sf->first_step = 0;
745   sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
746   sf->improved_mv_pred = 1;
747
748   /* default thresholds to 0 */
749   for (i = 0; i < MAX_MODES; ++i) sf->thresh_mult[i] = 0;
750
751   /* Count enabled references */
752   ref_frames = 1;
753   if (cpi->ref_frame_flags & VP8_LAST_FRAME) ref_frames++;
754   if (cpi->ref_frame_flags & VP8_GOLD_FRAME) ref_frames++;
755   if (cpi->ref_frame_flags & VP8_ALTR_FRAME) ref_frames++;
756
757   /* Convert speed to continuous range, with clamping */
758   if (Mode == 0) {
759     Speed = 0;
760   } else if (Mode == 2) {
761     Speed = RT(Speed);
762   } else {
763     if (Speed > 5) Speed = 5;
764     Speed = GOOD(Speed);
765   }
766
767   sf->thresh_mult[THR_ZERO1] = sf->thresh_mult[THR_NEAREST1] =
768       sf->thresh_mult[THR_NEAR1] = sf->thresh_mult[THR_DC] = 0; /* always */
769
770   sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO3] =
771       sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST3] =
772           sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR3] =
773               speed_map(Speed, thresh_mult_map_znn);
774
775   sf->thresh_mult[THR_V_PRED] = sf->thresh_mult[THR_H_PRED] =
776       speed_map(Speed, thresh_mult_map_vhpred);
777   sf->thresh_mult[THR_B_PRED] = speed_map(Speed, thresh_mult_map_bpred);
778   sf->thresh_mult[THR_TM] = speed_map(Speed, thresh_mult_map_tm);
779   sf->thresh_mult[THR_NEW1] = speed_map(Speed, thresh_mult_map_new1);
780   sf->thresh_mult[THR_NEW2] = sf->thresh_mult[THR_NEW3] =
781       speed_map(Speed, thresh_mult_map_new2);
782   sf->thresh_mult[THR_SPLIT1] = speed_map(Speed, thresh_mult_map_split1);
783   sf->thresh_mult[THR_SPLIT2] = sf->thresh_mult[THR_SPLIT3] =
784       speed_map(Speed, thresh_mult_map_split2);
785
786   // Special case for temporal layers.
787   // Reduce the thresholds for zero/nearest/near for GOLDEN, if GOLDEN is
788   // used as second reference. We don't modify thresholds for ALTREF case
789   // since ALTREF is usually used as long-term reference in temporal layers.
790   if ((cpi->Speed <= 6) && (cpi->oxcf.number_of_layers > 1) &&
791       (cpi->ref_frame_flags & VP8_LAST_FRAME) &&
792       (cpi->ref_frame_flags & VP8_GOLD_FRAME)) {
793     if (cpi->closest_reference_frame == GOLDEN_FRAME) {
794       sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO2] >> 3;
795       sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST2] >> 3;
796       sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR2] >> 3;
797     } else {
798       sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO2] >> 1;
799       sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST2] >> 1;
800       sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR2] >> 1;
801     }
802   }
803
804   cpi->mode_check_freq[THR_ZERO1] = cpi->mode_check_freq[THR_NEAREST1] =
805       cpi->mode_check_freq[THR_NEAR1] = cpi->mode_check_freq[THR_TM] =
806           cpi->mode_check_freq[THR_DC] = 0; /* always */
807
808   cpi->mode_check_freq[THR_ZERO2] = cpi->mode_check_freq[THR_ZERO3] =
809       cpi->mode_check_freq[THR_NEAREST2] = cpi->mode_check_freq[THR_NEAREST3] =
810           speed_map(Speed, mode_check_freq_map_zn2);
811
812   cpi->mode_check_freq[THR_NEAR2] = cpi->mode_check_freq[THR_NEAR3] =
813       speed_map(Speed, mode_check_freq_map_near2);
814
815   cpi->mode_check_freq[THR_V_PRED] = cpi->mode_check_freq[THR_H_PRED] =
816       cpi->mode_check_freq[THR_B_PRED] =
817           speed_map(Speed, mode_check_freq_map_vhbpred);
818   cpi->mode_check_freq[THR_NEW1] = speed_map(Speed, mode_check_freq_map_new1);
819   cpi->mode_check_freq[THR_NEW2] = cpi->mode_check_freq[THR_NEW3] =
820       speed_map(Speed, mode_check_freq_map_new2);
821   cpi->mode_check_freq[THR_SPLIT1] =
822       speed_map(Speed, mode_check_freq_map_split1);
823   cpi->mode_check_freq[THR_SPLIT2] = cpi->mode_check_freq[THR_SPLIT3] =
824       speed_map(Speed, mode_check_freq_map_split2);
825   Speed = cpi->Speed;
826   switch (Mode) {
827 #if !CONFIG_REALTIME_ONLY
828     case 0: /* best quality mode */
829       sf->first_step = 0;
830       sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
831       break;
832     case 1:
833     case 3:
834       if (Speed > 0) {
835         /* Disable coefficient optimization above speed 0 */
836         sf->optimize_coefficients = 0;
837         sf->use_fastquant_for_pick = 1;
838         sf->no_skip_block4x4_search = 0;
839
840         sf->first_step = 1;
841       }
842
843       if (Speed > 2) {
844         sf->improved_quant = 0;
845         sf->improved_dct = 0;
846
847         /* Only do recode loop on key frames, golden frames and
848          * alt ref frames
849          */
850         sf->recode_loop = 2;
851       }
852
853       if (Speed > 3) {
854         sf->auto_filter = 1;
855         sf->recode_loop = 0; /* recode loop off */
856         sf->RD = 0;          /* Turn rd off */
857       }
858
859       if (Speed > 4) {
860         sf->auto_filter = 0; /* Faster selection of loop filter */
861       }
862
863       break;
864 #endif
865     case 2:
866       sf->optimize_coefficients = 0;
867       sf->recode_loop = 0;
868       sf->auto_filter = 1;
869       sf->iterative_sub_pixel = 1;
870       sf->search_method = NSTEP;
871
872       if (Speed > 0) {
873         sf->improved_quant = 0;
874         sf->improved_dct = 0;
875
876         sf->use_fastquant_for_pick = 1;
877         sf->no_skip_block4x4_search = 0;
878         sf->first_step = 1;
879       }
880
881       if (Speed > 2) sf->auto_filter = 0; /* Faster selection of loop filter */
882
883       if (Speed > 3) {
884         sf->RD = 0;
885         sf->auto_filter = 1;
886       }
887
888       if (Speed > 4) {
889         sf->auto_filter = 0; /* Faster selection of loop filter */
890         sf->search_method = HEX;
891         sf->iterative_sub_pixel = 0;
892       }
893
894       if (Speed > 6) {
895         unsigned int sum = 0;
896         unsigned int total_mbs = cm->MBs;
897         int thresh;
898         unsigned int total_skip;
899
900         int min = 2000;
901
902         if (cpi->oxcf.encode_breakout > 2000) min = cpi->oxcf.encode_breakout;
903
904         min >>= 7;
905
906         for (i = 0; i < min; ++i) {
907           sum += cpi->mb.error_bins[i];
908         }
909
910         total_skip = sum;
911         sum = 0;
912
913         /* i starts from 2 to make sure thresh started from 2048 */
914         for (; i < 1024; ++i) {
915           sum += cpi->mb.error_bins[i];
916
917           if (10 * sum >=
918               (unsigned int)(cpi->Speed - 6) * (total_mbs - total_skip)) {
919             break;
920           }
921         }
922
923         i--;
924         thresh = (i << 7);
925
926         if (thresh < 2000) thresh = 2000;
927
928         if (ref_frames > 1) {
929           sf->thresh_mult[THR_NEW1] = thresh;
930           sf->thresh_mult[THR_NEAREST1] = thresh >> 1;
931           sf->thresh_mult[THR_NEAR1] = thresh >> 1;
932         }
933
934         if (ref_frames > 2) {
935           sf->thresh_mult[THR_NEW2] = thresh << 1;
936           sf->thresh_mult[THR_NEAREST2] = thresh;
937           sf->thresh_mult[THR_NEAR2] = thresh;
938         }
939
940         if (ref_frames > 3) {
941           sf->thresh_mult[THR_NEW3] = thresh << 1;
942           sf->thresh_mult[THR_NEAREST3] = thresh;
943           sf->thresh_mult[THR_NEAR3] = thresh;
944         }
945
946         sf->improved_mv_pred = 0;
947       }
948
949       if (Speed > 8) sf->quarter_pixel_search = 0;
950
951       if (cm->version == 0) {
952         cm->filter_type = NORMAL_LOOPFILTER;
953
954         if (Speed >= 14) cm->filter_type = SIMPLE_LOOPFILTER;
955       } else {
956         cm->filter_type = SIMPLE_LOOPFILTER;
957       }
958
959       /* This has a big hit on quality. Last resort */
960       if (Speed >= 15) sf->half_pixel_search = 0;
961
962       memset(cpi->mb.error_bins, 0, sizeof(cpi->mb.error_bins));
963
964   }; /* switch */
965
966   /* Slow quant, dct and trellis not worthwhile for first pass
967    * so make sure they are always turned off.
968    */
969   if (cpi->pass == 1) {
970     sf->improved_quant = 0;
971     sf->optimize_coefficients = 0;
972     sf->improved_dct = 0;
973   }
974
975   if (cpi->sf.search_method == NSTEP) {
976     vp8_init3smotion_compensation(&cpi->mb,
977                                   cm->yv12_fb[cm->lst_fb_idx].y_stride);
978   } else if (cpi->sf.search_method == DIAMOND) {
979     vp8_init_dsmotion_compensation(&cpi->mb,
980                                    cm->yv12_fb[cm->lst_fb_idx].y_stride);
981   }
982
983   if (cpi->sf.improved_dct) {
984     cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
985     cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
986   } else {
987     /* No fast FDCT defined for any platform at this time. */
988     cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
989     cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
990   }
991
992   cpi->mb.short_walsh4x4 = vp8_short_walsh4x4;
993
994   if (cpi->sf.improved_quant) {
995     cpi->mb.quantize_b = vp8_regular_quantize_b;
996   } else {
997     cpi->mb.quantize_b = vp8_fast_quantize_b;
998   }
999   if (cpi->sf.improved_quant != last_improved_quant) vp8cx_init_quantizer(cpi);
1000
1001   if (cpi->sf.iterative_sub_pixel == 1) {
1002     cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
1003   } else if (cpi->sf.quarter_pixel_search) {
1004     cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
1005   } else if (cpi->sf.half_pixel_search) {
1006     cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
1007   } else {
1008     cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1009   }
1010
1011   if (cpi->sf.optimize_coefficients == 1 && cpi->pass != 1) {
1012     cpi->mb.optimize = 1;
1013   } else {
1014     cpi->mb.optimize = 0;
1015   }
1016
1017   if (cpi->common.full_pixel) {
1018     cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1019   }
1020
1021 #ifdef SPEEDSTATS
1022   frames_at_speed[cpi->Speed]++;
1023 #endif
1024 }
1025 #undef GOOD
1026 #undef RT
1027
1028 static void alloc_raw_frame_buffers(VP8_COMP *cpi) {
1029 #if VP8_TEMPORAL_ALT_REF
1030   int width = (cpi->oxcf.Width + 15) & ~15;
1031   int height = (cpi->oxcf.Height + 15) & ~15;
1032 #endif
1033
1034   cpi->lookahead = vp8_lookahead_init(cpi->oxcf.Width, cpi->oxcf.Height,
1035                                       cpi->oxcf.lag_in_frames);
1036   if (!cpi->lookahead) {
1037     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1038                        "Failed to allocate lag buffers");
1039   }
1040
1041 #if VP8_TEMPORAL_ALT_REF
1042
1043   if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer, width, height,
1044                                   VP8BORDERINPIXELS)) {
1045     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1046                        "Failed to allocate altref buffer");
1047   }
1048
1049 #endif
1050 }
1051
1052 static void dealloc_raw_frame_buffers(VP8_COMP *cpi) {
1053 #if VP8_TEMPORAL_ALT_REF
1054   vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer);
1055 #endif
1056   vp8_lookahead_destroy(cpi->lookahead);
1057 }
1058
1059 static int vp8_alloc_partition_data(VP8_COMP *cpi) {
1060   vpx_free(cpi->mb.pip);
1061
1062   cpi->mb.pip =
1063       vpx_calloc((cpi->common.mb_cols + 1) * (cpi->common.mb_rows + 1),
1064                  sizeof(PARTITION_INFO));
1065   if (!cpi->mb.pip) return 1;
1066
1067   cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
1068
1069   return 0;
1070 }
1071
1072 void vp8_alloc_compressor_data(VP8_COMP *cpi) {
1073   VP8_COMMON *cm = &cpi->common;
1074
1075   int width = cm->Width;
1076   int height = cm->Height;
1077
1078   if (vp8_alloc_frame_buffers(cm, width, height)) {
1079     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1080                        "Failed to allocate frame buffers");
1081   }
1082
1083   if (vp8_alloc_partition_data(cpi)) {
1084     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1085                        "Failed to allocate partition data");
1086   }
1087
1088   if ((width & 0xf) != 0) width += 16 - (width & 0xf);
1089
1090   if ((height & 0xf) != 0) height += 16 - (height & 0xf);
1091
1092   if (vp8_yv12_alloc_frame_buffer(&cpi->pick_lf_lvl_frame, width, height,
1093                                   VP8BORDERINPIXELS)) {
1094     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1095                        "Failed to allocate last frame buffer");
1096   }
1097
1098   if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source, width, height,
1099                                   VP8BORDERINPIXELS)) {
1100     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1101                        "Failed to allocate scaled source buffer");
1102   }
1103
1104   vpx_free(cpi->tok);
1105
1106   {
1107 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1108     unsigned int tokens = 8 * 24 * 16; /* one MB for each thread */
1109 #else
1110     unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
1111 #endif
1112     CHECK_MEM_ERROR(cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1113   }
1114
1115   /* Data used for real time vc mode to see if gf needs refreshing */
1116   cpi->zeromv_count = 0;
1117
1118   /* Structures used to monitor GF usage */
1119   vpx_free(cpi->gf_active_flags);
1120   CHECK_MEM_ERROR(
1121       cpi->gf_active_flags,
1122       vpx_calloc(sizeof(*cpi->gf_active_flags), cm->mb_rows * cm->mb_cols));
1123   cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
1124
1125   vpx_free(cpi->mb_activity_map);
1126   CHECK_MEM_ERROR(
1127       cpi->mb_activity_map,
1128       vpx_calloc(sizeof(*cpi->mb_activity_map), cm->mb_rows * cm->mb_cols));
1129
1130   /* allocate memory for storing last frame's MVs for MV prediction. */
1131   vpx_free(cpi->lfmv);
1132   CHECK_MEM_ERROR(cpi->lfmv, vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2),
1133                                         sizeof(*cpi->lfmv)));
1134   vpx_free(cpi->lf_ref_frame_sign_bias);
1135   CHECK_MEM_ERROR(cpi->lf_ref_frame_sign_bias,
1136                   vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2),
1137                              sizeof(*cpi->lf_ref_frame_sign_bias)));
1138   vpx_free(cpi->lf_ref_frame);
1139   CHECK_MEM_ERROR(cpi->lf_ref_frame,
1140                   vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2),
1141                              sizeof(*cpi->lf_ref_frame)));
1142
1143   /* Create the encoder segmentation map and set all entries to 0 */
1144   vpx_free(cpi->segmentation_map);
1145   CHECK_MEM_ERROR(
1146       cpi->segmentation_map,
1147       vpx_calloc(cm->mb_rows * cm->mb_cols, sizeof(*cpi->segmentation_map)));
1148   cpi->cyclic_refresh_mode_index = 0;
1149   vpx_free(cpi->active_map);
1150   CHECK_MEM_ERROR(cpi->active_map, vpx_calloc(cm->mb_rows * cm->mb_cols,
1151                                               sizeof(*cpi->active_map)));
1152   memset(cpi->active_map, 1, (cm->mb_rows * cm->mb_cols));
1153
1154 #if CONFIG_MULTITHREAD
1155   if (width < 640) {
1156     cpi->mt_sync_range = 1;
1157   } else if (width <= 1280) {
1158     cpi->mt_sync_range = 4;
1159   } else if (width <= 2560) {
1160     cpi->mt_sync_range = 8;
1161   } else {
1162     cpi->mt_sync_range = 16;
1163   }
1164
1165   if (cpi->oxcf.multi_threaded > 1) {
1166     vpx_free(cpi->mt_current_mb_col);
1167     CHECK_MEM_ERROR(cpi->mt_current_mb_col,
1168                     vpx_malloc(sizeof(*cpi->mt_current_mb_col) * cm->mb_rows));
1169   }
1170
1171 #endif
1172
1173   vpx_free(cpi->tplist);
1174   CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cm->mb_rows));
1175
1176 #if CONFIG_TEMPORAL_DENOISING
1177   if (cpi->oxcf.noise_sensitivity > 0) {
1178     vp8_denoiser_free(&cpi->denoiser);
1179     if (vp8_denoiser_allocate(&cpi->denoiser, width, height, cm->mb_rows,
1180                               cm->mb_cols, cpi->oxcf.noise_sensitivity)) {
1181       vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1182                          "Failed to allocate denoiser");
1183     }
1184   }
1185 #endif
1186 }
1187
1188 /* Quant MOD */
1189 static const int q_trans[] = {
1190   0,  1,  2,  3,  4,  5,  7,   8,   9,   10,  12,  13,  15,  17,  18,  19,
1191   20, 21, 23, 24, 25, 26, 27,  28,  29,  30,  31,  33,  35,  37,  39,  41,
1192   43, 45, 47, 49, 51, 53, 55,  57,  59,  61,  64,  67,  70,  73,  76,  79,
1193   82, 85, 88, 91, 94, 97, 100, 103, 106, 109, 112, 115, 118, 121, 124, 127,
1194 };
1195
1196 int vp8_reverse_trans(int x) {
1197   int i;
1198
1199   for (i = 0; i < 64; ++i) {
1200     if (q_trans[i] >= x) return i;
1201   }
1202
1203   return 63;
1204 }
1205 void vp8_new_framerate(VP8_COMP *cpi, double framerate) {
1206   if (framerate < .1) framerate = 30;
1207
1208   cpi->framerate = framerate;
1209   cpi->output_framerate = framerate;
1210   cpi->per_frame_bandwidth =
1211       (int)(cpi->oxcf.target_bandwidth / cpi->output_framerate);
1212   cpi->av_per_frame_bandwidth = cpi->per_frame_bandwidth;
1213   cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth *
1214                                    cpi->oxcf.two_pass_vbrmin_section / 100);
1215
1216   /* Set Maximum gf/arf interval */
1217   cpi->max_gf_interval = ((int)(cpi->output_framerate / 2.0) + 2);
1218
1219   if (cpi->max_gf_interval < 12) cpi->max_gf_interval = 12;
1220
1221   /* Extended interval for genuinely static scenes */
1222   cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1223
1224   /* Special conditions when altr ref frame enabled in lagged compress mode */
1225   if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames) {
1226     if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1) {
1227       cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1228     }
1229
1230     if (cpi->twopass.static_scene_max_gf_interval >
1231         cpi->oxcf.lag_in_frames - 1) {
1232       cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1233     }
1234   }
1235
1236   if (cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval) {
1237     cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1238   }
1239 }
1240
1241 static void init_config(VP8_COMP *cpi, VP8_CONFIG *oxcf) {
1242   VP8_COMMON *cm = &cpi->common;
1243
1244   cpi->oxcf = *oxcf;
1245
1246   cpi->auto_gold = 1;
1247   cpi->auto_adjust_gold_quantizer = 1;
1248
1249   cm->version = oxcf->Version;
1250   vp8_setup_version(cm);
1251
1252   /* Frame rate is not available on the first frame, as it's derived from
1253    * the observed timestamps. The actual value used here doesn't matter
1254    * too much, as it will adapt quickly.
1255    */
1256   if (oxcf->timebase.num > 0) {
1257     cpi->framerate =
1258         (double)(oxcf->timebase.den) / (double)(oxcf->timebase.num);
1259   } else {
1260     cpi->framerate = 30;
1261   }
1262
1263   /* If the reciprocal of the timebase seems like a reasonable framerate,
1264    * then use that as a guess, otherwise use 30.
1265    */
1266   if (cpi->framerate > 180) cpi->framerate = 30;
1267
1268   cpi->ref_framerate = cpi->framerate;
1269
1270   cpi->ref_frame_flags = VP8_ALTR_FRAME | VP8_GOLD_FRAME | VP8_LAST_FRAME;
1271
1272   cm->refresh_golden_frame = 0;
1273   cm->refresh_last_frame = 1;
1274   cm->refresh_entropy_probs = 1;
1275
1276   /* change includes all joint functionality */
1277   vp8_change_config(cpi, oxcf);
1278
1279   /* Initialize active best and worst q and average q values. */
1280   cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1281   cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1282   cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1283
1284   /* Initialise the starting buffer levels */
1285   cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1286   cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1287
1288   cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1289   cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1290   cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1291   cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1292
1293   cpi->total_actual_bits = 0;
1294   cpi->total_target_vs_actual = 0;
1295
1296   /* Temporal scalabilty */
1297   if (cpi->oxcf.number_of_layers > 1) {
1298     unsigned int i;
1299     double prev_layer_framerate = 0;
1300
1301     for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
1302       init_temporal_layer_context(cpi, oxcf, i, prev_layer_framerate);
1303       prev_layer_framerate =
1304           cpi->output_framerate / cpi->oxcf.rate_decimator[i];
1305     }
1306   }
1307
1308 #if VP8_TEMPORAL_ALT_REF
1309   {
1310     int i;
1311
1312     cpi->fixed_divide[0] = 0;
1313
1314     for (i = 1; i < 512; ++i) cpi->fixed_divide[i] = 0x80000 / i;
1315   }
1316 #endif
1317 }
1318
1319 static void update_layer_contexts(VP8_COMP *cpi) {
1320   VP8_CONFIG *oxcf = &cpi->oxcf;
1321
1322   /* Update snapshots of the layer contexts to reflect new parameters */
1323   if (oxcf->number_of_layers > 1) {
1324     unsigned int i;
1325     double prev_layer_framerate = 0;
1326
1327     assert(oxcf->number_of_layers <= VPX_TS_MAX_LAYERS);
1328     for (i = 0; i < oxcf->number_of_layers && i < VPX_TS_MAX_LAYERS; ++i) {
1329       LAYER_CONTEXT *lc = &cpi->layer_context[i];
1330
1331       lc->framerate = cpi->ref_framerate / oxcf->rate_decimator[i];
1332       lc->target_bandwidth = oxcf->target_bitrate[i] * 1000;
1333
1334       lc->starting_buffer_level = rescale(
1335           (int)oxcf->starting_buffer_level_in_ms, lc->target_bandwidth, 1000);
1336
1337       if (oxcf->optimal_buffer_level == 0) {
1338         lc->optimal_buffer_level = lc->target_bandwidth / 8;
1339       } else {
1340         lc->optimal_buffer_level = rescale(
1341             (int)oxcf->optimal_buffer_level_in_ms, lc->target_bandwidth, 1000);
1342       }
1343
1344       if (oxcf->maximum_buffer_size == 0) {
1345         lc->maximum_buffer_size = lc->target_bandwidth / 8;
1346       } else {
1347         lc->maximum_buffer_size = rescale((int)oxcf->maximum_buffer_size_in_ms,
1348                                           lc->target_bandwidth, 1000);
1349       }
1350
1351       /* Work out the average size of a frame within this layer */
1352       if (i > 0) {
1353         lc->avg_frame_size_for_layer =
1354             (int)((oxcf->target_bitrate[i] - oxcf->target_bitrate[i - 1]) *
1355                   1000 / (lc->framerate - prev_layer_framerate));
1356       }
1357
1358       prev_layer_framerate = lc->framerate;
1359     }
1360   }
1361 }
1362
1363 void vp8_change_config(VP8_COMP *cpi, VP8_CONFIG *oxcf) {
1364   VP8_COMMON *cm = &cpi->common;
1365   int last_w, last_h;
1366   unsigned int prev_number_of_layers;
1367
1368   if (!cpi) return;
1369
1370   if (!oxcf) return;
1371
1372   if (cm->version != oxcf->Version) {
1373     cm->version = oxcf->Version;
1374     vp8_setup_version(cm);
1375   }
1376
1377   last_w = cpi->oxcf.Width;
1378   last_h = cpi->oxcf.Height;
1379   prev_number_of_layers = cpi->oxcf.number_of_layers;
1380
1381   cpi->oxcf = *oxcf;
1382
1383   switch (cpi->oxcf.Mode) {
1384     case MODE_REALTIME:
1385       cpi->pass = 0;
1386       cpi->compressor_speed = 2;
1387
1388       if (cpi->oxcf.cpu_used < -16) {
1389         cpi->oxcf.cpu_used = -16;
1390       }
1391
1392       if (cpi->oxcf.cpu_used > 16) cpi->oxcf.cpu_used = 16;
1393
1394       break;
1395
1396     case MODE_GOODQUALITY:
1397       cpi->pass = 0;
1398       cpi->compressor_speed = 1;
1399
1400       if (cpi->oxcf.cpu_used < -5) {
1401         cpi->oxcf.cpu_used = -5;
1402       }
1403
1404       if (cpi->oxcf.cpu_used > 5) cpi->oxcf.cpu_used = 5;
1405
1406       break;
1407
1408     case MODE_BESTQUALITY:
1409       cpi->pass = 0;
1410       cpi->compressor_speed = 0;
1411       break;
1412
1413     case MODE_FIRSTPASS:
1414       cpi->pass = 1;
1415       cpi->compressor_speed = 1;
1416       break;
1417     case MODE_SECONDPASS:
1418       cpi->pass = 2;
1419       cpi->compressor_speed = 1;
1420
1421       if (cpi->oxcf.cpu_used < -5) {
1422         cpi->oxcf.cpu_used = -5;
1423       }
1424
1425       if (cpi->oxcf.cpu_used > 5) cpi->oxcf.cpu_used = 5;
1426
1427       break;
1428     case MODE_SECONDPASS_BEST:
1429       cpi->pass = 2;
1430       cpi->compressor_speed = 0;
1431       break;
1432   }
1433
1434   if (cpi->pass == 0) cpi->auto_worst_q = 1;
1435
1436   cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1437   cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1438   cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1439
1440   if (oxcf->fixed_q >= 0) {
1441     if (oxcf->worst_allowed_q < 0) {
1442       cpi->oxcf.fixed_q = q_trans[0];
1443     } else {
1444       cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
1445     }
1446
1447     if (oxcf->alt_q < 0) {
1448       cpi->oxcf.alt_q = q_trans[0];
1449     } else {
1450       cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
1451     }
1452
1453     if (oxcf->key_q < 0) {
1454       cpi->oxcf.key_q = q_trans[0];
1455     } else {
1456       cpi->oxcf.key_q = q_trans[oxcf->key_q];
1457     }
1458
1459     if (oxcf->gold_q < 0) {
1460       cpi->oxcf.gold_q = q_trans[0];
1461     } else {
1462       cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
1463     }
1464   }
1465
1466   cpi->baseline_gf_interval =
1467       cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
1468
1469 #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1470   cpi->oxcf.token_partitions = 3;
1471 #endif
1472
1473   if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3) {
1474     cm->multi_token_partition = (TOKEN_PARTITION)cpi->oxcf.token_partitions;
1475   }
1476
1477   setup_features(cpi);
1478
1479   {
1480     int i;
1481
1482     for (i = 0; i < MAX_MB_SEGMENTS; ++i) {
1483       cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1484     }
1485   }
1486
1487   /* At the moment the first order values may not be > MAXQ */
1488   if (cpi->oxcf.fixed_q > MAXQ) cpi->oxcf.fixed_q = MAXQ;
1489
1490   /* local file playback mode == really big buffer */
1491   if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
1492     cpi->oxcf.starting_buffer_level = 60000;
1493     cpi->oxcf.optimal_buffer_level = 60000;
1494     cpi->oxcf.maximum_buffer_size = 240000;
1495     cpi->oxcf.starting_buffer_level_in_ms = 60000;
1496     cpi->oxcf.optimal_buffer_level_in_ms = 60000;
1497     cpi->oxcf.maximum_buffer_size_in_ms = 240000;
1498   }
1499
1500   /* Convert target bandwidth from Kbit/s to Bit/s */
1501   cpi->oxcf.target_bandwidth *= 1000;
1502
1503   cpi->oxcf.starting_buffer_level = rescale(
1504       (int)cpi->oxcf.starting_buffer_level, cpi->oxcf.target_bandwidth, 1000);
1505
1506   /* Set or reset optimal and maximum buffer levels. */
1507   if (cpi->oxcf.optimal_buffer_level == 0) {
1508     cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1509   } else {
1510     cpi->oxcf.optimal_buffer_level = rescale(
1511         (int)cpi->oxcf.optimal_buffer_level, cpi->oxcf.target_bandwidth, 1000);
1512   }
1513
1514   if (cpi->oxcf.maximum_buffer_size == 0) {
1515     cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1516   } else {
1517     cpi->oxcf.maximum_buffer_size = rescale((int)cpi->oxcf.maximum_buffer_size,
1518                                             cpi->oxcf.target_bandwidth, 1000);
1519   }
1520   // Under a configuration change, where maximum_buffer_size may change,
1521   // keep buffer level clipped to the maximum allowed buffer size.
1522   if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
1523     cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
1524     cpi->buffer_level = cpi->bits_off_target;
1525   }
1526
1527   /* Set up frame rate and related parameters rate control values. */
1528   vp8_new_framerate(cpi, cpi->framerate);
1529
1530   /* Set absolute upper and lower quality limits */
1531   cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1532   cpi->best_quality = cpi->oxcf.best_allowed_q;
1533
1534   /* active values should only be modified if out of new range */
1535   if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q) {
1536     cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1537   }
1538   /* less likely */
1539   else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q) {
1540     cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
1541   }
1542   if (cpi->active_best_quality < cpi->oxcf.best_allowed_q) {
1543     cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1544   }
1545   /* less likely */
1546   else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q) {
1547     cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
1548   }
1549
1550   cpi->buffered_mode = cpi->oxcf.optimal_buffer_level > 0;
1551
1552   cpi->cq_target_quality = cpi->oxcf.cq_level;
1553
1554   /* Only allow dropped frames in buffered mode */
1555   cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
1556
1557   cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1558
1559   // Check if the number of temporal layers has changed, and if so reset the
1560   // pattern counter and set/initialize the temporal layer context for the
1561   // new layer configuration.
1562   if (cpi->oxcf.number_of_layers != prev_number_of_layers) {
1563     // If the number of temporal layers are changed we must start at the
1564     // base of the pattern cycle, so set the layer id to 0 and reset
1565     // the temporal pattern counter.
1566     if (cpi->temporal_layer_id > 0) {
1567       cpi->temporal_layer_id = 0;
1568     }
1569     cpi->temporal_pattern_counter = 0;
1570     reset_temporal_layer_change(cpi, oxcf, prev_number_of_layers);
1571   }
1572
1573   if (!cpi->initial_width) {
1574     cpi->initial_width = cpi->oxcf.Width;
1575     cpi->initial_height = cpi->oxcf.Height;
1576   }
1577
1578   cm->Width = cpi->oxcf.Width;
1579   cm->Height = cpi->oxcf.Height;
1580   assert(cm->Width <= cpi->initial_width);
1581   assert(cm->Height <= cpi->initial_height);
1582
1583   /* TODO(jkoleszar): if an internal spatial resampling is active,
1584    * and we downsize the input image, maybe we should clear the
1585    * internal scale immediately rather than waiting for it to
1586    * correct.
1587    */
1588
1589   /* VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs) */
1590   if (cpi->oxcf.Sharpness > 7) cpi->oxcf.Sharpness = 7;
1591
1592   cm->sharpness_level = cpi->oxcf.Sharpness;
1593
1594   if (cm->horiz_scale != NORMAL || cm->vert_scale != NORMAL) {
1595     int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
1596     int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
1597
1598     Scale2Ratio(cm->horiz_scale, &hr, &hs);
1599     Scale2Ratio(cm->vert_scale, &vr, &vs);
1600
1601     /* always go to the next whole number */
1602     cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
1603     cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
1604   }
1605
1606   if (last_w != cpi->oxcf.Width || last_h != cpi->oxcf.Height) {
1607     cpi->force_next_frame_intra = 1;
1608   }
1609
1610   if (((cm->Width + 15) & ~15) != cm->yv12_fb[cm->lst_fb_idx].y_width ||
1611       ((cm->Height + 15) & ~15) != cm->yv12_fb[cm->lst_fb_idx].y_height ||
1612       cm->yv12_fb[cm->lst_fb_idx].y_width == 0) {
1613     dealloc_raw_frame_buffers(cpi);
1614     alloc_raw_frame_buffers(cpi);
1615     vp8_alloc_compressor_data(cpi);
1616   }
1617
1618   if (cpi->oxcf.fixed_q >= 0) {
1619     cpi->last_q[0] = cpi->oxcf.fixed_q;
1620     cpi->last_q[1] = cpi->oxcf.fixed_q;
1621   }
1622
1623   cpi->Speed = cpi->oxcf.cpu_used;
1624
1625   /* force to allowlag to 0 if lag_in_frames is 0; */
1626   if (cpi->oxcf.lag_in_frames == 0) {
1627     cpi->oxcf.allow_lag = 0;
1628   }
1629   /* Limit on lag buffers as these are not currently dynamically allocated */
1630   else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
1631     cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1632   }
1633
1634   /* YX Temp */
1635   cpi->alt_ref_source = NULL;
1636   cpi->is_src_frame_alt_ref = 0;
1637
1638 #if CONFIG_TEMPORAL_DENOISING
1639   if (cpi->oxcf.noise_sensitivity) {
1640     if (!cpi->denoiser.yv12_mc_running_avg.buffer_alloc) {
1641       int width = (cpi->oxcf.Width + 15) & ~15;
1642       int height = (cpi->oxcf.Height + 15) & ~15;
1643       if (vp8_denoiser_allocate(&cpi->denoiser, width, height, cm->mb_rows,
1644                                 cm->mb_cols, cpi->oxcf.noise_sensitivity)) {
1645         vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1646                            "Failed to allocate denoiser");
1647       }
1648     }
1649   }
1650 #endif
1651
1652 #if 0
1653     /* Experimental RD Code */
1654     cpi->frame_distortion = 0;
1655     cpi->last_frame_distortion = 0;
1656 #endif
1657 }
1658
1659 #ifndef M_LOG2_E
1660 #define M_LOG2_E 0.693147180559945309417
1661 #endif
1662 #define log2f(x) (log(x) / (float)M_LOG2_E)
1663
1664 static void cal_mvsadcosts(int *mvsadcost[2]) {
1665   int i = 1;
1666
1667   mvsadcost[0][0] = 300;
1668   mvsadcost[1][0] = 300;
1669
1670   do {
1671     double z = 256 * (2 * (log2f(8 * i) + .6));
1672     mvsadcost[0][i] = (int)z;
1673     mvsadcost[1][i] = (int)z;
1674     mvsadcost[0][-i] = (int)z;
1675     mvsadcost[1][-i] = (int)z;
1676   } while (++i <= mvfp_max);
1677 }
1678
1679 struct VP8_COMP *vp8_create_compressor(VP8_CONFIG *oxcf) {
1680   int i;
1681
1682   VP8_COMP *cpi;
1683   VP8_COMMON *cm;
1684
1685   cpi = vpx_memalign(32, sizeof(VP8_COMP));
1686   /* Check that the CPI instance is valid */
1687   if (!cpi) return 0;
1688
1689   cm = &cpi->common;
1690
1691   memset(cpi, 0, sizeof(VP8_COMP));
1692
1693   if (setjmp(cm->error.jmp)) {
1694     cpi->common.error.setjmp = 0;
1695     vp8_remove_compressor(&cpi);
1696     return 0;
1697   }
1698
1699   cpi->common.error.setjmp = 1;
1700
1701   CHECK_MEM_ERROR(cpi->mb.ss, vpx_calloc(sizeof(search_site),
1702                                          (MAX_MVSEARCH_STEPS * 8) + 1));
1703
1704   vp8_create_common(&cpi->common);
1705
1706   init_config(cpi, oxcf);
1707
1708   memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob,
1709          sizeof(vp8cx_base_skip_false_prob));
1710   cpi->common.current_video_frame = 0;
1711   cpi->temporal_pattern_counter = 0;
1712   cpi->temporal_layer_id = -1;
1713   cpi->kf_overspend_bits = 0;
1714   cpi->kf_bitrate_adjustment = 0;
1715   cpi->frames_till_gf_update_due = 0;
1716   cpi->gf_overspend_bits = 0;
1717   cpi->non_gf_bitrate_adjustment = 0;
1718   cpi->prob_last_coded = 128;
1719   cpi->prob_gf_coded = 128;
1720   cpi->prob_intra_coded = 63;
1721
1722   /* Prime the recent reference frame usage counters.
1723    * Hereafter they will be maintained as a sort of moving average
1724    */
1725   cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
1726   cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
1727   cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
1728   cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
1729
1730   /* Set reference frame sign bias for ALTREF frame to 1 (for now) */
1731   cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
1732
1733   cpi->twopass.gf_decay_rate = 0;
1734   cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1735
1736   cpi->gold_is_last = 0;
1737   cpi->alt_is_last = 0;
1738   cpi->gold_is_alt = 0;
1739
1740   cpi->active_map_enabled = 0;
1741
1742 #if 0
1743     /* Experimental code for lagged and one pass */
1744     /* Initialise one_pass GF frames stats */
1745     /* Update stats used for GF selection */
1746     if (cpi->pass == 0)
1747     {
1748         cpi->one_pass_frame_index = 0;
1749
1750         for (i = 0; i < MAX_LAG_BUFFERS; ++i)
1751         {
1752             cpi->one_pass_frame_stats[i].frames_so_far = 0;
1753             cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
1754             cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
1755             cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
1756             cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
1757             cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
1758             cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
1759             cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
1760             cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
1761         }
1762     }
1763 #endif
1764
1765   cpi->mse_source_denoised = 0;
1766
1767   /* Should we use the cyclic refresh method.
1768    * Currently this is tied to error resilliant mode
1769    */
1770   cpi->cyclic_refresh_mode_enabled = cpi->oxcf.error_resilient_mode;
1771   cpi->cyclic_refresh_mode_max_mbs_perframe =
1772       (cpi->common.mb_rows * cpi->common.mb_cols) / 7;
1773   if (cpi->oxcf.number_of_layers == 1) {
1774     cpi->cyclic_refresh_mode_max_mbs_perframe =
1775         (cpi->common.mb_rows * cpi->common.mb_cols) / 20;
1776   } else if (cpi->oxcf.number_of_layers == 2) {
1777     cpi->cyclic_refresh_mode_max_mbs_perframe =
1778         (cpi->common.mb_rows * cpi->common.mb_cols) / 10;
1779   }
1780   cpi->cyclic_refresh_mode_index = 0;
1781   cpi->cyclic_refresh_q = 32;
1782
1783   if (cpi->cyclic_refresh_mode_enabled) {
1784     CHECK_MEM_ERROR(cpi->cyclic_refresh_map,
1785                     vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1786   } else {
1787     cpi->cyclic_refresh_map = (signed char *)NULL;
1788   }
1789
1790   CHECK_MEM_ERROR(cpi->consec_zero_last,
1791                   vpx_calloc(cm->mb_rows * cm->mb_cols, 1));
1792   CHECK_MEM_ERROR(cpi->consec_zero_last_mvbias,
1793                   vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1794
1795 #ifdef VP8_ENTROPY_STATS
1796   init_context_counters();
1797 #endif
1798
1799   /*Initialize the feed-forward activity masking.*/
1800   cpi->activity_avg = 90 << 12;
1801
1802   /* Give a sensible default for the first frame. */
1803   cpi->frames_since_key = 8;
1804   cpi->key_frame_frequency = cpi->oxcf.key_freq;
1805   cpi->this_key_frame_forced = 0;
1806   cpi->next_key_frame_forced = 0;
1807
1808   cpi->source_alt_ref_pending = 0;
1809   cpi->source_alt_ref_active = 0;
1810   cpi->common.refresh_alt_ref_frame = 0;
1811
1812   cpi->force_maxqp = 0;
1813
1814   cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1815 #if CONFIG_INTERNAL_STATS
1816   cpi->b_calculate_ssimg = 0;
1817
1818   cpi->count = 0;
1819   cpi->bytes = 0;
1820
1821   if (cpi->b_calculate_psnr) {
1822     cpi->total_sq_error = 0.0;
1823     cpi->total_sq_error2 = 0.0;
1824     cpi->total_y = 0.0;
1825     cpi->total_u = 0.0;
1826     cpi->total_v = 0.0;
1827     cpi->total = 0.0;
1828     cpi->totalp_y = 0.0;
1829     cpi->totalp_u = 0.0;
1830     cpi->totalp_v = 0.0;
1831     cpi->totalp = 0.0;
1832     cpi->tot_recode_hits = 0;
1833     cpi->summed_quality = 0;
1834     cpi->summed_weights = 0;
1835   }
1836
1837 #endif
1838
1839   cpi->first_time_stamp_ever = 0x7FFFFFFF;
1840
1841   cpi->frames_till_gf_update_due = 0;
1842   cpi->key_frame_count = 1;
1843
1844   cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
1845   cpi->ni_tot_qi = 0;
1846   cpi->ni_frames = 0;
1847   cpi->total_byte_count = 0;
1848
1849   cpi->drop_frame = 0;
1850
1851   cpi->rate_correction_factor = 1.0;
1852   cpi->key_frame_rate_correction_factor = 1.0;
1853   cpi->gf_rate_correction_factor = 1.0;
1854   cpi->twopass.est_max_qcorrection_factor = 1.0;
1855
1856   for (i = 0; i < KEY_FRAME_CONTEXT; ++i) {
1857     cpi->prior_key_frame_distance[i] = (int)cpi->output_framerate;
1858   }
1859
1860 #ifdef OUTPUT_YUV_SRC
1861   yuv_file = fopen("bd.yuv", "ab");
1862 #endif
1863 #ifdef OUTPUT_YUV_DENOISED
1864   yuv_denoised_file = fopen("denoised.yuv", "ab");
1865 #endif
1866
1867 #if 0
1868     framepsnr = fopen("framepsnr.stt", "a");
1869     kf_list = fopen("kf_list.stt", "w");
1870 #endif
1871
1872   cpi->output_pkt_list = oxcf->output_pkt_list;
1873
1874 #if !CONFIG_REALTIME_ONLY
1875
1876   if (cpi->pass == 1) {
1877     vp8_init_first_pass(cpi);
1878   } else if (cpi->pass == 2) {
1879     size_t packet_sz = sizeof(FIRSTPASS_STATS);
1880     int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1881
1882     cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1883     cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1884     cpi->twopass.stats_in_end =
1885         (void *)((char *)cpi->twopass.stats_in + (packets - 1) * packet_sz);
1886     vp8_init_second_pass(cpi);
1887   }
1888
1889 #endif
1890
1891   if (cpi->compressor_speed == 2) {
1892     cpi->avg_encode_time = 0;
1893     cpi->avg_pick_mode_time = 0;
1894   }
1895
1896   vp8_set_speed_features(cpi);
1897
1898   /* Set starting values of RD threshold multipliers (128 = *1) */
1899   for (i = 0; i < MAX_MODES; ++i) {
1900     cpi->mb.rd_thresh_mult[i] = 128;
1901   }
1902
1903 #ifdef VP8_ENTROPY_STATS
1904   init_mv_ref_counts();
1905 #endif
1906
1907 #if CONFIG_MULTITHREAD
1908   if (vp8cx_create_encoder_threads(cpi)) {
1909     vp8_remove_compressor(&cpi);
1910     return 0;
1911   }
1912 #endif
1913
1914   cpi->fn_ptr[BLOCK_16X16].sdf = vpx_sad16x16;
1915   cpi->fn_ptr[BLOCK_16X16].vf = vpx_variance16x16;
1916   cpi->fn_ptr[BLOCK_16X16].svf = vpx_sub_pixel_variance16x16;
1917   cpi->fn_ptr[BLOCK_16X16].svf_halfpix_h = vpx_variance_halfpixvar16x16_h;
1918   cpi->fn_ptr[BLOCK_16X16].svf_halfpix_v = vpx_variance_halfpixvar16x16_v;
1919   cpi->fn_ptr[BLOCK_16X16].svf_halfpix_hv = vpx_variance_halfpixvar16x16_hv;
1920   cpi->fn_ptr[BLOCK_16X16].sdx3f = vpx_sad16x16x3;
1921   cpi->fn_ptr[BLOCK_16X16].sdx8f = vpx_sad16x16x8;
1922   cpi->fn_ptr[BLOCK_16X16].sdx4df = vpx_sad16x16x4d;
1923
1924   cpi->fn_ptr[BLOCK_16X8].sdf = vpx_sad16x8;
1925   cpi->fn_ptr[BLOCK_16X8].vf = vpx_variance16x8;
1926   cpi->fn_ptr[BLOCK_16X8].svf = vpx_sub_pixel_variance16x8;
1927   cpi->fn_ptr[BLOCK_16X8].svf_halfpix_h = NULL;
1928   cpi->fn_ptr[BLOCK_16X8].svf_halfpix_v = NULL;
1929   cpi->fn_ptr[BLOCK_16X8].svf_halfpix_hv = NULL;
1930   cpi->fn_ptr[BLOCK_16X8].sdx3f = vpx_sad16x8x3;
1931   cpi->fn_ptr[BLOCK_16X8].sdx8f = vpx_sad16x8x8;
1932   cpi->fn_ptr[BLOCK_16X8].sdx4df = vpx_sad16x8x4d;
1933
1934   cpi->fn_ptr[BLOCK_8X16].sdf = vpx_sad8x16;
1935   cpi->fn_ptr[BLOCK_8X16].vf = vpx_variance8x16;
1936   cpi->fn_ptr[BLOCK_8X16].svf = vpx_sub_pixel_variance8x16;
1937   cpi->fn_ptr[BLOCK_8X16].svf_halfpix_h = NULL;
1938   cpi->fn_ptr[BLOCK_8X16].svf_halfpix_v = NULL;
1939   cpi->fn_ptr[BLOCK_8X16].svf_halfpix_hv = NULL;
1940   cpi->fn_ptr[BLOCK_8X16].sdx3f = vpx_sad8x16x3;
1941   cpi->fn_ptr[BLOCK_8X16].sdx8f = vpx_sad8x16x8;
1942   cpi->fn_ptr[BLOCK_8X16].sdx4df = vpx_sad8x16x4d;
1943
1944   cpi->fn_ptr[BLOCK_8X8].sdf = vpx_sad8x8;
1945   cpi->fn_ptr[BLOCK_8X8].vf = vpx_variance8x8;
1946   cpi->fn_ptr[BLOCK_8X8].svf = vpx_sub_pixel_variance8x8;
1947   cpi->fn_ptr[BLOCK_8X8].svf_halfpix_h = NULL;
1948   cpi->fn_ptr[BLOCK_8X8].svf_halfpix_v = NULL;
1949   cpi->fn_ptr[BLOCK_8X8].svf_halfpix_hv = NULL;
1950   cpi->fn_ptr[BLOCK_8X8].sdx3f = vpx_sad8x8x3;
1951   cpi->fn_ptr[BLOCK_8X8].sdx8f = vpx_sad8x8x8;
1952   cpi->fn_ptr[BLOCK_8X8].sdx4df = vpx_sad8x8x4d;
1953
1954   cpi->fn_ptr[BLOCK_4X4].sdf = vpx_sad4x4;
1955   cpi->fn_ptr[BLOCK_4X4].vf = vpx_variance4x4;
1956   cpi->fn_ptr[BLOCK_4X4].svf = vpx_sub_pixel_variance4x4;
1957   cpi->fn_ptr[BLOCK_4X4].svf_halfpix_h = NULL;
1958   cpi->fn_ptr[BLOCK_4X4].svf_halfpix_v = NULL;
1959   cpi->fn_ptr[BLOCK_4X4].svf_halfpix_hv = NULL;
1960   cpi->fn_ptr[BLOCK_4X4].sdx3f = vpx_sad4x4x3;
1961   cpi->fn_ptr[BLOCK_4X4].sdx8f = vpx_sad4x4x8;
1962   cpi->fn_ptr[BLOCK_4X4].sdx4df = vpx_sad4x4x4d;
1963
1964 #if ARCH_X86 || ARCH_X86_64
1965   cpi->fn_ptr[BLOCK_16X16].copymem = vp8_copy32xn;
1966   cpi->fn_ptr[BLOCK_16X8].copymem = vp8_copy32xn;
1967   cpi->fn_ptr[BLOCK_8X16].copymem = vp8_copy32xn;
1968   cpi->fn_ptr[BLOCK_8X8].copymem = vp8_copy32xn;
1969   cpi->fn_ptr[BLOCK_4X4].copymem = vp8_copy32xn;
1970 #endif
1971
1972   cpi->full_search_sad = vp8_full_search_sad;
1973   cpi->diamond_search_sad = vp8_diamond_search_sad;
1974   cpi->refining_search_sad = vp8_refining_search_sad;
1975
1976   /* make sure frame 1 is okay */
1977   cpi->mb.error_bins[0] = cpi->common.MBs;
1978
1979   /* vp8cx_init_quantizer() is first called here. Add check in
1980    * vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only
1981    * called later when needed. This will avoid unnecessary calls of
1982    * vp8cx_init_quantizer() for every frame.
1983    */
1984   vp8cx_init_quantizer(cpi);
1985
1986   vp8_loop_filter_init(cm);
1987
1988   cpi->common.error.setjmp = 0;
1989
1990 #if CONFIG_MULTI_RES_ENCODING
1991
1992   /* Calculate # of MBs in a row in lower-resolution level image. */
1993   if (cpi->oxcf.mr_encoder_id > 0) vp8_cal_low_res_mb_cols(cpi);
1994
1995 #endif
1996
1997   /* setup RD costs to MACROBLOCK struct */
1998
1999   cpi->mb.mvcost[0] = &cpi->rd_costs.mvcosts[0][mv_max + 1];
2000   cpi->mb.mvcost[1] = &cpi->rd_costs.mvcosts[1][mv_max + 1];
2001   cpi->mb.mvsadcost[0] = &cpi->rd_costs.mvsadcosts[0][mvfp_max + 1];
2002   cpi->mb.mvsadcost[1] = &cpi->rd_costs.mvsadcosts[1][mvfp_max + 1];
2003
2004   cal_mvsadcosts(cpi->mb.mvsadcost);
2005
2006   cpi->mb.mbmode_cost = cpi->rd_costs.mbmode_cost;
2007   cpi->mb.intra_uv_mode_cost = cpi->rd_costs.intra_uv_mode_cost;
2008   cpi->mb.bmode_costs = cpi->rd_costs.bmode_costs;
2009   cpi->mb.inter_bmode_costs = cpi->rd_costs.inter_bmode_costs;
2010   cpi->mb.token_costs = cpi->rd_costs.token_costs;
2011
2012   /* setup block ptrs & offsets */
2013   vp8_setup_block_ptrs(&cpi->mb);
2014   vp8_setup_block_dptrs(&cpi->mb.e_mbd);
2015
2016   return cpi;
2017 }
2018
2019 void vp8_remove_compressor(VP8_COMP **ptr) {
2020   VP8_COMP *cpi = *ptr;
2021
2022   if (!cpi) return;
2023
2024   if (cpi && (cpi->common.current_video_frame > 0)) {
2025 #if !CONFIG_REALTIME_ONLY
2026
2027     if (cpi->pass == 2) {
2028       vp8_end_second_pass(cpi);
2029     }
2030
2031 #endif
2032
2033 #ifdef VP8_ENTROPY_STATS
2034     print_context_counters();
2035     print_tree_update_probs();
2036     print_mode_context();
2037 #endif
2038
2039 #if CONFIG_INTERNAL_STATS
2040
2041     if (cpi->pass != 1) {
2042       FILE *f = fopen("opsnr.stt", "a");
2043       double time_encoded =
2044           (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
2045           10000000.000;
2046       double total_encode_time =
2047           (cpi->time_receive_data + cpi->time_compress_data) / 1000.000;
2048       double dr = (double)cpi->bytes * 8.0 / 1000.0 / time_encoded;
2049       const double target_rate = (double)cpi->oxcf.target_bandwidth / 1000;
2050       const double rate_err = ((100.0 * (dr - target_rate)) / target_rate);
2051
2052       if (cpi->b_calculate_psnr) {
2053         if (cpi->oxcf.number_of_layers > 1) {
2054           int i;
2055
2056           fprintf(f,
2057                   "Layer\tBitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2058                   "GLPsnrP\tVPXSSIM\t\n");
2059           for (i = 0; i < (int)cpi->oxcf.number_of_layers; ++i) {
2060             double dr =
2061                 (double)cpi->bytes_in_layer[i] * 8.0 / 1000.0 / time_encoded;
2062             double samples = 3.0 / 2 * cpi->frames_in_layer[i] *
2063                              cpi->common.Width * cpi->common.Height;
2064             double total_psnr =
2065                 vpx_sse_to_psnr(samples, 255.0, cpi->total_error2[i]);
2066             double total_psnr2 =
2067                 vpx_sse_to_psnr(samples, 255.0, cpi->total_error2_p[i]);
2068             double total_ssim =
2069                 100 * pow(cpi->sum_ssim[i] / cpi->sum_weights[i], 8.0);
2070
2071             fprintf(f,
2072                     "%5d\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2073                     "%7.3f\t%7.3f\n",
2074                     i, dr, cpi->sum_psnr[i] / cpi->frames_in_layer[i],
2075                     total_psnr, cpi->sum_psnr_p[i] / cpi->frames_in_layer[i],
2076                     total_psnr2, total_ssim);
2077           }
2078         } else {
2079           double samples =
2080               3.0 / 2 * cpi->count * cpi->common.Width * cpi->common.Height;
2081           double total_psnr =
2082               vpx_sse_to_psnr(samples, 255.0, cpi->total_sq_error);
2083           double total_psnr2 =
2084               vpx_sse_to_psnr(samples, 255.0, cpi->total_sq_error2);
2085           double total_ssim =
2086               100 * pow(cpi->summed_quality / cpi->summed_weights, 8.0);
2087
2088           fprintf(f,
2089                   "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2090                   "GLPsnrP\tVPXSSIM\t  Time(us)  Rc-Err "
2091                   "Abs Err\n");
2092           fprintf(f,
2093                   "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2094                   "%7.3f\t%8.0f %7.2f %7.2f\n",
2095                   dr, cpi->total / cpi->count, total_psnr,
2096                   cpi->totalp / cpi->count, total_psnr2, total_ssim,
2097                   total_encode_time, rate_err, fabs(rate_err));
2098         }
2099       }
2100       fclose(f);
2101 #if 0
2102             f = fopen("qskip.stt", "a");
2103             fprintf(f, "minq:%d -maxq:%d skiptrue:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
2104             fclose(f);
2105 #endif
2106     }
2107
2108 #endif
2109
2110 #ifdef SPEEDSTATS
2111
2112     if (cpi->compressor_speed == 2) {
2113       int i;
2114       FILE *f = fopen("cxspeed.stt", "a");
2115       cnt_pm /= cpi->common.MBs;
2116
2117       for (i = 0; i < 16; ++i) fprintf(f, "%5d", frames_at_speed[i]);
2118
2119       fprintf(f, "\n");
2120       fclose(f);
2121     }
2122
2123 #endif
2124
2125 #ifdef MODE_STATS
2126     {
2127       extern int count_mb_seg[4];
2128       FILE *f = fopen("modes.stt", "a");
2129       double dr = (double)cpi->framerate * (double)bytes * (double)8 /
2130                   (double)count / (double)1000;
2131       fprintf(f, "intra_mode in Intra Frames:\n");
2132       fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1],
2133               y_modes[2], y_modes[3], y_modes[4]);
2134       fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1],
2135               uv_modes[2], uv_modes[3]);
2136       fprintf(f, "B: ");
2137       {
2138         int i;
2139
2140         for (i = 0; i < 10; ++i) fprintf(f, "%8d, ", b_modes[i]);
2141
2142         fprintf(f, "\n");
2143       }
2144
2145       fprintf(f, "Modes in Inter Frames:\n");
2146       fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
2147               inter_y_modes[0], inter_y_modes[1], inter_y_modes[2],
2148               inter_y_modes[3], inter_y_modes[4], inter_y_modes[5],
2149               inter_y_modes[6], inter_y_modes[7], inter_y_modes[8],
2150               inter_y_modes[9]);
2151       fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0],
2152               inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
2153       fprintf(f, "B: ");
2154       {
2155         int i;
2156
2157         for (i = 0; i < 15; ++i) fprintf(f, "%8d, ", inter_b_modes[i]);
2158
2159         fprintf(f, "\n");
2160       }
2161       fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1],
2162               count_mb_seg[2], count_mb_seg[3]);
2163       fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4],
2164               inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4],
2165               inter_b_modes[NEW4X4]);
2166
2167       fclose(f);
2168     }
2169 #endif
2170
2171 #ifdef VP8_ENTROPY_STATS
2172     {
2173       int i, j, k;
2174       FILE *fmode = fopen("modecontext.c", "w");
2175
2176       fprintf(fmode, "\n#include \"entropymode.h\"\n\n");
2177       fprintf(fmode, "const unsigned int vp8_kf_default_bmode_counts ");
2178       fprintf(fmode,
2179               "[VP8_BINTRAMODES] [VP8_BINTRAMODES] [VP8_BINTRAMODES] =\n{\n");
2180
2181       for (i = 0; i < 10; ++i) {
2182         fprintf(fmode, "    { /* Above Mode :  %d */\n", i);
2183
2184         for (j = 0; j < 10; ++j) {
2185           fprintf(fmode, "        {");
2186
2187           for (k = 0; k < 10; ++k) {
2188             if (!intra_mode_stats[i][j][k])
2189               fprintf(fmode, " %5d, ", 1);
2190             else
2191               fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
2192           }
2193
2194           fprintf(fmode, "}, /* left_mode %d */\n", j);
2195         }
2196
2197         fprintf(fmode, "    },\n");
2198       }
2199
2200       fprintf(fmode, "};\n");
2201       fclose(fmode);
2202     }
2203 #endif
2204
2205 #if defined(SECTIONBITS_OUTPUT)
2206
2207     if (0) {
2208       int i;
2209       FILE *f = fopen("tokenbits.stt", "a");
2210
2211       for (i = 0; i < 28; ++i) fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
2212
2213       fprintf(f, "\n");
2214       fclose(f);
2215     }
2216
2217 #endif
2218
2219 #if 0
2220         {
2221             printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2222             printf("\n_frames recive_data encod_mb_row compress_frame  Total\n");
2223             printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame, cpi->time_receive_data / 1000, cpi->time_encode_mb_row / 1000, cpi->time_compress_data / 1000, (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2224         }
2225 #endif
2226   }
2227
2228 #if CONFIG_MULTITHREAD
2229   vp8cx_remove_encoder_threads(cpi);
2230 #endif
2231
2232 #if CONFIG_TEMPORAL_DENOISING
2233   vp8_denoiser_free(&cpi->denoiser);
2234 #endif
2235   dealloc_compressor_data(cpi);
2236   vpx_free(cpi->mb.ss);
2237   vpx_free(cpi->tok);
2238   vpx_free(cpi->cyclic_refresh_map);
2239   vpx_free(cpi->consec_zero_last);
2240   vpx_free(cpi->consec_zero_last_mvbias);
2241
2242   vp8_remove_common(&cpi->common);
2243   vpx_free(cpi);
2244   *ptr = 0;
2245
2246 #ifdef OUTPUT_YUV_SRC
2247   fclose(yuv_file);
2248 #endif
2249 #ifdef OUTPUT_YUV_DENOISED
2250   fclose(yuv_denoised_file);
2251 #endif
2252
2253 #if 0
2254
2255     if (keyfile)
2256         fclose(keyfile);
2257
2258     if (framepsnr)
2259         fclose(framepsnr);
2260
2261     if (kf_list)
2262         fclose(kf_list);
2263
2264 #endif
2265 }
2266
2267 static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
2268                                  unsigned char *recon, int recon_stride,
2269                                  unsigned int cols, unsigned int rows) {
2270   unsigned int row, col;
2271   uint64_t total_sse = 0;
2272   int diff;
2273
2274   for (row = 0; row + 16 <= rows; row += 16) {
2275     for (col = 0; col + 16 <= cols; col += 16) {
2276       unsigned int sse;
2277
2278       vpx_mse16x16(orig + col, orig_stride, recon + col, recon_stride, &sse);
2279       total_sse += sse;
2280     }
2281
2282     /* Handle odd-sized width */
2283     if (col < cols) {
2284       unsigned int border_row, border_col;
2285       unsigned char *border_orig = orig;
2286       unsigned char *border_recon = recon;
2287
2288       for (border_row = 0; border_row < 16; ++border_row) {
2289         for (border_col = col; border_col < cols; ++border_col) {
2290           diff = border_orig[border_col] - border_recon[border_col];
2291           total_sse += diff * diff;
2292         }
2293
2294         border_orig += orig_stride;
2295         border_recon += recon_stride;
2296       }
2297     }
2298
2299     orig += orig_stride * 16;
2300     recon += recon_stride * 16;
2301   }
2302
2303   /* Handle odd-sized height */
2304   for (; row < rows; ++row) {
2305     for (col = 0; col < cols; ++col) {
2306       diff = orig[col] - recon[col];
2307       total_sse += diff * diff;
2308     }
2309
2310     orig += orig_stride;
2311     recon += recon_stride;
2312   }
2313
2314   vp8_clear_system_state();
2315   return total_sse;
2316 }
2317
2318 static void generate_psnr_packet(VP8_COMP *cpi) {
2319   YV12_BUFFER_CONFIG *orig = cpi->Source;
2320   YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2321   struct vpx_codec_cx_pkt pkt;
2322   uint64_t sse;
2323   int i;
2324   unsigned int width = cpi->common.Width;
2325   unsigned int height = cpi->common.Height;
2326
2327   pkt.kind = VPX_CODEC_PSNR_PKT;
2328   sse = calc_plane_error(orig->y_buffer, orig->y_stride, recon->y_buffer,
2329                          recon->y_stride, width, height);
2330   pkt.data.psnr.sse[0] = sse;
2331   pkt.data.psnr.sse[1] = sse;
2332   pkt.data.psnr.samples[0] = width * height;
2333   pkt.data.psnr.samples[1] = width * height;
2334
2335   width = (width + 1) / 2;
2336   height = (height + 1) / 2;
2337
2338   sse = calc_plane_error(orig->u_buffer, orig->uv_stride, recon->u_buffer,
2339                          recon->uv_stride, width, height);
2340   pkt.data.psnr.sse[0] += sse;
2341   pkt.data.psnr.sse[2] = sse;
2342   pkt.data.psnr.samples[0] += width * height;
2343   pkt.data.psnr.samples[2] = width * height;
2344
2345   sse = calc_plane_error(orig->v_buffer, orig->uv_stride, recon->v_buffer,
2346                          recon->uv_stride, width, height);
2347   pkt.data.psnr.sse[0] += sse;
2348   pkt.data.psnr.sse[3] = sse;
2349   pkt.data.psnr.samples[0] += width * height;
2350   pkt.data.psnr.samples[3] = width * height;
2351
2352   for (i = 0; i < 4; ++i) {
2353     pkt.data.psnr.psnr[i] = vpx_sse_to_psnr(pkt.data.psnr.samples[i], 255.0,
2354                                             (double)(pkt.data.psnr.sse[i]));
2355   }
2356
2357   vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2358 }
2359
2360 int vp8_use_as_reference(VP8_COMP *cpi, int ref_frame_flags) {
2361   if (ref_frame_flags > 7) return -1;
2362
2363   cpi->ref_frame_flags = ref_frame_flags;
2364   return 0;
2365 }
2366 int vp8_update_reference(VP8_COMP *cpi, int ref_frame_flags) {
2367   if (ref_frame_flags > 7) return -1;
2368
2369   cpi->common.refresh_golden_frame = 0;
2370   cpi->common.refresh_alt_ref_frame = 0;
2371   cpi->common.refresh_last_frame = 0;
2372
2373   if (ref_frame_flags & VP8_LAST_FRAME) cpi->common.refresh_last_frame = 1;
2374
2375   if (ref_frame_flags & VP8_GOLD_FRAME) cpi->common.refresh_golden_frame = 1;
2376
2377   if (ref_frame_flags & VP8_ALTR_FRAME) cpi->common.refresh_alt_ref_frame = 1;
2378
2379   return 0;
2380 }
2381
2382 int vp8_get_reference(VP8_COMP *cpi, enum vpx_ref_frame_type ref_frame_flag,
2383                       YV12_BUFFER_CONFIG *sd) {
2384   VP8_COMMON *cm = &cpi->common;
2385   int ref_fb_idx;
2386
2387   if (ref_frame_flag == VP8_LAST_FRAME) {
2388     ref_fb_idx = cm->lst_fb_idx;
2389   } else if (ref_frame_flag == VP8_GOLD_FRAME) {
2390     ref_fb_idx = cm->gld_fb_idx;
2391   } else if (ref_frame_flag == VP8_ALTR_FRAME) {
2392     ref_fb_idx = cm->alt_fb_idx;
2393   } else {
2394     return -1;
2395   }
2396
2397   vp8_yv12_copy_frame(&cm->yv12_fb[ref_fb_idx], sd);
2398
2399   return 0;
2400 }
2401 int vp8_set_reference(VP8_COMP *cpi, enum vpx_ref_frame_type ref_frame_flag,
2402                       YV12_BUFFER_CONFIG *sd) {
2403   VP8_COMMON *cm = &cpi->common;
2404
2405   int ref_fb_idx;
2406
2407   if (ref_frame_flag == VP8_LAST_FRAME) {
2408     ref_fb_idx = cm->lst_fb_idx;
2409   } else if (ref_frame_flag == VP8_GOLD_FRAME) {
2410     ref_fb_idx = cm->gld_fb_idx;
2411   } else if (ref_frame_flag == VP8_ALTR_FRAME) {
2412     ref_fb_idx = cm->alt_fb_idx;
2413   } else {
2414     return -1;
2415   }
2416
2417   vp8_yv12_copy_frame(sd, &cm->yv12_fb[ref_fb_idx]);
2418
2419   return 0;
2420 }
2421 int vp8_update_entropy(VP8_COMP *cpi, int update) {
2422   VP8_COMMON *cm = &cpi->common;
2423   cm->refresh_entropy_probs = update;
2424
2425   return 0;
2426 }
2427
2428 #if defined(OUTPUT_YUV_SRC) || defined(OUTPUT_YUV_DENOISED)
2429 void vp8_write_yuv_frame(FILE *yuv_file, YV12_BUFFER_CONFIG *s) {
2430   unsigned char *src = s->y_buffer;
2431   int h = s->y_height;
2432
2433   do {
2434     fwrite(src, s->y_width, 1, yuv_file);
2435     src += s->y_stride;
2436   } while (--h);
2437
2438   src = s->u_buffer;
2439   h = s->uv_height;
2440
2441   do {
2442     fwrite(src, s->uv_width, 1, yuv_file);
2443     src += s->uv_stride;
2444   } while (--h);
2445
2446   src = s->v_buffer;
2447   h = s->uv_height;
2448
2449   do {
2450     fwrite(src, s->uv_width, 1, yuv_file);
2451     src += s->uv_stride;
2452   } while (--h);
2453 }
2454 #endif
2455
2456 static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi) {
2457   VP8_COMMON *cm = &cpi->common;
2458
2459   /* are we resizing the image */
2460   if (cm->horiz_scale != 0 || cm->vert_scale != 0) {
2461 #if CONFIG_SPATIAL_RESAMPLING
2462     int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2463     int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2464     int tmp_height;
2465
2466     if (cm->vert_scale == 3) {
2467       tmp_height = 9;
2468     } else {
2469       tmp_height = 11;
2470     }
2471
2472     Scale2Ratio(cm->horiz_scale, &hr, &hs);
2473     Scale2Ratio(cm->vert_scale, &vr, &vs);
2474
2475     vpx_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
2476                     tmp_height, hs, hr, vs, vr, 0);
2477
2478     vp8_yv12_extend_frame_borders(&cpi->scaled_source);
2479     cpi->Source = &cpi->scaled_source;
2480 #endif
2481   } else {
2482     cpi->Source = sd;
2483   }
2484 }
2485
2486 static int resize_key_frame(VP8_COMP *cpi) {
2487 #if CONFIG_SPATIAL_RESAMPLING
2488   VP8_COMMON *cm = &cpi->common;
2489
2490   /* Do we need to apply resampling for one pass cbr.
2491    * In one pass this is more limited than in two pass cbr.
2492    * The test and any change is only made once per key frame sequence.
2493    */
2494   if (cpi->oxcf.allow_spatial_resampling &&
2495       (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) {
2496     int UNINITIALIZED_IS_SAFE(hr), UNINITIALIZED_IS_SAFE(hs);
2497     int UNINITIALIZED_IS_SAFE(vr), UNINITIALIZED_IS_SAFE(vs);
2498     int new_width, new_height;
2499
2500     /* If we are below the resample DOWN watermark then scale down a
2501      * notch.
2502      */
2503     if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark *
2504                              cpi->oxcf.optimal_buffer_level / 100)) {
2505       cm->horiz_scale =
2506           (cm->horiz_scale < ONETWO) ? cm->horiz_scale + 1 : ONETWO;
2507       cm->vert_scale = (cm->vert_scale < ONETWO) ? cm->vert_scale + 1 : ONETWO;
2508     }
2509     /* Should we now start scaling back up */
2510     else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark *
2511                                   cpi->oxcf.optimal_buffer_level / 100)) {
2512       cm->horiz_scale =
2513           (cm->horiz_scale > NORMAL) ? cm->horiz_scale - 1 : NORMAL;
2514       cm->vert_scale = (cm->vert_scale > NORMAL) ? cm->vert_scale - 1 : NORMAL;
2515     }
2516
2517     /* Get the new height and width */
2518     Scale2Ratio(cm->horiz_scale, &hr, &hs);
2519     Scale2Ratio(cm->vert_scale, &vr, &vs);
2520     new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2521     new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2522
2523     /* If the image size has changed we need to reallocate the buffers
2524      * and resample the source image
2525      */
2526     if ((cm->Width != new_width) || (cm->Height != new_height)) {
2527       cm->Width = new_width;
2528       cm->Height = new_height;
2529       vp8_alloc_compressor_data(cpi);
2530       scale_and_extend_source(cpi->un_scaled_source, cpi);
2531       return 1;
2532     }
2533   }
2534
2535 #endif
2536   return 0;
2537 }
2538
2539 static void update_alt_ref_frame_stats(VP8_COMP *cpi) {
2540   VP8_COMMON *cm = &cpi->common;
2541
2542   /* Select an interval before next GF or altref */
2543   if (!cpi->auto_gold) cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
2544
2545   if ((cpi->pass != 2) && cpi->frames_till_gf_update_due) {
2546     cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2547
2548     /* Set the bits per frame that we should try and recover in
2549      * subsequent inter frames to account for the extra GF spend...
2550      * note that his does not apply for GF updates that occur
2551      * coincident with a key frame as the extra cost of key frames is
2552      * dealt with elsewhere.
2553      */
2554     cpi->gf_overspend_bits += cpi->projected_frame_size;
2555     cpi->non_gf_bitrate_adjustment =
2556         cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2557   }
2558
2559   /* Update data structure that monitors level of reference to last GF */
2560   memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2561   cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2562
2563   /* this frame refreshes means next frames don't unless specified by user */
2564   cpi->frames_since_golden = 0;
2565
2566   /* Clear the alternate reference update pending flag. */
2567   cpi->source_alt_ref_pending = 0;
2568
2569   /* Set the alternate reference frame active flag */
2570   cpi->source_alt_ref_active = 1;
2571 }
2572 static void update_golden_frame_stats(VP8_COMP *cpi) {
2573   VP8_COMMON *cm = &cpi->common;
2574
2575   /* Update the Golden frame usage counts. */
2576   if (cm->refresh_golden_frame) {
2577     /* Select an interval before next GF */
2578     if (!cpi->auto_gold) cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
2579
2580     if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0)) {
2581       cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2582
2583       /* Set the bits per frame that we should try and recover in
2584        * subsequent inter frames to account for the extra GF spend...
2585        * note that his does not apply for GF updates that occur
2586        * coincident with a key frame as the extra cost of key frames
2587        * is dealt with elsewhere.
2588        */
2589       if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active) {
2590         /* Calcluate GF bits to be recovered
2591          * Projected size - av frame bits available for inter
2592          * frames for clip as a whole
2593          */
2594         cpi->gf_overspend_bits +=
2595             (cpi->projected_frame_size - cpi->inter_frame_target);
2596       }
2597
2598       cpi->non_gf_bitrate_adjustment =
2599           cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2600     }
2601
2602     /* Update data structure that monitors level of reference to last GF */
2603     memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2604     cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2605
2606     /* this frame refreshes means next frames don't unless specified by
2607      * user
2608      */
2609     cm->refresh_golden_frame = 0;
2610     cpi->frames_since_golden = 0;
2611
2612     cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
2613     cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
2614     cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
2615     cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
2616
2617     /* ******** Fixed Q test code only ************ */
2618     /* If we are going to use the ALT reference for the next group of
2619      * frames set a flag to say so.
2620      */
2621     if (cpi->oxcf.fixed_q >= 0 && cpi->oxcf.play_alternate &&
2622         !cpi->common.refresh_alt_ref_frame) {
2623       cpi->source_alt_ref_pending = 1;
2624       cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2625     }
2626
2627     if (!cpi->source_alt_ref_pending) cpi->source_alt_ref_active = 0;
2628
2629     /* Decrement count down till next gf */
2630     if (cpi->frames_till_gf_update_due > 0) cpi->frames_till_gf_update_due--;
2631
2632   } else if (!cpi->common.refresh_alt_ref_frame) {
2633     /* Decrement count down till next gf */
2634     if (cpi->frames_till_gf_update_due > 0) cpi->frames_till_gf_update_due--;
2635
2636     if (cpi->frames_till_alt_ref_frame) cpi->frames_till_alt_ref_frame--;
2637
2638     cpi->frames_since_golden++;
2639
2640     if (cpi->frames_since_golden > 1) {
2641       cpi->recent_ref_frame_usage[INTRA_FRAME] +=
2642           cpi->mb.count_mb_ref_frame_usage[INTRA_FRAME];
2643       cpi->recent_ref_frame_usage[LAST_FRAME] +=
2644           cpi->mb.count_mb_ref_frame_usage[LAST_FRAME];
2645       cpi->recent_ref_frame_usage[GOLDEN_FRAME] +=
2646           cpi->mb.count_mb_ref_frame_usage[GOLDEN_FRAME];
2647       cpi->recent_ref_frame_usage[ALTREF_FRAME] +=
2648           cpi->mb.count_mb_ref_frame_usage[ALTREF_FRAME];
2649     }
2650   }
2651 }
2652
2653 /* This function updates the reference frame probability estimates that
2654  * will be used during mode selection
2655  */
2656 static void update_rd_ref_frame_probs(VP8_COMP *cpi) {
2657   VP8_COMMON *cm = &cpi->common;
2658
2659   const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
2660   const int rf_intra = rfct[INTRA_FRAME];
2661   const int rf_inter =
2662       rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2663
2664   if (cm->frame_type == KEY_FRAME) {
2665     cpi->prob_intra_coded = 255;
2666     cpi->prob_last_coded = 128;
2667     cpi->prob_gf_coded = 128;
2668   } else if (!(rf_intra + rf_inter)) {
2669     cpi->prob_intra_coded = 63;
2670     cpi->prob_last_coded = 128;
2671     cpi->prob_gf_coded = 128;
2672   }
2673
2674   /* update reference frame costs since we can do better than what we got
2675    * last frame.
2676    */
2677   if (cpi->oxcf.number_of_layers == 1) {
2678     if (cpi->common.refresh_alt_ref_frame) {
2679       cpi->prob_intra_coded += 40;
2680       if (cpi->prob_intra_coded > 255) cpi->prob_intra_coded = 255;
2681       cpi->prob_last_coded = 200;
2682       cpi->prob_gf_coded = 1;
2683     } else if (cpi->frames_since_golden == 0) {
2684       cpi->prob_last_coded = 214;
2685     } else if (cpi->frames_since_golden == 1) {
2686       cpi->prob_last_coded = 192;
2687       cpi->prob_gf_coded = 220;
2688     } else if (cpi->source_alt_ref_active) {
2689       cpi->prob_gf_coded -= 20;
2690
2691       if (cpi->prob_gf_coded < 10) cpi->prob_gf_coded = 10;
2692     }
2693     if (!cpi->source_alt_ref_active) cpi->prob_gf_coded = 255;
2694   }
2695 }
2696
2697 #if !CONFIG_REALTIME_ONLY
2698 /* 1 = key, 0 = inter */
2699 static int decide_key_frame(VP8_COMP *cpi) {
2700   VP8_COMMON *cm = &cpi->common;
2701
2702   int code_key_frame = 0;
2703
2704   cpi->kf_boost = 0;
2705
2706   if (cpi->Speed > 11) return 0;
2707
2708   /* Clear down mmx registers */
2709   vp8_clear_system_state();
2710
2711   if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0)) {
2712     double change = 1.0 *
2713                     abs((int)(cpi->mb.intra_error - cpi->last_intra_error)) /
2714                     (1 + cpi->last_intra_error);
2715     double change2 =
2716         1.0 *
2717         abs((int)(cpi->mb.prediction_error - cpi->last_prediction_error)) /
2718         (1 + cpi->last_prediction_error);
2719     double minerror = cm->MBs * 256;
2720
2721     cpi->last_intra_error = cpi->mb.intra_error;
2722     cpi->last_prediction_error = cpi->mb.prediction_error;
2723
2724     if (10 * cpi->mb.intra_error / (1 + cpi->mb.prediction_error) < 15 &&
2725         cpi->mb.prediction_error > minerror &&
2726         (change > .25 || change2 > .25)) {
2727       /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra >
2728        * cpi->last_frame_percent_intra + 3*/
2729       return 1;
2730     }
2731
2732     return 0;
2733   }
2734
2735   /* If the following are true we might as well code a key frame */
2736   if (((cpi->this_frame_percent_intra == 100) &&
2737        (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
2738       ((cpi->this_frame_percent_intra > 95) &&
2739        (cpi->this_frame_percent_intra >=
2740         (cpi->last_frame_percent_intra + 5)))) {
2741     code_key_frame = 1;
2742   }
2743   /* in addition if the following are true and this is not a golden frame
2744    * then code a key frame Note that on golden frames there often seems
2745    * to be a pop in intra useage anyway hence this restriction is
2746    * designed to prevent spurious key frames. The Intra pop needs to be
2747    * investigated.
2748    */
2749   else if (((cpi->this_frame_percent_intra > 60) &&
2750             (cpi->this_frame_percent_intra >
2751              (cpi->last_frame_percent_intra * 2))) ||
2752            ((cpi->this_frame_percent_intra > 75) &&
2753             (cpi->this_frame_percent_intra >
2754              (cpi->last_frame_percent_intra * 3 / 2))) ||
2755            ((cpi->this_frame_percent_intra > 90) &&
2756             (cpi->this_frame_percent_intra >
2757              (cpi->last_frame_percent_intra + 10)))) {
2758     if (!cm->refresh_golden_frame) code_key_frame = 1;
2759   }
2760
2761   return code_key_frame;
2762 }
2763
2764 static void Pass1Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest,
2765                         unsigned int *frame_flags) {
2766   (void)size;
2767   (void)dest;
2768   (void)frame_flags;
2769   vp8_set_quantizer(cpi, 26);
2770
2771   vp8_first_pass(cpi);
2772 }
2773 #endif
2774
2775 #if 0
2776 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
2777 {
2778
2779     /* write the frame */
2780     FILE *yframe;
2781     int i;
2782     char filename[255];
2783
2784     sprintf(filename, "cx\\y%04d.raw", this_frame);
2785     yframe = fopen(filename, "wb");
2786
2787     for (i = 0; i < frame->y_height; ++i)
2788         fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
2789
2790     fclose(yframe);
2791     sprintf(filename, "cx\\u%04d.raw", this_frame);
2792     yframe = fopen(filename, "wb");
2793
2794     for (i = 0; i < frame->uv_height; ++i)
2795         fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2796
2797     fclose(yframe);
2798     sprintf(filename, "cx\\v%04d.raw", this_frame);
2799     yframe = fopen(filename, "wb");
2800
2801     for (i = 0; i < frame->uv_height; ++i)
2802         fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2803
2804     fclose(yframe);
2805 }
2806 #endif
2807 /* return of 0 means drop frame */
2808
2809 #if !CONFIG_REALTIME_ONLY
2810 /* Function to test for conditions that indeicate we should loop
2811  * back and recode a frame.
2812  */
2813 static int recode_loop_test(VP8_COMP *cpi, int high_limit, int low_limit, int q,
2814                             int maxq, int minq) {
2815   int force_recode = 0;
2816   VP8_COMMON *cm = &cpi->common;
2817
2818   /* Is frame recode allowed at all
2819    * Yes if either recode mode 1 is selected or mode two is selcted
2820    * and the frame is a key frame. golden frame or alt_ref_frame
2821    */
2822   if ((cpi->sf.recode_loop == 1) ||
2823       ((cpi->sf.recode_loop == 2) &&
2824        ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
2825         cm->refresh_alt_ref_frame))) {
2826     /* General over and under shoot tests */
2827     if (((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
2828         ((cpi->projected_frame_size < low_limit) && (q > minq))) {
2829       force_recode = 1;
2830     }
2831     /* Special Constrained quality tests */
2832     else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
2833       /* Undershoot and below auto cq level */
2834       if ((q > cpi->cq_target_quality) &&
2835           (cpi->projected_frame_size < ((cpi->this_frame_target * 7) >> 3))) {
2836         force_recode = 1;
2837       }
2838       /* Severe undershoot and between auto and user cq level */
2839       else if ((q > cpi->oxcf.cq_level) &&
2840                (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
2841                (cpi->active_best_quality > cpi->oxcf.cq_level)) {
2842         force_recode = 1;
2843         cpi->active_best_quality = cpi->oxcf.cq_level;
2844       }
2845     }
2846   }
2847
2848   return force_recode;
2849 }
2850 #endif  // !CONFIG_REALTIME_ONLY
2851
2852 static void update_reference_frames(VP8_COMP *cpi) {
2853   VP8_COMMON *cm = &cpi->common;
2854   YV12_BUFFER_CONFIG *yv12_fb = cm->yv12_fb;
2855
2856   /* At this point the new frame has been encoded.
2857    * If any buffer copy / swapping is signaled it should be done here.
2858    */
2859
2860   if (cm->frame_type == KEY_FRAME) {
2861     yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FRAME | VP8_ALTR_FRAME;
2862
2863     yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
2864     yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
2865
2866     cm->alt_fb_idx = cm->gld_fb_idx = cm->new_fb_idx;
2867
2868     cpi->current_ref_frames[GOLDEN_FRAME] = cm->current_video_frame;
2869     cpi->current_ref_frames[ALTREF_FRAME] = cm->current_video_frame;
2870   } else /* For non key frames */
2871   {
2872     if (cm->refresh_alt_ref_frame) {
2873       assert(!cm->copy_buffer_to_arf);
2874
2875       cm->yv12_fb[cm->new_fb_idx].flags |= VP8_ALTR_FRAME;
2876       cm->yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
2877       cm->alt_fb_idx = cm->new_fb_idx;
2878
2879       cpi->current_ref_frames[ALTREF_FRAME] = cm->current_video_frame;
2880     } else if (cm->copy_buffer_to_arf) {
2881       assert(!(cm->copy_buffer_to_arf & ~0x3));
2882
2883       if (cm->copy_buffer_to_arf == 1) {
2884         if (cm->alt_fb_idx != cm->lst_fb_idx) {
2885           yv12_fb[cm->lst_fb_idx].flags |= VP8_ALTR_FRAME;
2886           yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
2887           cm->alt_fb_idx = cm->lst_fb_idx;
2888
2889           cpi->current_ref_frames[ALTREF_FRAME] =
2890               cpi->current_ref_frames[LAST_FRAME];
2891         }
2892       } else /* if (cm->copy_buffer_to_arf == 2) */
2893       {
2894         if (cm->alt_fb_idx != cm->gld_fb_idx) {
2895           yv12_fb[cm->gld_fb_idx].flags |= VP8_ALTR_FRAME;
2896           yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
2897           cm->alt_fb_idx = cm->gld_fb_idx;
2898
2899           cpi->current_ref_frames[ALTREF_FRAME] =
2900               cpi->current_ref_frames[GOLDEN_FRAME];
2901         }
2902       }
2903     }
2904
2905     if (cm->refresh_golden_frame) {
2906       assert(!cm->copy_buffer_to_gf);
2907
2908       cm->yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FRAME;
2909       cm->yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
2910       cm->gld_fb_idx = cm->new_fb_idx;
2911
2912       cpi->current_ref_frames[GOLDEN_FRAME] = cm->current_video_frame;
2913     } else if (cm->copy_buffer_to_gf) {
2914       assert(!(cm->copy_buffer_to_arf & ~0x3));
2915
2916       if (cm->copy_buffer_to_gf == 1) {
2917         if (cm->gld_fb_idx != cm->lst_fb_idx) {
2918           yv12_fb[cm->lst_fb_idx].flags |= VP8_GOLD_FRAME;
2919           yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
2920           cm->gld_fb_idx = cm->lst_fb_idx;
2921
2922           cpi->current_ref_frames[GOLDEN_FRAME] =
2923               cpi->current_ref_frames[LAST_FRAME];
2924         }
2925       } else /* if (cm->copy_buffer_to_gf == 2) */
2926       {
2927         if (cm->alt_fb_idx != cm->gld_fb_idx) {
2928           yv12_fb[cm->alt_fb_idx].flags |= VP8_GOLD_FRAME;
2929           yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
2930           cm->gld_fb_idx = cm->alt_fb_idx;
2931
2932           cpi->current_ref_frames[GOLDEN_FRAME] =
2933               cpi->current_ref_frames[ALTREF_FRAME];
2934         }
2935       }
2936     }
2937   }
2938
2939   if (cm->refresh_last_frame) {
2940     cm->yv12_fb[cm->new_fb_idx].flags |= VP8_LAST_FRAME;
2941     cm->yv12_fb[cm->lst_fb_idx].flags &= ~VP8_LAST_FRAME;
2942     cm->lst_fb_idx = cm->new_fb_idx;
2943
2944     cpi->current_ref_frames[LAST_FRAME] = cm->current_video_frame;
2945   }
2946
2947 #if CONFIG_TEMPORAL_DENOISING
2948   if (cpi->oxcf.noise_sensitivity) {
2949     /* we shouldn't have to keep multiple copies as we know in advance which
2950      * buffer we should start - for now to get something up and running
2951      * I've chosen to copy the buffers
2952      */
2953     if (cm->frame_type == KEY_FRAME) {
2954       int i;
2955       for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i)
2956         vp8_yv12_copy_frame(cpi->Source, &cpi->denoiser.yv12_running_avg[i]);
2957     } else /* For non key frames */
2958     {
2959       vp8_yv12_extend_frame_borders(
2960           &cpi->denoiser.yv12_running_avg[INTRA_FRAME]);
2961
2962       if (cm->refresh_alt_ref_frame || cm->copy_buffer_to_arf) {
2963         vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
2964                             &cpi->denoiser.yv12_running_avg[ALTREF_FRAME]);
2965       }
2966       if (cm->refresh_golden_frame || cm->copy_buffer_to_gf) {
2967         vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
2968                             &cpi->denoiser.yv12_running_avg[GOLDEN_FRAME]);
2969       }
2970       if (cm->refresh_last_frame) {
2971         vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
2972                             &cpi->denoiser.yv12_running_avg[LAST_FRAME]);
2973       }
2974     }
2975     if (cpi->oxcf.noise_sensitivity == 4)
2976       vp8_yv12_copy_frame(cpi->Source, &cpi->denoiser.yv12_last_source);
2977   }
2978 #endif
2979 }
2980
2981 static int measure_square_diff_partial(YV12_BUFFER_CONFIG *source,
2982                                        YV12_BUFFER_CONFIG *dest,
2983                                        VP8_COMP *cpi) {
2984   int i, j;
2985   int Total = 0;
2986   int num_blocks = 0;
2987   int skip = 2;
2988   int min_consec_zero_last = 10;
2989   int tot_num_blocks = (source->y_height * source->y_width) >> 8;
2990   unsigned char *src = source->y_buffer;
2991   unsigned char *dst = dest->y_buffer;
2992
2993   /* Loop through the Y plane, every |skip| blocks along rows and colmumns,
2994    * summing the square differences, and only for blocks that have been
2995    * zero_last mode at least |x| frames in a row.
2996    */
2997   for (i = 0; i < source->y_height; i += 16 * skip) {
2998     int block_index_row = (i >> 4) * cpi->common.mb_cols;
2999     for (j = 0; j < source->y_width; j += 16 * skip) {
3000       int index = block_index_row + (j >> 4);
3001       if (cpi->consec_zero_last[index] >= min_consec_zero_last) {
3002         unsigned int sse;
3003         Total += vpx_mse16x16(src + j, source->y_stride, dst + j,
3004                               dest->y_stride, &sse);
3005         num_blocks++;
3006       }
3007     }
3008     src += 16 * skip * source->y_stride;
3009     dst += 16 * skip * dest->y_stride;
3010   }
3011   // Only return non-zero if we have at least ~1/16 samples for estimate.
3012   if (num_blocks > (tot_num_blocks >> 4)) {
3013     return (Total / num_blocks);
3014   } else {
3015     return 0;
3016   }
3017 }
3018
3019 #if CONFIG_TEMPORAL_DENOISING
3020 static void process_denoiser_mode_change(VP8_COMP *cpi) {
3021   const VP8_COMMON *const cm = &cpi->common;
3022   int i, j;
3023   int total = 0;
3024   int num_blocks = 0;
3025   // Number of blocks skipped along row/column in computing the
3026   // nmse (normalized mean square error) of source.
3027   int skip = 2;
3028   // Only select blocks for computing nmse that have been encoded
3029   // as ZERO LAST min_consec_zero_last frames in a row.
3030   // Scale with number of temporal layers.
3031   int min_consec_zero_last = 12 / cpi->oxcf.number_of_layers;
3032   // Decision is tested for changing the denoising mode every
3033   // num_mode_change times this function is called. Note that this
3034   // function called every 8 frames, so (8 * num_mode_change) is number
3035   // of frames where denoising mode change is tested for switch.
3036   int num_mode_change = 20;
3037   // Framerate factor, to compensate for larger mse at lower framerates.
3038   // Use ref_framerate, which is full source framerate for temporal layers.
3039   // TODO(marpan): Adjust this factor.
3040   int fac_framerate = cpi->ref_framerate < 25.0f ? 80 : 100;
3041   int tot_num_blocks = cm->mb_rows * cm->mb_cols;
3042   int ystride = cpi->Source->y_stride;
3043   unsigned char *src = cpi->Source->y_buffer;
3044   unsigned char *dst = cpi->denoiser.yv12_last_source.y_buffer;
3045   static const unsigned char const_source[16] = { 128, 128, 128, 128, 128, 128,
3046                                                   128, 128, 128, 128, 128, 128,
3047                                                   128, 128, 128, 128 };
3048   int bandwidth = (int)(cpi->target_bandwidth);
3049   // For temporal layers, use full bandwidth (top layer).
3050   if (cpi->oxcf.number_of_layers > 1) {
3051     LAYER_CONTEXT *lc = &cpi->layer_context[cpi->oxcf.number_of_layers - 1];
3052     bandwidth = (int)(lc->target_bandwidth);
3053   }
3054   // Loop through the Y plane, every skip blocks along rows and columns,
3055   // summing the normalized mean square error, only for blocks that have
3056   // been encoded as ZEROMV LAST at least min_consec_zero_last least frames in
3057   // a row and have small sum difference between current and previous frame.
3058   // Normalization here is by the contrast of the current frame block.
3059   for (i = 0; i < cm->Height; i += 16 * skip) {
3060     int block_index_row = (i >> 4) * cm->mb_cols;
3061     for (j = 0; j < cm->Width; j += 16 * skip) {
3062       int index = block_index_row + (j >> 4);
3063       if (cpi->consec_zero_last[index] >= min_consec_zero_last) {
3064         unsigned int sse;
3065         const unsigned int var =
3066             vpx_variance16x16(src + j, ystride, dst + j, ystride, &sse);
3067         // Only consider this block as valid for noise measurement
3068         // if the sum_diff average of the current and previous frame
3069         // is small (to avoid effects from lighting change).
3070         if ((sse - var) < 128) {
3071           unsigned int sse2;
3072           const unsigned int act =
3073               vpx_variance16x16(src + j, ystride, const_source, 0, &sse2);
3074           if (act > 0) total += sse / act;
3075           num_blocks++;
3076         }
3077       }
3078     }
3079     src += 16 * skip * ystride;
3080     dst += 16 * skip * ystride;
3081   }
3082   total = total * fac_framerate / 100;
3083
3084   // Only consider this frame as valid sample if we have computed nmse over
3085   // at least ~1/16 blocks, and Total > 0 (Total == 0 can happen if the
3086   // application inputs duplicate frames, or contrast is all zero).
3087   if (total > 0 && (num_blocks > (tot_num_blocks >> 4))) {
3088     // Update the recursive mean square source_diff.
3089     total = (total << 8) / num_blocks;
3090     if (cpi->denoiser.nmse_source_diff_count == 0) {
3091       // First sample in new interval.
3092       cpi->denoiser.nmse_source_diff = total;
3093       cpi->denoiser.qp_avg = cm->base_qindex;
3094     } else {
3095       // For subsequent samples, use average with weight ~1/4 for new sample.
3096       cpi->denoiser.nmse_source_diff =
3097           (int)((total + 3 * cpi->denoiser.nmse_source_diff) >> 2);
3098       cpi->denoiser.qp_avg =
3099           (int)((cm->base_qindex + 3 * cpi->denoiser.qp_avg) >> 2);
3100     }
3101     cpi->denoiser.nmse_source_diff_count++;
3102   }
3103   // Check for changing the denoiser mode, when we have obtained #samples =
3104   // num_mode_change. Condition the change also on the bitrate and QP.
3105   if (cpi->denoiser.nmse_source_diff_count == num_mode_change) {
3106     // Check for going up: from normal to aggressive mode.
3107     if ((cpi->denoiser.denoiser_mode == kDenoiserOnYUV) &&
3108         (cpi->denoiser.nmse_source_diff >
3109          cpi->denoiser.threshold_aggressive_mode) &&
3110         (cpi->denoiser.qp_avg < cpi->denoiser.qp_threshold_up &&
3111          bandwidth > cpi->denoiser.bitrate_threshold)) {
3112       vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUVAggressive);
3113     } else {
3114       // Check for going down: from aggressive to normal mode.
3115       if (((cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) &&
3116            (cpi->denoiser.nmse_source_diff <
3117             cpi->denoiser.threshold_aggressive_mode)) ||
3118           ((cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) &&
3119            (cpi->denoiser.qp_avg > cpi->denoiser.qp_threshold_down ||
3120             bandwidth < cpi->denoiser.bitrate_threshold))) {
3121         vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
3122       }
3123     }
3124     // Reset metric and counter for next interval.
3125     cpi->denoiser.nmse_source_diff = 0;
3126     cpi->denoiser.qp_avg = 0;
3127     cpi->denoiser.nmse_source_diff_count = 0;
3128   }
3129 }
3130 #endif
3131
3132 void vp8_loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm) {
3133   const FRAME_TYPE frame_type = cm->frame_type;
3134
3135   int update_any_ref_buffers = 1;
3136   if (cpi->common.refresh_last_frame == 0 &&
3137       cpi->common.refresh_golden_frame == 0 &&
3138       cpi->common.refresh_alt_ref_frame == 0) {
3139     update_any_ref_buffers = 0;
3140   }
3141
3142   if (cm->no_lpf) {
3143     cm->filter_level = 0;
3144   } else {
3145     struct vpx_usec_timer timer;
3146
3147     vp8_clear_system_state();
3148
3149     vpx_usec_timer_start(&timer);
3150     if (cpi->sf.auto_filter == 0) {
3151 #if CONFIG_TEMPORAL_DENOISING
3152       if (cpi->oxcf.noise_sensitivity && cm->frame_type != KEY_FRAME) {
3153         // Use the denoised buffer for selecting base loop filter level.
3154         // Denoised signal for current frame is stored in INTRA_FRAME.
3155         // No denoising on key frames.
3156         vp8cx_pick_filter_level_fast(
3157             &cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi);
3158       } else {
3159         vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3160       }
3161 #else
3162       vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3163 #endif
3164     } else {
3165 #if CONFIG_TEMPORAL_DENOISING
3166       if (cpi->oxcf.noise_sensitivity && cm->frame_type != KEY_FRAME) {
3167         // Use the denoised buffer for selecting base loop filter level.
3168         // Denoised signal for current frame is stored in INTRA_FRAME.
3169         // No denoising on key frames.
3170         vp8cx_pick_filter_level(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
3171                                 cpi);
3172       } else {
3173         vp8cx_pick_filter_level(cpi->Source, cpi);
3174       }
3175 #else
3176       vp8cx_pick_filter_level(cpi->Source, cpi);
3177 #endif
3178     }
3179
3180     if (cm->filter_level > 0) {
3181       vp8cx_set_alt_lf_level(cpi, cm->filter_level);
3182     }
3183
3184     vpx_usec_timer_mark(&timer);
3185     cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3186   }
3187
3188 #if CONFIG_MULTITHREAD
3189   if (cpi->b_multi_threaded) {
3190     sem_post(&cpi->h_event_end_lpf); /* signal that we have set filter_level */
3191   }
3192 #endif
3193
3194   // No need to apply loop-filter if the encoded frame does not update
3195   // any reference buffers.
3196   if (cm->filter_level > 0 && update_any_ref_buffers) {
3197     vp8_loop_filter_frame(cm, &cpi->mb.e_mbd, frame_type);
3198   }
3199
3200   vp8_yv12_extend_frame_borders(cm->frame_to_show);
3201 }
3202
3203 static void encode_frame_to_data_rate(VP8_COMP *cpi, unsigned long *size,
3204                                       unsigned char *dest,
3205                                       unsigned char *dest_end,
3206                                       unsigned int *frame_flags) {
3207   int Q;
3208   int frame_over_shoot_limit;
3209   int frame_under_shoot_limit;
3210
3211   int Loop = 0;
3212   int loop_count;
3213
3214   VP8_COMMON *cm = &cpi->common;
3215   int active_worst_qchanged = 0;
3216
3217 #if !CONFIG_REALTIME_ONLY
3218   int q_low;
3219   int q_high;
3220   int zbin_oq_high;
3221   int zbin_oq_low = 0;
3222   int top_index;
3223   int bottom_index;
3224   int overshoot_seen = 0;
3225   int undershoot_seen = 0;
3226 #endif
3227
3228   int drop_mark = (int)(cpi->oxcf.drop_frames_water_mark *
3229                         cpi->oxcf.optimal_buffer_level / 100);
3230   int drop_mark75 = drop_mark * 2 / 3;
3231   int drop_mark50 = drop_mark / 4;
3232   int drop_mark25 = drop_mark / 8;
3233
3234   /* Clear down mmx registers to allow floating point in what follows */
3235   vp8_clear_system_state();
3236
3237   if (cpi->force_next_frame_intra) {
3238     cm->frame_type = KEY_FRAME; /* delayed intra frame */
3239     cpi->force_next_frame_intra = 0;
3240   }
3241
3242   /* For an alt ref frame in 2 pass we skip the call to the second pass
3243    * function that sets the target bandwidth
3244    */
3245   switch (cpi->pass) {
3246 #if !CONFIG_REALTIME_ONLY
3247     case 2:
3248       if (cpi->common.refresh_alt_ref_frame) {
3249         /* Per frame bit target for the alt ref frame */
3250         cpi->per_frame_bandwidth = cpi->twopass.gf_bits;
3251         /* per second target bitrate */
3252         cpi->target_bandwidth =
3253             (int)(cpi->twopass.gf_bits * cpi->output_framerate);
3254       }
3255       break;
3256 #endif  // !CONFIG_REALTIME_ONLY
3257     default:
3258       cpi->per_frame_bandwidth =
3259           (int)(cpi->target_bandwidth / cpi->output_framerate);
3260       break;
3261   }
3262
3263   /* Default turn off buffer to buffer copying */
3264   cm->copy_buffer_to_gf = 0;
3265   cm->copy_buffer_to_arf = 0;
3266
3267   /* Clear zbin over-quant value and mode boost values. */
3268   cpi->mb.zbin_over_quant = 0;
3269   cpi->mb.zbin_mode_boost = 0;
3270
3271   /* Enable or disable mode based tweaking of the zbin
3272    * For 2 Pass Only used where GF/ARF prediction quality
3273    * is above a threshold
3274    */
3275   cpi->mb.zbin_mode_boost_enabled = 1;
3276   if (cpi->pass == 2) {
3277     if (cpi->gfu_boost <= 400) {
3278       cpi->mb.zbin_mode_boost_enabled = 0;
3279     }
3280   }
3281
3282   /* Current default encoder behaviour for the altref sign bias */
3283   if (cpi->source_alt_ref_active) {
3284     cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
3285   } else {
3286     cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
3287   }
3288
3289   /* Check to see if a key frame is signaled
3290    * For two pass with auto key frame enabled cm->frame_type may already
3291    * be set, but not for one pass.
3292    */
3293   if ((cm->current_video_frame == 0) || (cm->frame_flags & FRAMEFLAGS_KEY) ||
3294       (cpi->oxcf.auto_key &&
3295        (cpi->frames_since_key % cpi->key_frame_frequency == 0))) {
3296     /* Key frame from VFW/auto-keyframe/first frame */
3297     cm->frame_type = KEY_FRAME;
3298 #if CONFIG_TEMPORAL_DENOISING
3299     if (cpi->oxcf.noise_sensitivity == 4) {
3300       // For adaptive mode, reset denoiser to normal mode on key frame.
3301       vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
3302     }
3303 #endif
3304   }
3305
3306 #if CONFIG_MULTI_RES_ENCODING
3307   if (cpi->oxcf.mr_total_resolutions > 1) {
3308     LOWER_RES_FRAME_INFO *low_res_frame_info =
3309         (LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info;
3310
3311     if (cpi->oxcf.mr_encoder_id) {
3312       // TODO(marpan): This constraint shouldn't be needed, as we would like
3313       // to allow for key frame setting (forced or periodic) defined per
3314       // spatial layer. For now, keep this in.
3315       cm->frame_type = low_res_frame_info->frame_type;
3316
3317       // Check if lower resolution is available for motion vector reuse.
3318       if (cm->frame_type != KEY_FRAME) {
3319         cpi->mr_low_res_mv_avail = 1;
3320         cpi->mr_low_res_mv_avail &= !(low_res_frame_info->is_frame_dropped);
3321
3322         if (cpi->ref_frame_flags & VP8_LAST_FRAME)
3323           cpi->mr_low_res_mv_avail &=
3324               (cpi->current_ref_frames[LAST_FRAME] ==
3325                low_res_frame_info->low_res_ref_frames[LAST_FRAME]);
3326
3327         if (cpi->ref_frame_flags & VP8_GOLD_FRAME)
3328           cpi->mr_low_res_mv_avail &=
3329               (cpi->current_ref_frames[GOLDEN_FRAME] ==
3330                low_res_frame_info->low_res_ref_frames[GOLDEN_FRAME]);
3331
3332         // Don't use altref to determine whether low res is available.
3333         // TODO (marpan): Should we make this type of condition on a
3334         // per-reference frame basis?
3335         /*
3336         if (cpi->ref_frame_flags & VP8_ALTR_FRAME)
3337             cpi->mr_low_res_mv_avail &= (cpi->current_ref_frames[ALTREF_FRAME]
3338                      == low_res_frame_info->low_res_ref_frames[ALTREF_FRAME]);
3339         */
3340       }
3341     }
3342
3343     // On a key frame: For the lowest resolution, keep track of the key frame
3344     // counter value. For the higher resolutions, reset the current video
3345     // frame counter to that of the lowest resolution.
3346     // This is done to the handle the case where we may stop/start encoding
3347     // higher layer(s). The restart-encoding of higher layer is only signaled
3348     // by a key frame for now.
3349     // TODO (marpan): Add flag to indicate restart-encoding of higher layer.
3350     if (cm->frame_type == KEY_FRAME) {
3351       if (cpi->oxcf.mr_encoder_id) {
3352         // If the initial starting value of the buffer level is zero (this can
3353         // happen because we may have not started encoding this higher stream),
3354         // then reset it to non-zero value based on |starting_buffer_level|.
3355         if (cpi->common.current_video_frame == 0 && cpi->buffer_level == 0) {
3356           unsigned int i;
3357           cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
3358           cpi->buffer_level = cpi->oxcf.starting_buffer_level;
3359           for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
3360             LAYER_CONTEXT *lc = &cpi->layer_context[i];
3361             lc->bits_off_target = lc->starting_buffer_level;
3362             lc->buffer_level = lc->starting_buffer_level;
3363           }
3364         }
3365         cpi->common.current_video_frame =
3366             low_res_frame_info->key_frame_counter_value;
3367       } else {
3368         low_res_frame_info->key_frame_counter_value =
3369             cpi->common.current_video_frame;
3370       }
3371     }
3372   }
3373 #endif
3374
3375   // Find the reference frame closest to the current frame.
3376   cpi->closest_reference_frame = LAST_FRAME;
3377   if (cm->frame_type != KEY_FRAME) {
3378     int i;
3379     MV_REFERENCE_FRAME closest_ref = INTRA_FRAME;
3380     if (cpi->ref_frame_flags & VP8_LAST_FRAME) {
3381       closest_ref = LAST_FRAME;
3382     } else if (cpi->ref_frame_flags & VP8_GOLD_FRAME) {
3383       closest_ref = GOLDEN_FRAME;
3384     } else if (cpi->ref_frame_flags & VP8_ALTR_FRAME) {
3385       closest_ref = ALTREF_FRAME;
3386     }
3387     for (i = 1; i <= 3; ++i) {
3388       vpx_ref_frame_type_t ref_frame_type =
3389           (vpx_ref_frame_type_t)((i == 3) ? 4 : i);
3390       if (cpi->ref_frame_flags & ref_frame_type) {
3391         if ((cm->current_video_frame - cpi->current_ref_frames[i]) <
3392             (cm->current_video_frame - cpi->current_ref_frames[closest_ref])) {
3393           closest_ref = i;
3394         }
3395       }
3396     }
3397     cpi->closest_reference_frame = closest_ref;
3398   }
3399
3400   /* Set various flags etc to special state if it is a key frame */
3401   if (cm->frame_type == KEY_FRAME) {
3402     int i;
3403
3404     // Set the loop filter deltas and segmentation map update
3405     setup_features(cpi);
3406
3407     /* The alternate reference frame cannot be active for a key frame */
3408     cpi->source_alt_ref_active = 0;
3409
3410     /* Reset the RD threshold multipliers to default of * 1 (128) */
3411     for (i = 0; i < MAX_MODES; ++i) {
3412       cpi->mb.rd_thresh_mult[i] = 128;
3413     }
3414
3415     // Reset the zero_last counter to 0 on key frame.
3416     memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
3417     memset(cpi->consec_zero_last_mvbias, 0,
3418            (cpi->common.mb_rows * cpi->common.mb_cols));
3419   }
3420
3421 #if 0
3422     /* Experimental code for lagged compress and one pass
3423      * Initialise one_pass GF frames stats
3424      * Update stats used for GF selection
3425      */
3426     {
3427         cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
3428
3429         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
3430         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
3431         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
3432         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
3433         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
3434         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
3435         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
3436         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
3437         cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
3438     }
3439 #endif
3440
3441   update_rd_ref_frame_probs(cpi);
3442
3443   if (cpi->drop_frames_allowed) {
3444     /* The reset to decimation 0 is only done here for one pass.
3445      * Once it is set two pass leaves decimation on till the next kf.
3446      */
3447     if ((cpi->buffer_level > drop_mark) && (cpi->decimation_factor > 0)) {
3448       cpi->decimation_factor--;
3449     }
3450
3451     if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0) {
3452       cpi->decimation_factor = 1;
3453
3454     } else if (cpi->buffer_level < drop_mark25 &&
3455                (cpi->decimation_factor == 2 || cpi->decimation_factor == 3)) {
3456       cpi->decimation_factor = 3;
3457     } else if (cpi->buffer_level < drop_mark50 &&
3458                (cpi->decimation_factor == 1 || cpi->decimation_factor == 2)) {
3459       cpi->decimation_factor = 2;
3460     } else if (cpi->buffer_level < drop_mark75 &&
3461                (cpi->decimation_factor == 0 || cpi->decimation_factor == 1)) {
3462       cpi->decimation_factor = 1;
3463     }
3464   }
3465
3466   /* The following decimates the frame rate according to a regular
3467    * pattern (i.e. to 1/2 or 2/3 frame rate) This can be used to help
3468    * prevent buffer under-run in CBR mode. Alternatively it might be
3469    * desirable in some situations to drop frame rate but throw more bits
3470    * at each frame.
3471    *
3472    * Note that dropping a key frame can be problematic if spatial
3473    * resampling is also active
3474    */
3475   if (cpi->decimation_factor > 0) {
3476     switch (cpi->decimation_factor) {
3477       case 1:
3478         cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2;
3479         break;
3480       case 2:
3481         cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3482         break;
3483       case 3:
3484         cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3485         break;
3486     }
3487
3488     /* Note that we should not throw out a key frame (especially when
3489      * spatial resampling is enabled).
3490      */
3491     if (cm->frame_type == KEY_FRAME) {
3492       cpi->decimation_count = cpi->decimation_factor;
3493     } else if (cpi->decimation_count > 0) {
3494       cpi->decimation_count--;
3495
3496       cpi->bits_off_target += cpi->av_per_frame_bandwidth;
3497       if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
3498         cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
3499       }
3500
3501 #if CONFIG_MULTI_RES_ENCODING
3502       vp8_store_drop_frame_info(cpi);
3503 #endif
3504
3505       cm->current_video_frame++;
3506       cpi->frames_since_key++;
3507       // We advance the temporal pattern for dropped frames.
3508       cpi->temporal_pattern_counter++;
3509
3510 #if CONFIG_INTERNAL_STATS
3511       cpi->count++;
3512 #endif
3513
3514       cpi->buffer_level = cpi->bits_off_target;
3515
3516       if (cpi->oxcf.number_of_layers > 1) {
3517         unsigned int i;
3518
3519         /* Propagate bits saved by dropping the frame to higher
3520          * layers
3521          */
3522         for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
3523           LAYER_CONTEXT *lc = &cpi->layer_context[i];
3524           lc->bits_off_target += (int)(lc->target_bandwidth / lc->framerate);
3525           if (lc->bits_off_target > lc->maximum_buffer_size) {
3526             lc->bits_off_target = lc->maximum_buffer_size;
3527           }
3528           lc->buffer_level = lc->bits_off_target;
3529         }
3530       }
3531
3532       return;
3533     } else {
3534       cpi->decimation_count = cpi->decimation_factor;
3535     }
3536   } else {
3537     cpi->decimation_count = 0;
3538   }
3539
3540   /* Decide how big to make the frame */
3541   if (!vp8_pick_frame_size(cpi)) {
3542 /*TODO: 2 drop_frame and return code could be put together. */
3543 #if CONFIG_MULTI_RES_ENCODING
3544     vp8_store_drop_frame_info(cpi);
3545 #endif
3546     cm->current_video_frame++;
3547     cpi->frames_since_key++;
3548     // We advance the temporal pattern for dropped frames.
3549     cpi->temporal_pattern_counter++;
3550     return;
3551   }
3552
3553   /* Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
3554    * This has a knock on effect on active best quality as well.
3555    * For CBR if the buffer reaches its maximum level then we can no longer
3556    * save up bits for later frames so we might as well use them up
3557    * on the current frame.
3558    */
3559   if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
3560       (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) &&
3561       cpi->buffered_mode) {
3562     /* Max adjustment is 1/4 */
3563     int Adjustment = cpi->active_worst_quality / 4;
3564
3565     if (Adjustment) {
3566       int buff_lvl_step;
3567
3568       if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size) {
3569         buff_lvl_step = (int)((cpi->oxcf.maximum_buffer_size -
3570                                cpi->oxcf.optimal_buffer_level) /
3571                               Adjustment);
3572
3573         if (buff_lvl_step) {
3574           Adjustment =
3575               (int)((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) /
3576                     buff_lvl_step);
3577         } else {
3578           Adjustment = 0;
3579         }
3580       }
3581
3582       cpi->active_worst_quality -= Adjustment;
3583
3584       if (cpi->active_worst_quality < cpi->active_best_quality) {
3585         cpi->active_worst_quality = cpi->active_best_quality;
3586       }
3587     }
3588   }
3589
3590   /* Set an active best quality and if necessary active worst quality
3591    * There is some odd behavior for one pass here that needs attention.
3592    */
3593   if ((cpi->pass == 2) || (cpi->ni_frames > 150)) {
3594     vp8_clear_system_state();
3595
3596     Q = cpi->active_worst_quality;
3597
3598     if (cm->frame_type == KEY_FRAME) {
3599       if (cpi->pass == 2) {
3600         if (cpi->gfu_boost > 600) {
3601           cpi->active_best_quality = kf_low_motion_minq[Q];
3602         } else {
3603           cpi->active_best_quality = kf_high_motion_minq[Q];
3604         }
3605
3606         /* Special case for key frames forced because we have reached
3607          * the maximum key frame interval. Here force the Q to a range
3608          * based on the ambient Q to reduce the risk of popping
3609          */
3610         if (cpi->this_key_frame_forced) {
3611           if (cpi->active_best_quality > cpi->avg_frame_qindex * 7 / 8) {
3612             cpi->active_best_quality = cpi->avg_frame_qindex * 7 / 8;
3613           } else if (cpi->active_best_quality<cpi->avg_frame_qindex>> 2) {
3614             cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
3615           }
3616         }
3617       }
3618       /* One pass more conservative */
3619       else {
3620         cpi->active_best_quality = kf_high_motion_minq[Q];
3621       }
3622     }
3623
3624     else if (cpi->oxcf.number_of_layers == 1 &&
3625              (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame)) {
3626       /* Use the lower of cpi->active_worst_quality and recent
3627        * average Q as basis for GF/ARF Q limit unless last frame was
3628        * a key frame.
3629        */
3630       if ((cpi->frames_since_key > 1) &&
3631           (cpi->avg_frame_qindex < cpi->active_worst_quality)) {
3632         Q = cpi->avg_frame_qindex;
3633       }
3634
3635       /* For constrained quality dont allow Q less than the cq level */
3636       if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3637           (Q < cpi->cq_target_quality)) {
3638         Q = cpi->cq_target_quality;
3639       }
3640
3641       if (cpi->pass == 2) {
3642         if (cpi->gfu_boost > 1000) {
3643           cpi->active_best_quality = gf_low_motion_minq[Q];
3644         } else if (cpi->gfu_boost < 400) {
3645           cpi->active_best_quality = gf_high_motion_minq[Q];
3646         } else {
3647           cpi->active_best_quality = gf_mid_motion_minq[Q];
3648         }
3649
3650         /* Constrained quality use slightly lower active best. */
3651         if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
3652           cpi->active_best_quality = cpi->active_best_quality * 15 / 16;
3653         }
3654       }
3655       /* One pass more conservative */
3656       else {
3657         cpi->active_best_quality = gf_high_motion_minq[Q];
3658       }
3659     } else {
3660       cpi->active_best_quality = inter_minq[Q];
3661
3662       /* For the constant/constrained quality mode we dont want
3663        * q to fall below the cq level.
3664        */
3665       if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3666           (cpi->active_best_quality < cpi->cq_target_quality)) {
3667         /* If we are strongly undershooting the target rate in the last
3668          * frames then use the user passed in cq value not the auto
3669          * cq value.
3670          */
3671         if (cpi->rolling_actual_bits < cpi->min_frame_bandwidth) {
3672           cpi->active_best_quality = cpi->oxcf.cq_level;
3673         } else {
3674           cpi->active_best_quality = cpi->cq_target_quality;
3675         }
3676       }
3677     }
3678
3679     /* If CBR and the buffer is as full then it is reasonable to allow
3680      * higher quality on the frames to prevent bits just going to waste.
3681      */
3682     if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
3683       /* Note that the use of >= here elliminates the risk of a devide
3684        * by 0 error in the else if clause
3685        */
3686       if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size) {
3687         cpi->active_best_quality = cpi->best_quality;
3688
3689       } else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level) {
3690         int Fraction =
3691             (int)(((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) /
3692                   (cpi->oxcf.maximum_buffer_size -
3693                    cpi->oxcf.optimal_buffer_level));
3694         int min_qadjustment =
3695             ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
3696
3697         cpi->active_best_quality -= min_qadjustment;
3698       }
3699     }
3700   }
3701   /* Make sure constrained quality mode limits are adhered to for the first
3702    * few frames of one pass encodes
3703    */
3704   else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
3705     if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
3706         cpi->common.refresh_alt_ref_frame) {
3707       cpi->active_best_quality = cpi->best_quality;
3708     } else if (cpi->active_best_quality < cpi->cq_target_quality) {
3709       cpi->active_best_quality = cpi->cq_target_quality;
3710     }
3711   }
3712
3713   /* Clip the active best and worst quality values to limits */
3714   if (cpi->active_worst_quality > cpi->worst_quality) {
3715     cpi->active_worst_quality = cpi->worst_quality;
3716   }
3717
3718   if (cpi->active_best_quality < cpi->best_quality) {
3719     cpi->active_best_quality = cpi->best_quality;
3720   }
3721
3722   if (cpi->active_worst_quality < cpi->active_best_quality) {
3723     cpi->active_worst_quality = cpi->active_best_quality;
3724   }
3725
3726   /* Determine initial Q to try */
3727   Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3728
3729 #if !CONFIG_REALTIME_ONLY
3730
3731   /* Set highest allowed value for Zbin over quant */
3732   if (cm->frame_type == KEY_FRAME) {
3733     zbin_oq_high = 0;
3734   } else if ((cpi->oxcf.number_of_layers == 1) &&
3735              ((cm->refresh_alt_ref_frame ||
3736                (cm->refresh_golden_frame && !cpi->source_alt_ref_active)))) {
3737     zbin_oq_high = 16;
3738   } else {
3739     zbin_oq_high = ZBIN_OQ_MAX;
3740   }
3741 #endif
3742
3743   /* Setup background Q adjustment for error resilient mode.
3744    * For multi-layer encodes only enable this for the base layer.
3745   */
3746   if (cpi->cyclic_refresh_mode_enabled) {
3747     // Special case for screen_content_mode with golden frame updates.
3748     int disable_cr_gf =
3749         (cpi->oxcf.screen_content_mode == 2 && cm->refresh_golden_frame);
3750     if (cpi->current_layer == 0 && cpi->force_maxqp == 0 && !disable_cr_gf) {
3751       cyclic_background_refresh(cpi, Q, 0);
3752     } else {
3753       disable_segmentation(cpi);
3754     }
3755   }
3756
3757   vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
3758                                 &frame_over_shoot_limit);
3759
3760 #if !CONFIG_REALTIME_ONLY
3761   /* Limit Q range for the adaptive loop. */
3762   bottom_index = cpi->active_best_quality;
3763   top_index = cpi->active_worst_quality;
3764   q_low = cpi->active_best_quality;
3765   q_high = cpi->active_worst_quality;
3766 #endif
3767
3768   vp8_save_coding_context(cpi);
3769
3770   loop_count = 0;
3771
3772   scale_and_extend_source(cpi->un_scaled_source, cpi);
3773
3774 #if CONFIG_TEMPORAL_DENOISING && CONFIG_POSTPROC
3775   // Option to apply spatial blur under the aggressive or adaptive
3776   // (temporal denoising) mode.
3777   if (cpi->oxcf.noise_sensitivity >= 3) {
3778     if (cpi->denoiser.denoise_pars.spatial_blur != 0) {
3779       vp8_de_noise(cm, cpi->Source, cpi->Source,
3780                    cpi->denoiser.denoise_pars.spatial_blur, 1, 0, 0);
3781     }
3782   }
3783 #endif
3784
3785 #if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC && !(CONFIG_TEMPORAL_DENOISING)
3786
3787   if (cpi->oxcf.noise_sensitivity > 0) {
3788     unsigned char *src;
3789     int l = 0;
3790
3791     switch (cpi->oxcf.noise_sensitivity) {
3792       case 1: l = 20; break;
3793       case 2: l = 40; break;
3794       case 3: l = 60; break;
3795       case 4: l = 80; break;
3796       case 5: l = 100; break;
3797       case 6: l = 150; break;
3798     }
3799
3800     if (cm->frame_type == KEY_FRAME) {
3801       vp8_de_noise(cm, cpi->Source, cpi->Source, l, 1, 0, 1);
3802     } else {
3803       vp8_de_noise(cm, cpi->Source, cpi->Source, l, 1, 0, 1);
3804
3805       src = cpi->Source->y_buffer;
3806
3807       if (cpi->Source->y_stride < 0) {
3808         src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
3809       }
3810     }
3811   }
3812
3813 #endif
3814
3815 #ifdef OUTPUT_YUV_SRC
3816   vp8_write_yuv_frame(yuv_file, cpi->Source);
3817 #endif
3818
3819   do {
3820     vp8_clear_system_state();
3821
3822     vp8_set_quantizer(cpi, Q);
3823
3824     /* setup skip prob for costing in mode/mv decision */
3825     if (cpi->common.mb_no_coeff_skip) {
3826       cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
3827
3828       if (cm->frame_type != KEY_FRAME) {
3829         if (cpi->common.refresh_alt_ref_frame) {
3830           if (cpi->last_skip_false_probs[2] != 0) {
3831             cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3832           }
3833
3834           /*
3835                               if(cpi->last_skip_false_probs[2]!=0 && abs(Q-
3836              cpi->last_skip_probs_q[2])<=16 )
3837              cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3838                               else if (cpi->last_skip_false_probs[2]!=0)
3839              cpi->prob_skip_false = (cpi->last_skip_false_probs[2]  +
3840              cpi->prob_skip_false ) / 2;
3841              */
3842         } else if (cpi->common.refresh_golden_frame) {
3843           if (cpi->last_skip_false_probs[1] != 0) {
3844             cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3845           }
3846
3847           /*
3848                               if(cpi->last_skip_false_probs[1]!=0 && abs(Q-
3849              cpi->last_skip_probs_q[1])<=16 )
3850              cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3851                               else if (cpi->last_skip_false_probs[1]!=0)
3852              cpi->prob_skip_false = (cpi->last_skip_false_probs[1]  +
3853              cpi->prob_skip_false ) / 2;
3854              */
3855         } else {
3856           if (cpi->last_skip_false_probs[0] != 0) {
3857             cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3858           }
3859
3860           /*
3861           if(cpi->last_skip_false_probs[0]!=0 && abs(Q-
3862           cpi->last_skip_probs_q[0])<=16 )
3863               cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3864           else if(cpi->last_skip_false_probs[0]!=0)
3865               cpi->prob_skip_false = (cpi->last_skip_false_probs[0]  +
3866           cpi->prob_skip_false ) / 2;
3867               */
3868         }
3869
3870         /* as this is for cost estimate, let's make sure it does not
3871          * go extreme eitehr way
3872          */
3873         if (cpi->prob_skip_false < 5) cpi->prob_skip_false = 5;
3874
3875         if (cpi->prob_skip_false > 250) cpi->prob_skip_false = 250;
3876
3877         if (cpi->oxcf.number_of_layers == 1 && cpi->is_src_frame_alt_ref) {
3878           cpi->prob_skip_false = 1;
3879         }
3880       }
3881
3882 #if 0
3883
3884             if (cpi->pass != 1)
3885             {
3886                 FILE *f = fopen("skip.stt", "a");
3887                 fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
3888                 fclose(f);
3889             }
3890
3891 #endif
3892     }
3893
3894     if (cm->frame_type == KEY_FRAME) {
3895       if (resize_key_frame(cpi)) {
3896         /* If the frame size has changed, need to reset Q, quantizer,
3897          * and background refresh.
3898          */
3899         Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3900         if (cpi->cyclic_refresh_mode_enabled) {
3901           if (cpi->current_layer == 0) {
3902             cyclic_background_refresh(cpi, Q, 0);
3903           } else {
3904             disable_segmentation(cpi);
3905           }
3906         }
3907         // Reset the zero_last counter to 0 on key frame.
3908         memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
3909         memset(cpi->consec_zero_last_mvbias, 0,
3910                (cpi->common.mb_rows * cpi->common.mb_cols));
3911         vp8_set_quantizer(cpi, Q);
3912       }
3913
3914       vp8_setup_key_frame(cpi);
3915     }
3916
3917 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
3918     {
3919       if (cpi->oxcf.error_resilient_mode) cm->refresh_entropy_probs = 0;
3920
3921       if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
3922         if (cm->frame_type == KEY_FRAME) cm->refresh_entropy_probs = 1;
3923       }
3924
3925       if (cm->refresh_entropy_probs == 0) {
3926         /* save a copy for later refresh */
3927         memcpy(&cm->lfc, &cm->fc, sizeof(cm->fc));
3928       }
3929
3930       vp8_update_coef_context(cpi);
3931
3932       vp8_update_coef_probs(cpi);
3933
3934       /* transform / motion compensation build reconstruction frame
3935        * +pack coef partitions
3936        */
3937       vp8_encode_frame(cpi);
3938
3939       /* cpi->projected_frame_size is not needed for RT mode */
3940     }
3941 #else
3942     /* transform / motion compensation build reconstruction frame */
3943     vp8_encode_frame(cpi);
3944
3945     if (cpi->oxcf.screen_content_mode == 2) {
3946       if (vp8_drop_encodedframe_overshoot(cpi, Q)) return;
3947     }
3948
3949     cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
3950     cpi->projected_frame_size =
3951         (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
3952 #endif
3953     vp8_clear_system_state();
3954
3955     /* Test to see if the stats generated for this frame indicate that
3956      * we should have coded a key frame (assuming that we didn't)!
3957      */
3958
3959     if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME &&
3960         cpi->compressor_speed != 2) {
3961 #if !CONFIG_REALTIME_ONLY
3962       if (decide_key_frame(cpi)) {
3963         /* Reset all our sizing numbers and recode */
3964         cm->frame_type = KEY_FRAME;
3965
3966         vp8_pick_frame_size(cpi);
3967
3968         /* Clear the Alt reference frame active flag when we have
3969          * a key frame
3970          */
3971         cpi->source_alt_ref_active = 0;
3972
3973         // Set the loop filter deltas and segmentation map update
3974         setup_features(cpi);
3975
3976         vp8_restore_coding_context(cpi);
3977
3978         Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3979
3980         vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
3981                                       &frame_over_shoot_limit);
3982
3983         /* Limit Q range for the adaptive loop. */
3984         bottom_index = cpi->active_best_quality;
3985         top_index = cpi->active_worst_quality;
3986         q_low = cpi->active_best_quality;
3987         q_high = cpi->active_worst_quality;
3988
3989         loop_count++;
3990         Loop = 1;
3991
3992         continue;
3993       }
3994 #endif
3995     }
3996
3997     vp8_clear_system_state();
3998
3999     if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
4000
4001     /* Are we are overshooting and up against the limit of active max Q. */
4002     if (((cpi->pass != 2) ||
4003          (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
4004         (Q == cpi->active_worst_quality) &&
4005         (cpi->active_worst_quality < cpi->worst_quality) &&
4006         (cpi->projected_frame_size > frame_over_shoot_limit)) {
4007       int over_size_percent =
4008           ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) /
4009           frame_over_shoot_limit;
4010
4011       /* If so is there any scope for relaxing it */
4012       while ((cpi->active_worst_quality < cpi->worst_quality) &&
4013              (over_size_percent > 0)) {
4014         cpi->active_worst_quality++;
4015         /* Assume 1 qstep = about 4% on frame size. */
4016         over_size_percent = (int)(over_size_percent * 0.96);
4017       }
4018 #if !CONFIG_REALTIME_ONLY
4019       top_index = cpi->active_worst_quality;
4020 #endif  // !CONFIG_REALTIME_ONLY
4021         /* If we have updated the active max Q do not call
4022          * vp8_update_rate_correction_factors() this loop.
4023          */
4024       active_worst_qchanged = 1;
4025     } else {
4026       active_worst_qchanged = 0;
4027     }
4028
4029 #if CONFIG_REALTIME_ONLY
4030     Loop = 0;
4031 #else
4032     /* Special case handling for forced key frames */
4033     if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
4034       int last_q = Q;
4035       int kf_err = vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
4036
4037       /* The key frame is not good enough */
4038       if (kf_err > ((cpi->ambient_err * 7) >> 3)) {
4039         /* Lower q_high */
4040         q_high = (Q > q_low) ? (Q - 1) : q_low;
4041
4042         /* Adjust Q */
4043         Q = (q_high + q_low) >> 1;
4044       }
4045       /* The key frame is much better than the previous frame */
4046       else if (kf_err < (cpi->ambient_err >> 1)) {
4047         /* Raise q_low */
4048         q_low = (Q < q_high) ? (Q + 1) : q_high;
4049
4050         /* Adjust Q */
4051         Q = (q_high + q_low + 1) >> 1;
4052       }
4053
4054       /* Clamp Q to upper and lower limits: */
4055       if (Q > q_high) {
4056         Q = q_high;
4057       } else if (Q < q_low) {
4058         Q = q_low;
4059       }
4060
4061       Loop = Q != last_q;
4062     }
4063
4064     /* Is the projected frame size out of range and are we allowed
4065      * to attempt to recode.
4066      */
4067     else if (recode_loop_test(cpi, frame_over_shoot_limit,
4068                               frame_under_shoot_limit, Q, top_index,
4069                               bottom_index)) {
4070       int last_q = Q;
4071       int Retries = 0;
4072
4073       /* Frame size out of permitted range. Update correction factor
4074        * & compute new Q to try...
4075        */
4076
4077       /* Frame is too large */
4078       if (cpi->projected_frame_size > cpi->this_frame_target) {
4079         /* Raise Qlow as to at least the current value */
4080         q_low = (Q < q_high) ? (Q + 1) : q_high;
4081
4082         /* If we are using over quant do the same for zbin_oq_low */
4083         if (cpi->mb.zbin_over_quant > 0) {
4084           zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
4085                             ? (cpi->mb.zbin_over_quant + 1)
4086                             : zbin_oq_high;
4087         }
4088
4089         if (undershoot_seen) {
4090           /* Update rate_correction_factor unless
4091            * cpi->active_worst_quality has changed.
4092            */
4093           if (!active_worst_qchanged) {
4094             vp8_update_rate_correction_factors(cpi, 1);
4095           }
4096
4097           Q = (q_high + q_low + 1) / 2;
4098
4099           /* Adjust cpi->zbin_over_quant (only allowed when Q
4100            * is max)
4101            */
4102           if (Q < MAXQ) {
4103             cpi->mb.zbin_over_quant = 0;
4104           } else {
4105             zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
4106                               ? (cpi->mb.zbin_over_quant + 1)
4107                               : zbin_oq_high;
4108             cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
4109           }
4110         } else {
4111           /* Update rate_correction_factor unless
4112            * cpi->active_worst_quality has changed.
4113            */
4114           if (!active_worst_qchanged) {
4115             vp8_update_rate_correction_factors(cpi, 0);
4116           }
4117
4118           Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4119
4120           while (((Q < q_low) || (cpi->mb.zbin_over_quant < zbin_oq_low)) &&
4121                  (Retries < 10)) {
4122             vp8_update_rate_correction_factors(cpi, 0);
4123             Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4124             Retries++;
4125           }
4126         }
4127
4128         overshoot_seen = 1;
4129       }
4130       /* Frame is too small */
4131       else {
4132         if (cpi->mb.zbin_over_quant == 0) {
4133           /* Lower q_high if not using over quant */
4134           q_high = (Q > q_low) ? (Q - 1) : q_low;
4135         } else {
4136           /* else lower zbin_oq_high */
4137           zbin_oq_high = (cpi->mb.zbin_over_quant > zbin_oq_low)
4138                              ? (cpi->mb.zbin_over_quant - 1)
4139                              : zbin_oq_low;
4140         }
4141
4142         if (overshoot_seen) {
4143           /* Update rate_correction_factor unless
4144            * cpi->active_worst_quality has changed.
4145            */
4146           if (!active_worst_qchanged) {
4147             vp8_update_rate_correction_factors(cpi, 1);
4148           }
4149
4150           Q = (q_high + q_low) / 2;
4151
4152           /* Adjust cpi->zbin_over_quant (only allowed when Q
4153            * is max)
4154            */
4155           if (Q < MAXQ) {
4156             cpi->mb.zbin_over_quant = 0;
4157           } else {
4158             cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
4159           }
4160         } else {
4161           /* Update rate_correction_factor unless
4162            * cpi->active_worst_quality has changed.
4163            */
4164           if (!active_worst_qchanged) {
4165             vp8_update_rate_correction_factors(cpi, 0);
4166           }
4167
4168           Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4169
4170           /* Special case reset for qlow for constrained quality.
4171            * This should only trigger where there is very substantial
4172            * undershoot on a frame and the auto cq level is above
4173            * the user passsed in value.
4174            */
4175           if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
4176               (Q < q_low)) {
4177             q_low = Q;
4178           }
4179
4180           while (((Q > q_high) || (cpi->mb.zbin_over_quant > zbin_oq_high)) &&
4181                  (Retries < 10)) {
4182             vp8_update_rate_correction_factors(cpi, 0);
4183             Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4184             Retries++;
4185           }
4186         }
4187
4188         undershoot_seen = 1;
4189       }
4190
4191       /* Clamp Q to upper and lower limits: */
4192       if (Q > q_high) {
4193         Q = q_high;
4194       } else if (Q < q_low) {
4195         Q = q_low;
4196       }
4197
4198       /* Clamp cpi->zbin_over_quant */
4199       cpi->mb.zbin_over_quant = (cpi->mb.zbin_over_quant < zbin_oq_low)
4200                                     ? zbin_oq_low
4201                                     : (cpi->mb.zbin_over_quant > zbin_oq_high)
4202                                           ? zbin_oq_high
4203                                           : cpi->mb.zbin_over_quant;
4204
4205       Loop = Q != last_q;
4206     } else {
4207       Loop = 0;
4208     }
4209 #endif  // CONFIG_REALTIME_ONLY
4210
4211     if (cpi->is_src_frame_alt_ref) Loop = 0;
4212
4213     if (Loop == 1) {
4214       vp8_restore_coding_context(cpi);
4215       loop_count++;
4216 #if CONFIG_INTERNAL_STATS
4217       cpi->tot_recode_hits++;
4218 #endif
4219     }
4220   } while (Loop == 1);
4221
4222 #if 0
4223     /* Experimental code for lagged and one pass
4224      * Update stats used for one pass GF selection
4225      */
4226     {
4227         cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
4228         cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
4229         cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
4230     }
4231 #endif
4232
4233   /* Special case code to reduce pulsing when key frames are forced at a
4234    * fixed interval. Note the reconstruction error if it is the frame before
4235    * the force key frame
4236    */
4237   if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
4238     cpi->ambient_err =
4239         vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
4240   }
4241
4242 /* This frame's MVs are saved and will be used in next frame's MV predictor.
4243  * Last frame has one more line(add to bottom) and one more column(add to
4244  * right) than cm->mip. The edge elements are initialized to 0.
4245  */
4246 #if CONFIG_MULTI_RES_ENCODING
4247   if (!cpi->oxcf.mr_encoder_id && cm->show_frame)
4248 #else
4249   if (cm->show_frame) /* do not save for altref frame */
4250 #endif
4251   {
4252     int mb_row;
4253     int mb_col;
4254     /* Point to beginning of allocated MODE_INFO arrays. */
4255     MODE_INFO *tmp = cm->mip;
4256
4257     if (cm->frame_type != KEY_FRAME) {
4258       for (mb_row = 0; mb_row < cm->mb_rows + 1; ++mb_row) {
4259         for (mb_col = 0; mb_col < cm->mb_cols + 1; ++mb_col) {
4260           if (tmp->mbmi.ref_frame != INTRA_FRAME) {
4261             cpi->lfmv[mb_col + mb_row * (cm->mode_info_stride + 1)].as_int =
4262                 tmp->mbmi.mv.as_int;
4263           }
4264
4265           cpi->lf_ref_frame_sign_bias[mb_col +
4266                                       mb_row * (cm->mode_info_stride + 1)] =
4267               cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
4268           cpi->lf_ref_frame[mb_col + mb_row * (cm->mode_info_stride + 1)] =
4269               tmp->mbmi.ref_frame;
4270           tmp++;
4271         }
4272       }
4273     }
4274   }
4275
4276   /* Count last ref frame 0,0 usage on current encoded frame. */
4277   {
4278     int mb_row;
4279     int mb_col;
4280     /* Point to beginning of MODE_INFO arrays. */
4281     MODE_INFO *tmp = cm->mi;
4282
4283     cpi->zeromv_count = 0;
4284
4285     if (cm->frame_type != KEY_FRAME) {
4286       for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
4287         for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
4288           if (tmp->mbmi.mode == ZEROMV && tmp->mbmi.ref_frame == LAST_FRAME) {
4289             cpi->zeromv_count++;
4290           }
4291           tmp++;
4292         }
4293         tmp++;
4294       }
4295     }
4296   }
4297
4298 #if CONFIG_MULTI_RES_ENCODING
4299   vp8_cal_dissimilarity(cpi);
4300 #endif
4301
4302   /* Update the GF useage maps.
4303    * This is done after completing the compression of a frame when all
4304    * modes etc. are finalized but before loop filter
4305    */
4306   if (cpi->oxcf.number_of_layers == 1) {
4307     vp8_update_gf_useage_maps(cpi, cm, &cpi->mb);
4308   }
4309
4310   if (cm->frame_type == KEY_FRAME) cm->refresh_last_frame = 1;
4311
4312 #if 0
4313     {
4314         FILE *f = fopen("gfactive.stt", "a");
4315         fprintf(f, "%8d %8d %8d %8d %8d\n", cm->current_video_frame, (100 * cpi->gf_active_count) / (cpi->common.mb_rows * cpi->common.mb_cols), cpi->this_iiratio, cpi->next_iiratio, cm->refresh_golden_frame);
4316         fclose(f);
4317     }
4318 #endif
4319
4320   /* For inter frames the current default behavior is that when
4321    * cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
4322    * This is purely an encoder decision at present.
4323    */
4324   if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame) {
4325     cm->copy_buffer_to_arf = 2;
4326   } else {
4327     cm->copy_buffer_to_arf = 0;
4328   }
4329
4330   cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
4331
4332 #if CONFIG_TEMPORAL_DENOISING
4333   // Get some measure of the amount of noise, by measuring the (partial) mse
4334   // between source and denoised buffer, for y channel. Partial refers to
4335   // computing the sse for a sub-sample of the frame (i.e., skip x blocks along
4336   // row/column),
4337   // and only for blocks in that set that are consecutive ZEROMV_LAST mode.
4338   // Do this every ~8 frames, to further reduce complexity.
4339   // TODO(marpan): Keep this for now for the case cpi->oxcf.noise_sensitivity <
4340   // 4,
4341   // should be removed in favor of the process_denoiser_mode_change() function
4342   // below.
4343   if (cpi->oxcf.noise_sensitivity > 0 && cpi->oxcf.noise_sensitivity < 4 &&
4344       !cpi->oxcf.screen_content_mode && cpi->frames_since_key % 8 == 0 &&
4345       cm->frame_type != KEY_FRAME) {
4346     cpi->mse_source_denoised = measure_square_diff_partial(
4347         &cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi->Source, cpi);
4348   }
4349
4350   // For the adaptive denoising mode (noise_sensitivity == 4), sample the mse
4351   // of source diff (between current and previous frame), and determine if we
4352   // should switch the denoiser mode. Sampling refers to computing the mse for
4353   // a sub-sample of the frame (i.e., skip x blocks along row/column), and
4354   // only for blocks in that set that have used ZEROMV LAST, along with some
4355   // constraint on the sum diff between blocks. This process is called every
4356   // ~8 frames, to further reduce complexity.
4357   if (cpi->oxcf.noise_sensitivity == 4 && !cpi->oxcf.screen_content_mode &&
4358       cpi->frames_since_key % 8 == 0 && cm->frame_type != KEY_FRAME) {
4359     process_denoiser_mode_change(cpi);
4360   }
4361 #endif
4362
4363 #if CONFIG_MULTITHREAD
4364   if (cpi->b_multi_threaded) {
4365     /* start loopfilter in separate thread */
4366     sem_post(&cpi->h_event_start_lpf);
4367   } else
4368 #endif
4369   {
4370     vp8_loopfilter_frame(cpi, cm);
4371   }
4372
4373   update_reference_frames(cpi);
4374
4375 #ifdef OUTPUT_YUV_DENOISED
4376   vp8_write_yuv_frame(yuv_denoised_file,
4377                       &cpi->denoiser.yv12_running_avg[INTRA_FRAME]);
4378 #endif
4379
4380 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
4381   if (cpi->oxcf.error_resilient_mode) {
4382     cm->refresh_entropy_probs = 0;
4383   }
4384 #endif
4385
4386 #if CONFIG_MULTITHREAD
4387   /* wait that filter_level is picked so that we can continue with stream
4388    * packing */
4389   if (cpi->b_multi_threaded) sem_wait(&cpi->h_event_end_lpf);
4390 #endif
4391
4392   /* build the bitstream */
4393   vp8_pack_bitstream(cpi, dest, dest_end, size);
4394
4395 #if CONFIG_MULTITHREAD
4396   /* wait for the lpf thread done */
4397   if (cpi->b_multi_threaded) {
4398     sem_wait(&cpi->h_event_end_lpf);
4399   }
4400 #endif
4401
4402   /* Move storing frame_type out of the above loop since it is also
4403    * needed in motion search besides loopfilter */
4404   cm->last_frame_type = cm->frame_type;
4405
4406   /* Update rate control heuristics */
4407   cpi->total_byte_count += (*size);
4408   cpi->projected_frame_size = (*size) << 3;
4409
4410   if (cpi->oxcf.number_of_layers > 1) {
4411     unsigned int i;
4412     for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
4413       cpi->layer_context[i].total_byte_count += (*size);
4414     }
4415   }
4416
4417   if (!active_worst_qchanged) vp8_update_rate_correction_factors(cpi, 2);
4418
4419   cpi->last_q[cm->frame_type] = cm->base_qindex;
4420
4421   if (cm->frame_type == KEY_FRAME) {
4422     vp8_adjust_key_frame_context(cpi);
4423   }
4424
4425   /* Keep a record of ambient average Q. */
4426   if (cm->frame_type != KEY_FRAME) {
4427     cpi->avg_frame_qindex =
4428         (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
4429   }
4430
4431   /* Keep a record from which we can calculate the average Q excluding
4432    * GF updates and key frames
4433    */
4434   if ((cm->frame_type != KEY_FRAME) &&
4435       ((cpi->oxcf.number_of_layers > 1) ||
4436        (!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame))) {
4437     cpi->ni_frames++;
4438
4439     /* Calculate the average Q for normal inter frames (not key or GFU
4440      * frames).
4441      */
4442     if (cpi->pass == 2) {
4443       cpi->ni_tot_qi += Q;
4444       cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4445     } else {
4446       /* Damp value for first few frames */
4447       if (cpi->ni_frames > 150) {
4448         cpi->ni_tot_qi += Q;
4449         cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4450       }
4451       /* For one pass, early in the clip ... average the current frame Q
4452        * value with the worstq entered by the user as a dampening measure
4453        */
4454       else {
4455         cpi->ni_tot_qi += Q;
4456         cpi->ni_av_qi =
4457             ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
4458       }
4459
4460       /* If the average Q is higher than what was used in the last
4461        * frame (after going through the recode loop to keep the frame
4462        * size within range) then use the last frame value - 1. The -1
4463        * is designed to stop Q and hence the data rate, from
4464        * progressively falling away during difficult sections, but at
4465        * the same time reduce the number of itterations around the
4466        * recode loop.
4467        */
4468       if (Q > cpi->ni_av_qi) cpi->ni_av_qi = Q - 1;
4469     }
4470   }
4471
4472   /* Update the buffer level variable. */
4473   /* Non-viewable frames are a special case and are treated as pure overhead. */
4474   if (!cm->show_frame) {
4475     cpi->bits_off_target -= cpi->projected_frame_size;
4476   } else {
4477     cpi->bits_off_target +=
4478         cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
4479   }
4480
4481   /* Clip the buffer level to the maximum specified buffer size */
4482   if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
4483     cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
4484   }
4485
4486   // If the frame dropper is not enabled, don't let the buffer level go below
4487   // some threshold, given here by -|maximum_buffer_size|. For now we only do
4488   // this for screen content input.
4489   if (cpi->drop_frames_allowed == 0 && cpi->oxcf.screen_content_mode &&
4490       cpi->bits_off_target < -cpi->oxcf.maximum_buffer_size) {
4491     cpi->bits_off_target = -cpi->oxcf.maximum_buffer_size;
4492   }
4493
4494   /* Rolling monitors of whether we are over or underspending used to
4495    * help regulate min and Max Q in two pass.
4496    */
4497   cpi->rolling_target_bits =
4498       ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
4499   cpi->rolling_actual_bits =
4500       ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
4501   cpi->long_rolling_target_bits =
4502       ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
4503   cpi->long_rolling_actual_bits =
4504       ((cpi->long_rolling_actual_bits * 31) + cpi->projected_frame_size + 16) /
4505       32;
4506
4507   /* Actual bits spent */
4508   cpi->total_actual_bits += cpi->projected_frame_size;
4509
4510   /* Debug stats */
4511   cpi->total_target_vs_actual +=
4512       (cpi->this_frame_target - cpi->projected_frame_size);
4513
4514   cpi->buffer_level = cpi->bits_off_target;
4515
4516   /* Propagate values to higher temporal layers */
4517   if (cpi->oxcf.number_of_layers > 1) {
4518     unsigned int i;
4519
4520     for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
4521       LAYER_CONTEXT *lc = &cpi->layer_context[i];
4522       int bits_off_for_this_layer = (int)(lc->target_bandwidth / lc->framerate -
4523                                           cpi->projected_frame_size);
4524
4525       lc->bits_off_target += bits_off_for_this_layer;
4526
4527       /* Clip buffer level to maximum buffer size for the layer */
4528       if (lc->bits_off_target > lc->maximum_buffer_size) {
4529         lc->bits_off_target = lc->maximum_buffer_size;
4530       }
4531
4532       lc->total_actual_bits += cpi->projected_frame_size;
4533       lc->total_target_vs_actual += bits_off_for_this_layer;
4534       lc->buffer_level = lc->bits_off_target;
4535     }
4536   }
4537
4538   /* Update bits left to the kf and gf groups to account for overshoot
4539    * or undershoot on these frames
4540    */
4541   if (cm->frame_type == KEY_FRAME) {
4542     cpi->twopass.kf_group_bits +=
4543         cpi->this_frame_target - cpi->projected_frame_size;
4544
4545     if (cpi->twopass.kf_group_bits < 0) cpi->twopass.kf_group_bits = 0;
4546   } else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame) {
4547     cpi->twopass.gf_group_bits +=
4548         cpi->this_frame_target - cpi->projected_frame_size;
4549
4550     if (cpi->twopass.gf_group_bits < 0) cpi->twopass.gf_group_bits = 0;
4551   }
4552
4553   if (cm->frame_type != KEY_FRAME) {
4554     if (cpi->common.refresh_alt_ref_frame) {
4555       cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
4556       cpi->last_skip_probs_q[2] = cm->base_qindex;
4557     } else if (cpi->common.refresh_golden_frame) {
4558       cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
4559       cpi->last_skip_probs_q[1] = cm->base_qindex;
4560     } else {
4561       cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
4562       cpi->last_skip_probs_q[0] = cm->base_qindex;
4563
4564       /* update the baseline */
4565       cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
4566     }
4567   }
4568
4569 #if 0 && CONFIG_INTERNAL_STATS
4570     {
4571         FILE *f = fopen("tmp.stt", "a");
4572
4573         vp8_clear_system_state();
4574
4575         if (cpi->twopass.total_left_stats.coded_error != 0.0)
4576             fprintf(f, "%10d %10d %10d %10d %10d %10"PRId64" %10"PRId64
4577                        "%10"PRId64" %10d %6d %6d %6d %6d %5d %5d %5d %8d "
4578                        "%8.2lf %"PRId64" %10.3lf %10"PRId64" %8d\n",
4579                        cpi->common.current_video_frame, cpi->this_frame_target,
4580                        cpi->projected_frame_size,
4581                        (cpi->projected_frame_size - cpi->this_frame_target),
4582                        cpi->total_target_vs_actual,
4583                        cpi->buffer_level,
4584                        (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4585                        cpi->total_actual_bits, cm->base_qindex,
4586                        cpi->active_best_quality, cpi->active_worst_quality,
4587                        cpi->ni_av_qi, cpi->cq_target_quality,
4588                        cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4589                        cm->frame_type, cpi->gfu_boost,
4590                        cpi->twopass.est_max_qcorrection_factor,
4591                        cpi->twopass.bits_left,
4592                        cpi->twopass.total_left_stats.coded_error,
4593                        (double)cpi->twopass.bits_left /
4594                            cpi->twopass.total_left_stats.coded_error,
4595                        cpi->tot_recode_hits);
4596         else
4597             fprintf(f, "%10d %10d %10d %10d %10d %10"PRId64" %10"PRId64
4598                        "%10"PRId64" %10d %6d %6d %6d %6d %5d %5d %5d %8d "
4599                        "%8.2lf %"PRId64" %10.3lf %8d\n",
4600                        cpi->common.current_video_frame, cpi->this_frame_target,
4601                        cpi->projected_frame_size,
4602                        (cpi->projected_frame_size - cpi->this_frame_target),
4603                        cpi->total_target_vs_actual,
4604                        cpi->buffer_level,
4605                        (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4606                        cpi->total_actual_bits, cm->base_qindex,
4607                        cpi->active_best_quality, cpi->active_worst_quality,
4608                        cpi->ni_av_qi, cpi->cq_target_quality,
4609                        cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4610                        cm->frame_type, cpi->gfu_boost,
4611                        cpi->twopass.est_max_qcorrection_factor,
4612                        cpi->twopass.bits_left,
4613                        cpi->twopass.total_left_stats.coded_error,
4614                        cpi->tot_recode_hits);
4615
4616         fclose(f);
4617
4618         {
4619             FILE *fmodes = fopen("Modes.stt", "a");
4620
4621             fprintf(fmodes, "%6d:%1d:%1d:%1d ",
4622                         cpi->common.current_video_frame,
4623                         cm->frame_type, cm->refresh_golden_frame,
4624                         cm->refresh_alt_ref_frame);
4625
4626             fprintf(fmodes, "\n");
4627
4628             fclose(fmodes);
4629         }
4630     }
4631
4632 #endif
4633
4634   if (cm->refresh_golden_frame == 1) {
4635     cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
4636   } else {
4637     cm->frame_flags = cm->frame_flags & ~FRAMEFLAGS_GOLDEN;
4638   }
4639
4640   if (cm->refresh_alt_ref_frame == 1) {
4641     cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
4642   } else {
4643     cm->frame_flags = cm->frame_flags & ~FRAMEFLAGS_ALTREF;
4644   }
4645
4646   if (cm->refresh_last_frame & cm->refresh_golden_frame) { /* both refreshed */
4647     cpi->gold_is_last = 1;
4648   } else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) {
4649     /* 1 refreshed but not the other */
4650     cpi->gold_is_last = 0;
4651   }
4652
4653   if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) { /* both refreshed */
4654     cpi->alt_is_last = 1;
4655   } else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) {
4656     /* 1 refreshed but not the other */
4657     cpi->alt_is_last = 0;
4658   }
4659
4660   if (cm->refresh_alt_ref_frame &
4661       cm->refresh_golden_frame) { /* both refreshed */
4662     cpi->gold_is_alt = 1;
4663   } else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) {
4664     /* 1 refreshed but not the other */
4665     cpi->gold_is_alt = 0;
4666   }
4667
4668   cpi->ref_frame_flags = VP8_ALTR_FRAME | VP8_GOLD_FRAME | VP8_LAST_FRAME;
4669
4670   if (cpi->gold_is_last) cpi->ref_frame_flags &= ~VP8_GOLD_FRAME;
4671
4672   if (cpi->alt_is_last) cpi->ref_frame_flags &= ~VP8_ALTR_FRAME;
4673
4674   if (cpi->gold_is_alt) cpi->ref_frame_flags &= ~VP8_ALTR_FRAME;
4675
4676   if (!cpi->oxcf.error_resilient_mode) {
4677     if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame &&
4678         (cm->frame_type != KEY_FRAME)) {
4679       /* Update the alternate reference frame stats as appropriate. */
4680       update_alt_ref_frame_stats(cpi);
4681     } else {
4682       /* Update the Golden frame stats as appropriate. */
4683       update_golden_frame_stats(cpi);
4684     }
4685   }
4686
4687   if (cm->frame_type == KEY_FRAME) {
4688     /* Tell the caller that the frame was coded as a key frame */
4689     *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
4690
4691     /* As this frame is a key frame  the next defaults to an inter frame. */
4692     cm->frame_type = INTER_FRAME;
4693
4694     cpi->last_frame_percent_intra = 100;
4695   } else {
4696     *frame_flags = cm->frame_flags & ~FRAMEFLAGS_KEY;
4697
4698     cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
4699   }
4700
4701   /* Clear the one shot update flags for segmentation map and mode/ref
4702    * loop filter deltas.
4703    */
4704   cpi->mb.e_mbd.update_mb_segmentation_map = 0;
4705   cpi->mb.e_mbd.update_mb_segmentation_data = 0;
4706   cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
4707
4708   /* Dont increment frame counters if this was an altref buffer update
4709    * not a real frame
4710    */
4711   if (cm->show_frame) {
4712     cm->current_video_frame++;
4713     cpi->frames_since_key++;
4714     cpi->temporal_pattern_counter++;
4715   }
4716
4717 /* reset to normal state now that we are done. */
4718
4719 #if 0
4720     {
4721         char filename[512];
4722         FILE *recon_file;
4723         sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
4724         recon_file = fopen(filename, "wb");
4725         fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
4726                cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
4727         fclose(recon_file);
4728     }
4729 #endif
4730
4731   /* DEBUG */
4732   /* vp8_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show); */
4733 }
4734 #if !CONFIG_REALTIME_ONLY
4735 static void Pass2Encode(VP8_COMP *cpi, unsigned long *size, unsigned char *dest,
4736                         unsigned char *dest_end, unsigned int *frame_flags) {
4737   if (!cpi->common.refresh_alt_ref_frame) vp8_second_pass(cpi);
4738
4739   encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4740   cpi->twopass.bits_left -= 8 * (int)(*size);
4741
4742   if (!cpi->common.refresh_alt_ref_frame) {
4743     double two_pass_min_rate =
4744         (double)(cpi->oxcf.target_bandwidth *
4745                  cpi->oxcf.two_pass_vbrmin_section / 100);
4746     cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->framerate);
4747   }
4748 }
4749 #endif
4750
4751 int vp8_receive_raw_frame(VP8_COMP *cpi, unsigned int frame_flags,
4752                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
4753                           int64_t end_time) {
4754   struct vpx_usec_timer timer;
4755   int res = 0;
4756
4757   vpx_usec_timer_start(&timer);
4758
4759   /* Reinit the lookahead buffer if the frame size changes */
4760   if (sd->y_width != cpi->oxcf.Width || sd->y_height != cpi->oxcf.Height) {
4761     assert(cpi->oxcf.lag_in_frames < 2);
4762     dealloc_raw_frame_buffers(cpi);
4763     alloc_raw_frame_buffers(cpi);
4764   }
4765
4766   if (vp8_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
4767                          cpi->active_map_enabled ? cpi->active_map : NULL)) {
4768     res = -1;
4769   }
4770   vpx_usec_timer_mark(&timer);
4771   cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4772
4773   return res;
4774 }
4775
4776 static int frame_is_reference(const VP8_COMP *cpi) {
4777   const VP8_COMMON *cm = &cpi->common;
4778   const MACROBLOCKD *xd = &cpi->mb.e_mbd;
4779
4780   return cm->frame_type == KEY_FRAME || cm->refresh_last_frame ||
4781          cm->refresh_golden_frame || cm->refresh_alt_ref_frame ||
4782          cm->copy_buffer_to_gf || cm->copy_buffer_to_arf ||
4783          cm->refresh_entropy_probs || xd->mode_ref_lf_delta_update ||
4784          xd->update_mb_segmentation_map || xd->update_mb_segmentation_data;
4785 }
4786
4787 int vp8_get_compressed_data(VP8_COMP *cpi, unsigned int *frame_flags,
4788                             unsigned long *size, unsigned char *dest,
4789                             unsigned char *dest_end, int64_t *time_stamp,
4790                             int64_t *time_end, int flush) {
4791   VP8_COMMON *cm;
4792   struct vpx_usec_timer tsctimer;
4793   struct vpx_usec_timer ticktimer;
4794   struct vpx_usec_timer cmptimer;
4795   YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4796
4797   if (!cpi) return -1;
4798
4799   cm = &cpi->common;
4800
4801   if (setjmp(cpi->common.error.jmp)) {
4802     cpi->common.error.setjmp = 0;
4803     vp8_clear_system_state();
4804     return VPX_CODEC_CORRUPT_FRAME;
4805   }
4806
4807   cpi->common.error.setjmp = 1;
4808
4809   vpx_usec_timer_start(&cmptimer);
4810
4811   cpi->source = NULL;
4812
4813 #if !CONFIG_REALTIME_ONLY
4814   /* Should we code an alternate reference frame */
4815   if (cpi->oxcf.error_resilient_mode == 0 && cpi->oxcf.play_alternate &&
4816       cpi->source_alt_ref_pending) {
4817     if ((cpi->source = vp8_lookahead_peek(
4818              cpi->lookahead, cpi->frames_till_gf_update_due, PEEK_FORWARD))) {
4819       cpi->alt_ref_source = cpi->source;
4820       if (cpi->oxcf.arnr_max_frames > 0) {
4821         vp8_temporal_filter_prepare_c(cpi, cpi->frames_till_gf_update_due);
4822         force_src_buffer = &cpi->alt_ref_buffer;
4823       }
4824       cpi->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
4825       cm->refresh_alt_ref_frame = 1;
4826       cm->refresh_golden_frame = 0;
4827       cm->refresh_last_frame = 0;
4828       cm->show_frame = 0;
4829       /* Clear Pending alt Ref flag. */
4830       cpi->source_alt_ref_pending = 0;
4831       cpi->is_src_frame_alt_ref = 0;
4832     }
4833   }
4834 #endif
4835
4836   if (!cpi->source) {
4837     /* Read last frame source if we are encoding first pass. */
4838     if (cpi->pass == 1 && cm->current_video_frame > 0) {
4839       if ((cpi->last_source =
4840                vp8_lookahead_peek(cpi->lookahead, 1, PEEK_BACKWARD)) == NULL) {
4841         return -1;
4842       }
4843     }
4844
4845     if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush))) {
4846       cm->show_frame = 1;
4847
4848       cpi->is_src_frame_alt_ref =
4849           cpi->alt_ref_source && (cpi->source == cpi->alt_ref_source);
4850
4851       if (cpi->is_src_frame_alt_ref) cpi->alt_ref_source = NULL;
4852     }
4853   }
4854
4855   if (cpi->source) {
4856     cpi->Source = force_src_buffer ? force_src_buffer : &cpi->source->img;
4857     cpi->un_scaled_source = cpi->Source;
4858     *time_stamp = cpi->source->ts_start;
4859     *time_end = cpi->source->ts_end;
4860     *frame_flags = cpi->source->flags;
4861
4862     if (cpi->pass == 1 && cm->current_video_frame > 0) {
4863       cpi->last_frame_unscaled_source = &cpi->last_source->img;
4864     }
4865   } else {
4866     *size = 0;
4867 #if !CONFIG_REALTIME_ONLY
4868
4869     if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
4870       vp8_end_first_pass(cpi); /* get last stats packet */
4871       cpi->twopass.first_pass_done = 1;
4872     }
4873
4874 #endif
4875
4876     return -1;
4877   }
4878
4879   if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
4880     cpi->first_time_stamp_ever = cpi->source->ts_start;
4881     cpi->last_end_time_stamp_seen = cpi->source->ts_start;
4882   }
4883
4884   /* adjust frame rates based on timestamps given */
4885   if (cm->show_frame) {
4886     int64_t this_duration;
4887     int step = 0;
4888
4889     if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
4890       this_duration = cpi->source->ts_end - cpi->source->ts_start;
4891       step = 1;
4892     } else {
4893       int64_t last_duration;
4894
4895       this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
4896       last_duration = cpi->last_end_time_stamp_seen - cpi->last_time_stamp_seen;
4897       /* do a step update if the duration changes by 10% */
4898       if (last_duration) {
4899         step = (int)(((this_duration - last_duration) * 10 / last_duration));
4900       }
4901     }
4902
4903     if (this_duration) {
4904       if (step) {
4905         cpi->ref_framerate = 10000000.0 / this_duration;
4906       } else {
4907         double avg_duration, interval;
4908
4909         /* Average this frame's rate into the last second's average
4910          * frame rate. If we haven't seen 1 second yet, then average
4911          * over the whole interval seen.
4912          */
4913         interval = (double)(cpi->source->ts_end - cpi->first_time_stamp_ever);
4914         if (interval > 10000000.0) interval = 10000000;
4915
4916         avg_duration = 10000000.0 / cpi->ref_framerate;
4917         avg_duration *= (interval - avg_duration + this_duration);
4918         avg_duration /= interval;
4919
4920         cpi->ref_framerate = 10000000.0 / avg_duration;
4921       }
4922 #if CONFIG_MULTI_RES_ENCODING
4923       if (cpi->oxcf.mr_total_resolutions > 1) {
4924         LOWER_RES_FRAME_INFO *low_res_frame_info =
4925             (LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info;
4926         // Frame rate should be the same for all spatial layers in
4927         // multi-res-encoding (simulcast), so we constrain the frame for
4928         // higher layers to be that of lowest resolution. This is needed
4929         // as he application may decide to skip encoding a high layer and
4930         // then start again, in which case a big jump in time-stamps will
4931         // be received for that high layer, which will yield an incorrect
4932         // frame rate (from time-stamp adjustment in above calculation).
4933         if (cpi->oxcf.mr_encoder_id) {
4934           cpi->ref_framerate = low_res_frame_info->low_res_framerate;
4935         } else {
4936           // Keep track of frame rate for lowest resolution.
4937           low_res_frame_info->low_res_framerate = cpi->ref_framerate;
4938         }
4939       }
4940 #endif
4941       if (cpi->oxcf.number_of_layers > 1) {
4942         unsigned int i;
4943
4944         /* Update frame rates for each layer */
4945         assert(cpi->oxcf.number_of_layers <= VPX_TS_MAX_LAYERS);
4946         for (i = 0; i < cpi->oxcf.number_of_layers && i < VPX_TS_MAX_LAYERS;
4947              ++i) {
4948           LAYER_CONTEXT *lc = &cpi->layer_context[i];
4949           lc->framerate = cpi->ref_framerate / cpi->oxcf.rate_decimator[i];
4950         }
4951       } else {
4952         vp8_new_framerate(cpi, cpi->ref_framerate);
4953       }
4954     }
4955
4956     cpi->last_time_stamp_seen = cpi->source->ts_start;
4957     cpi->last_end_time_stamp_seen = cpi->source->ts_end;
4958   }
4959
4960   if (cpi->oxcf.number_of_layers > 1) {
4961     int layer;
4962
4963     update_layer_contexts(cpi);
4964
4965     /* Restore layer specific context & set frame rate */
4966     if (cpi->temporal_layer_id >= 0) {
4967       layer = cpi->temporal_layer_id;
4968     } else {
4969       layer =
4970           cpi->oxcf
4971               .layer_id[cpi->temporal_pattern_counter % cpi->oxcf.periodicity];
4972     }
4973     restore_layer_context(cpi, layer);
4974     vp8_new_framerate(cpi, cpi->layer_context[layer].framerate);
4975   }
4976
4977   if (cpi->compressor_speed == 2) {
4978     vpx_usec_timer_start(&tsctimer);
4979     vpx_usec_timer_start(&ticktimer);
4980   }
4981
4982   cpi->lf_zeromv_pct = (cpi->zeromv_count * 100) / cm->MBs;
4983
4984 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
4985   {
4986     int i;
4987     const int num_part = (1 << cm->multi_token_partition);
4988     /* the available bytes in dest */
4989     const unsigned long dest_size = dest_end - dest;
4990     const int tok_part_buff_size = (dest_size * 9) / (10 * num_part);
4991
4992     unsigned char *dp = dest;
4993
4994     cpi->partition_d[0] = dp;
4995     dp += dest_size / 10; /* reserve 1/10 for control partition */
4996     cpi->partition_d_end[0] = dp;
4997
4998     for (i = 0; i < num_part; ++i) {
4999       cpi->partition_d[i + 1] = dp;
5000       dp += tok_part_buff_size;
5001       cpi->partition_d_end[i + 1] = dp;
5002     }
5003   }
5004 #endif
5005
5006   /* start with a 0 size frame */
5007   *size = 0;
5008
5009   /* Clear down mmx registers */
5010   vp8_clear_system_state();
5011
5012   cm->frame_type = INTER_FRAME;
5013   cm->frame_flags = *frame_flags;
5014
5015 #if 0
5016
5017     if (cm->refresh_alt_ref_frame)
5018     {
5019         cm->refresh_golden_frame = 0;
5020         cm->refresh_last_frame = 0;
5021     }
5022     else
5023     {
5024         cm->refresh_golden_frame = 0;
5025         cm->refresh_last_frame = 1;
5026     }
5027
5028 #endif
5029   /* find a free buffer for the new frame */
5030   {
5031     int i = 0;
5032     for (; i < NUM_YV12_BUFFERS; ++i) {
5033       if (!cm->yv12_fb[i].flags) {
5034         cm->new_fb_idx = i;
5035         break;
5036       }
5037     }
5038
5039     assert(i < NUM_YV12_BUFFERS);
5040   }
5041   switch (cpi->pass) {
5042 #if !CONFIG_REALTIME_ONLY
5043     case 1: Pass1Encode(cpi, size, dest, frame_flags); break;
5044     case 2: Pass2Encode(cpi, size, dest, dest_end, frame_flags); break;
5045 #endif  // !CONFIG_REALTIME_ONLY
5046     default:
5047       encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
5048       break;
5049   }
5050
5051   if (cpi->compressor_speed == 2) {
5052     unsigned int duration, duration2;
5053     vpx_usec_timer_mark(&tsctimer);
5054     vpx_usec_timer_mark(&ticktimer);
5055
5056     duration = (int)(vpx_usec_timer_elapsed(&ticktimer));
5057     duration2 = (unsigned int)((double)duration / 2);
5058
5059     if (cm->frame_type != KEY_FRAME) {
5060       if (cpi->avg_encode_time == 0) {
5061         cpi->avg_encode_time = duration;
5062       } else {
5063         cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
5064       }
5065     }
5066
5067     if (duration2) {
5068       {
5069         if (cpi->avg_pick_mode_time == 0) {
5070           cpi->avg_pick_mode_time = duration2;
5071         } else {
5072           cpi->avg_pick_mode_time =
5073               (7 * cpi->avg_pick_mode_time + duration2) >> 3;
5074         }
5075       }
5076     }
5077   }
5078
5079   if (cm->refresh_entropy_probs == 0) {
5080     memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
5081   }
5082
5083   /* Save the contexts separately for alt ref, gold and last. */
5084   /* (TODO jbb -> Optimize this with pointers to avoid extra copies. ) */
5085   if (cm->refresh_alt_ref_frame) memcpy(&cpi->lfc_a, &cm->fc, sizeof(cm->fc));
5086
5087   if (cm->refresh_golden_frame) memcpy(&cpi->lfc_g, &cm->fc, sizeof(cm->fc));
5088
5089   if (cm->refresh_last_frame) memcpy(&cpi->lfc_n, &cm->fc, sizeof(cm->fc));
5090
5091   /* if its a dropped frame honor the requests on subsequent frames */
5092   if (*size > 0) {
5093     cpi->droppable = !frame_is_reference(cpi);
5094
5095     /* return to normal state */
5096     cm->refresh_entropy_probs = 1;
5097     cm->refresh_alt_ref_frame = 0;
5098     cm->refresh_golden_frame = 0;
5099     cm->refresh_last_frame = 1;
5100     cm->frame_type = INTER_FRAME;
5101   }
5102
5103   /* Save layer specific state */
5104   if (cpi->oxcf.number_of_layers > 1) save_layer_context(cpi);
5105
5106   vpx_usec_timer_mark(&cmptimer);
5107   cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
5108
5109   if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame) {
5110     generate_psnr_packet(cpi);
5111   }
5112
5113 #if CONFIG_INTERNAL_STATS
5114
5115   if (cpi->pass != 1) {
5116     cpi->bytes += *size;
5117
5118     if (cm->show_frame) {
5119       cpi->common.show_frame_mi = cpi->common.mi;
5120       cpi->count++;
5121
5122       if (cpi->b_calculate_psnr) {
5123         uint64_t ye, ue, ve;
5124         double frame_psnr;
5125         YV12_BUFFER_CONFIG *orig = cpi->Source;
5126         YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
5127         unsigned int y_width = cpi->common.Width;
5128         unsigned int y_height = cpi->common.Height;
5129         unsigned int uv_width = (y_width + 1) / 2;
5130         unsigned int uv_height = (y_height + 1) / 2;
5131         int y_samples = y_height * y_width;
5132         int uv_samples = uv_height * uv_width;
5133         int t_samples = y_samples + 2 * uv_samples;
5134         double sq_error;
5135
5136         ye = calc_plane_error(orig->y_buffer, orig->y_stride, recon->y_buffer,
5137                               recon->y_stride, y_width, y_height);
5138
5139         ue = calc_plane_error(orig->u_buffer, orig->uv_stride, recon->u_buffer,
5140                               recon->uv_stride, uv_width, uv_height);
5141
5142         ve = calc_plane_error(orig->v_buffer, orig->uv_stride, recon->v_buffer,
5143                               recon->uv_stride, uv_width, uv_height);
5144
5145         sq_error = (double)(ye + ue + ve);
5146
5147         frame_psnr = vpx_sse_to_psnr(t_samples, 255.0, sq_error);
5148
5149         cpi->total_y += vpx_sse_to_psnr(y_samples, 255.0, (double)ye);
5150         cpi->total_u += vpx_sse_to_psnr(uv_samples, 255.0, (double)ue);
5151         cpi->total_v += vpx_sse_to_psnr(uv_samples, 255.0, (double)ve);
5152         cpi->total_sq_error += sq_error;
5153         cpi->total += frame_psnr;
5154 #if CONFIG_POSTPROC
5155         {
5156           YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
5157           double sq_error2;
5158           double frame_psnr2, frame_ssim2 = 0;
5159           double weight = 0;
5160
5161           vp8_deblock(cm, cm->frame_to_show, &cm->post_proc_buffer,
5162                       cm->filter_level * 10 / 6, 1, 0);
5163           vp8_clear_system_state();
5164
5165           ye = calc_plane_error(orig->y_buffer, orig->y_stride, pp->y_buffer,
5166                                 pp->y_stride, y_width, y_height);
5167
5168           ue = calc_plane_error(orig->u_buffer, orig->uv_stride, pp->u_buffer,
5169                                 pp->uv_stride, uv_width, uv_height);
5170
5171           ve = calc_plane_error(orig->v_buffer, orig->uv_stride, pp->v_buffer,
5172                                 pp->uv_stride, uv_width, uv_height);
5173
5174           sq_error2 = (double)(ye + ue + ve);
5175
5176           frame_psnr2 = vpx_sse_to_psnr(t_samples, 255.0, sq_error2);
5177
5178           cpi->totalp_y += vpx_sse_to_psnr(y_samples, 255.0, (double)ye);
5179           cpi->totalp_u += vpx_sse_to_psnr(uv_samples, 255.0, (double)ue);
5180           cpi->totalp_v += vpx_sse_to_psnr(uv_samples, 255.0, (double)ve);
5181           cpi->total_sq_error2 += sq_error2;
5182           cpi->totalp += frame_psnr2;
5183
5184           frame_ssim2 =
5185               vpx_calc_ssim(cpi->Source, &cm->post_proc_buffer, &weight);
5186
5187           cpi->summed_quality += frame_ssim2 * weight;
5188           cpi->summed_weights += weight;
5189
5190           if (cpi->oxcf.number_of_layers > 1) {
5191             unsigned int i;
5192
5193             for (i = cpi->current_layer; i < cpi->oxcf.number_of_layers; ++i) {
5194               cpi->frames_in_layer[i]++;
5195
5196               cpi->bytes_in_layer[i] += *size;
5197               cpi->sum_psnr[i] += frame_psnr;
5198               cpi->sum_psnr_p[i] += frame_psnr2;
5199               cpi->total_error2[i] += sq_error;
5200               cpi->total_error2_p[i] += sq_error2;
5201               cpi->sum_ssim[i] += frame_ssim2 * weight;
5202               cpi->sum_weights[i] += weight;
5203             }
5204           }
5205         }
5206 #endif
5207       }
5208     }
5209   }
5210
5211 #if 0
5212
5213     if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
5214     {
5215         skiptruecount += cpi->skip_true_count;
5216         skipfalsecount += cpi->skip_false_count;
5217     }
5218
5219 #endif
5220 #if 0
5221
5222     if (cpi->pass != 1)
5223     {
5224         FILE *f = fopen("skip.stt", "a");
5225         fprintf(f, "frame:%4d flags:%4x Q:%4d P:%4d Size:%5d\n", cpi->common.current_video_frame, *frame_flags, cpi->common.base_qindex, cpi->prob_skip_false, *size);
5226
5227         if (cpi->is_src_frame_alt_ref == 1)
5228             fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
5229
5230         fclose(f);
5231     }
5232
5233 #endif
5234 #endif
5235
5236   cpi->common.error.setjmp = 0;
5237
5238   return 0;
5239 }
5240
5241 int vp8_get_preview_raw_frame(VP8_COMP *cpi, YV12_BUFFER_CONFIG *dest,
5242                               vp8_ppflags_t *flags) {
5243   if (cpi->common.refresh_alt_ref_frame) {
5244     return -1;
5245   } else {
5246     int ret;
5247
5248 #if CONFIG_POSTPROC
5249     cpi->common.show_frame_mi = cpi->common.mi;
5250     ret = vp8_post_proc_frame(&cpi->common, dest, flags);
5251 #else
5252     (void)flags;
5253
5254     if (cpi->common.frame_to_show) {
5255       *dest = *cpi->common.frame_to_show;
5256       dest->y_width = cpi->common.Width;
5257       dest->y_height = cpi->common.Height;
5258       dest->uv_height = cpi->common.Height / 2;
5259       ret = 0;
5260     } else {
5261       ret = -1;
5262     }
5263
5264 #endif
5265     vp8_clear_system_state();
5266     return ret;
5267   }
5268 }
5269
5270 int vp8_set_roimap(VP8_COMP *cpi, unsigned char *map, unsigned int rows,
5271                    unsigned int cols, int delta_q[4], int delta_lf[4],
5272                    unsigned int threshold[4]) {
5273   signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
5274   int internal_delta_q[MAX_MB_SEGMENTS];
5275   const int range = 63;
5276   int i;
5277
5278   // This method is currently incompatible with the cyclic refresh method
5279   if (cpi->cyclic_refresh_mode_enabled) return -1;
5280
5281   // Check number of rows and columns match
5282   if (cpi->common.mb_rows != (int)rows || cpi->common.mb_cols != (int)cols) {
5283     return -1;
5284   }
5285
5286   // Range check the delta Q values and convert the external Q range values
5287   // to internal ones.
5288   if ((abs(delta_q[0]) > range) || (abs(delta_q[1]) > range) ||
5289       (abs(delta_q[2]) > range) || (abs(delta_q[3]) > range)) {
5290     return -1;
5291   }
5292
5293   // Range check the delta lf values
5294   if ((abs(delta_lf[0]) > range) || (abs(delta_lf[1]) > range) ||
5295       (abs(delta_lf[2]) > range) || (abs(delta_lf[3]) > range)) {
5296     return -1;
5297   }
5298
5299   if (!map) {
5300     disable_segmentation(cpi);
5301     return 0;
5302   }
5303
5304   // Translate the external delta q values to internal values.
5305   for (i = 0; i < MAX_MB_SEGMENTS; ++i) {
5306     internal_delta_q[i] =
5307         (delta_q[i] >= 0) ? q_trans[delta_q[i]] : -q_trans[-delta_q[i]];
5308   }
5309
5310   /* Set the segmentation Map */
5311   set_segmentation_map(cpi, map);
5312
5313   /* Activate segmentation. */
5314   enable_segmentation(cpi);
5315
5316   /* Set up the quant segment data */
5317   feature_data[MB_LVL_ALT_Q][0] = internal_delta_q[0];
5318   feature_data[MB_LVL_ALT_Q][1] = internal_delta_q[1];
5319   feature_data[MB_LVL_ALT_Q][2] = internal_delta_q[2];
5320   feature_data[MB_LVL_ALT_Q][3] = internal_delta_q[3];
5321
5322   /* Set up the loop segment data s */
5323   feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
5324   feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
5325   feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
5326   feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
5327
5328   cpi->segment_encode_breakout[0] = threshold[0];
5329   cpi->segment_encode_breakout[1] = threshold[1];
5330   cpi->segment_encode_breakout[2] = threshold[2];
5331   cpi->segment_encode_breakout[3] = threshold[3];
5332
5333   /* Initialise the feature data structure */
5334   set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
5335
5336   return 0;
5337 }
5338
5339 int vp8_set_active_map(VP8_COMP *cpi, unsigned char *map, unsigned int rows,
5340                        unsigned int cols) {
5341   if ((int)rows == cpi->common.mb_rows && (int)cols == cpi->common.mb_cols) {
5342     if (map) {
5343       memcpy(cpi->active_map, map, rows * cols);
5344       cpi->active_map_enabled = 1;
5345     } else {
5346       cpi->active_map_enabled = 0;
5347     }
5348
5349     return 0;
5350   } else {
5351     return -1;
5352   }
5353 }
5354
5355 int vp8_set_internal_size(VP8_COMP *cpi, VPX_SCALING horiz_mode,
5356                           VPX_SCALING vert_mode) {
5357   if (horiz_mode <= ONETWO) {
5358     cpi->common.horiz_scale = horiz_mode;
5359   } else {
5360     return -1;
5361   }
5362
5363   if (vert_mode <= ONETWO) {
5364     cpi->common.vert_scale = vert_mode;
5365   } else {
5366     return -1;
5367   }
5368
5369   return 0;
5370 }
5371
5372 int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest) {
5373   int i, j;
5374   int Total = 0;
5375
5376   unsigned char *src = source->y_buffer;
5377   unsigned char *dst = dest->y_buffer;
5378
5379   /* Loop through the Y plane raw and reconstruction data summing
5380    * (square differences)
5381    */
5382   for (i = 0; i < source->y_height; i += 16) {
5383     for (j = 0; j < source->y_width; j += 16) {
5384       unsigned int sse;
5385       Total += vpx_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
5386                             &sse);
5387     }
5388
5389     src += 16 * source->y_stride;
5390     dst += 16 * dest->y_stride;
5391   }
5392
5393   return Total;
5394 }
5395
5396 int vp8_get_quantizer(VP8_COMP *cpi) { return cpi->common.base_qindex; }