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