blob: 9cdc1e5bff2547b518c1d9ba55d2f6519aae40dd [file] [log] [blame]
John Koleszar0ea50ce2010-05-18 11:58:33 -04001/*
John Koleszarc2140b82010-09-09 08:16:39 -04002 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
John Koleszar0ea50ce2010-05-18 11:58:33 -04003 *
John Koleszar94c52e42010-06-18 12:39:21 -04004 * Use of this source code is governed by a BSD-style license
John Koleszar09202d82010-06-04 16:19:40 -04005 * 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
John Koleszar94c52e42010-06-18 12:39:21 -04007 * in the file PATENTS. All contributing project authors may
John Koleszar09202d82010-06-04 16:19:40 -04008 * be found in the AUTHORS file in the root of the source tree.
John Koleszar0ea50ce2010-05-18 11:58:33 -04009 */
10
John Koleszar0ea50ce2010-05-18 11:58:33 -040011#include "math.h"
12#include "limits.h"
13#include "block.h"
14#include "onyx_int.h"
15#include "variance.h"
16#include "encodeintra.h"
John Koleszar02321de2011-02-10 14:41:38 -050017#include "vp8/common/setupintrarecon.h"
John Koleszar0ea50ce2010-05-18 11:58:33 -040018#include "mcomp.h"
Paul Wilkins11694aa2011-06-28 17:29:47 +010019#include "firstpass.h"
John Koleszar0ea50ce2010-05-18 11:58:33 -040020#include "vpx_scale/vpxscale.h"
21#include "encodemb.h"
John Koleszar02321de2011-02-10 14:41:38 -050022#include "vp8/common/extend.h"
23#include "vp8/common/systemdependent.h"
John Koleszar0ea50ce2010-05-18 11:58:33 -040024#include "vpx_scale/yv12extend.h"
25#include "vpx_mem/vpx_mem.h"
John Koleszar02321de2011-02-10 14:41:38 -050026#include "vp8/common/swapyv12buffer.h"
John Koleszar0ea50ce2010-05-18 11:58:33 -040027#include <stdio.h>
28#include "rdopt.h"
John Koleszar02321de2011-02-10 14:41:38 -050029#include "vp8/common/quant_common.h"
John Koleszar0ea50ce2010-05-18 11:58:33 -040030#include "encodemv.h"
31
32//#define OUTPUT_FPF 1
John Koleszar0ea50ce2010-05-18 11:58:33 -040033
34#if CONFIG_RUNTIME_CPU_DETECT
35#define IF_RTCD(x) (x)
36#else
37#define IF_RTCD(x) NULL
38#endif
39
40extern void vp8_build_block_offsets(MACROBLOCK *x);
41extern void vp8_setup_block_ptrs(MACROBLOCK *x);
42extern void vp8cx_frame_init_quantizer(VP8_COMP *cpi);
Scott LaVarnway6b255012011-05-12 10:50:16 -040043extern void vp8_set_mbmode_and_mvs(MACROBLOCK *x, MB_PREDICTION_MODE mb, int_mv *mv);
John Koleszar0ea50ce2010-05-18 11:58:33 -040044extern void vp8_alloc_compressor_data(VP8_COMP *cpi);
45
46//#define GFQ_ADJUSTMENT (40 + ((15*Q)/10))
47//#define GFQ_ADJUSTMENT (80 + ((15*Q)/10))
48#define GFQ_ADJUSTMENT vp8_gf_boost_qadjustment[Q]
49extern int vp8_kf_boost_qadjustment[QINDEX_RANGE];
50
51extern const int vp8_gf_boost_qadjustment[QINDEX_RANGE];
52
Paul Wilkins11694aa2011-06-28 17:29:47 +010053#define IIFACTOR 1.5
John Koleszar0ea50ce2010-05-18 11:58:33 -040054#define IIKFACTOR1 1.40
55#define IIKFACTOR2 1.5
Paul Wilkinsb095d9d2011-01-04 17:55:49 +000056#define RMAX 14.0
57#define GF_RMAX 48.0
John Koleszar0ea50ce2010-05-18 11:58:33 -040058
Paul Wilkinsb095d9d2011-01-04 17:55:49 +000059#define KF_MB_INTRA_MIN 300
60#define GF_MB_INTRA_MIN 200
Paul Wilkinse0846c92011-01-07 18:29:37 +000061
John Koleszar0ea50ce2010-05-18 11:58:33 -040062#define DOUBLE_DIVIDE_CHECK(X) ((X)<0?(X)-.000001:(X)+.000001)
63
64#define POW1 (double)cpi->oxcf.two_pass_vbrbias/100.0
65#define POW2 (double)cpi->oxcf.two_pass_vbrbias/100.0
66
Paul Wilkins11694aa2011-06-28 17:29:47 +010067#define NEW_BOOST 1
68
John Koleszar0ea50ce2010-05-18 11:58:33 -040069static int vscale_lookup[7] = {0, 1, 1, 2, 2, 3, 3};
70static int hscale_lookup[7] = {0, 0, 1, 1, 2, 2, 3};
71
Paul Wilkinse0846c92011-01-07 18:29:37 +000072
John Koleszar429dc672011-03-17 17:07:59 -040073static const int cq_level[QINDEX_RANGE] =
Paul Wilkinse0846c92011-01-07 18:29:37 +000074{
75 0,0,1,1,2,3,3,4,4,5,6,6,7,8,8,9,
76 9,10,11,11,12,13,13,14,15,15,16,17,17,18,19,20,
77 20,21,22,22,23,24,24,25,26,27,27,28,29,30,30,31,
78 32,33,33,34,35,36,36,37,38,39,39,40,41,42,42,43,
79 44,45,46,46,47,48,49,50,50,51,52,53,54,55,55,56,
80 57,58,59,60,60,61,62,63,64,65,66,67,67,68,69,70,
81 71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,
82 86,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
83};
84
John Koleszar429dc672011-03-17 17:07:59 -040085static void find_next_key_frame(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame);
John Koleszar0ea50ce2010-05-18 11:58:33 -040086
John Koleszar0ea50ce2010-05-18 11:58:33 -040087// Resets the first pass file to the given position using a relative seek from the current position
88static void reset_fpf_position(VP8_COMP *cpi, FIRSTPASS_STATS *Position)
89{
John Koleszar63cb1a72011-05-19 17:16:39 -040090 cpi->twopass.stats_in = Position;
John Koleszar0ea50ce2010-05-18 11:58:33 -040091}
92
93static int lookup_next_frame_stats(VP8_COMP *cpi, FIRSTPASS_STATS *next_frame)
94{
John Koleszar63cb1a72011-05-19 17:16:39 -040095 if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end)
John Koleszar0ea50ce2010-05-18 11:58:33 -040096 return EOF;
97
John Koleszar63cb1a72011-05-19 17:16:39 -040098 *next_frame = *cpi->twopass.stats_in;
John Koleszar0ea50ce2010-05-18 11:58:33 -040099 return 1;
100}
101
Paul Wilkins11694aa2011-06-28 17:29:47 +0100102// Read frame stats at an offset from the current position
103static int read_frame_stats( VP8_COMP *cpi,
104 FIRSTPASS_STATS *frame_stats,
105 int offset )
106{
107 FIRSTPASS_STATS * fps_ptr = cpi->twopass.stats_in;
108
109 // Check legality of offset
110 if ( offset >= 0 )
111 {
112 if ( &fps_ptr[offset] >= cpi->twopass.stats_in_end )
113 return EOF;
114 }
115 else if ( offset < 0 )
116 {
117 if ( &fps_ptr[offset] < cpi->twopass.stats_in_start )
118 return EOF;
119 }
120
121 *frame_stats = fps_ptr[offset];
122 return 1;
123}
124
125static int input_stats(VP8_COMP *cpi, FIRSTPASS_STATS *fps)
126{
127 if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end)
128 return EOF;
129
130 *fps = *cpi->twopass.stats_in;
131 cpi->twopass.stats_in =
132 (void*)((char *)cpi->twopass.stats_in + sizeof(FIRSTPASS_STATS));
133 return 1;
134}
135
136static void output_stats(const VP8_COMP *cpi,
137 struct vpx_codec_pkt_list *pktlist,
138 FIRSTPASS_STATS *stats)
139{
140 struct vpx_codec_cx_pkt pkt;
141 pkt.kind = VPX_CODEC_STATS_PKT;
142 pkt.data.twopass_stats.buf = stats;
143 pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
144 vpx_codec_pkt_list_add(pktlist, &pkt);
145
146// TEMP debug code
147#if OUTPUT_FPF
148
149 {
150 FILE *fpfile;
151 fpfile = fopen("firstpass.stt", "a");
152
153 fprintf(fpfile, "%12.0f %12.0f %12.0f %12.4f %12.4f %12.4f %12.4f"
154 " %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f"
155 " %12.0f %12.4f\n",
156 stats->frame,
157 stats->intra_error,
158 stats->coded_error,
159 stats->ssim_weighted_pred_err,
160 stats->pcnt_inter,
161 stats->pcnt_motion,
162 stats->pcnt_second_ref,
163 stats->pcnt_neutral,
164 stats->MVr,
165 stats->mvr_abs,
166 stats->MVc,
167 stats->mvc_abs,
168 stats->MVrv,
169 stats->MVcv,
170 stats->mv_in_out_count,
171 stats->count,
172 stats->duration);
173 fclose(fpfile);
174 }
175#endif
176}
177
178static void zero_stats(FIRSTPASS_STATS *section)
179{
180 section->frame = 0.0;
181 section->intra_error = 0.0;
182 section->coded_error = 0.0;
183 section->ssim_weighted_pred_err = 0.0;
184 section->pcnt_inter = 0.0;
185 section->pcnt_motion = 0.0;
186 section->pcnt_second_ref = 0.0;
187 section->pcnt_neutral = 0.0;
188 section->MVr = 0.0;
189 section->mvr_abs = 0.0;
190 section->MVc = 0.0;
191 section->mvc_abs = 0.0;
192 section->MVrv = 0.0;
193 section->MVcv = 0.0;
194 section->mv_in_out_count = 0.0;
195 section->count = 0.0;
196 section->duration = 1.0;
197}
198
199static void accumulate_stats(FIRSTPASS_STATS *section, FIRSTPASS_STATS *frame)
200{
201 section->frame += frame->frame;
202 section->intra_error += frame->intra_error;
203 section->coded_error += frame->coded_error;
204 section->ssim_weighted_pred_err += frame->ssim_weighted_pred_err;
205 section->pcnt_inter += frame->pcnt_inter;
206 section->pcnt_motion += frame->pcnt_motion;
207 section->pcnt_second_ref += frame->pcnt_second_ref;
208 section->pcnt_neutral += frame->pcnt_neutral;
209 section->MVr += frame->MVr;
210 section->mvr_abs += frame->mvr_abs;
211 section->MVc += frame->MVc;
212 section->mvc_abs += frame->mvc_abs;
213 section->MVrv += frame->MVrv;
214 section->MVcv += frame->MVcv;
215 section->mv_in_out_count += frame->mv_in_out_count;
216 section->count += frame->count;
217 section->duration += frame->duration;
218}
219
220static void avg_stats(FIRSTPASS_STATS *section)
221{
222 if (section->count < 1.0)
223 return;
224
225 section->intra_error /= section->count;
226 section->coded_error /= section->count;
227 section->ssim_weighted_pred_err /= section->count;
228 section->pcnt_inter /= section->count;
229 section->pcnt_second_ref /= section->count;
230 section->pcnt_neutral /= section->count;
231 section->pcnt_motion /= section->count;
232 section->MVr /= section->count;
233 section->mvr_abs /= section->count;
234 section->MVc /= section->count;
235 section->mvc_abs /= section->count;
236 section->MVrv /= section->count;
237 section->MVcv /= section->count;
238 section->mv_in_out_count /= section->count;
239 section->duration /= section->count;
240}
241
John Koleszar0ea50ce2010-05-18 11:58:33 -0400242// Calculate a modified Error used in distributing bits between easier and harder frames
243static double calculate_modified_err(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame)
244{
John Koleszar63cb1a72011-05-19 17:16:39 -0400245 double av_err = cpi->twopass.total_stats->ssim_weighted_pred_err;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400246 double this_err = this_frame->ssim_weighted_pred_err;
247 double modified_err;
248
249 //double relative_next_iiratio;
250 //double next_iiratio;
251 //double sum_iiratio;
252 //int i;
253
254 //FIRSTPASS_STATS next_frame;
255 //FIRSTPASS_STATS *start_pos;
256
John Koleszar63cb1a72011-05-19 17:16:39 -0400257 /*start_pos = cpi->twopass.stats_in;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400258 sum_iiratio = 0.0;
259 i = 0;
John Koleszar429dc672011-03-17 17:07:59 -0400260 while ( (i < 1) && input_stats(cpi,&next_frame) != EOF )
John Koleszar0ea50ce2010-05-18 11:58:33 -0400261 {
262
263 next_iiratio = next_frame.intra_error / DOUBLE_DIVIDE_CHECK(next_frame.coded_error);
264 next_iiratio = ( next_iiratio < 1.0 ) ? 1.0 : (next_iiratio > 20.0) ? 20.0 : next_iiratio;
265 sum_iiratio += next_iiratio;
266 i++;
267 }
268 if ( i > 0 )
269 {
John Koleszar63cb1a72011-05-19 17:16:39 -0400270 relative_next_iiratio = sum_iiratio / DOUBLE_DIVIDE_CHECK(cpi->twopass.avg_iiratio * (double)i);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400271 }
272 else
273 {
274 relative_next_iiratio = 1.0;
275 }
276 reset_fpf_position(cpi, start_pos);*/
277
278 if (this_err > av_err)
279 modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW1);
280 else
281 modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW2);
282
283 /*
284 relative_next_iiratio = pow(relative_next_iiratio,0.25);
285 modified_err = modified_err * relative_next_iiratio;
286 */
287
288 return modified_err;
289}
290
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500291static const double weight_table[256] = {
2920.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
2930.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
2940.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
2950.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
2960.020000, 0.031250, 0.062500, 0.093750, 0.125000, 0.156250, 0.187500, 0.218750,
2970.250000, 0.281250, 0.312500, 0.343750, 0.375000, 0.406250, 0.437500, 0.468750,
2980.500000, 0.531250, 0.562500, 0.593750, 0.625000, 0.656250, 0.687500, 0.718750,
2990.750000, 0.781250, 0.812500, 0.843750, 0.875000, 0.906250, 0.937500, 0.968750,
3001.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3011.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3021.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3031.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3041.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3051.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3061.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3071.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3081.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3091.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3101.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3111.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3121.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3131.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3141.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3151.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3161.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3171.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3181.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3191.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3201.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3211.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3221.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
3231.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000
324};
325
John Koleszar429dc672011-03-17 17:07:59 -0400326static double simple_weight(YV12_BUFFER_CONFIG *source)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400327{
328 int i, j;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400329
330 unsigned char *src = source->y_buffer;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400331 double sum_weights = 0.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400332
333 // Loop throught the Y plane raw examining levels and creating a weight for the image
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500334 i = source->y_height;
335 do
John Koleszar0ea50ce2010-05-18 11:58:33 -0400336 {
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500337 j = source->y_width;
338 do
John Koleszar0ea50ce2010-05-18 11:58:33 -0400339 {
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500340 sum_weights += weight_table[ *src];
341 src++;
342 }while(--j);
343 src -= source->y_width;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400344 src += source->y_stride;
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500345 }while(--i);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400346
347 sum_weights /= (source->y_height * source->y_width);
348
349 return sum_weights;
350}
351
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500352
John Koleszar0ea50ce2010-05-18 11:58:33 -0400353// This function returns the current per frame maximum bitrate target
John Koleszar429dc672011-03-17 17:07:59 -0400354static int frame_max_bits(VP8_COMP *cpi)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400355{
356 // Max allocation for a single frame based on the max section guidelines passed in and how many bits are left
357 int max_bits;
358
359 // For CBR we need to also consider buffer fullness.
John Koleszare9613172011-08-12 14:51:36 -0400360 // If we are running below the optimal level then we need to gradually tighten up on max_bits.
John Koleszar0ea50ce2010-05-18 11:58:33 -0400361 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
362 {
John Koleszare9613172011-08-12 14:51:36 -0400363 double buffer_fullness_ratio = (double)cpi->buffer_level / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.optimal_buffer_level);
364
365 // For CBR base this on the target average bits per frame plus the maximum sedction rate passed in by the user
366 max_bits = (int)(cpi->av_per_frame_bandwidth * ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
367
368 // If our buffer is below the optimum level
369 if (buffer_fullness_ratio < 1.0)
370 {
371 // The lower of max_bits / 4 or cpi->av_per_frame_bandwidth / 4.
372 int min_max_bits = ((cpi->av_per_frame_bandwidth >> 2) < (max_bits >> 2)) ? cpi->av_per_frame_bandwidth >> 2 : max_bits >> 2;
373
374 max_bits = (int)(max_bits * buffer_fullness_ratio);
375
376 if (max_bits < min_max_bits)
377 max_bits = min_max_bits; // Lowest value we will set ... which should allow the buffer to refil.
378 }
John Koleszar0ea50ce2010-05-18 11:58:33 -0400379 }
380 // VBR
381 else
382 {
383 // For VBR base this on the bits and frames left plus the two_pass_vbrmax_section rate passed in by the user
John Koleszar63cb1a72011-05-19 17:16:39 -0400384 max_bits = (int)(((double)cpi->twopass.bits_left / (cpi->twopass.total_stats->count - (double)cpi->common.current_video_frame)) * ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
John Koleszar0ea50ce2010-05-18 11:58:33 -0400385 }
386
387 // Trap case where we are out of bits
388 if (max_bits < 0)
389 max_bits = 0;
390
391 return max_bits;
392}
393
John Koleszar0ea50ce2010-05-18 11:58:33 -0400394void vp8_init_first_pass(VP8_COMP *cpi)
395{
John Koleszar63cb1a72011-05-19 17:16:39 -0400396 zero_stats(cpi->twopass.total_stats);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400397}
398
399void vp8_end_first_pass(VP8_COMP *cpi)
400{
John Koleszar63cb1a72011-05-19 17:16:39 -0400401 output_stats(cpi, cpi->output_pkt_list, cpi->twopass.total_stats);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400402}
John Koleszarbb7dd5b2010-10-14 16:40:12 -0400403
John Koleszar429dc672011-03-17 17:07:59 -0400404static void zz_motion_search( VP8_COMP *cpi, MACROBLOCK * x, YV12_BUFFER_CONFIG * recon_buffer, int * best_motion_err, int recon_yoffset )
John Koleszar0ea50ce2010-05-18 11:58:33 -0400405{
406 MACROBLOCKD * const xd = & x->e_mbd;
407 BLOCK *b = &x->block[0];
408 BLOCKD *d = &x->e_mbd.block[0];
409
410 unsigned char *src_ptr = (*(b->base_src) + b->src);
411 int src_stride = b->src_stride;
412 unsigned char *ref_ptr;
413 int ref_stride=d->pre_stride;
414
415 // Set up pointers for this macro block recon buffer
416 xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
417
418 ref_ptr = (unsigned char *)(*(d->base_pre) + d->pre );
419
420 VARIANCE_INVOKE(IF_RTCD(&cpi->rtcd.variance), mse16x16) ( src_ptr, src_stride, ref_ptr, ref_stride, (unsigned int *)(best_motion_err));
421}
422
Scott LaVarnway6b255012011-05-12 10:50:16 -0400423static void first_pass_motion_search(VP8_COMP *cpi, MACROBLOCK *x,
424 int_mv *ref_mv, MV *best_mv,
425 YV12_BUFFER_CONFIG *recon_buffer,
426 int *best_motion_err, int recon_yoffset )
John Koleszar0ea50ce2010-05-18 11:58:33 -0400427{
428 MACROBLOCKD *const xd = & x->e_mbd;
429 BLOCK *b = &x->block[0];
430 BLOCKD *d = &x->e_mbd.block[0];
431 int num00;
432
Scott LaVarnway6b255012011-05-12 10:50:16 -0400433 int_mv tmp_mv;
Yunqing Wang40991fa2011-07-07 11:21:41 -0400434 int_mv ref_mv_full;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400435
436 int tmp_err;
437 int step_param = 3; //3; // Dont search over full range for first pass
438 int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param; //3;
439 int n;
John Koleszar209d82a2010-10-26 15:34:16 -0400440 vp8_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[BLOCK_16X16];
John Koleszar0ea50ce2010-05-18 11:58:33 -0400441 int new_mv_mode_penalty = 256;
442
John Koleszar209d82a2010-10-26 15:34:16 -0400443 // override the default variance function to use MSE
John Koleszar0ea50ce2010-05-18 11:58:33 -0400444 v_fn_ptr.vf = VARIANCE_INVOKE(IF_RTCD(&cpi->rtcd.variance), mse16x16);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400445
446 // Set up pointers for this macro block recon buffer
447 xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
448
449 // Initial step/diamond search centred on best mv
Scott LaVarnway6b255012011-05-12 10:50:16 -0400450 tmp_mv.as_int = 0;
Yunqing Wang40991fa2011-07-07 11:21:41 -0400451 ref_mv_full.as_mv.col = ref_mv->as_mv.col>>3;
452 ref_mv_full.as_mv.row = ref_mv->as_mv.row>>3;
453 tmp_err = cpi->diamond_search_sad(x, b, d, &ref_mv_full, &tmp_mv, step_param,
Yaowu Xu5b2fb322011-06-01 11:41:05 -0700454 x->sadperbit16, &num00, &v_fn_ptr,
455 x->mvcost, ref_mv);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400456 if ( tmp_err < INT_MAX-new_mv_mode_penalty )
457 tmp_err += new_mv_mode_penalty;
458
459 if (tmp_err < *best_motion_err)
460 {
461 *best_motion_err = tmp_err;
Scott LaVarnway6b255012011-05-12 10:50:16 -0400462 best_mv->row = tmp_mv.as_mv.row;
463 best_mv->col = tmp_mv.as_mv.col;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400464 }
465
466 // Further step/diamond searches as necessary
467 n = num00;
468 num00 = 0;
469
470 while (n < further_steps)
471 {
472 n++;
473
474 if (num00)
475 num00--;
476 else
477 {
Yunqing Wang40991fa2011-07-07 11:21:41 -0400478 tmp_err = cpi->diamond_search_sad(x, b, d, &ref_mv_full, &tmp_mv,
Yaowu Xu5b2fb322011-06-01 11:41:05 -0700479 step_param + n, x->sadperbit16,
480 &num00, &v_fn_ptr, x->mvcost,
481 ref_mv);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400482 if ( tmp_err < INT_MAX-new_mv_mode_penalty )
483 tmp_err += new_mv_mode_penalty;
484
485 if (tmp_err < *best_motion_err)
486 {
487 *best_motion_err = tmp_err;
Scott LaVarnway6b255012011-05-12 10:50:16 -0400488 best_mv->row = tmp_mv.as_mv.row;
489 best_mv->col = tmp_mv.as_mv.col;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400490 }
491 }
492 }
493}
494
495void vp8_first_pass(VP8_COMP *cpi)
496{
497 int mb_row, mb_col;
498 MACROBLOCK *const x = & cpi->mb;
499 VP8_COMMON *const cm = & cpi->common;
500 MACROBLOCKD *const xd = & x->e_mbd;
501
John Koleszar0ea50ce2010-05-18 11:58:33 -0400502 int recon_yoffset, recon_uvoffset;
Fritz Koenig0ce39012010-07-22 08:07:32 -0400503 YV12_BUFFER_CONFIG *lst_yv12 = &cm->yv12_fb[cm->lst_fb_idx];
504 YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
505 YV12_BUFFER_CONFIG *gld_yv12 = &cm->yv12_fb[cm->gld_fb_idx];
506 int recon_y_stride = lst_yv12->y_stride;
507 int recon_uv_stride = lst_yv12->uv_stride;
James Zernb45065d2011-07-25 18:44:59 -0700508 int64_t intra_error = 0;
509 int64_t coded_error = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400510
511 int sum_mvr = 0, sum_mvc = 0;
512 int sum_mvr_abs = 0, sum_mvc_abs = 0;
513 int sum_mvrs = 0, sum_mvcs = 0;
514 int mvcount = 0;
515 int intercount = 0;
516 int second_ref_count = 0;
517 int intrapenalty = 256;
Paul Wilkinsbc9c30a2011-03-07 15:58:07 +0000518 int neutral_count = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400519
520 int sum_in_vectors = 0;
521
Scott LaVarnway6b255012011-05-12 10:50:16 -0400522 int_mv zero_ref_mv;
523
524 zero_ref_mv.as_int = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400525
John Koleszar0ea50ce2010-05-18 11:58:33 -0400526 vp8_clear_system_state(); //__asm emms;
527
528 x->src = * cpi->Source;
Fritz Koenig0ce39012010-07-22 08:07:32 -0400529 xd->pre = *lst_yv12;
530 xd->dst = *new_yv12;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400531
Scott LaVarnway0de458f2010-09-02 16:17:52 -0400532 x->partition_info = x->pi;
533
Scott LaVarnway9c7a0092010-08-12 16:25:43 -0400534 xd->mode_info_context = cm->mi;
535
John Koleszar0ea50ce2010-05-18 11:58:33 -0400536 vp8_build_block_offsets(x);
537
538 vp8_setup_block_dptrs(&x->e_mbd);
539
540 vp8_setup_block_ptrs(x);
541
542 // set up frame new frame for intra coded blocks
Fritz Koenig0ce39012010-07-22 08:07:32 -0400543 vp8_setup_intra_recon(new_yv12);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400544 vp8cx_frame_init_quantizer(cpi);
545
546 // Initialise the MV cost table to the defaults
547 //if( cm->current_video_frame == 0)
548 //if ( 0 )
549 {
550 int flag[2] = {1, 1};
551 vp8_initialize_rd_consts(cpi, vp8_dc_quant(cm->base_qindex, cm->y1dc_delta_q));
552 vpx_memcpy(cm->fc.mvc, vp8_default_mv_context, sizeof(vp8_default_mv_context));
Yunqing Wang3d681582011-04-01 16:41:58 -0400553 vp8_build_component_cost_table(cpi->mb.mvcost, (const MV_CONTEXT *) cm->fc.mvc, flag);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400554 }
555
556 // for each macroblock row in image
557 for (mb_row = 0; mb_row < cm->mb_rows; mb_row++)
558 {
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500559 int_mv best_ref_mv;
560
561 best_ref_mv.as_int = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400562
563 // reset above block coeffs
564 xd->up_available = (mb_row != 0);
565 recon_yoffset = (mb_row * recon_y_stride * 16);
566 recon_uvoffset = (mb_row * recon_uv_stride * 8);
567
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500568 // Set up limit values for motion vectors to prevent them extending outside the UMV borders
569 x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16));
570 x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16) + (VP8BORDERINPIXELS - 16);
571
572
John Koleszar0ea50ce2010-05-18 11:58:33 -0400573 // for each macroblock col in image
574 for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
575 {
576 int this_error;
577 int gf_motion_error = INT_MAX;
578 int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
579
Fritz Koenig0ce39012010-07-22 08:07:32 -0400580 xd->dst.y_buffer = new_yv12->y_buffer + recon_yoffset;
581 xd->dst.u_buffer = new_yv12->u_buffer + recon_uvoffset;
582 xd->dst.v_buffer = new_yv12->v_buffer + recon_uvoffset;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400583 xd->left_available = (mb_col != 0);
584
Yunqing Wang0d870982011-06-23 13:54:02 -0400585 //Copy current mb to a buffer
586 RECON_INVOKE(&xd->rtcd->recon, copy16x16)(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
587
John Koleszar0ea50ce2010-05-18 11:58:33 -0400588 // do intra 16x16 prediction
Tero Rintaluoma99090472011-06-14 13:39:06 +0300589 this_error = vp8_encode_intra(cpi, x, use_dc_pred);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400590
591 // "intrapenalty" below deals with situations where the intra and inter error scores are very low (eg a plain black frame)
592 // We do not have special cases in first pass for 0,0 and nearest etc so all inter modes carry an overhead cost estimate fot the mv.
593 // When the error score is very low this causes us to pick all or lots of INTRA modes and throw lots of key frames.
594 // This penalty adds a cost matching that of a 0,0 mv to the intra case.
595 this_error += intrapenalty;
596
597 // Cumulative intra error total
James Zernb45065d2011-07-25 18:44:59 -0700598 intra_error += (int64_t)this_error;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400599
John Koleszar0ea50ce2010-05-18 11:58:33 -0400600 // Set up limit values for motion vectors to prevent them extending outside the UMV borders
601 x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16));
602 x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + (VP8BORDERINPIXELS - 16);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400603
604 // Other than for the first frame do a motion search
605 if (cm->current_video_frame > 0)
606 {
John Koleszar0ea50ce2010-05-18 11:58:33 -0400607 BLOCKD *d = &x->e_mbd.block[0];
608 MV tmp_mv = {0, 0};
609 int tmp_err;
610 int motion_error = INT_MAX;
611
612 // Simple 0,0 motion with no mv overhead
John Koleszar429dc672011-03-17 17:07:59 -0400613 zz_motion_search( cpi, x, lst_yv12, &motion_error, recon_yoffset );
John Koleszar0ea50ce2010-05-18 11:58:33 -0400614 d->bmi.mv.as_mv.row = 0;
615 d->bmi.mv.as_mv.col = 0;
616
Adrian Grange0618ff12010-07-01 14:17:04 +0100617 // Test last reference frame using the previous best mv as the
618 // starting point (best reference) for the search
Scott LaVarnway6b255012011-05-12 10:50:16 -0400619 first_pass_motion_search(cpi, x, &best_ref_mv,
Fritz Koenig0ce39012010-07-22 08:07:32 -0400620 &d->bmi.mv.as_mv, lst_yv12,
Adrian Grange0618ff12010-07-01 14:17:04 +0100621 &motion_error, recon_yoffset);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400622
623 // If the current best reference mv is not centred on 0,0 then do a 0,0 based search as well
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500624 if (best_ref_mv.as_int)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400625 {
626 tmp_err = INT_MAX;
John Koleszar429dc672011-03-17 17:07:59 -0400627 first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv,
Fritz Koenig0ce39012010-07-22 08:07:32 -0400628 lst_yv12, &tmp_err, recon_yoffset);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400629
630 if ( tmp_err < motion_error )
631 {
632 motion_error = tmp_err;
633 d->bmi.mv.as_mv.row = tmp_mv.row;
634 d->bmi.mv.as_mv.col = tmp_mv.col;
635 }
John Koleszar0ea50ce2010-05-18 11:58:33 -0400636 }
637
638 // Experimental search in a second reference frame ((0,0) based only)
639 if (cm->current_video_frame > 1)
640 {
John Koleszar429dc672011-03-17 17:07:59 -0400641 first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv, gld_yv12, &gf_motion_error, recon_yoffset);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400642
643 if ((gf_motion_error < motion_error) && (gf_motion_error < this_error))
644 {
645 second_ref_count++;
646 //motion_error = gf_motion_error;
647 //d->bmi.mv.as_mv.row = tmp_mv.row;
648 //d->bmi.mv.as_mv.col = tmp_mv.col;
649 }
650 /*else
651 {
652 xd->pre.y_buffer = cm->last_frame.y_buffer + recon_yoffset;
653 xd->pre.u_buffer = cm->last_frame.u_buffer + recon_uvoffset;
654 xd->pre.v_buffer = cm->last_frame.v_buffer + recon_uvoffset;
655 }*/
656
657
658 // Reset to last frame as reference buffer
Fritz Koenig0ce39012010-07-22 08:07:32 -0400659 xd->pre.y_buffer = lst_yv12->y_buffer + recon_yoffset;
660 xd->pre.u_buffer = lst_yv12->u_buffer + recon_uvoffset;
661 xd->pre.v_buffer = lst_yv12->v_buffer + recon_uvoffset;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400662 }
663
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500664 /* Intra assumed best */
665 best_ref_mv.as_int = 0;
666
John Koleszar0ea50ce2010-05-18 11:58:33 -0400667 if (motion_error <= this_error)
668 {
Paul Wilkinsbc9c30a2011-03-07 15:58:07 +0000669 // Keep a count of cases where the inter and intra were
670 // very close and very low. This helps with scene cut
671 // detection for example in cropped clips with black bars
672 // at the sides or top and bottom.
673 if( (((this_error-intrapenalty) * 9) <=
674 (motion_error*10)) &&
675 (this_error < (2*intrapenalty)) )
676 {
677 neutral_count++;
678 }
679
John Koleszar0ea50ce2010-05-18 11:58:33 -0400680 d->bmi.mv.as_mv.row <<= 3;
681 d->bmi.mv.as_mv.col <<= 3;
682 this_error = motion_error;
Scott LaVarnway6b255012011-05-12 10:50:16 -0400683 vp8_set_mbmode_and_mvs(x, NEWMV, &d->bmi.mv);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400684 vp8_encode_inter16x16y(IF_RTCD(&cpi->rtcd), x);
685 sum_mvr += d->bmi.mv.as_mv.row;
686 sum_mvr_abs += abs(d->bmi.mv.as_mv.row);
687 sum_mvc += d->bmi.mv.as_mv.col;
688 sum_mvc_abs += abs(d->bmi.mv.as_mv.col);
689 sum_mvrs += d->bmi.mv.as_mv.row * d->bmi.mv.as_mv.row;
690 sum_mvcs += d->bmi.mv.as_mv.col * d->bmi.mv.as_mv.col;
691 intercount++;
692
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500693 best_ref_mv.as_int = d->bmi.mv.as_int;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400694
695 // Was the vector non-zero
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500696 if (d->bmi.mv.as_int)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400697 {
698 mvcount++;
699
John Koleszar0ea50ce2010-05-18 11:58:33 -0400700 // Does the Row vector point inwards or outwards
701 if (mb_row < cm->mb_rows / 2)
702 {
703 if (d->bmi.mv.as_mv.row > 0)
704 sum_in_vectors--;
705 else if (d->bmi.mv.as_mv.row < 0)
706 sum_in_vectors++;
707 }
708 else if (mb_row > cm->mb_rows / 2)
709 {
710 if (d->bmi.mv.as_mv.row > 0)
711 sum_in_vectors++;
712 else if (d->bmi.mv.as_mv.row < 0)
713 sum_in_vectors--;
714 }
715
716 // Does the Row vector point inwards or outwards
717 if (mb_col < cm->mb_cols / 2)
718 {
719 if (d->bmi.mv.as_mv.col > 0)
720 sum_in_vectors--;
721 else if (d->bmi.mv.as_mv.col < 0)
722 sum_in_vectors++;
723 }
724 else if (mb_col > cm->mb_cols / 2)
725 {
726 if (d->bmi.mv.as_mv.col > 0)
727 sum_in_vectors++;
728 else if (d->bmi.mv.as_mv.col < 0)
729 sum_in_vectors--;
730 }
Adrian Grange1b2f8302010-09-28 15:23:41 +0100731 }
John Koleszar0ea50ce2010-05-18 11:58:33 -0400732 }
John Koleszar0ea50ce2010-05-18 11:58:33 -0400733 }
734
James Zernb45065d2011-07-25 18:44:59 -0700735 coded_error += (int64_t)this_error;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400736
737 // adjust to the next column of macroblocks
738 x->src.y_buffer += 16;
739 x->src.u_buffer += 8;
740 x->src.v_buffer += 8;
741
742 recon_yoffset += 16;
743 recon_uvoffset += 8;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400744 }
745
746 // adjust to the next row of mbs
747 x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
748 x->src.u_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
749 x->src.v_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
750
751 //extend the recon for intra prediction
Fritz Koenig0ce39012010-07-22 08:07:32 -0400752 vp8_extend_mb_row(new_yv12, xd->dst.y_buffer + 16, xd->dst.u_buffer + 8, xd->dst.v_buffer + 8);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400753 vp8_clear_system_state(); //__asm emms;
754 }
755
756 vp8_clear_system_state(); //__asm emms;
757 {
758 double weight = 0.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400759
760 FIRSTPASS_STATS fps;
761
762 fps.frame = cm->current_video_frame ;
763 fps.intra_error = intra_error >> 8;
764 fps.coded_error = coded_error >> 8;
John Koleszar429dc672011-03-17 17:07:59 -0400765 weight = simple_weight(cpi->Source);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400766
Scott LaVarnway3c18a2b2011-01-26 16:42:56 -0500767
John Koleszar0ea50ce2010-05-18 11:58:33 -0400768 if (weight < 0.1)
769 weight = 0.1;
770
771 fps.ssim_weighted_pred_err = fps.coded_error * weight;
772
773 fps.pcnt_inter = 0.0;
774 fps.pcnt_motion = 0.0;
775 fps.MVr = 0.0;
776 fps.mvr_abs = 0.0;
777 fps.MVc = 0.0;
778 fps.mvc_abs = 0.0;
779 fps.MVrv = 0.0;
780 fps.MVcv = 0.0;
781 fps.mv_in_out_count = 0.0;
782 fps.count = 1.0;
783
784 fps.pcnt_inter = 1.0 * (double)intercount / cm->MBs;
785 fps.pcnt_second_ref = 1.0 * (double)second_ref_count / cm->MBs;
Paul Wilkinsbc9c30a2011-03-07 15:58:07 +0000786 fps.pcnt_neutral = 1.0 * (double)neutral_count / cm->MBs;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400787
788 if (mvcount > 0)
789 {
790 fps.MVr = (double)sum_mvr / (double)mvcount;
791 fps.mvr_abs = (double)sum_mvr_abs / (double)mvcount;
792 fps.MVc = (double)sum_mvc / (double)mvcount;
793 fps.mvc_abs = (double)sum_mvc_abs / (double)mvcount;
794 fps.MVrv = ((double)sum_mvrs - (fps.MVr * fps.MVr / (double)mvcount)) / (double)mvcount;
795 fps.MVcv = ((double)sum_mvcs - (fps.MVc * fps.MVc / (double)mvcount)) / (double)mvcount;
796 fps.mv_in_out_count = (double)sum_in_vectors / (double)(mvcount * 2);
797
798 fps.pcnt_motion = 1.0 * (double)mvcount / cpi->common.MBs;
799 }
800
801 // TODO: handle the case when duration is set to 0, or something less
802 // than the full time between subsequent cpi->source_time_stamp s .
John Koleszar88841f12011-04-13 14:00:18 -0400803 fps.duration = cpi->source->ts_end
804 - cpi->source->ts_start;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400805
Adrian Grangeed40ff92011-03-10 11:32:48 -0800806 // don't want to do output stats with a stack variable!
John Koleszar63cb1a72011-05-19 17:16:39 -0400807 memcpy(cpi->twopass.this_frame_stats,
John Koleszarbb7dd5b2010-10-14 16:40:12 -0400808 &fps,
809 sizeof(FIRSTPASS_STATS));
John Koleszar63cb1a72011-05-19 17:16:39 -0400810 output_stats(cpi, cpi->output_pkt_list, cpi->twopass.this_frame_stats);
811 accumulate_stats(cpi->twopass.total_stats, &fps);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400812 }
813
814 // Copy the previous Last Frame into the GF buffer if specific conditions for doing so are met
815 if ((cm->current_video_frame > 0) &&
John Koleszar63cb1a72011-05-19 17:16:39 -0400816 (cpi->twopass.this_frame_stats->pcnt_inter > 0.20) &&
817 ((cpi->twopass.this_frame_stats->intra_error / cpi->twopass.this_frame_stats->coded_error) > 2.0))
John Koleszar0ea50ce2010-05-18 11:58:33 -0400818 {
Fritz Koenig0ce39012010-07-22 08:07:32 -0400819 vp8_yv12_copy_frame_ptr(lst_yv12, gld_yv12);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400820 }
821
822 // swap frame pointers so last frame refers to the frame we just compressed
Fritz Koenig0ce39012010-07-22 08:07:32 -0400823 vp8_swap_yv12_buffer(lst_yv12, new_yv12);
824 vp8_yv12_extend_frame_borders(lst_yv12);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400825
826 // Special case for the first frame. Copy into the GF buffer as a second reference.
827 if (cm->current_video_frame == 0)
828 {
Fritz Koenig0ce39012010-07-22 08:07:32 -0400829 vp8_yv12_copy_frame_ptr(lst_yv12, gld_yv12);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400830 }
831
832
833 // use this to see what the first pass reconstruction looks like
834 if (0)
835 {
836 char filename[512];
837 FILE *recon_file;
838 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
839
840 if (cm->current_video_frame == 0)
841 recon_file = fopen(filename, "wb");
842 else
843 recon_file = fopen(filename, "ab");
844
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700845 if(fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file));
John Koleszar0ea50ce2010-05-18 11:58:33 -0400846 fclose(recon_file);
847 }
848
849 cm->current_video_frame++;
850
851}
852extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
853
Paul Wilkins405499d2011-01-10 16:02:51 +0000854#define BASE_ERRPERMB 150
James Berryf3e9e2a2011-03-10 11:13:44 -0500855static int estimate_max_q(VP8_COMP *cpi, double section_err, int section_target_bandwitdh)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400856{
857 int Q;
James Berryf3e9e2a2011-03-10 11:13:44 -0500858 int num_mbs = cpi->common.MBs;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400859 int target_norm_bits_per_mb;
860
861 double err_per_mb = section_err / num_mbs;
862 double correction_factor;
863 double corr_high;
864 double speed_correction = 1.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400865 double pow_highq = 0.90;
866 double pow_lowq = 0.40;
867
868 if (section_target_bandwitdh <= 0)
John Koleszar63cb1a72011-05-19 17:16:39 -0400869 return cpi->twopass.maxq_max_limit; // Highest value allowed
John Koleszar0ea50ce2010-05-18 11:58:33 -0400870
871 target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20)) ? (512 * section_target_bandwitdh) / num_mbs : 512 * (section_target_bandwitdh / num_mbs);
872
873 // Calculate a corrective factor based on a rolling ratio of bits spent vs target bits
Paul Wilkins744f4822011-08-17 14:14:23 +0100874 if ((cpi->rolling_target_bits > 0) && (cpi->active_worst_quality < cpi->worst_quality))
John Koleszar0ea50ce2010-05-18 11:58:33 -0400875 {
Paul Wilkins744f4822011-08-17 14:14:23 +0100876 double rolling_ratio;
877
John Koleszar0ea50ce2010-05-18 11:58:33 -0400878 rolling_ratio = (double)cpi->rolling_actual_bits / (double)cpi->rolling_target_bits;
879
John Koleszar63cb1a72011-05-19 17:16:39 -0400880 //if ( cpi->twopass.est_max_qcorrection_factor > rolling_ratio )
John Koleszar0ea50ce2010-05-18 11:58:33 -0400881 if (rolling_ratio < 0.95)
John Koleszar63cb1a72011-05-19 17:16:39 -0400882 //cpi->twopass.est_max_qcorrection_factor *= adjustment_rate;
883 cpi->twopass.est_max_qcorrection_factor -= 0.005;
884 //else if ( cpi->twopass.est_max_qcorrection_factor < rolling_ratio )
John Koleszar0ea50ce2010-05-18 11:58:33 -0400885 else if (rolling_ratio > 1.05)
John Koleszar63cb1a72011-05-19 17:16:39 -0400886 cpi->twopass.est_max_qcorrection_factor += 0.005;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400887
John Koleszar63cb1a72011-05-19 17:16:39 -0400888 //cpi->twopass.est_max_qcorrection_factor /= adjustment_rate;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400889
Paul Wilkins11694aa2011-06-28 17:29:47 +0100890 cpi->twopass.est_max_qcorrection_factor =
891 (cpi->twopass.est_max_qcorrection_factor < 0.1)
892 ? 0.1
893 : (cpi->twopass.est_max_qcorrection_factor > 10.0)
894 ? 10.0 : cpi->twopass.est_max_qcorrection_factor;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400895 }
896
897 // Corrections for higher compression speed settings (reduced compression expected)
898 if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1))
899 {
900 if (cpi->oxcf.cpu_used <= 5)
901 speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
902 else
903 speed_correction = 1.25;
904 }
905
906 // Correction factor used for Q values >= 20
907 corr_high = pow(err_per_mb / BASE_ERRPERMB, pow_highq);
Paul Wilkins3af35932011-01-07 16:33:59 +0000908 corr_high = (corr_high < 0.05)
909 ? 0.05 : (corr_high > 5.0) ? 5.0 : corr_high;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400910
Paul Wilkinse0846c92011-01-07 18:29:37 +0000911 // Try and pick a max Q that will be high enough to encode the
Paul Wilkins3af35932011-01-07 16:33:59 +0000912 // content at the given rate.
John Koleszar63cb1a72011-05-19 17:16:39 -0400913 for (Q = cpi->twopass.maxq_min_limit; Q < cpi->twopass.maxq_max_limit; Q++)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400914 {
915 int bits_per_mb_at_this_q;
916
917 if (Q < 50)
918 {
919 correction_factor = pow(err_per_mb / BASE_ERRPERMB, (pow_lowq + Q * 0.01));
920 correction_factor = (correction_factor < 0.05) ? 0.05 : (correction_factor > 5.0) ? 5.0 : correction_factor;
921 }
922 else
923 correction_factor = corr_high;
924
John Koleszar63cb1a72011-05-19 17:16:39 -0400925 bits_per_mb_at_this_q = (int)(.5 + correction_factor
926 * speed_correction * cpi->twopass.est_max_qcorrection_factor
927 * cpi->twopass.section_max_qfactor
928 * (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400929
930 if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
931 break;
932 }
933
Paul Wilkinse0846c92011-01-07 18:29:37 +0000934 // Restriction on active max q for constrained quality mode.
935 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
936 (Q < cpi->cq_target_quality) )
Paul Wilkins55acda92011-01-12 17:08:42 +0000937 //(Q < cpi->oxcf.cq_level;) )
Paul Wilkinse0846c92011-01-07 18:29:37 +0000938 {
939 Q = cpi->cq_target_quality;
Paul Wilkins55acda92011-01-12 17:08:42 +0000940 //Q = cpi->oxcf.cq_level;
Paul Wilkinse0846c92011-01-07 18:29:37 +0000941 }
942
Paul Wilkinscf7c4732011-01-10 16:41:53 +0000943 // Adjust maxq_min_limit and maxq_max_limit limits based on
944 // averaga q observed in clip for non kf/gf.arf frames
945 // Give average a chance to settle though.
946 if ( (cpi->ni_frames >
John Koleszar63cb1a72011-05-19 17:16:39 -0400947 ((unsigned int)cpi->twopass.total_stats->count >> 8)) &&
Paul Wilkinscf7c4732011-01-10 16:41:53 +0000948 (cpi->ni_frames > 150) )
949 {
John Koleszar63cb1a72011-05-19 17:16:39 -0400950 cpi->twopass.maxq_max_limit = ((cpi->ni_av_qi + 32) < cpi->worst_quality)
Paul Wilkinscf7c4732011-01-10 16:41:53 +0000951 ? (cpi->ni_av_qi + 32) : cpi->worst_quality;
John Koleszar63cb1a72011-05-19 17:16:39 -0400952 cpi->twopass.maxq_min_limit = ((cpi->ni_av_qi - 32) > cpi->best_quality)
Paul Wilkinscf7c4732011-01-10 16:41:53 +0000953 ? (cpi->ni_av_qi - 32) : cpi->best_quality;
954 }
955
John Koleszar0ea50ce2010-05-18 11:58:33 -0400956 return Q;
957}
James Berryf3e9e2a2011-03-10 11:13:44 -0500958static int estimate_q(VP8_COMP *cpi, double section_err, int section_target_bandwitdh)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400959{
960 int Q;
James Berryf3e9e2a2011-03-10 11:13:44 -0500961 int num_mbs = cpi->common.MBs;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400962 int target_norm_bits_per_mb;
963
964 double err_per_mb = section_err / num_mbs;
965 double correction_factor;
966 double corr_high;
967 double speed_correction = 1.0;
968 double pow_highq = 0.90;
969 double pow_lowq = 0.40;
970
971 target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20)) ? (512 * section_target_bandwitdh) / num_mbs : 512 * (section_target_bandwitdh / num_mbs);
972
973 // Corrections for higher compression speed settings (reduced compression expected)
974 if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1))
975 {
976 if (cpi->oxcf.cpu_used <= 5)
977 speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
978 else
979 speed_correction = 1.25;
980 }
981
982 // Correction factor used for Q values >= 20
983 corr_high = pow(err_per_mb / BASE_ERRPERMB, pow_highq);
984 corr_high = (corr_high < 0.05) ? 0.05 : (corr_high > 5.0) ? 5.0 : corr_high;
985
986 // Try and pick a Q that can encode the content at the given rate.
987 for (Q = 0; Q < MAXQ; Q++)
988 {
989 int bits_per_mb_at_this_q;
990
991 if (Q < 50)
992 {
993 correction_factor = pow(err_per_mb / BASE_ERRPERMB, (pow_lowq + Q * 0.01));
994 correction_factor = (correction_factor < 0.05) ? 0.05 : (correction_factor > 5.0) ? 5.0 : correction_factor;
995 }
996 else
997 correction_factor = corr_high;
998
John Koleszar63cb1a72011-05-19 17:16:39 -0400999 bits_per_mb_at_this_q = (int)(.5 + correction_factor * speed_correction * cpi->twopass.est_max_qcorrection_factor * (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001000
1001 if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
1002 break;
1003 }
1004
1005 return Q;
1006}
1007
1008// Estimate a worst case Q for a KF group
James Berryf3e9e2a2011-03-10 11:13:44 -05001009static int estimate_kf_group_q(VP8_COMP *cpi, double section_err, int section_target_bandwitdh, double group_iiratio)
John Koleszar0ea50ce2010-05-18 11:58:33 -04001010{
1011 int Q;
James Berryf3e9e2a2011-03-10 11:13:44 -05001012 int num_mbs = cpi->common.MBs;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001013 int target_norm_bits_per_mb = (512 * section_target_bandwitdh) / num_mbs;
1014 int bits_per_mb_at_this_q;
1015
1016 double err_per_mb = section_err / num_mbs;
1017 double err_correction_factor;
1018 double corr_high;
1019 double speed_correction = 1.0;
1020 double current_spend_ratio = 1.0;
1021
1022 double pow_highq = (POW1 < 0.6) ? POW1 + 0.3 : 0.90;
1023 double pow_lowq = (POW1 < 0.7) ? POW1 + 0.1 : 0.80;
1024
1025 double iiratio_correction_factor = 1.0;
1026
1027 double combined_correction_factor;
1028
1029 // Trap special case where the target is <= 0
1030 if (target_norm_bits_per_mb <= 0)
1031 return MAXQ * 2;
1032
1033 // Calculate a corrective factor based on a rolling ratio of bits spent vs target bits
1034 // This is clamped to the range 0.1 to 10.0
1035 if (cpi->long_rolling_target_bits <= 0)
1036 current_spend_ratio = 10.0;
1037 else
1038 {
1039 current_spend_ratio = (double)cpi->long_rolling_actual_bits / (double)cpi->long_rolling_target_bits;
1040 current_spend_ratio = (current_spend_ratio > 10.0) ? 10.0 : (current_spend_ratio < 0.1) ? 0.1 : current_spend_ratio;
1041 }
1042
1043 // Calculate a correction factor based on the quality of prediction in the sequence as indicated by intra_inter error score ratio (IIRatio)
1044 // The idea here is to favour subsampling in the hardest sections vs the easyest.
1045 iiratio_correction_factor = 1.0 - ((group_iiratio - 6.0) * 0.1);
1046
1047 if (iiratio_correction_factor < 0.5)
1048 iiratio_correction_factor = 0.5;
1049
1050 // Corrections for higher compression speed settings (reduced compression expected)
1051 if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1))
1052 {
1053 if (cpi->oxcf.cpu_used <= 5)
1054 speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
1055 else
1056 speed_correction = 1.25;
1057 }
1058
1059 // Combine the various factors calculated above
1060 combined_correction_factor = speed_correction * iiratio_correction_factor * current_spend_ratio;
1061
1062 // Correction factor used for Q values >= 20
1063 corr_high = pow(err_per_mb / BASE_ERRPERMB, pow_highq);
1064 corr_high = (corr_high < 0.05) ? 0.05 : (corr_high > 5.0) ? 5.0 : corr_high;
1065
1066 // Try and pick a Q that should be high enough to encode the content at the given rate.
1067 for (Q = 0; Q < MAXQ; Q++)
1068 {
1069 // Q values < 20 treated as a special case
1070 if (Q < 20)
1071 {
1072 err_correction_factor = pow(err_per_mb / BASE_ERRPERMB, (pow_lowq + Q * 0.01));
1073 err_correction_factor = (err_correction_factor < 0.05) ? 0.05 : (err_correction_factor > 5.0) ? 5.0 : err_correction_factor;
1074 }
1075 else
1076 err_correction_factor = corr_high;
1077
1078 bits_per_mb_at_this_q = (int)(.5 + err_correction_factor * combined_correction_factor * (double)vp8_bits_per_mb[INTER_FRAME][Q]);
1079
1080 if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
1081 break;
1082 }
1083
1084 // If we could not hit the target even at Max Q then estimate what Q would have bee required
1085 while ((bits_per_mb_at_this_q > target_norm_bits_per_mb) && (Q < (MAXQ * 2)))
1086 {
1087
1088 bits_per_mb_at_this_q = (int)(0.96 * bits_per_mb_at_this_q);
1089 Q++;
1090 }
1091
1092 if (0)
1093 {
1094 FILE *f = fopen("estkf_q.stt", "a");
1095 fprintf(f, "%8d %8d %8d %8.2f %8.3f %8.2f %8.3f %8.3f %8.3f %8d\n", cpi->common.current_video_frame, bits_per_mb_at_this_q,
1096 target_norm_bits_per_mb, err_per_mb, err_correction_factor,
1097 current_spend_ratio, group_iiratio, iiratio_correction_factor,
1098 (double)cpi->buffer_level / (double)cpi->oxcf.optimal_buffer_level, Q);
1099 fclose(f);
1100 }
1101
1102 return Q;
1103}
Paul Wilkinse0846c92011-01-07 18:29:37 +00001104
1105// For cq mode estimate a cq level that matches the observed
1106// complexity and data rate.
James Berryf3e9e2a2011-03-10 11:13:44 -05001107static int estimate_cq(VP8_COMP *cpi, double section_err, int section_target_bandwitdh)
Paul Wilkinse0846c92011-01-07 18:29:37 +00001108{
1109 int Q;
James Berryf3e9e2a2011-03-10 11:13:44 -05001110 int num_mbs = cpi->common.MBs;
Paul Wilkinse0846c92011-01-07 18:29:37 +00001111 int target_norm_bits_per_mb;
1112
1113 double err_per_mb = section_err / num_mbs;
1114 double correction_factor;
1115 double corr_high;
1116 double speed_correction = 1.0;
1117 double pow_highq = 0.90;
1118 double pow_lowq = 0.40;
1119 double clip_iiratio;
1120 double clip_iifactor;
1121
1122 target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
1123 ? (512 * section_target_bandwitdh) / num_mbs
1124 : 512 * (section_target_bandwitdh / num_mbs);
1125
1126 // Corrections for higher compression speed settings
1127 // (reduced compression expected)
1128 if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1))
1129 {
1130 if (cpi->oxcf.cpu_used <= 5)
1131 speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
1132 else
1133 speed_correction = 1.25;
1134 }
1135 // II ratio correction factor for clip as a whole
John Koleszar63cb1a72011-05-19 17:16:39 -04001136 clip_iiratio = cpi->twopass.total_stats->intra_error /
1137 DOUBLE_DIVIDE_CHECK(cpi->twopass.total_stats->coded_error);
Paul Wilkinse0846c92011-01-07 18:29:37 +00001138 clip_iifactor = 1.0 - ((clip_iiratio - 10.0) * 0.025);
1139 if (clip_iifactor < 0.80)
1140 clip_iifactor = 0.80;
1141
1142 // Correction factor used for Q values >= 20
1143 corr_high = pow(err_per_mb / BASE_ERRPERMB, pow_highq);
1144 corr_high = (corr_high < 0.05) ? 0.05 : (corr_high > 5.0) ? 5.0 : corr_high;
1145
1146 // Try and pick a Q that can encode the content at the given rate.
1147 for (Q = 0; Q < MAXQ; Q++)
1148 {
1149 int bits_per_mb_at_this_q;
1150
1151 if (Q < 50)
1152 {
1153 correction_factor =
1154 pow( err_per_mb / BASE_ERRPERMB, (pow_lowq + Q * 0.01));
1155
1156 correction_factor = (correction_factor < 0.05) ? 0.05
1157 : (correction_factor > 5.0) ? 5.0
1158 : correction_factor;
1159 }
1160 else
1161 correction_factor = corr_high;
1162
1163 bits_per_mb_at_this_q =
1164 (int)( .5 + correction_factor *
1165 speed_correction *
1166 clip_iifactor *
1167 (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0);
1168
1169 if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
1170 break;
1171 }
1172
1173 return cq_level[Q];
1174}
1175
John Koleszar0ea50ce2010-05-18 11:58:33 -04001176extern void vp8_new_frame_rate(VP8_COMP *cpi, double framerate);
1177
1178void vp8_init_second_pass(VP8_COMP *cpi)
1179{
1180 FIRSTPASS_STATS this_frame;
1181 FIRSTPASS_STATS *start_pos;
1182
1183 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100);
1184
John Koleszar63cb1a72011-05-19 17:16:39 -04001185 zero_stats(cpi->twopass.total_stats);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001186
John Koleszar63cb1a72011-05-19 17:16:39 -04001187 if (!cpi->twopass.stats_in_end)
John Koleszar0ea50ce2010-05-18 11:58:33 -04001188 return;
1189
John Koleszar63cb1a72011-05-19 17:16:39 -04001190 *cpi->twopass.total_stats = *cpi->twopass.stats_in_end;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001191
John Koleszar63cb1a72011-05-19 17:16:39 -04001192 cpi->twopass.total_error_left = cpi->twopass.total_stats->ssim_weighted_pred_err;
1193 cpi->twopass.total_intra_error_left = cpi->twopass.total_stats->intra_error;
1194 cpi->twopass.total_coded_error_left = cpi->twopass.total_stats->coded_error;
1195 cpi->twopass.start_tot_err_left = cpi->twopass.total_error_left;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001196
James Zernb45065d2011-07-25 18:44:59 -07001197 //cpi->twopass.bits_left = (int64_t)(cpi->twopass.total_stats->count * cpi->oxcf.target_bandwidth / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.frame_rate));
1198 //cpi->twopass.bits_left -= (int64_t)(cpi->twopass.total_stats->count * two_pass_min_rate / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.frame_rate));
John Koleszar0ea50ce2010-05-18 11:58:33 -04001199
1200 // each frame can have a different duration, as the frame rate in the source
1201 // isn't guaranteed to be constant. The frame rate prior to the first frame
1202 // encoded in the second pass is a guess. However the sum duration is not.
1203 // Its calculated based on the actual durations of all frames from the first
1204 // pass.
John Koleszar63cb1a72011-05-19 17:16:39 -04001205 vp8_new_frame_rate(cpi, 10000000.0 * cpi->twopass.total_stats->count / cpi->twopass.total_stats->duration);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001206
1207 cpi->output_frame_rate = cpi->oxcf.frame_rate;
James Zernb45065d2011-07-25 18:44:59 -07001208 cpi->twopass.bits_left = (int64_t)(cpi->twopass.total_stats->duration * cpi->oxcf.target_bandwidth / 10000000.0) ;
1209 cpi->twopass.bits_left -= (int64_t)(cpi->twopass.total_stats->duration * two_pass_min_rate / 10000000.0);
John Koleszar63cb1a72011-05-19 17:16:39 -04001210 cpi->twopass.clip_bits_total = cpi->twopass.bits_left;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001211
Paul Wilkinsb095d9d2011-01-04 17:55:49 +00001212 // Calculate a minimum intra value to be used in determining the IIratio
1213 // scores used in the second pass. We have this minimum to make sure
1214 // that clips that are static but "low complexity" in the intra domain
1215 // are still boosted appropriately for KF/GF/ARF
John Koleszar63cb1a72011-05-19 17:16:39 -04001216 cpi->twopass.kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
1217 cpi->twopass.gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
Paul Wilkinsb095d9d2011-01-04 17:55:49 +00001218
John Koleszar63cb1a72011-05-19 17:16:39 -04001219 avg_stats(cpi->twopass.total_stats);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001220
1221 // Scan the first pass file and calculate an average Intra / Inter error score ratio for the sequence
1222 {
1223 double sum_iiratio = 0.0;
1224 double IIRatio;
1225
John Koleszar63cb1a72011-05-19 17:16:39 -04001226 start_pos = cpi->twopass.stats_in; // Note starting "file" position
John Koleszar0ea50ce2010-05-18 11:58:33 -04001227
John Koleszar429dc672011-03-17 17:07:59 -04001228 while (input_stats(cpi, &this_frame) != EOF)
John Koleszar0ea50ce2010-05-18 11:58:33 -04001229 {
1230 IIRatio = this_frame.intra_error / DOUBLE_DIVIDE_CHECK(this_frame.coded_error);
1231 IIRatio = (IIRatio < 1.0) ? 1.0 : (IIRatio > 20.0) ? 20.0 : IIRatio;
1232 sum_iiratio += IIRatio;
1233 }
1234
John Koleszar63cb1a72011-05-19 17:16:39 -04001235 cpi->twopass.avg_iiratio = sum_iiratio / DOUBLE_DIVIDE_CHECK((double)cpi->twopass.total_stats->count);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001236
1237 // Reset file position
1238 reset_fpf_position(cpi, start_pos);
1239 }
1240
1241 // Scan the first pass file and calculate a modified total error based upon the bias/power function
1242 // used to allocate bits
1243 {
John Koleszar63cb1a72011-05-19 17:16:39 -04001244 start_pos = cpi->twopass.stats_in; // Note starting "file" position
John Koleszar0ea50ce2010-05-18 11:58:33 -04001245
John Koleszar63cb1a72011-05-19 17:16:39 -04001246 cpi->twopass.modified_error_total = 0.0;
1247 cpi->twopass.modified_error_used = 0.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001248
John Koleszar429dc672011-03-17 17:07:59 -04001249 while (input_stats(cpi, &this_frame) != EOF)
John Koleszar0ea50ce2010-05-18 11:58:33 -04001250 {
John Koleszar63cb1a72011-05-19 17:16:39 -04001251 cpi->twopass.modified_error_total += calculate_modified_err(cpi, &this_frame);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001252 }
John Koleszar63cb1a72011-05-19 17:16:39 -04001253 cpi->twopass.modified_error_left = cpi->twopass.modified_error_total;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001254
1255 reset_fpf_position(cpi, start_pos); // Reset file position
1256
1257 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04001258}
1259
1260void vp8_end_second_pass(VP8_COMP *cpi)
1261{
John Koleszar0ea50ce2010-05-18 11:58:33 -04001262}
1263
Paul Wilkins0cdfef12011-01-21 17:52:00 +00001264// This function gives and estimate of how badly we believe
Adrian Grangeed40ff92011-03-10 11:32:48 -08001265// the prediction quality is decaying from frame to frame.
John Koleszar429dc672011-03-17 17:07:59 -04001266static double get_prediction_decay_rate(VP8_COMP *cpi, FIRSTPASS_STATS *next_frame)
Paul Wilkins0cdfef12011-01-21 17:52:00 +00001267{
1268 double prediction_decay_rate;
1269 double motion_decay;
1270 double motion_pct = next_frame->pcnt_motion;
1271
Paul Wilkins0cdfef12011-01-21 17:52:00 +00001272 // Initial basis is the % mbs inter coded
1273 prediction_decay_rate = next_frame->pcnt_inter;
1274
1275 // High % motion -> somewhat higher decay rate
1276 motion_decay = (1.0 - (motion_pct / 20.0));
1277 if (motion_decay < prediction_decay_rate)
1278 prediction_decay_rate = motion_decay;
1279
1280 // Adjustment to decay rate based on speed of motion
1281 {
1282 double this_mv_rabs;
1283 double this_mv_cabs;
1284 double distance_factor;
1285
1286 this_mv_rabs = fabs(next_frame->mvr_abs * motion_pct);
1287 this_mv_cabs = fabs(next_frame->mvc_abs * motion_pct);
1288
1289 distance_factor = sqrt((this_mv_rabs * this_mv_rabs) +
1290 (this_mv_cabs * this_mv_cabs)) / 250.0;
1291 distance_factor = ((distance_factor > 1.0)
1292 ? 0.0 : (1.0 - distance_factor));
1293 if (distance_factor < prediction_decay_rate)
1294 prediction_decay_rate = distance_factor;
1295 }
1296
1297 return prediction_decay_rate;
1298}
Paul Wilkinsbc9c30a2011-03-07 15:58:07 +00001299
Paul Wilkinsde87c422011-03-08 14:46:22 +00001300// Function to test for a condition where a complex transition is followed
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00001301// by a static section. For example in slide shows where there is a fade
1302// between slides. This is to help with more optimal kf and gf positioning.
John Koleszar429dc672011-03-17 17:07:59 -04001303static int detect_transition_to_still(
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00001304 VP8_COMP *cpi,
1305 int frame_interval,
1306 int still_interval,
1307 double loop_decay_rate,
1308 double decay_accumulator )
1309{
1310 BOOL trans_to_still = FALSE;
1311
1312 // Break clause to detect very still sections after motion
Paul Wilkinsde87c422011-03-08 14:46:22 +00001313 // For example a static image after a fade or other transition
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00001314 // instead of a clean scene cut.
1315 if ( (frame_interval > MIN_GF_INTERVAL) &&
1316 (loop_decay_rate >= 0.999) &&
1317 (decay_accumulator < 0.9) )
1318 {
1319 int j;
John Koleszar63cb1a72011-05-19 17:16:39 -04001320 FIRSTPASS_STATS * position = cpi->twopass.stats_in;
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00001321 FIRSTPASS_STATS tmp_next_frame;
1322 double decay_rate;
1323
1324 // Look ahead a few frames to see if static condition
1325 // persists...
1326 for ( j = 0; j < still_interval; j++ )
1327 {
John Koleszar429dc672011-03-17 17:07:59 -04001328 if (EOF == input_stats(cpi, &tmp_next_frame))
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00001329 break;
1330
1331 decay_rate = get_prediction_decay_rate(cpi, &tmp_next_frame);
1332 if ( decay_rate < 0.999 )
1333 break;
1334 }
1335 // Reset file position
1336 reset_fpf_position(cpi, position);
1337
1338 // Only if it does do we signal a transition to still
1339 if ( j == still_interval )
1340 trans_to_still = TRUE;
1341 }
1342
1343 return trans_to_still;
1344}
Paul Wilkins0cdfef12011-01-21 17:52:00 +00001345
Paul Wilkins11694aa2011-06-28 17:29:47 +01001346// This function detects a flash through the high relative pcnt_second_ref
1347// score in the frame following a flash frame. The offset passed in should
1348// reflect this
1349static BOOL detect_flash( VP8_COMP *cpi, int offset )
1350{
1351 FIRSTPASS_STATS next_frame;
1352
1353 BOOL flash_detected = FALSE;
1354
1355 // Read the frame data.
1356 // The return is FALSE (no flash detected) if not a valid frame
1357 if ( read_frame_stats(cpi, &next_frame, offset) != EOF )
1358 {
1359 // What we are looking for here is a situation where there is a
1360 // brief break in prediction (such as a flash) but subsequent frames
1361 // are reasonably well predicted by an earlier (pre flash) frame.
1362 // The recovery after a flash is indicated by a high pcnt_second_ref
1363 // comapred to pcnt_inter.
1364 if ( (next_frame.pcnt_second_ref > next_frame.pcnt_inter) &&
1365 (next_frame.pcnt_second_ref >= 0.5 ) )
1366 {
1367 flash_detected = TRUE;
1368
1369 /*if (1)
1370 {
1371 FILE *f = fopen("flash.stt", "a");
1372 fprintf(f, "%8.0f %6.2f %6.2f\n",
1373 next_frame.frame,
1374 next_frame.pcnt_inter,
1375 next_frame.pcnt_second_ref);
1376 fclose(f);
1377 }*/
1378 }
1379 }
1380
1381 return flash_detected;
1382}
1383
1384// Update the motion related elements to the GF arf boost calculation
1385static void accumulate_frame_motion_stats(
1386 VP8_COMP *cpi,
1387 FIRSTPASS_STATS * this_frame,
1388 double * this_frame_mv_in_out,
1389 double * mv_in_out_accumulator,
1390 double * abs_mv_in_out_accumulator,
1391 double * mv_ratio_accumulator )
1392{
1393 //double this_frame_mv_in_out;
1394 double this_frame_mvr_ratio;
1395 double this_frame_mvc_ratio;
1396 double motion_pct;
1397
1398 // Accumulate motion stats.
1399 motion_pct = this_frame->pcnt_motion;
1400
1401 // Accumulate Motion In/Out of frame stats
1402 *this_frame_mv_in_out = this_frame->mv_in_out_count * motion_pct;
1403 *mv_in_out_accumulator += this_frame->mv_in_out_count * motion_pct;
1404 *abs_mv_in_out_accumulator +=
1405 fabs(this_frame->mv_in_out_count * motion_pct);
1406
1407 // Accumulate a measure of how uniform (or conversely how random)
1408 // the motion field is. (A ratio of absmv / mv)
1409 if (motion_pct > 0.05)
1410 {
1411 this_frame_mvr_ratio = fabs(this_frame->mvr_abs) /
1412 DOUBLE_DIVIDE_CHECK(fabs(this_frame->MVr));
1413
1414 this_frame_mvc_ratio = fabs(this_frame->mvc_abs) /
1415 DOUBLE_DIVIDE_CHECK(fabs(this_frame->MVc));
1416
1417 *mv_ratio_accumulator +=
1418 (this_frame_mvr_ratio < this_frame->mvr_abs)
1419 ? (this_frame_mvr_ratio * motion_pct)
1420 : this_frame->mvr_abs * motion_pct;
1421
1422 *mv_ratio_accumulator +=
1423 (this_frame_mvc_ratio < this_frame->mvc_abs)
1424 ? (this_frame_mvc_ratio * motion_pct)
1425 : this_frame->mvc_abs * motion_pct;
1426
1427 }
1428}
1429
1430// Calculate a baseline boost number for the current frame.
1431static double calc_frame_boost(
1432 VP8_COMP *cpi,
1433 FIRSTPASS_STATS * this_frame,
1434 double this_frame_mv_in_out )
1435{
1436 double frame_boost;
1437
1438 // Underlying boost factor is based on inter intra error ratio
1439 if (this_frame->intra_error > cpi->twopass.gf_intra_err_min)
1440 frame_boost = (IIFACTOR * this_frame->intra_error /
1441 DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1442 else
1443 frame_boost = (IIFACTOR * cpi->twopass.gf_intra_err_min /
1444 DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
1445
1446 // Increase boost for frames where new data coming into frame
1447 // (eg zoom out). Slightly reduce boost if there is a net balance
1448 // of motion out of the frame (zoom in).
1449 // The range for this_frame_mv_in_out is -1.0 to +1.0
1450 if (this_frame_mv_in_out > 0.0)
1451 frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
1452 // In extreme case boost is halved
1453 else
1454 frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
1455
1456 // Clip to maximum
1457 if (frame_boost > GF_RMAX)
1458 frame_boost = GF_RMAX;
1459
1460 return frame_boost;
1461}
1462
1463#if NEW_BOOST
1464static int calc_arf_boost(
1465 VP8_COMP *cpi,
1466 int offset,
1467 int f_frames,
1468 int b_frames,
1469 int *f_boost,
1470 int *b_boost )
1471{
1472 FIRSTPASS_STATS this_frame;
1473
1474 int i;
1475 double boost_score = 0.0;
1476 double fwd_boost_score = 0.0;
1477 double mv_ratio_accumulator = 0.0;
1478 double decay_accumulator = 1.0;
1479 double this_frame_mv_in_out = 0.0;
1480 double mv_in_out_accumulator = 0.0;
1481 double abs_mv_in_out_accumulator = 0.0;
1482 double r;
1483 BOOL flash_detected = FALSE;
1484
1485 // Search forward from the proposed arf/next gf position
1486 for ( i = 0; i < f_frames; i++ )
1487 {
1488 if ( read_frame_stats(cpi, &this_frame, (i+offset)) == EOF )
1489 break;
1490
1491 // Update the motion related elements to the boost calculation
1492 accumulate_frame_motion_stats( cpi, &this_frame,
1493 &this_frame_mv_in_out, &mv_in_out_accumulator,
1494 &abs_mv_in_out_accumulator, &mv_ratio_accumulator );
1495
1496 // Calculate the baseline boost number for this frame
1497 r = calc_frame_boost( cpi, &this_frame, this_frame_mv_in_out );
1498
1499 // We want to discount the the flash frame itself and the recovery
1500 // frame that follows as both will have poor scores.
1501 flash_detected = detect_flash(cpi, (i+offset)) ||
1502 detect_flash(cpi, (i+offset+1));
1503
1504 // Cumulative effect of prediction quality decay
1505 if ( !flash_detected )
1506 {
1507 decay_accumulator =
1508 decay_accumulator *
1509 get_prediction_decay_rate(cpi, &this_frame);
1510 decay_accumulator =
1511 decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
1512 }
1513 boost_score += (decay_accumulator * r);
1514
1515 // Break out conditions.
1516 if ( (!flash_detected) &&
1517 ((mv_ratio_accumulator > 100.0) ||
1518 (abs_mv_in_out_accumulator > 3.0) ||
1519 (mv_in_out_accumulator < -2.0) ) )
1520 {
1521 break;
1522 }
1523 }
1524
1525 *f_boost = (int)(boost_score * 100.0) >> 4;
1526
1527 // Reset for backward looking loop
1528 boost_score = 0.0;
1529 mv_ratio_accumulator = 0.0;
1530 decay_accumulator = 1.0;
1531 this_frame_mv_in_out = 0.0;
1532 mv_in_out_accumulator = 0.0;
1533 abs_mv_in_out_accumulator = 0.0;
1534
1535 // Search forward from the proposed arf/next gf position
1536 for ( i = -1; i >= -b_frames; i-- )
1537 {
1538 if ( read_frame_stats(cpi, &this_frame, (i+offset)) == EOF )
1539 break;
1540
1541 // Update the motion related elements to the boost calculation
1542 accumulate_frame_motion_stats( cpi, &this_frame,
1543 &this_frame_mv_in_out, &mv_in_out_accumulator,
1544 &abs_mv_in_out_accumulator, &mv_ratio_accumulator );
1545
1546 // Calculate the baseline boost number for this frame
1547 r = calc_frame_boost( cpi, &this_frame, this_frame_mv_in_out );
1548
1549 // We want to discount the the flash frame itself and the recovery
1550 // frame that follows as both will have poor scores.
1551 flash_detected = detect_flash(cpi, (i+offset)) ||
1552 detect_flash(cpi, (i+offset+1));
1553
1554 // Cumulative effect of prediction quality decay
1555 if ( !flash_detected )
1556 {
1557 decay_accumulator =
1558 decay_accumulator *
1559 get_prediction_decay_rate(cpi, &this_frame);
1560 decay_accumulator =
1561 decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
1562 }
1563
1564 boost_score += (decay_accumulator * r);
1565
1566 // Break out conditions.
1567 if ( (!flash_detected) &&
1568 ((mv_ratio_accumulator > 100.0) ||
1569 (abs_mv_in_out_accumulator > 3.0) ||
1570 (mv_in_out_accumulator < -2.0) ) )
1571 {
1572 break;
1573 }
1574 }
1575 *b_boost = (int)(boost_score * 100.0) >> 4;
1576
1577 return (*f_boost + *b_boost);
1578}
1579#endif
1580
John Koleszar0ea50ce2010-05-18 11:58:33 -04001581// Analyse and define a gf/arf group .
1582static void define_gf_group(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame)
1583{
1584 FIRSTPASS_STATS next_frame;
1585 FIRSTPASS_STATS *start_pos;
1586 int i;
Paul Wilkins11694aa2011-06-28 17:29:47 +01001587 double r;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001588 double boost_score = 0.0;
1589 double old_boost_score = 0.0;
1590 double gf_group_err = 0.0;
1591 double gf_first_frame_err = 0.0;
1592 double mod_frame_err = 0.0;
1593
John Koleszar0ea50ce2010-05-18 11:58:33 -04001594 double mv_ratio_accumulator = 0.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001595 double decay_accumulator = 1.0;
1596
Paul Wilkins80645832011-01-20 18:01:20 +00001597 double loop_decay_rate = 1.00; // Starting decay rate
John Koleszar0ea50ce2010-05-18 11:58:33 -04001598
1599 double this_frame_mv_in_out = 0.0;
1600 double mv_in_out_accumulator = 0.0;
1601 double abs_mv_in_out_accumulator = 0.0;
1602 double mod_err_per_mb_accumulator = 0.0;
1603
John Koleszare9613172011-08-12 14:51:36 -04001604 int max_bits = frame_max_bits(cpi); // Max for a single frame
John Koleszar0ea50ce2010-05-18 11:58:33 -04001605
Paul Wilkins80645832011-01-20 18:01:20 +00001606 unsigned int allow_alt_ref =
1607 cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames;
1608
Paul Wilkins11694aa2011-06-28 17:29:47 +01001609 int alt_boost = 0;
1610 int f_boost = 0;
1611 int b_boost = 0;
1612 BOOL flash_detected;
1613
John Koleszar63cb1a72011-05-19 17:16:39 -04001614 cpi->twopass.gf_group_bits = 0;
1615 cpi->twopass.gf_decay_rate = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001616
1617 vp8_clear_system_state(); //__asm emms;
1618
John Koleszar63cb1a72011-05-19 17:16:39 -04001619 start_pos = cpi->twopass.stats_in;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001620
Guillermo Ballester Valor5a726202010-06-11 14:33:49 -04001621 vpx_memset(&next_frame, 0, sizeof(next_frame)); // assure clean
1622
Paul Wilkins11694aa2011-06-28 17:29:47 +01001623 // Load stats for the current frame.
John Koleszar0ea50ce2010-05-18 11:58:33 -04001624 mod_frame_err = calculate_modified_err(cpi, this_frame);
1625
Paul Wilkins80645832011-01-20 18:01:20 +00001626 // Note the error of the frame at the start of the group (this will be
1627 // the GF frame error if we code a normal gf
John Koleszar0ea50ce2010-05-18 11:58:33 -04001628 gf_first_frame_err = mod_frame_err;
1629
Paul Wilkins80645832011-01-20 18:01:20 +00001630 // Special treatment if the current frame is a key frame (which is also
1631 // a gf). If it is then its error score (and hence bit allocation) need
1632 // to be subtracted out from the calculation for the GF group
John Koleszar0ea50ce2010-05-18 11:58:33 -04001633 if (cpi->common.frame_type == KEY_FRAME)
1634 gf_group_err -= gf_first_frame_err;
1635
Paul Wilkins80645832011-01-20 18:01:20 +00001636 // Scan forward to try and work out how many frames the next gf group
1637 // should contain and what level of boost is appropriate for the GF
1638 // or ARF that will be coded with the group
John Koleszar0ea50ce2010-05-18 11:58:33 -04001639 i = 0;
1640
John Koleszar63cb1a72011-05-19 17:16:39 -04001641 while (((i < cpi->twopass.static_scene_max_gf_interval) ||
1642 ((cpi->twopass.frames_to_key - i) < MIN_GF_INTERVAL)) &&
1643 (i < cpi->twopass.frames_to_key))
John Koleszar0ea50ce2010-05-18 11:58:33 -04001644 {
Paul Wilkins80645832011-01-20 18:01:20 +00001645 i++; // Increment the loop counter
John Koleszar0ea50ce2010-05-18 11:58:33 -04001646
1647 // Accumulate error score of frames in this gf group
1648 mod_frame_err = calculate_modified_err(cpi, this_frame);
1649
1650 gf_group_err += mod_frame_err;
1651
Paul Wilkins80645832011-01-20 18:01:20 +00001652 mod_err_per_mb_accumulator +=
1653 mod_frame_err / DOUBLE_DIVIDE_CHECK((double)cpi->common.MBs);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001654
John Koleszar429dc672011-03-17 17:07:59 -04001655 if (EOF == input_stats(cpi, &next_frame))
John Koleszar0ea50ce2010-05-18 11:58:33 -04001656 break;
1657
Paul Wilkins11694aa2011-06-28 17:29:47 +01001658 // Test for the case where there is a brief flash but the prediction
1659 // quality back to an earlier frame is then restored.
1660 flash_detected = detect_flash(cpi, 0);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001661
Paul Wilkins11694aa2011-06-28 17:29:47 +01001662 // Update the motion related elements to the boost calculation
1663 accumulate_frame_motion_stats( cpi, &next_frame,
1664 &this_frame_mv_in_out, &mv_in_out_accumulator,
1665 &abs_mv_in_out_accumulator, &mv_ratio_accumulator );
John Koleszar0ea50ce2010-05-18 11:58:33 -04001666
Paul Wilkins11694aa2011-06-28 17:29:47 +01001667 // Calculate a baseline boost number for this frame
1668 r = calc_frame_boost( cpi, &next_frame, this_frame_mv_in_out );
1669
1670 // Cumulative effect of prediction quality decay
1671 if ( !flash_detected )
John Koleszar0ea50ce2010-05-18 11:58:33 -04001672 {
Paul Wilkins11694aa2011-06-28 17:29:47 +01001673 loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
1674 decay_accumulator = decay_accumulator * loop_decay_rate;
1675 decay_accumulator =
1676 decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001677 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04001678 boost_score += (decay_accumulator * r);
1679
Paul Wilkins80645832011-01-20 18:01:20 +00001680 // Break clause to detect very still sections after motion
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00001681 // For example a staic image after a fade or other transition.
1682 if ( detect_transition_to_still( cpi, i, 5,
Paul Wilkins11694aa2011-06-28 17:29:47 +01001683 loop_decay_rate,
1684 decay_accumulator ) )
Paul Wilkins80645832011-01-20 18:01:20 +00001685 {
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00001686 allow_alt_ref = FALSE;
1687 boost_score = old_boost_score;
1688 break;
Paul Wilkins80645832011-01-20 18:01:20 +00001689 }
1690
John Koleszar0ea50ce2010-05-18 11:58:33 -04001691 // Break out conditions.
Paul Wilkins11694aa2011-06-28 17:29:47 +01001692 if (
Paul Wilkins57136a22011-01-18 15:19:05 +00001693 // Break at cpi->max_gf_interval unless almost totally static
Paul Wilkins80645832011-01-20 18:01:20 +00001694 (i >= cpi->max_gf_interval && (decay_accumulator < 0.995)) ||
John Koleszar0ea50ce2010-05-18 11:58:33 -04001695 (
Paul Wilkins57136a22011-01-18 15:19:05 +00001696 // Dont break out with a very short interval
1697 (i > MIN_GF_INTERVAL) &&
1698 // Dont break out very close to a key frame
John Koleszar63cb1a72011-05-19 17:16:39 -04001699 ((cpi->twopass.frames_to_key - i) >= MIN_GF_INTERVAL) &&
John Koleszar0ea50ce2010-05-18 11:58:33 -04001700 ((boost_score > 20.0) || (next_frame.pcnt_inter < 0.75)) &&
Paul Wilkins11694aa2011-06-28 17:29:47 +01001701 (!flash_detected) &&
John Koleszar0ea50ce2010-05-18 11:58:33 -04001702 ((mv_ratio_accumulator > 100.0) ||
1703 (abs_mv_in_out_accumulator > 3.0) ||
1704 (mv_in_out_accumulator < -2.0) ||
Paul Wilkins57136a22011-01-18 15:19:05 +00001705 ((boost_score - old_boost_score) < 2.0))
1706 ) )
John Koleszar0ea50ce2010-05-18 11:58:33 -04001707 {
1708 boost_score = old_boost_score;
1709 break;
1710 }
1711
1712 vpx_memcpy(this_frame, &next_frame, sizeof(*this_frame));
1713
1714 old_boost_score = boost_score;
1715 }
1716
John Koleszar63cb1a72011-05-19 17:16:39 -04001717 cpi->twopass.gf_decay_rate =
Paul Wilkins80645832011-01-20 18:01:20 +00001718 (i > 0) ? (int)(100.0 * (1.0 - decay_accumulator)) / i : 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001719
1720 // When using CBR apply additional buffer related upper limits
1721 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
1722 {
1723 double max_boost;
1724
1725 // For cbr apply buffer related limits
1726 if (cpi->drop_frames_allowed)
1727 {
Paul Wilkins80645832011-01-20 18:01:20 +00001728 int df_buffer_level = cpi->oxcf.drop_frames_water_mark *
1729 (cpi->oxcf.optimal_buffer_level / 100);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001730
1731 if (cpi->buffer_level > df_buffer_level)
1732 max_boost = ((double)((cpi->buffer_level - df_buffer_level) * 2 / 3) * 16.0) / DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
1733 else
1734 max_boost = 0.0;
1735 }
1736 else if (cpi->buffer_level > 0)
1737 {
1738 max_boost = ((double)(cpi->buffer_level * 2 / 3) * 16.0) / DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
1739 }
1740 else
1741 {
1742 max_boost = 0.0;
1743 }
1744
1745 if (boost_score > max_boost)
1746 boost_score = max_boost;
1747 }
1748
Ronald S. Bultje9f002be2011-06-02 09:14:51 -07001749 // Dont allow conventional gf too near the next kf
1750 if ((cpi->twopass.frames_to_key - i) < MIN_GF_INTERVAL)
1751 {
1752 while (i < cpi->twopass.frames_to_key)
1753 {
1754 i++;
1755
1756 if (EOF == input_stats(cpi, this_frame))
1757 break;
1758
1759 if (i < cpi->twopass.frames_to_key)
1760 {
1761 mod_frame_err = calculate_modified_err(cpi, this_frame);
1762 gf_group_err += mod_frame_err;
1763 }
1764 }
1765 }
1766
Paul Wilkins11694aa2011-06-28 17:29:47 +01001767 cpi->gfu_boost = (int)(boost_score * 100.0) >> 4;
1768
1769#if NEW_BOOST
1770 // Alterrnative boost calculation for alt ref
1771 alt_boost = calc_arf_boost( cpi, 0, (i-1), (i-1), &f_boost, &b_boost );
1772#endif
1773
John Koleszar0ea50ce2010-05-18 11:58:33 -04001774 // Should we use the alternate refernce frame
Paul Wilkins80645832011-01-20 18:01:20 +00001775 if (allow_alt_ref &&
John Koleszar0ea50ce2010-05-18 11:58:33 -04001776 (i >= MIN_GF_INTERVAL) &&
Paul Wilkins80645832011-01-20 18:01:20 +00001777 // dont use ARF very near next kf
John Koleszar63cb1a72011-05-19 17:16:39 -04001778 (i <= (cpi->twopass.frames_to_key - MIN_GF_INTERVAL)) &&
Paul Wilkins11694aa2011-06-28 17:29:47 +01001779#if NEW_BOOST
1780 ((next_frame.pcnt_inter > 0.75) ||
1781 (next_frame.pcnt_second_ref > 0.5)) &&
1782 ((mv_in_out_accumulator / (double)i > -0.2) ||
1783 (mv_in_out_accumulator > -2.0)) &&
1784 (b_boost > 100) &&
1785 (f_boost > 100) )
1786#else
1787 (next_frame.pcnt_inter > 0.75) &&
1788 ((mv_in_out_accumulator / (double)i > -0.2) ||
1789 (mv_in_out_accumulator > -2.0)) &&
1790 (cpi->gfu_boost > 100) &&
1791 (cpi->twopass.gf_decay_rate <=
1792 (ARF_DECAY_THRESH + (cpi->gfu_boost / 200))) )
1793#endif
John Koleszar0ea50ce2010-05-18 11:58:33 -04001794 {
1795 int Boost;
1796 int allocation_chunks;
Paul Wilkins11694aa2011-06-28 17:29:47 +01001797 int Q = (cpi->oxcf.fixed_q < 0)
1798 ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001799 int tmp_q;
1800 int arf_frame_bits = 0;
1801 int group_bits;
1802
Paul Wilkins11694aa2011-06-28 17:29:47 +01001803#if NEW_BOOST
1804 cpi->gfu_boost = alt_boost;
1805#endif
1806
John Koleszar0ea50ce2010-05-18 11:58:33 -04001807 // Estimate the bits to be allocated to the group as a whole
Paul Wilkins11694aa2011-06-28 17:29:47 +01001808 if ((cpi->twopass.kf_group_bits > 0) &&
1809 (cpi->twopass.kf_group_error_left > 0))
1810 {
1811 group_bits = (int)((double)cpi->twopass.kf_group_bits *
1812 (gf_group_err / (double)cpi->twopass.kf_group_error_left));
1813 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04001814 else
1815 group_bits = 0;
1816
1817 // Boost for arf frame
Paul Wilkins11694aa2011-06-28 17:29:47 +01001818#if NEW_BOOST
1819 Boost = (alt_boost * GFQ_ADJUSTMENT) / 100;
1820#else
John Koleszar0ea50ce2010-05-18 11:58:33 -04001821 Boost = (cpi->gfu_boost * 3 * GFQ_ADJUSTMENT) / (2 * 100);
Paul Wilkins11694aa2011-06-28 17:29:47 +01001822#endif
Paul Wilkins513f8e62010-11-10 10:09:45 +00001823 Boost += (i * 50);
Paul Wilkins11694aa2011-06-28 17:29:47 +01001824
1825 // Set max and minimum boost and hence minimum allocation
1826 if (Boost > ((cpi->baseline_gf_interval + 1) * 200))
1827 Boost = ((cpi->baseline_gf_interval + 1) * 200);
1828 else if (Boost < 125)
1829 Boost = 125;
1830
John Koleszar0ea50ce2010-05-18 11:58:33 -04001831 allocation_chunks = (i * 100) + Boost;
1832
1833 // Normalize Altboost and allocations chunck down to prevent overflow
1834 while (Boost > 1000)
1835 {
1836 Boost /= 2;
1837 allocation_chunks /= 2;
1838 }
1839
Paul Wilkins11694aa2011-06-28 17:29:47 +01001840 // Calculate the number of bits to be spent on the arf based on the
1841 // boost number
1842 arf_frame_bits = (int)((double)Boost * (group_bits /
1843 (double)allocation_chunks));
John Koleszar0ea50ce2010-05-18 11:58:33 -04001844
Paul Wilkins11694aa2011-06-28 17:29:47 +01001845 // Estimate if there are enough bits available to make worthwhile use
1846 // of an arf.
James Berryf3e9e2a2011-03-10 11:13:44 -05001847 tmp_q = estimate_q(cpi, mod_frame_err, (int)arf_frame_bits);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001848
Paul Wilkins11694aa2011-06-28 17:29:47 +01001849 // Only use an arf if it is likely we will be able to code
1850 // it at a lower Q than the surrounding frames.
John Koleszar0ea50ce2010-05-18 11:58:33 -04001851 if (tmp_q < cpi->worst_quality)
1852 {
Adrian Grange1b2f8302010-09-28 15:23:41 +01001853 int half_gf_int;
1854 int frames_after_arf;
1855 int frames_bwd = cpi->oxcf.arnr_max_frames - 1;
1856 int frames_fwd = cpi->oxcf.arnr_max_frames - 1;
1857
John Koleszar0ea50ce2010-05-18 11:58:33 -04001858 cpi->source_alt_ref_pending = TRUE;
1859
Paul Wilkins11694aa2011-06-28 17:29:47 +01001860 // For alt ref frames the error score for the end frame of the
1861 // group (the alt ref frame) should not contribute to the group
1862 // total and hence the number of bit allocated to the group.
1863 // Rather it forms part of the next group (it is the GF at the
1864 // start of the next group)
1865 // gf_group_err -= mod_frame_err;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001866
Paul Wilkins11694aa2011-06-28 17:29:47 +01001867 // For alt ref frames alt ref frame is technically part of the
1868 // GF frame for the next group but we always base the error
1869 // calculation and bit allocation on the current group of frames.
1870
1871 // Set the interval till the next gf or arf.
1872 // For ARFs this is the number of frames to be coded before the
1873 // future frame that is coded as an ARF.
John Koleszar0ea50ce2010-05-18 11:58:33 -04001874 // The future frame itself is part of the next group
Paul Wilkins11694aa2011-06-28 17:29:47 +01001875 cpi->baseline_gf_interval = i;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001876
Adrian Grange1b2f8302010-09-28 15:23:41 +01001877 // Define the arnr filter width for this group of frames:
1878 // We only filter frames that lie within a distance of half
1879 // the GF interval from the ARF frame. We also have to trap
1880 // cases where the filter extends beyond the end of clip.
1881 // Note: this_frame->frame has been updated in the loop
1882 // so it now points at the ARF frame.
1883 half_gf_int = cpi->baseline_gf_interval >> 1;
Paul Wilkins11694aa2011-06-28 17:29:47 +01001884 frames_after_arf = cpi->twopass.total_stats->count -
1885 this_frame->frame - 1;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001886
Adrian Grange1b2f8302010-09-28 15:23:41 +01001887 switch (cpi->oxcf.arnr_type)
1888 {
1889 case 1: // Backward filter
1890 frames_fwd = 0;
1891 if (frames_bwd > half_gf_int)
1892 frames_bwd = half_gf_int;
1893 break;
1894
1895 case 2: // Forward filter
1896 if (frames_fwd > half_gf_int)
1897 frames_fwd = half_gf_int;
1898 if (frames_fwd > frames_after_arf)
1899 frames_fwd = frames_after_arf;
1900 frames_bwd = 0;
1901 break;
1902
1903 case 3: // Centered filter
1904 default:
1905 frames_fwd >>= 1;
1906 if (frames_fwd > frames_after_arf)
1907 frames_fwd = frames_after_arf;
1908 if (frames_fwd > half_gf_int)
1909 frames_fwd = half_gf_int;
1910
1911 frames_bwd = frames_fwd;
1912
1913 // For even length filter there is one more frame backward
1914 // than forward: e.g. len=6 ==> bbbAff, len=7 ==> bbbAfff.
1915 if (frames_bwd < half_gf_int)
1916 frames_bwd += (cpi->oxcf.arnr_max_frames+1) & 0x1;
1917 break;
1918 }
1919
1920 cpi->active_arnr_frames = frames_bwd + 1 + frames_fwd;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001921 }
1922 else
1923 {
1924 cpi->source_alt_ref_pending = FALSE;
1925 cpi->baseline_gf_interval = i;
1926 }
1927 }
1928 else
1929 {
1930 cpi->source_alt_ref_pending = FALSE;
1931 cpi->baseline_gf_interval = i;
1932 }
1933
Paul Wilkins11694aa2011-06-28 17:29:47 +01001934 // Now decide how many bits should be allocated to the GF group as a
1935 // proportion of those remaining in the kf group.
1936 // The final key frame group in the clip is treated as a special case
1937 // where cpi->twopass.kf_group_bits is tied to cpi->twopass.bits_left.
1938 // This is also important for short clips where there may only be one
1939 // key frame.
1940 if (cpi->twopass.frames_to_key >= (int)(cpi->twopass.total_stats->count -
1941 cpi->common.current_video_frame))
John Koleszar0ea50ce2010-05-18 11:58:33 -04001942 {
Paul Wilkins11694aa2011-06-28 17:29:47 +01001943 cpi->twopass.kf_group_bits =
1944 (cpi->twopass.bits_left > 0) ? cpi->twopass.bits_left : 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001945 }
1946
1947 // Calculate the bits to be allocated to the group as a whole
Paul Wilkins11694aa2011-06-28 17:29:47 +01001948 if ((cpi->twopass.kf_group_bits > 0) &&
1949 (cpi->twopass.kf_group_error_left > 0))
1950 {
1951 cpi->twopass.gf_group_bits =
1952 (int)((double)cpi->twopass.kf_group_bits *
1953 (gf_group_err / (double)cpi->twopass.kf_group_error_left));
1954 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04001955 else
John Koleszar63cb1a72011-05-19 17:16:39 -04001956 cpi->twopass.gf_group_bits = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001957
Paul Wilkins11694aa2011-06-28 17:29:47 +01001958 cpi->twopass.gf_group_bits =
1959 (cpi->twopass.gf_group_bits < 0)
1960 ? 0
1961 : (cpi->twopass.gf_group_bits > cpi->twopass.kf_group_bits)
1962 ? cpi->twopass.kf_group_bits : cpi->twopass.gf_group_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001963
Paul Wilkins11694aa2011-06-28 17:29:47 +01001964 // Clip cpi->twopass.gf_group_bits based on user supplied data rate
1965 // variability limit (cpi->oxcf.two_pass_vbrmax_section)
John Koleszare9613172011-08-12 14:51:36 -04001966 if (cpi->twopass.gf_group_bits > max_bits * cpi->baseline_gf_interval)
1967 cpi->twopass.gf_group_bits = max_bits * cpi->baseline_gf_interval;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001968
1969 // Reset the file position
1970 reset_fpf_position(cpi, start_pos);
1971
Paul Wilkins70b885a2010-11-12 11:35:30 +00001972 // Update the record of error used so far (only done once per gf group)
John Koleszar63cb1a72011-05-19 17:16:39 -04001973 cpi->twopass.modified_error_used += gf_group_err;
Paul Wilkins70b885a2010-11-12 11:35:30 +00001974
John Koleszar0ea50ce2010-05-18 11:58:33 -04001975 // Assign bits to the arf or gf.
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04001976 for (i = 0; i <= (cpi->source_alt_ref_pending && cpi->common.frame_type != KEY_FRAME); i++) {
John Koleszar0ea50ce2010-05-18 11:58:33 -04001977 int Boost;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001978 int allocation_chunks;
1979 int Q = (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04001980 int gf_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001981
1982 // For ARF frames
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04001983 if (cpi->source_alt_ref_pending && i == 0)
John Koleszar0ea50ce2010-05-18 11:58:33 -04001984 {
Paul Wilkins11694aa2011-06-28 17:29:47 +01001985#if NEW_BOOST
1986 Boost = (alt_boost * GFQ_ADJUSTMENT) / 100;
1987#else
John Koleszar0ea50ce2010-05-18 11:58:33 -04001988 Boost = (cpi->gfu_boost * 3 * GFQ_ADJUSTMENT) / (2 * 100);
Paul Wilkins11694aa2011-06-28 17:29:47 +01001989#endif
John Koleszar0ea50ce2010-05-18 11:58:33 -04001990 Boost += (cpi->baseline_gf_interval * 50);
1991
1992 // Set max and minimum boost and hence minimum allocation
1993 if (Boost > ((cpi->baseline_gf_interval + 1) * 200))
1994 Boost = ((cpi->baseline_gf_interval + 1) * 200);
1995 else if (Boost < 125)
1996 Boost = 125;
1997
Paul Wilkins11694aa2011-06-28 17:29:47 +01001998 allocation_chunks =
1999 ((cpi->baseline_gf_interval + 1) * 100) + Boost;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002000 }
2001 // Else for standard golden frames
2002 else
2003 {
2004 // boost based on inter / intra ratio of subsequent frames
2005 Boost = (cpi->gfu_boost * GFQ_ADJUSTMENT) / 100;
2006
2007 // Set max and minimum boost and hence minimum allocation
2008 if (Boost > (cpi->baseline_gf_interval * 150))
2009 Boost = (cpi->baseline_gf_interval * 150);
2010 else if (Boost < 125)
2011 Boost = 125;
2012
Paul Wilkins11694aa2011-06-28 17:29:47 +01002013 allocation_chunks =
2014 (cpi->baseline_gf_interval * 100) + (Boost - 100);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002015 }
2016
2017 // Normalize Altboost and allocations chunck down to prevent overflow
2018 while (Boost > 1000)
2019 {
2020 Boost /= 2;
2021 allocation_chunks /= 2;
2022 }
2023
Paul Wilkins11694aa2011-06-28 17:29:47 +01002024 // Calculate the number of bits to be spent on the gf or arf based on
2025 // the boost number
2026 gf_bits = (int)((double)Boost *
2027 (cpi->twopass.gf_group_bits /
2028 (double)allocation_chunks));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002029
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002030 // If the frame that is to be boosted is simpler than the average for
2031 // the gf/arf group then use an alternative calculation
John Koleszar0ea50ce2010-05-18 11:58:33 -04002032 // based on the error score of the frame itself
2033 if (mod_frame_err < gf_group_err / (double)cpi->baseline_gf_interval)
2034 {
2035 double alt_gf_grp_bits;
2036 int alt_gf_bits;
2037
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002038 alt_gf_grp_bits =
John Koleszar63cb1a72011-05-19 17:16:39 -04002039 (double)cpi->twopass.kf_group_bits *
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002040 (mod_frame_err * (double)cpi->baseline_gf_interval) /
John Koleszar63cb1a72011-05-19 17:16:39 -04002041 DOUBLE_DIVIDE_CHECK((double)cpi->twopass.kf_group_error_left);
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002042
2043 alt_gf_bits = (int)((double)Boost * (alt_gf_grp_bits /
2044 (double)allocation_chunks));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002045
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002046 if (gf_bits > alt_gf_bits)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002047 {
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002048 gf_bits = alt_gf_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002049 }
2050 }
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002051 // Else if it is harder than other frames in the group make sure it at
2052 // least receives an allocation in keeping with its relative error
2053 // score, otherwise it may be worse off than an "un-boosted" frame
John Koleszar0ea50ce2010-05-18 11:58:33 -04002054 else
2055 {
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002056 int alt_gf_bits =
John Koleszar63cb1a72011-05-19 17:16:39 -04002057 (int)((double)cpi->twopass.kf_group_bits *
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002058 mod_frame_err /
John Koleszar63cb1a72011-05-19 17:16:39 -04002059 DOUBLE_DIVIDE_CHECK((double)cpi->twopass.kf_group_error_left));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002060
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002061 if (alt_gf_bits > gf_bits)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002062 {
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002063 gf_bits = alt_gf_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002064 }
2065 }
2066
John Koleszare9613172011-08-12 14:51:36 -04002067 // Apply an additional limit for CBR
2068 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2069 {
2070 if (cpi->twopass.gf_bits > (cpi->buffer_level >> 1))
2071 cpi->twopass.gf_bits = cpi->buffer_level >> 1;
2072 }
2073
John Koleszar0ea50ce2010-05-18 11:58:33 -04002074 // Dont allow a negative value for gf_bits
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002075 if (gf_bits < 0)
2076 gf_bits = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002077
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002078 gf_bits += cpi->min_frame_bandwidth; // Add in minimum for a frame
2079
2080 if (i == 0)
2081 {
2082 cpi->twopass.gf_bits = gf_bits;
2083 }
2084 if (i == 1 || (!cpi->source_alt_ref_pending && (cpi->common.frame_type != KEY_FRAME)))
2085 {
2086 cpi->per_frame_bandwidth = gf_bits; // Per frame bit target for this frame
2087 }
2088 }
2089
2090 {
John Koleszar0ea50ce2010-05-18 11:58:33 -04002091 // Adjust KF group bits and error remainin
John Koleszar63cb1a72011-05-19 17:16:39 -04002092 cpi->twopass.kf_group_error_left -= gf_group_err;
2093 cpi->twopass.kf_group_bits -= cpi->twopass.gf_group_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002094
John Koleszar63cb1a72011-05-19 17:16:39 -04002095 if (cpi->twopass.kf_group_bits < 0)
2096 cpi->twopass.kf_group_bits = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002097
2098 // Note the error score left in the remaining frames of the group.
2099 // For normal GFs we want to remove the error score for the first frame of the group (except in Key frame case where this has already happened)
2100 if (!cpi->source_alt_ref_pending && cpi->common.frame_type != KEY_FRAME)
John Koleszar63cb1a72011-05-19 17:16:39 -04002101 cpi->twopass.gf_group_error_left = gf_group_err - gf_first_frame_err;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002102 else
John Koleszar63cb1a72011-05-19 17:16:39 -04002103 cpi->twopass.gf_group_error_left = gf_group_err;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002104
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002105 cpi->twopass.gf_group_bits -= cpi->twopass.gf_bits - cpi->min_frame_bandwidth;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002106
John Koleszar63cb1a72011-05-19 17:16:39 -04002107 if (cpi->twopass.gf_group_bits < 0)
2108 cpi->twopass.gf_group_bits = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002109
Paul Wilkins744f4822011-08-17 14:14:23 +01002110 // This condition could fail if there are two kfs very close together
2111 // despite (MIN_GF_INTERVAL) and would cause a devide by 0 in the
2112 // calculation of cpi->twopass.alt_extra_bits.
2113 if ( cpi->baseline_gf_interval >= 3 )
John Koleszar0ea50ce2010-05-18 11:58:33 -04002114 {
Paul Wilkins11694aa2011-06-28 17:29:47 +01002115#if NEW_BOOST
2116 int boost = (cpi->source_alt_ref_pending)
2117 ? b_boost : cpi->gfu_boost;
2118#else
2119 int boost = cpi->gfu_boost;
2120#endif
Paul Wilkins744f4822011-08-17 14:14:23 +01002121 if ( boost >= 150 )
Paul Wilkins11694aa2011-06-28 17:29:47 +01002122 {
Paul Wilkins744f4822011-08-17 14:14:23 +01002123 int pct_extra;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002124
Paul Wilkins744f4822011-08-17 14:14:23 +01002125 pct_extra = (boost - 100) / 50;
2126 pct_extra = (pct_extra > 20) ? 20 : pct_extra;
2127
2128 cpi->twopass.alt_extra_bits =
Paul Wilkins11694aa2011-06-28 17:29:47 +01002129 (cpi->twopass.gf_group_bits * pct_extra) / 100;
Paul Wilkins744f4822011-08-17 14:14:23 +01002130 cpi->twopass.gf_group_bits -= cpi->twopass.alt_extra_bits;
2131 cpi->twopass.alt_extra_bits /=
2132 ((cpi->baseline_gf_interval-1)>>1);
Paul Wilkins11694aa2011-06-28 17:29:47 +01002133 }
2134 else
Paul Wilkins744f4822011-08-17 14:14:23 +01002135 cpi->twopass.alt_extra_bits = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002136 }
Paul Wilkins744f4822011-08-17 14:14:23 +01002137 else
2138 cpi->twopass.alt_extra_bits = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002139 }
2140
2141 // Adjustment to estimate_max_q based on a measure of complexity of the section
2142 if (cpi->common.frame_type != KEY_FRAME)
2143 {
2144 FIRSTPASS_STATS sectionstats;
2145 double Ratio;
2146
John Koleszar429dc672011-03-17 17:07:59 -04002147 zero_stats(&sectionstats);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002148 reset_fpf_position(cpi, start_pos);
2149
2150 for (i = 0 ; i < cpi->baseline_gf_interval ; i++)
2151 {
John Koleszar429dc672011-03-17 17:07:59 -04002152 input_stats(cpi, &next_frame);
2153 accumulate_stats(&sectionstats, &next_frame);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002154 }
2155
John Koleszar429dc672011-03-17 17:07:59 -04002156 avg_stats(&sectionstats);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002157
John Koleszar63cb1a72011-05-19 17:16:39 -04002158 cpi->twopass.section_intra_rating =
Paul Wilkinse0846c92011-01-07 18:29:37 +00002159 sectionstats.intra_error /
2160 DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002161
2162 Ratio = sectionstats.intra_error / DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
2163 //if( (Ratio > 11) ) //&& (sectionstats.pcnt_second_ref < .20) )
2164 //{
John Koleszar63cb1a72011-05-19 17:16:39 -04002165 cpi->twopass.section_max_qfactor = 1.0 - ((Ratio - 10.0) * 0.025);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002166
John Koleszar63cb1a72011-05-19 17:16:39 -04002167 if (cpi->twopass.section_max_qfactor < 0.80)
2168 cpi->twopass.section_max_qfactor = 0.80;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002169
2170 //}
2171 //else
John Koleszar63cb1a72011-05-19 17:16:39 -04002172 // cpi->twopass.section_max_qfactor = 1.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002173
2174 reset_fpf_position(cpi, start_pos);
2175 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04002176}
2177
2178// Allocate bits to a normal frame that is neither a gf an arf or a key frame.
2179static void assign_std_frame_bits(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame)
2180{
2181 int target_frame_size; // gf_group_error_left
2182
2183 double modified_err;
2184 double err_fraction; // What portion of the remaining GF group error is used by this frame
2185
2186 int max_bits = frame_max_bits(cpi); // Max for a single frame
2187
John Koleszar0ea50ce2010-05-18 11:58:33 -04002188 // Calculate modified prediction error used in bit allocation
2189 modified_err = calculate_modified_err(cpi, this_frame);
2190
John Koleszar63cb1a72011-05-19 17:16:39 -04002191 if (cpi->twopass.gf_group_error_left > 0)
2192 err_fraction = modified_err / cpi->twopass.gf_group_error_left; // What portion of the remaining GF group error is used by this frame
John Koleszar0ea50ce2010-05-18 11:58:33 -04002193 else
2194 err_fraction = 0.0;
2195
John Koleszar63cb1a72011-05-19 17:16:39 -04002196 target_frame_size = (int)((double)cpi->twopass.gf_group_bits * err_fraction); // How many of those bits available for allocation should we give it?
John Koleszar0ea50ce2010-05-18 11:58:33 -04002197
John Koleszar63cb1a72011-05-19 17:16:39 -04002198 // Clip to target size to 0 - max_bits (or cpi->twopass.gf_group_bits) at the top end.
John Koleszar0ea50ce2010-05-18 11:58:33 -04002199 if (target_frame_size < 0)
2200 target_frame_size = 0;
2201 else
2202 {
2203 if (target_frame_size > max_bits)
2204 target_frame_size = max_bits;
2205
John Koleszar63cb1a72011-05-19 17:16:39 -04002206 if (target_frame_size > cpi->twopass.gf_group_bits)
2207 target_frame_size = cpi->twopass.gf_group_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002208 }
2209
John Koleszar63cb1a72011-05-19 17:16:39 -04002210 cpi->twopass.gf_group_error_left -= modified_err; // Adjust error remaining
2211 cpi->twopass.gf_group_bits -= target_frame_size; // Adjust bits remaining
John Koleszar0ea50ce2010-05-18 11:58:33 -04002212
John Koleszar63cb1a72011-05-19 17:16:39 -04002213 if (cpi->twopass.gf_group_bits < 0)
2214 cpi->twopass.gf_group_bits = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002215
2216 target_frame_size += cpi->min_frame_bandwidth; // Add in the minimum number of bits that is set aside for every frame.
2217
Paul Wilkins744f4822011-08-17 14:14:23 +01002218 // Every other frame gets a few extra bits
2219 if ( (cpi->common.frames_since_golden & 0x01) &&
2220 (cpi->frames_till_gf_update_due > 0) )
2221 {
2222 target_frame_size += cpi->twopass.alt_extra_bits;
2223 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04002224
2225 cpi->per_frame_bandwidth = target_frame_size; // Per frame bit target for this frame
2226}
2227
2228void vp8_second_pass(VP8_COMP *cpi)
2229{
2230 int tmp_q;
John Koleszar63cb1a72011-05-19 17:16:39 -04002231 int frames_left = (int)(cpi->twopass.total_stats->count - cpi->common.current_video_frame);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002232
2233 FIRSTPASS_STATS this_frame;
2234 FIRSTPASS_STATS this_frame_copy;
2235
John Koleszar0ea50ce2010-05-18 11:58:33 -04002236 double this_frame_error;
2237 double this_frame_intra_error;
2238 double this_frame_coded_error;
2239
2240 FIRSTPASS_STATS *start_pos;
2241
John Koleszar63cb1a72011-05-19 17:16:39 -04002242 if (!cpi->twopass.stats_in)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002243 {
2244 return ;
2245 }
2246
2247 vp8_clear_system_state();
2248
John Koleszar429dc672011-03-17 17:07:59 -04002249 if (EOF == input_stats(cpi, &this_frame))
John Koleszar0ea50ce2010-05-18 11:58:33 -04002250 return;
2251
John Koleszar0ea50ce2010-05-18 11:58:33 -04002252 this_frame_error = this_frame.ssim_weighted_pred_err;
2253 this_frame_intra_error = this_frame.intra_error;
2254 this_frame_coded_error = this_frame.coded_error;
2255
John Koleszar63cb1a72011-05-19 17:16:39 -04002256 start_pos = cpi->twopass.stats_in;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002257
2258 // keyframe and section processing !
John Koleszar63cb1a72011-05-19 17:16:39 -04002259 if (cpi->twopass.frames_to_key == 0)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002260 {
2261 // Define next KF group and assign bits to it
2262 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
John Koleszar429dc672011-03-17 17:07:59 -04002263 find_next_key_frame(cpi, &this_frame_copy);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002264
2265 // Special case: Error error_resilient_mode mode does not make much sense for two pass but with its current meaning but this code is designed to stop
2266 // outlandish behaviour if someone does set it when using two pass. It effectively disables GF groups.
2267 // This is temporary code till we decide what should really happen in this case.
2268 if (cpi->oxcf.error_resilient_mode)
2269 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002270 cpi->twopass.gf_group_bits = cpi->twopass.kf_group_bits;
2271 cpi->twopass.gf_group_error_left = cpi->twopass.kf_group_error_left;
2272 cpi->baseline_gf_interval = cpi->twopass.frames_to_key;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002273 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2274 cpi->source_alt_ref_pending = FALSE;
2275 }
2276
2277 }
2278
2279 // Is this a GF / ARF (Note that a KF is always also a GF)
2280 if (cpi->frames_till_gf_update_due == 0)
2281 {
2282 // Define next gf group and assign bits to it
2283 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2284 define_gf_group(cpi, &this_frame_copy);
2285
2286 // If we are going to code an altref frame at the end of the group and the current frame is not a key frame....
2287 // If the previous group used an arf this frame has already benefited from that arf boost and it should not be given extra bits
2288 // If the previous group was NOT coded using arf we may want to apply some boost to this GF as well
2289 if (cpi->source_alt_ref_pending && (cpi->common.frame_type != KEY_FRAME))
2290 {
2291 // Assign a standard frames worth of bits from those allocated to the GF group
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002292 int bak = cpi->per_frame_bandwidth;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002293 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2294 assign_std_frame_bits(cpi, &this_frame_copy);
Ronald S. Bultje87fd66b2011-06-16 13:01:27 -04002295 cpi->per_frame_bandwidth = bak;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002296 }
2297 }
2298
2299 // Otherwise this is an ordinary frame
2300 else
2301 {
2302 // Special case: Error error_resilient_mode mode does not make much sense for two pass but with its current meaning but this code is designed to stop
2303 // outlandish behaviour if someone does set it when using two pass. It effectively disables GF groups.
2304 // This is temporary code till we decide what should really happen in this case.
2305 if (cpi->oxcf.error_resilient_mode)
2306 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002307 cpi->frames_till_gf_update_due = cpi->twopass.frames_to_key;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002308
2309 if (cpi->common.frame_type != KEY_FRAME)
2310 {
2311 // Assign bits from those allocated to the GF group
2312 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2313 assign_std_frame_bits(cpi, &this_frame_copy);
2314 }
2315 }
2316 else
2317 {
2318 // Assign bits from those allocated to the GF group
2319 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2320 assign_std_frame_bits(cpi, &this_frame_copy);
2321 }
2322 }
2323
Paul Wilkinsa04ed232010-06-09 15:03:48 +01002324 // Keep a globally available copy of this and the next frame's iiratio.
John Koleszar63cb1a72011-05-19 17:16:39 -04002325 cpi->twopass.this_iiratio = this_frame_intra_error /
Paul Wilkinsa04ed232010-06-09 15:03:48 +01002326 DOUBLE_DIVIDE_CHECK(this_frame_coded_error);
Paul Wilkins28de6702010-06-07 17:34:46 +01002327 {
2328 FIRSTPASS_STATS next_frame;
2329 if ( lookup_next_frame_stats(cpi, &next_frame) != EOF )
Paul Wilkinsa04ed232010-06-09 15:03:48 +01002330 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002331 cpi->twopass.next_iiratio = next_frame.intra_error /
Paul Wilkinsa04ed232010-06-09 15:03:48 +01002332 DOUBLE_DIVIDE_CHECK(next_frame.coded_error);
2333 }
Paul Wilkins28de6702010-06-07 17:34:46 +01002334 }
2335
John Koleszar0ea50ce2010-05-18 11:58:33 -04002336 // Set nominal per second bandwidth for this frame
2337 cpi->target_bandwidth = cpi->per_frame_bandwidth * cpi->output_frame_rate;
2338 if (cpi->target_bandwidth < 0)
2339 cpi->target_bandwidth = 0;
2340
2341 if (cpi->common.current_video_frame == 0)
2342 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002343 cpi->twopass.est_max_qcorrection_factor = 1.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002344
Paul Wilkinse0846c92011-01-07 18:29:37 +00002345 // Experimental code to try and set a cq_level in constrained
2346 // quality mode.
2347 if ( cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY )
2348 {
2349 int est_cq;
2350
2351 est_cq =
2352 estimate_cq( cpi,
John Koleszar63cb1a72011-05-19 17:16:39 -04002353 (cpi->twopass.total_coded_error_left / frames_left),
2354 (int)(cpi->twopass.bits_left / frames_left));
Paul Wilkinse0846c92011-01-07 18:29:37 +00002355
2356 cpi->cq_target_quality = cpi->oxcf.cq_level;
2357 if ( est_cq > cpi->cq_target_quality )
2358 cpi->cq_target_quality = est_cq;
2359 }
2360
2361 // guess at maxq needed in 2nd pass
John Koleszar63cb1a72011-05-19 17:16:39 -04002362 cpi->twopass.maxq_max_limit = cpi->worst_quality;
2363 cpi->twopass.maxq_min_limit = cpi->best_quality;
Paul Wilkins3af35932011-01-07 16:33:59 +00002364 tmp_q = estimate_max_q( cpi,
John Koleszar63cb1a72011-05-19 17:16:39 -04002365 (cpi->twopass.total_coded_error_left / frames_left),
2366 (int)(cpi->twopass.bits_left / frames_left));
Paul Wilkins3af35932011-01-07 16:33:59 +00002367
Paul Wilkinse0846c92011-01-07 18:29:37 +00002368 // Limit the maxq value returned subsequently.
Paul Wilkinscf7c4732011-01-10 16:41:53 +00002369 // This increases the risk of overspend or underspend if the initial
Paul Wilkins3af35932011-01-07 16:33:59 +00002370 // estimate for the clip is bad, but helps prevent excessive
2371 // variation in Q, especially near the end of a clip
2372 // where for example a small overspend may cause Q to crash
John Koleszar63cb1a72011-05-19 17:16:39 -04002373 cpi->twopass.maxq_max_limit = ((tmp_q + 32) < cpi->worst_quality)
Paul Wilkins3af35932011-01-07 16:33:59 +00002374 ? (tmp_q + 32) : cpi->worst_quality;
John Koleszar63cb1a72011-05-19 17:16:39 -04002375 cpi->twopass.maxq_min_limit = ((tmp_q - 32) > cpi->best_quality)
Paul Wilkins3af35932011-01-07 16:33:59 +00002376 ? (tmp_q - 32) : cpi->best_quality;
2377
2378 cpi->active_worst_quality = tmp_q;
2379 cpi->ni_av_qi = tmp_q;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002380 }
Paul Wilkinse0846c92011-01-07 18:29:37 +00002381
Paul Wilkins513f8e62010-11-10 10:09:45 +00002382 // The last few frames of a clip almost always have to few or too many
2383 // bits and for the sake of over exact rate control we dont want to make
2384 // radical adjustments to the allowed quantizer range just to use up a
2385 // few surplus bits or get beneath the target rate.
2386 else if ( (cpi->common.current_video_frame <
John Koleszar63cb1a72011-05-19 17:16:39 -04002387 (((unsigned int)cpi->twopass.total_stats->count * 255)>>8)) &&
Paul Wilkins513f8e62010-11-10 10:09:45 +00002388 ((cpi->common.current_video_frame + cpi->baseline_gf_interval) <
John Koleszar63cb1a72011-05-19 17:16:39 -04002389 (unsigned int)cpi->twopass.total_stats->count) )
John Koleszar0ea50ce2010-05-18 11:58:33 -04002390 {
2391 if (frames_left < 1)
2392 frames_left = 1;
2393
John Koleszar63cb1a72011-05-19 17:16:39 -04002394 tmp_q = estimate_max_q(cpi, (cpi->twopass.total_coded_error_left / frames_left), (int)(cpi->twopass.bits_left / frames_left));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002395
2396 // Move active_worst_quality but in a damped way
2397 if (tmp_q > cpi->active_worst_quality)
2398 cpi->active_worst_quality ++;
2399 else if (tmp_q < cpi->active_worst_quality)
2400 cpi->active_worst_quality --;
2401
2402 cpi->active_worst_quality = ((cpi->active_worst_quality * 3) + tmp_q + 2) / 4;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002403 }
2404
John Koleszar63cb1a72011-05-19 17:16:39 -04002405 cpi->twopass.frames_to_key --;
2406 cpi->twopass.total_error_left -= this_frame_error;
2407 cpi->twopass.total_intra_error_left -= this_frame_intra_error;
2408 cpi->twopass.total_coded_error_left -= this_frame_coded_error;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002409}
2410
2411
2412static BOOL test_candidate_kf(VP8_COMP *cpi, FIRSTPASS_STATS *last_frame, FIRSTPASS_STATS *this_frame, FIRSTPASS_STATS *next_frame)
2413{
2414 BOOL is_viable_kf = FALSE;
2415
2416 // Does the frame satisfy the primary criteria of a key frame
2417 // If so, then examine how well it predicts subsequent frames
2418 if ((this_frame->pcnt_second_ref < 0.10) &&
2419 (next_frame->pcnt_second_ref < 0.10) &&
2420 ((this_frame->pcnt_inter < 0.05) ||
2421 (
Paul Wilkinsbc9c30a2011-03-07 15:58:07 +00002422 ((this_frame->pcnt_inter - this_frame->pcnt_neutral) < .25) &&
John Koleszar0ea50ce2010-05-18 11:58:33 -04002423 ((this_frame->intra_error / DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) < 2.5) &&
2424 ((fabs(last_frame->coded_error - this_frame->coded_error) / DOUBLE_DIVIDE_CHECK(this_frame->coded_error) > .40) ||
2425 (fabs(last_frame->intra_error - this_frame->intra_error) / DOUBLE_DIVIDE_CHECK(this_frame->intra_error) > .40) ||
2426 ((next_frame->intra_error / DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) > 3.5)
2427 )
2428 )
2429 )
2430 )
2431 {
2432 int i;
2433 FIRSTPASS_STATS *start_pos;
2434
2435 FIRSTPASS_STATS local_next_frame;
2436
2437 double boost_score = 0.0;
2438 double old_boost_score = 0.0;
2439 double decay_accumulator = 1.0;
2440 double next_iiratio;
2441
2442 vpx_memcpy(&local_next_frame, next_frame, sizeof(*next_frame));
2443
2444 // Note the starting file position so we can reset to it
John Koleszar63cb1a72011-05-19 17:16:39 -04002445 start_pos = cpi->twopass.stats_in;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002446
2447 // Examine how well the key frame predicts subsequent frames
2448 for (i = 0 ; i < 16; i++)
2449 {
2450 next_iiratio = (IIKFACTOR1 * local_next_frame.intra_error / DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error)) ;
2451
2452 if (next_iiratio > RMAX)
2453 next_iiratio = RMAX;
2454
2455 // Cumulative effect of decay in prediction quality
2456 if (local_next_frame.pcnt_inter > 0.85)
2457 decay_accumulator = decay_accumulator * local_next_frame.pcnt_inter;
2458 else
2459 decay_accumulator = decay_accumulator * ((0.85 + local_next_frame.pcnt_inter) / 2.0);
2460
2461 //decay_accumulator = decay_accumulator * local_next_frame.pcnt_inter;
2462
2463 // Keep a running total
2464 boost_score += (decay_accumulator * next_iiratio);
2465
2466 // Test various breakout clauses
2467 if ((local_next_frame.pcnt_inter < 0.05) ||
2468 (next_iiratio < 1.5) ||
Paul Wilkinsbc9c30a2011-03-07 15:58:07 +00002469 (((local_next_frame.pcnt_inter -
2470 local_next_frame.pcnt_neutral) < 0.20) &&
2471 (next_iiratio < 3.0)) ||
John Koleszar0ea50ce2010-05-18 11:58:33 -04002472 ((boost_score - old_boost_score) < 0.5) ||
2473 (local_next_frame.intra_error < 200)
2474 )
2475 {
2476 break;
2477 }
2478
2479 old_boost_score = boost_score;
2480
2481 // Get the next frame details
John Koleszar429dc672011-03-17 17:07:59 -04002482 if (EOF == input_stats(cpi, &local_next_frame))
John Koleszar0ea50ce2010-05-18 11:58:33 -04002483 break;
2484 }
2485
2486 // If there is tolerable prediction for at least the next 3 frames then break out else discard this pottential key frame and move on
2487 if (boost_score > 5.0 && (i > 3))
2488 is_viable_kf = TRUE;
2489 else
2490 {
2491 // Reset the file position
2492 reset_fpf_position(cpi, start_pos);
2493
2494 is_viable_kf = FALSE;
2495 }
2496 }
2497
2498 return is_viable_kf;
2499}
John Koleszar429dc672011-03-17 17:07:59 -04002500static void find_next_key_frame(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002501{
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00002502 int i,j;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002503 FIRSTPASS_STATS last_frame;
2504 FIRSTPASS_STATS first_frame;
2505 FIRSTPASS_STATS next_frame;
2506 FIRSTPASS_STATS *start_position;
2507
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00002508 double decay_accumulator = 1.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002509 double boost_score = 0;
2510 double old_boost_score = 0.0;
2511 double loop_decay_rate;
2512
2513 double kf_mod_err = 0.0;
2514 double kf_group_err = 0.0;
2515 double kf_group_intra_err = 0.0;
2516 double kf_group_coded_err = 0.0;
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00002517 double recent_loop_decay[8] = {1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0};
John Koleszar0ea50ce2010-05-18 11:58:33 -04002518
Guillermo Ballester Valor5a726202010-06-11 14:33:49 -04002519 vpx_memset(&next_frame, 0, sizeof(next_frame)); // assure clean
2520
John Koleszar0ea50ce2010-05-18 11:58:33 -04002521 vp8_clear_system_state(); //__asm emms;
John Koleszar63cb1a72011-05-19 17:16:39 -04002522 start_position = cpi->twopass.stats_in;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002523
2524 cpi->common.frame_type = KEY_FRAME;
2525
Paul Wilkins55acda92011-01-12 17:08:42 +00002526 // is this a forced key frame by interval
2527 cpi->this_key_frame_forced = cpi->next_key_frame_forced;
2528
John Koleszar0ea50ce2010-05-18 11:58:33 -04002529 // Clear the alt ref active flag as this can never be active on a key frame
2530 cpi->source_alt_ref_active = FALSE;
2531
2532 // Kf is always a gf so clear frames till next gf counter
2533 cpi->frames_till_gf_update_due = 0;
2534
John Koleszar63cb1a72011-05-19 17:16:39 -04002535 cpi->twopass.frames_to_key = 1;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002536
2537 // Take a copy of the initial frame details
2538 vpx_memcpy(&first_frame, this_frame, sizeof(*this_frame));
2539
John Koleszar63cb1a72011-05-19 17:16:39 -04002540 cpi->twopass.kf_group_bits = 0; // Total bits avaialable to kf group
2541 cpi->twopass.kf_group_error_left = 0; // Group modified error score.
John Koleszar0ea50ce2010-05-18 11:58:33 -04002542
2543 kf_mod_err = calculate_modified_err(cpi, this_frame);
2544
2545 // find the next keyframe
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00002546 i = 0;
John Koleszar63cb1a72011-05-19 17:16:39 -04002547 while (cpi->twopass.stats_in < cpi->twopass.stats_in_end)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002548 {
2549 // Accumulate kf group error
2550 kf_group_err += calculate_modified_err(cpi, this_frame);
2551
2552 // These figures keep intra and coded error counts for all frames including key frames in the group.
2553 // The effect of the key frame itself can be subtracted out using the first_frame data collected above
2554 kf_group_intra_err += this_frame->intra_error;
2555 kf_group_coded_err += this_frame->coded_error;
2556
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002557 // load a the next frame's stats
John Koleszar0ea50ce2010-05-18 11:58:33 -04002558 vpx_memcpy(&last_frame, this_frame, sizeof(*this_frame));
John Koleszar429dc672011-03-17 17:07:59 -04002559 input_stats(cpi, this_frame);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002560
2561 // Provided that we are not at the end of the file...
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002562 if (cpi->oxcf.auto_key
2563 && lookup_next_frame_stats(cpi, &next_frame) != EOF)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002564 {
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00002565 // Normal scene cut check
Paul Wilkins744f4822011-08-17 14:14:23 +01002566 if ( ( i >= MIN_GF_INTERVAL ) &&
2567 test_candidate_kf(cpi, &last_frame, this_frame, &next_frame) )
2568 {
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002569 break;
Paul Wilkins744f4822011-08-17 14:14:23 +01002570 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04002571
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00002572 // How fast is prediction quality decaying
2573 loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
2574
2575 // We want to know something about the recent past... rather than
2576 // as used elsewhere where we are concened with decay in prediction
2577 // quality since the last GF or KF.
2578 recent_loop_decay[i%8] = loop_decay_rate;
2579 decay_accumulator = 1.0;
2580 for (j = 0; j < 8; j++)
2581 {
2582 decay_accumulator = decay_accumulator * recent_loop_decay[j];
2583 }
2584
2585 // Special check for transition or high motion followed by a
2586 // to a static scene.
2587 if ( detect_transition_to_still( cpi, i,
2588 (cpi->key_frame_frequency-i),
2589 loop_decay_rate,
2590 decay_accumulator ) )
2591 {
2592 break;
2593 }
2594
2595
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002596 // Step on to the next frame
John Koleszar63cb1a72011-05-19 17:16:39 -04002597 cpi->twopass.frames_to_key ++;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002598
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002599 // If we don't have a real key frame within the next two
2600 // forcekeyframeevery intervals then break out of the loop.
John Koleszar63cb1a72011-05-19 17:16:39 -04002601 if (cpi->twopass.frames_to_key >= 2 *(int)cpi->key_frame_frequency)
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002602 break;
2603 } else
John Koleszar63cb1a72011-05-19 17:16:39 -04002604 cpi->twopass.frames_to_key ++;
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00002605
2606 i++;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002607 }
2608
2609 // If there is a max kf interval set by the user we must obey it.
2610 // We already breakout of the loop above at 2x max.
2611 // This code centers the extra kf if the actual natural
2612 // interval is between 1x and 2x
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002613 if (cpi->oxcf.auto_key
John Koleszar63cb1a72011-05-19 17:16:39 -04002614 && cpi->twopass.frames_to_key > (int)cpi->key_frame_frequency )
John Koleszar0ea50ce2010-05-18 11:58:33 -04002615 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002616 FIRSTPASS_STATS *current_pos = cpi->twopass.stats_in;
Paul Wilkins336aa0b2011-01-25 12:29:06 +00002617 FIRSTPASS_STATS tmp_frame;
2618
John Koleszar63cb1a72011-05-19 17:16:39 -04002619 cpi->twopass.frames_to_key /= 2;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002620
Paul Wilkins336aa0b2011-01-25 12:29:06 +00002621 // Copy first frame details
2622 vpx_memcpy(&tmp_frame, &first_frame, sizeof(first_frame));
2623
2624 // Reset to the start of the group
2625 reset_fpf_position(cpi, start_position);
2626
2627 kf_group_err = 0;
2628 kf_group_intra_err = 0;
2629 kf_group_coded_err = 0;
2630
2631 // Rescan to get the correct error data for the forced kf group
John Koleszar63cb1a72011-05-19 17:16:39 -04002632 for( i = 0; i < cpi->twopass.frames_to_key; i++ )
Paul Wilkins336aa0b2011-01-25 12:29:06 +00002633 {
2634 // Accumulate kf group errors
2635 kf_group_err += calculate_modified_err(cpi, &tmp_frame);
2636 kf_group_intra_err += tmp_frame.intra_error;
2637 kf_group_coded_err += tmp_frame.coded_error;
2638
2639 // Load a the next frame's stats
John Koleszar429dc672011-03-17 17:07:59 -04002640 input_stats(cpi, &tmp_frame);
Paul Wilkins336aa0b2011-01-25 12:29:06 +00002641 }
2642
2643 // Reset to the start of the group
2644 reset_fpf_position(cpi, current_pos);
Paul Wilkins55acda92011-01-12 17:08:42 +00002645
2646 cpi->next_key_frame_forced = TRUE;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002647 }
Paul Wilkins55acda92011-01-12 17:08:42 +00002648 else
2649 cpi->next_key_frame_forced = FALSE;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002650
2651 // Special case for the last frame of the file
John Koleszar63cb1a72011-05-19 17:16:39 -04002652 if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002653 {
2654 // Accumulate kf group error
2655 kf_group_err += calculate_modified_err(cpi, this_frame);
2656
2657 // These figures keep intra and coded error counts for all frames including key frames in the group.
2658 // The effect of the key frame itself can be subtracted out using the first_frame data collected above
2659 kf_group_intra_err += this_frame->intra_error;
2660 kf_group_coded_err += this_frame->coded_error;
2661 }
2662
2663 // Calculate the number of bits that should be assigned to the kf group.
John Koleszar63cb1a72011-05-19 17:16:39 -04002664 if ((cpi->twopass.bits_left > 0) && (cpi->twopass.modified_error_left > 0.0))
John Koleszar0ea50ce2010-05-18 11:58:33 -04002665 {
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002666 // Max for a single normal frame (not key frame)
2667 int max_bits = frame_max_bits(cpi);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002668
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002669 // Maximum bits for the kf group
James Zernb45065d2011-07-25 18:44:59 -07002670 int64_t max_grp_bits;
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002671
2672 // Default allocation based on bits left and relative
2673 // complexity of the section
James Zernb45065d2011-07-25 18:44:59 -07002674 cpi->twopass.kf_group_bits = (int64_t)( cpi->twopass.bits_left *
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002675 ( kf_group_err /
John Koleszar63cb1a72011-05-19 17:16:39 -04002676 cpi->twopass.modified_error_left ));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002677
2678 // Clip based on maximum per frame rate defined by the user.
James Zernb45065d2011-07-25 18:44:59 -07002679 max_grp_bits = (int64_t)max_bits * (int64_t)cpi->twopass.frames_to_key;
John Koleszar63cb1a72011-05-19 17:16:39 -04002680 if (cpi->twopass.kf_group_bits > max_grp_bits)
2681 cpi->twopass.kf_group_bits = max_grp_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002682
2683 // Additional special case for CBR if buffer is getting full.
2684 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2685 {
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002686 int opt_buffer_lvl = cpi->oxcf.optimal_buffer_level;
2687 int buffer_lvl = cpi->buffer_level;
2688
2689 // If the buffer is near or above the optimal and this kf group is
2690 // not being allocated much then increase the allocation a bit.
2691 if (buffer_lvl >= opt_buffer_lvl)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002692 {
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002693 int high_water_mark = (opt_buffer_lvl +
2694 cpi->oxcf.maximum_buffer_size) >> 1;
2695
James Zernb45065d2011-07-25 18:44:59 -07002696 int64_t av_group_bits;
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002697
2698 // Av bits per frame * number of frames
James Zernb45065d2011-07-25 18:44:59 -07002699 av_group_bits = (int64_t)cpi->av_per_frame_bandwidth *
2700 (int64_t)cpi->twopass.frames_to_key;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002701
2702 // We are at or above the maximum.
2703 if (cpi->buffer_level >= high_water_mark)
2704 {
James Zernb45065d2011-07-25 18:44:59 -07002705 int64_t min_group_bits;
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002706
2707 min_group_bits = av_group_bits +
James Zernb45065d2011-07-25 18:44:59 -07002708 (int64_t)(buffer_lvl -
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002709 high_water_mark);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002710
John Koleszar63cb1a72011-05-19 17:16:39 -04002711 if (cpi->twopass.kf_group_bits < min_group_bits)
2712 cpi->twopass.kf_group_bits = min_group_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002713 }
2714 // We are above optimal but below the maximum
John Koleszar63cb1a72011-05-19 17:16:39 -04002715 else if (cpi->twopass.kf_group_bits < av_group_bits)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002716 {
James Zernb45065d2011-07-25 18:44:59 -07002717 int64_t bits_below_av = av_group_bits -
John Koleszar63cb1a72011-05-19 17:16:39 -04002718 cpi->twopass.kf_group_bits;
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002719
John Koleszar63cb1a72011-05-19 17:16:39 -04002720 cpi->twopass.kf_group_bits +=
James Zernb45065d2011-07-25 18:44:59 -07002721 (int64_t)((double)bits_below_av *
Paul Wilkins9404c7d2010-07-23 17:01:12 +01002722 (double)(buffer_lvl - opt_buffer_lvl) /
2723 (double)(high_water_mark - opt_buffer_lvl));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002724 }
2725 }
2726 }
2727 }
2728 else
John Koleszar63cb1a72011-05-19 17:16:39 -04002729 cpi->twopass.kf_group_bits = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002730
2731 // Reset the first pass file position
2732 reset_fpf_position(cpi, start_position);
2733
2734 // determine how big to make this keyframe based on how well the subsequent frames use inter blocks
2735 decay_accumulator = 1.0;
2736 boost_score = 0.0;
2737 loop_decay_rate = 1.00; // Starting decay rate
2738
John Koleszar63cb1a72011-05-19 17:16:39 -04002739 for (i = 0 ; i < cpi->twopass.frames_to_key ; i++)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002740 {
2741 double r;
2742
John Koleszar429dc672011-03-17 17:07:59 -04002743 if (EOF == input_stats(cpi, &next_frame))
John Koleszar0ea50ce2010-05-18 11:58:33 -04002744 break;
2745
John Koleszar63cb1a72011-05-19 17:16:39 -04002746 if (next_frame.intra_error > cpi->twopass.kf_intra_err_min)
Paul Wilkinsb095d9d2011-01-04 17:55:49 +00002747 r = (IIKFACTOR2 * next_frame.intra_error /
2748 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2749 else
John Koleszar63cb1a72011-05-19 17:16:39 -04002750 r = (IIKFACTOR2 * cpi->twopass.kf_intra_err_min /
Paul Wilkinsb095d9d2011-01-04 17:55:49 +00002751 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002752
2753 if (r > RMAX)
2754 r = RMAX;
2755
Paul Wilkins9fc8cb32011-03-07 15:11:09 +00002756 // How fast is prediction quality decaying
2757 loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002758
2759 decay_accumulator = decay_accumulator * loop_decay_rate;
Paul Wilkins788c0eb2010-10-02 17:31:46 +01002760 decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002761
2762 boost_score += (decay_accumulator * r);
2763
2764 if ((i > MIN_GF_INTERVAL) &&
2765 ((boost_score - old_boost_score) < 1.0))
2766 {
2767 break;
2768 }
2769
2770 old_boost_score = boost_score;
2771 }
2772
2773 if (1)
2774 {
2775 FIRSTPASS_STATS sectionstats;
2776 double Ratio;
2777
John Koleszar429dc672011-03-17 17:07:59 -04002778 zero_stats(&sectionstats);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002779 reset_fpf_position(cpi, start_position);
2780
John Koleszar63cb1a72011-05-19 17:16:39 -04002781 for (i = 0 ; i < cpi->twopass.frames_to_key ; i++)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002782 {
John Koleszar429dc672011-03-17 17:07:59 -04002783 input_stats(cpi, &next_frame);
2784 accumulate_stats(&sectionstats, &next_frame);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002785 }
2786
John Koleszar429dc672011-03-17 17:07:59 -04002787 avg_stats(&sectionstats);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002788
John Koleszar63cb1a72011-05-19 17:16:39 -04002789 cpi->twopass.section_intra_rating =
2790 sectionstats.intra_error
2791 / DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002792
2793 Ratio = sectionstats.intra_error / DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
2794 // if( (Ratio > 11) ) //&& (sectionstats.pcnt_second_ref < .20) )
2795 //{
John Koleszar63cb1a72011-05-19 17:16:39 -04002796 cpi->twopass.section_max_qfactor = 1.0 - ((Ratio - 10.0) * 0.025);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002797
John Koleszar63cb1a72011-05-19 17:16:39 -04002798 if (cpi->twopass.section_max_qfactor < 0.80)
2799 cpi->twopass.section_max_qfactor = 0.80;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002800
2801 //}
2802 //else
John Koleszar63cb1a72011-05-19 17:16:39 -04002803 // cpi->twopass.section_max_qfactor = 1.0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002804 }
2805
2806 // When using CBR apply additional buffer fullness related upper limits
2807 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2808 {
2809 double max_boost;
2810
2811 if (cpi->drop_frames_allowed)
2812 {
2813 int df_buffer_level = cpi->oxcf.drop_frames_water_mark * (cpi->oxcf.optimal_buffer_level / 100);
2814
2815 if (cpi->buffer_level > df_buffer_level)
2816 max_boost = ((double)((cpi->buffer_level - df_buffer_level) * 2 / 3) * 16.0) / DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
2817 else
2818 max_boost = 0.0;
2819 }
2820 else if (cpi->buffer_level > 0)
2821 {
2822 max_boost = ((double)(cpi->buffer_level * 2 / 3) * 16.0) / DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
2823 }
2824 else
2825 {
2826 max_boost = 0.0;
2827 }
2828
2829 if (boost_score > max_boost)
2830 boost_score = max_boost;
2831 }
2832
2833 // Reset the first pass file position
2834 reset_fpf_position(cpi, start_position);
2835
2836 // Work out how many bits to allocate for the key frame itself
2837 if (1)
2838 {
2839 int kf_boost = boost_score;
2840 int allocation_chunks;
John Koleszar63cb1a72011-05-19 17:16:39 -04002841 int Counter = cpi->twopass.frames_to_key;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002842 int alt_kf_bits;
Fritz Koenig0ce39012010-07-22 08:07:32 -04002843 YV12_BUFFER_CONFIG *lst_yv12 = &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
John Koleszar0ea50ce2010-05-18 11:58:33 -04002844 // Min boost based on kf interval
2845#if 0
2846
2847 while ((kf_boost < 48) && (Counter > 0))
2848 {
2849 Counter -= 2;
2850 kf_boost ++;
2851 }
2852
2853#endif
2854
2855 if (kf_boost < 48)
2856 {
2857 kf_boost += ((Counter + 1) >> 1);
2858
2859 if (kf_boost > 48) kf_boost = 48;
2860 }
2861
2862 // bigger frame sizes need larger kf boosts, smaller frames smaller boosts...
Fritz Koenig0ce39012010-07-22 08:07:32 -04002863 if ((lst_yv12->y_width * lst_yv12->y_height) > (320 * 240))
2864 kf_boost += 2 * (lst_yv12->y_width * lst_yv12->y_height) / (320 * 240);
2865 else if ((lst_yv12->y_width * lst_yv12->y_height) < (320 * 240))
2866 kf_boost -= 4 * (320 * 240) / (lst_yv12->y_width * lst_yv12->y_height);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002867
2868 kf_boost = (int)((double)kf_boost * 100.0) >> 4; // Scale 16 to 100
2869
2870 // Adjustment to boost based on recent average q
Paul Wilkinsb095d9d2011-01-04 17:55:49 +00002871 //kf_boost = kf_boost * vp8_kf_boost_qadjustment[cpi->ni_av_qi] / 100;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002872
2873 if (kf_boost < 250) // Min KF boost
2874 kf_boost = 250;
2875
2876 // We do three calculations for kf size.
2877 // The first is based on the error score for the whole kf group.
2878 // The second (optionaly) on the key frames own error if this is smaller than the average for the group.
2879 // The final one insures that the frame receives at least the allocation it would have received based on its own error score vs the error score remaining
2880
John Koleszar63cb1a72011-05-19 17:16:39 -04002881 allocation_chunks = ((cpi->twopass.frames_to_key - 1) * 100) + kf_boost; // cpi->twopass.frames_to_key-1 because key frame itself is taken care of by kf_boost
John Koleszar0ea50ce2010-05-18 11:58:33 -04002882
2883 // Normalize Altboost and allocations chunck down to prevent overflow
2884 while (kf_boost > 1000)
2885 {
2886 kf_boost /= 2;
2887 allocation_chunks /= 2;
2888 }
2889
John Koleszar63cb1a72011-05-19 17:16:39 -04002890 cpi->twopass.kf_group_bits = (cpi->twopass.kf_group_bits < 0) ? 0 : cpi->twopass.kf_group_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002891
2892 // Calculate the number of bits to be spent on the key frame
John Koleszar63cb1a72011-05-19 17:16:39 -04002893 cpi->twopass.kf_bits = (int)((double)kf_boost * ((double)cpi->twopass.kf_group_bits / (double)allocation_chunks));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002894
2895 // Apply an additional limit for CBR
2896 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2897 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002898 if (cpi->twopass.kf_bits > ((3 * cpi->buffer_level) >> 2))
2899 cpi->twopass.kf_bits = (3 * cpi->buffer_level) >> 2;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002900 }
2901
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002902 // If the key frame is actually easier than the average for the
2903 // kf group (which does sometimes happen... eg a blank intro frame)
2904 // Then use an alternate calculation based on the kf error score
2905 // which should give a smaller key frame.
John Koleszar63cb1a72011-05-19 17:16:39 -04002906 if (kf_mod_err < kf_group_err / cpi->twopass.frames_to_key)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002907 {
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002908 double alt_kf_grp_bits =
John Koleszar63cb1a72011-05-19 17:16:39 -04002909 ((double)cpi->twopass.bits_left *
2910 (kf_mod_err * (double)cpi->twopass.frames_to_key) /
2911 DOUBLE_DIVIDE_CHECK(cpi->twopass.modified_error_left));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002912
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002913 alt_kf_bits = (int)((double)kf_boost *
2914 (alt_kf_grp_bits / (double)allocation_chunks));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002915
John Koleszar63cb1a72011-05-19 17:16:39 -04002916 if (cpi->twopass.kf_bits > alt_kf_bits)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002917 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002918 cpi->twopass.kf_bits = alt_kf_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002919 }
2920 }
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002921 // Else if it is much harder than other frames in the group make sure
2922 // it at least receives an allocation in keeping with its relative
2923 // error score
John Koleszar0ea50ce2010-05-18 11:58:33 -04002924 else
2925 {
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002926 alt_kf_bits =
John Koleszar63cb1a72011-05-19 17:16:39 -04002927 (int)((double)cpi->twopass.bits_left *
Paul Wilkinsc239a1b2010-08-20 12:27:26 +01002928 (kf_mod_err /
John Koleszar63cb1a72011-05-19 17:16:39 -04002929 DOUBLE_DIVIDE_CHECK(cpi->twopass.modified_error_left)));
John Koleszar0ea50ce2010-05-18 11:58:33 -04002930
John Koleszar63cb1a72011-05-19 17:16:39 -04002931 if (alt_kf_bits > cpi->twopass.kf_bits)
John Koleszar0ea50ce2010-05-18 11:58:33 -04002932 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002933 cpi->twopass.kf_bits = alt_kf_bits;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002934 }
2935 }
2936
John Koleszar63cb1a72011-05-19 17:16:39 -04002937 cpi->twopass.kf_group_bits -= cpi->twopass.kf_bits;
2938 cpi->twopass.kf_bits += cpi->min_frame_bandwidth; // Add in the minimum frame allowance
John Koleszar0ea50ce2010-05-18 11:58:33 -04002939
John Koleszar63cb1a72011-05-19 17:16:39 -04002940 cpi->per_frame_bandwidth = cpi->twopass.kf_bits; // Peer frame bit target for this frame
2941 cpi->target_bandwidth = cpi->twopass.kf_bits * cpi->output_frame_rate; // Convert to a per second bitrate
John Koleszar0ea50ce2010-05-18 11:58:33 -04002942 }
2943
2944 // Note the total error score of the kf group minus the key frame itself
John Koleszar63cb1a72011-05-19 17:16:39 -04002945 cpi->twopass.kf_group_error_left = (int)(kf_group_err - kf_mod_err);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002946
2947 // Adjust the count of total modified error left.
2948 // The count of bits left is adjusted elsewhere based on real coded frame sizes
John Koleszar63cb1a72011-05-19 17:16:39 -04002949 cpi->twopass.modified_error_left -= kf_group_err;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002950
2951 if (cpi->oxcf.allow_spatial_resampling)
2952 {
2953 int resample_trigger = FALSE;
2954 int last_kf_resampled = FALSE;
2955 int kf_q;
2956 int scale_val = 0;
2957 int hr, hs, vr, vs;
2958 int new_width = cpi->oxcf.Width;
2959 int new_height = cpi->oxcf.Height;
2960
2961 int projected_buffer_level = cpi->buffer_level;
2962 int tmp_q;
2963
2964 double projected_bits_perframe;
2965 double group_iiratio = (kf_group_intra_err - first_frame.intra_error) / (kf_group_coded_err - first_frame.coded_error);
John Koleszar63cb1a72011-05-19 17:16:39 -04002966 double err_per_frame = kf_group_err / cpi->twopass.frames_to_key;
John Koleszar0ea50ce2010-05-18 11:58:33 -04002967 double bits_per_frame;
2968 double av_bits_per_frame;
2969 double effective_size_ratio;
2970
2971 if ((cpi->common.Width != cpi->oxcf.Width) || (cpi->common.Height != cpi->oxcf.Height))
2972 last_kf_resampled = TRUE;
2973
2974 // Set back to unscaled by defaults
2975 cpi->common.horiz_scale = NORMAL;
2976 cpi->common.vert_scale = NORMAL;
2977
2978 // Calculate Average bits per frame.
John Koleszar63cb1a72011-05-19 17:16:39 -04002979 //av_bits_per_frame = cpi->twopass.bits_left/(double)(cpi->twopass.total_stats->count - cpi->common.current_video_frame);
John Koleszar0ea50ce2010-05-18 11:58:33 -04002980 av_bits_per_frame = cpi->oxcf.target_bandwidth / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.frame_rate);
2981 //if ( av_bits_per_frame < 0.0 )
2982 // av_bits_per_frame = 0.0
2983
2984 // CBR... Use the clip average as the target for deciding resample
2985 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2986 {
2987 bits_per_frame = av_bits_per_frame;
2988 }
2989
2990 // In VBR we want to avoid downsampling in easy section unless we are under extreme pressure
2991 // So use the larger of target bitrate for this sectoion or average bitrate for sequence
2992 else
2993 {
John Koleszar63cb1a72011-05-19 17:16:39 -04002994 bits_per_frame = cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key; // This accounts for how hard the section is...
John Koleszar0ea50ce2010-05-18 11:58:33 -04002995
2996 if (bits_per_frame < av_bits_per_frame) // Dont turn to resampling in easy sections just because they have been assigned a small number of bits
2997 bits_per_frame = av_bits_per_frame;
2998 }
2999
3000 // bits_per_frame should comply with our minimum
3001 if (bits_per_frame < (cpi->oxcf.target_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100))
3002 bits_per_frame = (cpi->oxcf.target_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100);
3003
3004 // Work out if spatial resampling is necessary
James Berryf3e9e2a2011-03-10 11:13:44 -05003005 kf_q = estimate_kf_group_q(cpi, err_per_frame, bits_per_frame, group_iiratio);
John Koleszar0ea50ce2010-05-18 11:58:33 -04003006
3007 // If we project a required Q higher than the maximum allowed Q then make a guess at the actual size of frames in this section
3008 projected_bits_perframe = bits_per_frame;
3009 tmp_q = kf_q;
3010
3011 while (tmp_q > cpi->worst_quality)
3012 {
3013 projected_bits_perframe *= 1.04;
3014 tmp_q--;
3015 }
3016
3017 // Guess at buffer level at the end of the section
John Koleszar63cb1a72011-05-19 17:16:39 -04003018 projected_buffer_level = cpi->buffer_level - (int)((projected_bits_perframe - av_bits_per_frame) * cpi->twopass.frames_to_key);
John Koleszar0ea50ce2010-05-18 11:58:33 -04003019
3020 if (0)
3021 {
3022 FILE *f = fopen("Subsamle.stt", "a");
John Koleszar63cb1a72011-05-19 17:16:39 -04003023 fprintf(f, " %8d %8d %8d %8d %12.0f %8d %8d %8d\n", cpi->common.current_video_frame, kf_q, cpi->common.horiz_scale, cpi->common.vert_scale, kf_group_err / cpi->twopass.frames_to_key, (int)(cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key), new_height, new_width);
John Koleszar0ea50ce2010-05-18 11:58:33 -04003024 fclose(f);
3025 }
3026
3027 // The trigger for spatial resampling depends on the various parameters such as whether we are streaming (CBR) or VBR.
3028 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
3029 {
3030 // Trigger resample if we are projected to fall below down sample level or
3031 // resampled last time and are projected to remain below the up sample level
3032 if ((projected_buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100)) ||
3033 (last_kf_resampled && (projected_buffer_level < (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))))
3034 //( ((cpi->buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100))) &&
3035 // ((projected_buffer_level < (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))) ))
3036 resample_trigger = TRUE;
3037 else
3038 resample_trigger = FALSE;
3039 }
3040 else
3041 {
James Zernb45065d2011-07-25 18:44:59 -07003042 int64_t clip_bits = (int64_t)(cpi->twopass.total_stats->count * cpi->oxcf.target_bandwidth / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.frame_rate));
3043 int64_t over_spend = cpi->oxcf.starting_buffer_level - cpi->buffer_level;
John Koleszar0ea50ce2010-05-18 11:58:33 -04003044
3045 if ((last_kf_resampled && (kf_q > cpi->worst_quality)) || // If triggered last time the threshold for triggering again is reduced
3046 ((kf_q > cpi->worst_quality) && // Projected Q higher than allowed and ...
3047 (over_spend > clip_bits / 20))) // ... Overspend > 5% of total bits
3048 resample_trigger = TRUE;
3049 else
3050 resample_trigger = FALSE;
3051
3052 }
3053
3054 if (resample_trigger)
3055 {
3056 while ((kf_q >= cpi->worst_quality) && (scale_val < 6))
3057 {
3058 scale_val ++;
3059
3060 cpi->common.vert_scale = vscale_lookup[scale_val];
3061 cpi->common.horiz_scale = hscale_lookup[scale_val];
3062
3063 Scale2Ratio(cpi->common.horiz_scale, &hr, &hs);
3064 Scale2Ratio(cpi->common.vert_scale, &vr, &vs);
3065
3066 new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
3067 new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
3068
3069 // Reducing the area to 1/4 does not reduce the complexity (err_per_frame) to 1/4...
3070 // effective_sizeratio attempts to provide a crude correction for this
3071 effective_size_ratio = (double)(new_width * new_height) / (double)(cpi->oxcf.Width * cpi->oxcf.Height);
3072 effective_size_ratio = (1.0 + (3.0 * effective_size_ratio)) / 4.0;
3073
3074 // Now try again and see what Q we get with the smaller image size
James Berryf3e9e2a2011-03-10 11:13:44 -05003075 kf_q = estimate_kf_group_q(cpi, err_per_frame * effective_size_ratio, bits_per_frame, group_iiratio);
John Koleszar0ea50ce2010-05-18 11:58:33 -04003076
3077 if (0)
3078 {
3079 FILE *f = fopen("Subsamle.stt", "a");
John Koleszar63cb1a72011-05-19 17:16:39 -04003080 fprintf(f, "******** %8d %8d %8d %12.0f %8d %8d %8d\n", kf_q, cpi->common.horiz_scale, cpi->common.vert_scale, kf_group_err / cpi->twopass.frames_to_key, (int)(cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key), new_height, new_width);
John Koleszar0ea50ce2010-05-18 11:58:33 -04003081 fclose(f);
3082 }
3083 }
3084 }
3085
3086 if ((cpi->common.Width != new_width) || (cpi->common.Height != new_height))
3087 {
3088 cpi->common.Width = new_width;
3089 cpi->common.Height = new_height;
3090 vp8_alloc_compressor_data(cpi);
3091 }
3092 }
3093}