2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
16 #include "encodeintra.h"
17 #include "vp8/common/setupintrarecon.h"
19 #include "vpx_scale/vpxscale.h"
21 #include "vp8/common/extend.h"
22 #include "vp8/common/systemdependent.h"
23 #include "vpx_scale/yv12extend.h"
24 #include "vpx_mem/vpx_mem.h"
25 #include "vp8/common/swapyv12buffer.h"
28 #include "vp8/common/quant_common.h"
31 //#define OUTPUT_FPF 1
33 #if CONFIG_RUNTIME_CPU_DETECT
34 #define IF_RTCD(x) (x)
36 #define IF_RTCD(x) NULL
39 extern void vp8_build_block_offsets(MACROBLOCK *x);
40 extern void vp8_setup_block_ptrs(MACROBLOCK *x);
41 extern void vp8cx_frame_init_quantizer(VP8_COMP *cpi);
42 extern void vp8_set_mbmode_and_mvs(MACROBLOCK *x, MB_PREDICTION_MODE mb, int_mv *mv);
43 extern void vp8_alloc_compressor_data(VP8_COMP *cpi);
45 //#define GFQ_ADJUSTMENT (40 + ((15*Q)/10))
46 //#define GFQ_ADJUSTMENT (80 + ((15*Q)/10))
47 #define GFQ_ADJUSTMENT vp8_gf_boost_qadjustment[Q]
48 extern int vp8_kf_boost_qadjustment[QINDEX_RANGE];
50 extern const int vp8_gf_boost_qadjustment[QINDEX_RANGE];
53 #define IIKFACTOR1 1.40
54 #define IIKFACTOR2 1.5
58 #define KF_MB_INTRA_MIN 300
59 #define GF_MB_INTRA_MIN 200
61 #define DOUBLE_DIVIDE_CHECK(X) ((X)<0?(X)-.000001:(X)+.000001)
63 #define POW1 (double)cpi->oxcf.two_pass_vbrbias/100.0
64 #define POW2 (double)cpi->oxcf.two_pass_vbrbias/100.0
66 static int vscale_lookup[7] = {0, 1, 1, 2, 2, 3, 3};
67 static int hscale_lookup[7] = {0, 0, 1, 1, 2, 2, 3};
70 static const int cq_level[QINDEX_RANGE] =
72 0,0,1,1,2,3,3,4,4,5,6,6,7,8,8,9,
73 9,10,11,11,12,13,13,14,15,15,16,17,17,18,19,20,
74 20,21,22,22,23,24,24,25,26,27,27,28,29,30,30,31,
75 32,33,33,34,35,36,36,37,38,39,39,40,41,42,42,43,
76 44,45,46,46,47,48,49,50,50,51,52,53,54,55,55,56,
77 57,58,59,60,60,61,62,63,64,65,66,67,67,68,69,70,
78 71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,
79 86,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
82 static void find_next_key_frame(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame);
84 static int encode_intra(VP8_COMP *cpi, MACROBLOCK *x, int use_dc_pred)
88 int intra_pred_var = 0;
93 x->e_mbd.mode_info_context->mbmi.mode = DC_PRED;
94 x->e_mbd.mode_info_context->mbmi.uv_mode = DC_PRED;
95 x->e_mbd.mode_info_context->mbmi.ref_frame = INTRA_FRAME;
97 vp8_encode_intra16x16mby(IF_RTCD(&cpi->rtcd), x);
101 for (i = 0; i < 16; i++)
103 BLOCKD *b = &x->e_mbd.block[i];
104 BLOCK *be = &x->block[i];
106 vp8_encode_intra4x4block(IF_RTCD(&cpi->rtcd), x, be, b, B_DC_PRED);
110 intra_pred_var = VARIANCE_INVOKE(&cpi->rtcd.variance, getmbss)(x->src_diff);
112 return intra_pred_var;
115 // Resets the first pass file to the given position using a relative seek from the current position
116 static void reset_fpf_position(VP8_COMP *cpi, FIRSTPASS_STATS *Position)
118 cpi->stats_in = Position;
121 static int lookup_next_frame_stats(VP8_COMP *cpi, FIRSTPASS_STATS *next_frame)
123 if (cpi->stats_in >= cpi->stats_in_end)
126 *next_frame = *cpi->stats_in;
130 // Calculate a modified Error used in distributing bits between easier and harder frames
131 static double calculate_modified_err(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame)
133 double av_err = cpi->total_stats->ssim_weighted_pred_err;
134 double this_err = this_frame->ssim_weighted_pred_err;
137 //double relative_next_iiratio;
138 //double next_iiratio;
139 //double sum_iiratio;
142 //FIRSTPASS_STATS next_frame;
143 //FIRSTPASS_STATS *start_pos;
145 /*start_pos = cpi->stats_in;
148 while ( (i < 1) && input_stats(cpi,&next_frame) != EOF )
151 next_iiratio = next_frame.intra_error / DOUBLE_DIVIDE_CHECK(next_frame.coded_error);
152 next_iiratio = ( next_iiratio < 1.0 ) ? 1.0 : (next_iiratio > 20.0) ? 20.0 : next_iiratio;
153 sum_iiratio += next_iiratio;
158 relative_next_iiratio = sum_iiratio / DOUBLE_DIVIDE_CHECK(cpi->avg_iiratio * (double)i);
162 relative_next_iiratio = 1.0;
164 reset_fpf_position(cpi, start_pos);*/
166 if (this_err > av_err)
167 modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW1);
169 modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW2);
172 relative_next_iiratio = pow(relative_next_iiratio,0.25);
173 modified_err = modified_err * relative_next_iiratio;
179 static const double weight_table[256] = {
180 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
181 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
182 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
183 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
184 0.020000, 0.031250, 0.062500, 0.093750, 0.125000, 0.156250, 0.187500, 0.218750,
185 0.250000, 0.281250, 0.312500, 0.343750, 0.375000, 0.406250, 0.437500, 0.468750,
186 0.500000, 0.531250, 0.562500, 0.593750, 0.625000, 0.656250, 0.687500, 0.718750,
187 0.750000, 0.781250, 0.812500, 0.843750, 0.875000, 0.906250, 0.937500, 0.968750,
188 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
189 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
190 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
191 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
192 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
193 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
194 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
195 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
196 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
197 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
198 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
199 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
200 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
201 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
202 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
203 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
204 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
205 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
206 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
207 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
208 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
209 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
210 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
211 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000
214 static double simple_weight(YV12_BUFFER_CONFIG *source)
218 unsigned char *src = source->y_buffer;
219 double sum_weights = 0.0;
221 // Loop throught the Y plane raw examining levels and creating a weight for the image
222 i = source->y_height;
228 sum_weights += weight_table[ *src];
231 src -= source->y_width;
232 src += source->y_stride;
235 sum_weights /= (source->y_height * source->y_width);
241 // This function returns the current per frame maximum bitrate target
242 static int frame_max_bits(VP8_COMP *cpi)
244 // Max allocation for a single frame based on the max section guidelines passed in and how many bits are left
247 // For CBR we need to also consider buffer fullness.
248 // If we are running below the optimal level then we need to gradually tighten up on max_bits.
249 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
251 double buffer_fullness_ratio = (double)cpi->buffer_level / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.optimal_buffer_level);
253 // For CBR base this on the target average bits per frame plus the maximum sedction rate passed in by the user
254 max_bits = (int)(cpi->av_per_frame_bandwidth * ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
256 // If our buffer is below the optimum level
257 if (buffer_fullness_ratio < 1.0)
259 // The lower of max_bits / 4 or cpi->av_per_frame_bandwidth / 4.
260 int min_max_bits = ((cpi->av_per_frame_bandwidth >> 2) < (max_bits >> 2)) ? cpi->av_per_frame_bandwidth >> 2 : max_bits >> 2;
262 max_bits = (int)(max_bits * buffer_fullness_ratio);
264 if (max_bits < min_max_bits)
265 max_bits = min_max_bits; // Lowest value we will set ... which should allow the buffer to refil.
271 // For VBR base this on the bits and frames left plus the two_pass_vbrmax_section rate passed in by the user
272 max_bits = (int)(((double)cpi->bits_left / (cpi->total_stats->count - (double)cpi->common.current_video_frame)) * ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
275 // Trap case where we are out of bits
283 static void output_stats(const VP8_COMP *cpi,
284 struct vpx_codec_pkt_list *pktlist,
285 FIRSTPASS_STATS *stats)
287 struct vpx_codec_cx_pkt pkt;
288 pkt.kind = VPX_CODEC_STATS_PKT;
289 pkt.data.twopass_stats.buf = stats;
290 pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
291 vpx_codec_pkt_list_add(pktlist, &pkt);
298 fpfile = fopen("firstpass.stt", "a");
300 fprintf(fpfile, "%12.0f %12.0f %12.0f %12.4f %12.4f %12.4f %12.4f"
301 " %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f"
306 stats->ssim_weighted_pred_err,
309 stats->pcnt_second_ref,
317 stats->mv_in_out_count,
325 static int input_stats(VP8_COMP *cpi, FIRSTPASS_STATS *fps)
327 if (cpi->stats_in >= cpi->stats_in_end)
330 *fps = *cpi->stats_in;
331 cpi->stats_in = (void*)((char *)cpi->stats_in + sizeof(FIRSTPASS_STATS));
335 static void zero_stats(FIRSTPASS_STATS *section)
337 section->frame = 0.0;
338 section->intra_error = 0.0;
339 section->coded_error = 0.0;
340 section->ssim_weighted_pred_err = 0.0;
341 section->pcnt_inter = 0.0;
342 section->pcnt_motion = 0.0;
343 section->pcnt_second_ref = 0.0;
344 section->pcnt_neutral = 0.0;
346 section->mvr_abs = 0.0;
348 section->mvc_abs = 0.0;
351 section->mv_in_out_count = 0.0;
352 section->count = 0.0;
353 section->duration = 1.0;
355 static void accumulate_stats(FIRSTPASS_STATS *section, FIRSTPASS_STATS *frame)
357 section->frame += frame->frame;
358 section->intra_error += frame->intra_error;
359 section->coded_error += frame->coded_error;
360 section->ssim_weighted_pred_err += frame->ssim_weighted_pred_err;
361 section->pcnt_inter += frame->pcnt_inter;
362 section->pcnt_motion += frame->pcnt_motion;
363 section->pcnt_second_ref += frame->pcnt_second_ref;
364 section->pcnt_neutral += frame->pcnt_neutral;
365 section->MVr += frame->MVr;
366 section->mvr_abs += frame->mvr_abs;
367 section->MVc += frame->MVc;
368 section->mvc_abs += frame->mvc_abs;
369 section->MVrv += frame->MVrv;
370 section->MVcv += frame->MVcv;
371 section->mv_in_out_count += frame->mv_in_out_count;
372 section->count += frame->count;
373 section->duration += frame->duration;
375 static void avg_stats(FIRSTPASS_STATS *section)
377 if (section->count < 1.0)
380 section->intra_error /= section->count;
381 section->coded_error /= section->count;
382 section->ssim_weighted_pred_err /= section->count;
383 section->pcnt_inter /= section->count;
384 section->pcnt_second_ref /= section->count;
385 section->pcnt_neutral /= section->count;
386 section->pcnt_motion /= section->count;
387 section->MVr /= section->count;
388 section->mvr_abs /= section->count;
389 section->MVc /= section->count;
390 section->mvc_abs /= section->count;
391 section->MVrv /= section->count;
392 section->MVcv /= section->count;
393 section->mv_in_out_count /= section->count;
394 section->duration /= section->count;
397 void vp8_init_first_pass(VP8_COMP *cpi)
399 zero_stats(cpi->total_stats);
402 void vp8_end_first_pass(VP8_COMP *cpi)
404 output_stats(cpi, cpi->output_pkt_list, cpi->total_stats);
407 static void zz_motion_search( VP8_COMP *cpi, MACROBLOCK * x, YV12_BUFFER_CONFIG * recon_buffer, int * best_motion_err, int recon_yoffset )
409 MACROBLOCKD * const xd = & x->e_mbd;
410 BLOCK *b = &x->block[0];
411 BLOCKD *d = &x->e_mbd.block[0];
413 unsigned char *src_ptr = (*(b->base_src) + b->src);
414 int src_stride = b->src_stride;
415 unsigned char *ref_ptr;
416 int ref_stride=d->pre_stride;
418 // Set up pointers for this macro block recon buffer
419 xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
421 ref_ptr = (unsigned char *)(*(d->base_pre) + d->pre );
423 VARIANCE_INVOKE(IF_RTCD(&cpi->rtcd.variance), mse16x16) ( src_ptr, src_stride, ref_ptr, ref_stride, (unsigned int *)(best_motion_err));
426 static void first_pass_motion_search(VP8_COMP *cpi, MACROBLOCK *x,
427 int_mv *ref_mv, MV *best_mv,
428 YV12_BUFFER_CONFIG *recon_buffer,
429 int *best_motion_err, int recon_yoffset )
431 MACROBLOCKD *const xd = & x->e_mbd;
432 BLOCK *b = &x->block[0];
433 BLOCKD *d = &x->e_mbd.block[0];
439 int step_param = 3; //3; // Dont search over full range for first pass
440 int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param; //3;
442 vp8_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[BLOCK_16X16];
443 int new_mv_mode_penalty = 256;
445 // override the default variance function to use MSE
446 v_fn_ptr.vf = VARIANCE_INVOKE(IF_RTCD(&cpi->rtcd.variance), mse16x16);
448 // Set up pointers for this macro block recon buffer
449 xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
451 // Initial step/diamond search centred on best mv
453 tmp_err = cpi->diamond_search_sad(x, b, d, ref_mv, &tmp_mv, step_param, x->errorperbit, &num00, &v_fn_ptr, x->mvcost, ref_mv);
454 if ( tmp_err < INT_MAX-new_mv_mode_penalty )
455 tmp_err += new_mv_mode_penalty;
457 if (tmp_err < *best_motion_err)
459 *best_motion_err = tmp_err;
460 best_mv->row = tmp_mv.as_mv.row;
461 best_mv->col = tmp_mv.as_mv.col;
464 // Further step/diamond searches as necessary
468 while (n < further_steps)
476 tmp_err = cpi->diamond_search_sad(x, b, d, ref_mv, &tmp_mv, step_param + n, x->errorperbit, &num00, &v_fn_ptr, x->mvcost, ref_mv);
477 if ( tmp_err < INT_MAX-new_mv_mode_penalty )
478 tmp_err += new_mv_mode_penalty;
480 if (tmp_err < *best_motion_err)
482 *best_motion_err = tmp_err;
483 best_mv->row = tmp_mv.as_mv.row;
484 best_mv->col = tmp_mv.as_mv.col;
490 void vp8_first_pass(VP8_COMP *cpi)
493 MACROBLOCK *const x = & cpi->mb;
494 VP8_COMMON *const cm = & cpi->common;
495 MACROBLOCKD *const xd = & x->e_mbd;
497 int recon_yoffset, recon_uvoffset;
498 YV12_BUFFER_CONFIG *lst_yv12 = &cm->yv12_fb[cm->lst_fb_idx];
499 YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
500 YV12_BUFFER_CONFIG *gld_yv12 = &cm->yv12_fb[cm->gld_fb_idx];
501 int recon_y_stride = lst_yv12->y_stride;
502 int recon_uv_stride = lst_yv12->uv_stride;
503 long long intra_error = 0;
504 long long coded_error = 0;
506 int sum_mvr = 0, sum_mvc = 0;
507 int sum_mvr_abs = 0, sum_mvc_abs = 0;
508 int sum_mvrs = 0, sum_mvcs = 0;
511 int second_ref_count = 0;
512 int intrapenalty = 256;
513 int neutral_count = 0;
515 int sum_in_vectors = 0;
519 zero_ref_mv.as_int = 0;
521 vp8_clear_system_state(); //__asm emms;
523 x->src = * cpi->Source;
527 x->partition_info = x->pi;
529 xd->mode_info_context = cm->mi;
531 vp8_build_block_offsets(x);
533 vp8_setup_block_dptrs(&x->e_mbd);
535 vp8_setup_block_ptrs(x);
537 // set up frame new frame for intra coded blocks
538 vp8_setup_intra_recon(new_yv12);
539 vp8cx_frame_init_quantizer(cpi);
541 // Initialise the MV cost table to the defaults
542 //if( cm->current_video_frame == 0)
545 int flag[2] = {1, 1};
546 vp8_initialize_rd_consts(cpi, vp8_dc_quant(cm->base_qindex, cm->y1dc_delta_q));
547 vpx_memcpy(cm->fc.mvc, vp8_default_mv_context, sizeof(vp8_default_mv_context));
548 vp8_build_component_cost_table(cpi->mb.mvcost, (const MV_CONTEXT *) cm->fc.mvc, flag);
551 // for each macroblock row in image
552 for (mb_row = 0; mb_row < cm->mb_rows; mb_row++)
556 best_ref_mv.as_int = 0;
558 // reset above block coeffs
559 xd->up_available = (mb_row != 0);
560 recon_yoffset = (mb_row * recon_y_stride * 16);
561 recon_uvoffset = (mb_row * recon_uv_stride * 8);
563 // Set up limit values for motion vectors to prevent them extending outside the UMV borders
564 x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16));
565 x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16) + (VP8BORDERINPIXELS - 16);
568 // for each macroblock col in image
569 for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
572 int gf_motion_error = INT_MAX;
573 int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
575 xd->dst.y_buffer = new_yv12->y_buffer + recon_yoffset;
576 xd->dst.u_buffer = new_yv12->u_buffer + recon_uvoffset;
577 xd->dst.v_buffer = new_yv12->v_buffer + recon_uvoffset;
578 xd->left_available = (mb_col != 0);
580 // do intra 16x16 prediction
581 this_error = encode_intra(cpi, x, use_dc_pred);
583 // "intrapenalty" below deals with situations where the intra and inter error scores are very low (eg a plain black frame)
584 // 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.
585 // When the error score is very low this causes us to pick all or lots of INTRA modes and throw lots of key frames.
586 // This penalty adds a cost matching that of a 0,0 mv to the intra case.
587 this_error += intrapenalty;
589 // Cumulative intra error total
590 intra_error += (long long)this_error;
592 // Set up limit values for motion vectors to prevent them extending outside the UMV borders
593 x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16));
594 x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + (VP8BORDERINPIXELS - 16);
596 // Other than for the first frame do a motion search
597 if (cm->current_video_frame > 0)
599 BLOCKD *d = &x->e_mbd.block[0];
602 int motion_error = INT_MAX;
604 // Simple 0,0 motion with no mv overhead
605 zz_motion_search( cpi, x, lst_yv12, &motion_error, recon_yoffset );
606 d->bmi.mv.as_mv.row = 0;
607 d->bmi.mv.as_mv.col = 0;
609 // Test last reference frame using the previous best mv as the
610 // starting point (best reference) for the search
611 first_pass_motion_search(cpi, x, &best_ref_mv,
612 &d->bmi.mv.as_mv, lst_yv12,
613 &motion_error, recon_yoffset);
615 // If the current best reference mv is not centred on 0,0 then do a 0,0 based search as well
616 if (best_ref_mv.as_int)
619 first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv,
620 lst_yv12, &tmp_err, recon_yoffset);
622 if ( tmp_err < motion_error )
624 motion_error = tmp_err;
625 d->bmi.mv.as_mv.row = tmp_mv.row;
626 d->bmi.mv.as_mv.col = tmp_mv.col;
630 // Experimental search in a second reference frame ((0,0) based only)
631 if (cm->current_video_frame > 1)
633 first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv, gld_yv12, &gf_motion_error, recon_yoffset);
635 if ((gf_motion_error < motion_error) && (gf_motion_error < this_error))
638 //motion_error = gf_motion_error;
639 //d->bmi.mv.as_mv.row = tmp_mv.row;
640 //d->bmi.mv.as_mv.col = tmp_mv.col;
644 xd->pre.y_buffer = cm->last_frame.y_buffer + recon_yoffset;
645 xd->pre.u_buffer = cm->last_frame.u_buffer + recon_uvoffset;
646 xd->pre.v_buffer = cm->last_frame.v_buffer + recon_uvoffset;
650 // Reset to last frame as reference buffer
651 xd->pre.y_buffer = lst_yv12->y_buffer + recon_yoffset;
652 xd->pre.u_buffer = lst_yv12->u_buffer + recon_uvoffset;
653 xd->pre.v_buffer = lst_yv12->v_buffer + recon_uvoffset;
656 /* Intra assumed best */
657 best_ref_mv.as_int = 0;
659 if (motion_error <= this_error)
661 // Keep a count of cases where the inter and intra were
662 // very close and very low. This helps with scene cut
663 // detection for example in cropped clips with black bars
664 // at the sides or top and bottom.
665 if( (((this_error-intrapenalty) * 9) <=
666 (motion_error*10)) &&
667 (this_error < (2*intrapenalty)) )
672 d->bmi.mv.as_mv.row <<= 3;
673 d->bmi.mv.as_mv.col <<= 3;
674 this_error = motion_error;
675 vp8_set_mbmode_and_mvs(x, NEWMV, &d->bmi.mv);
676 vp8_encode_inter16x16y(IF_RTCD(&cpi->rtcd), x);
677 sum_mvr += d->bmi.mv.as_mv.row;
678 sum_mvr_abs += abs(d->bmi.mv.as_mv.row);
679 sum_mvc += d->bmi.mv.as_mv.col;
680 sum_mvc_abs += abs(d->bmi.mv.as_mv.col);
681 sum_mvrs += d->bmi.mv.as_mv.row * d->bmi.mv.as_mv.row;
682 sum_mvcs += d->bmi.mv.as_mv.col * d->bmi.mv.as_mv.col;
685 best_ref_mv.as_int = d->bmi.mv.as_int;
687 // Was the vector non-zero
688 if (d->bmi.mv.as_int)
692 // Does the Row vector point inwards or outwards
693 if (mb_row < cm->mb_rows / 2)
695 if (d->bmi.mv.as_mv.row > 0)
697 else if (d->bmi.mv.as_mv.row < 0)
700 else if (mb_row > cm->mb_rows / 2)
702 if (d->bmi.mv.as_mv.row > 0)
704 else if (d->bmi.mv.as_mv.row < 0)
708 // Does the Row vector point inwards or outwards
709 if (mb_col < cm->mb_cols / 2)
711 if (d->bmi.mv.as_mv.col > 0)
713 else if (d->bmi.mv.as_mv.col < 0)
716 else if (mb_col > cm->mb_cols / 2)
718 if (d->bmi.mv.as_mv.col > 0)
720 else if (d->bmi.mv.as_mv.col < 0)
727 coded_error += (long long)this_error;
729 // adjust to the next column of macroblocks
730 x->src.y_buffer += 16;
731 x->src.u_buffer += 8;
732 x->src.v_buffer += 8;
738 // adjust to the next row of mbs
739 x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
740 x->src.u_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
741 x->src.v_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
743 //extend the recon for intra prediction
744 vp8_extend_mb_row(new_yv12, xd->dst.y_buffer + 16, xd->dst.u_buffer + 8, xd->dst.v_buffer + 8);
745 vp8_clear_system_state(); //__asm emms;
748 vp8_clear_system_state(); //__asm emms;
754 fps.frame = cm->current_video_frame ;
755 fps.intra_error = intra_error >> 8;
756 fps.coded_error = coded_error >> 8;
757 weight = simple_weight(cpi->Source);
763 fps.ssim_weighted_pred_err = fps.coded_error * weight;
765 fps.pcnt_inter = 0.0;
766 fps.pcnt_motion = 0.0;
773 fps.mv_in_out_count = 0.0;
776 fps.pcnt_inter = 1.0 * (double)intercount / cm->MBs;
777 fps.pcnt_second_ref = 1.0 * (double)second_ref_count / cm->MBs;
778 fps.pcnt_neutral = 1.0 * (double)neutral_count / cm->MBs;
782 fps.MVr = (double)sum_mvr / (double)mvcount;
783 fps.mvr_abs = (double)sum_mvr_abs / (double)mvcount;
784 fps.MVc = (double)sum_mvc / (double)mvcount;
785 fps.mvc_abs = (double)sum_mvc_abs / (double)mvcount;
786 fps.MVrv = ((double)sum_mvrs - (fps.MVr * fps.MVr / (double)mvcount)) / (double)mvcount;
787 fps.MVcv = ((double)sum_mvcs - (fps.MVc * fps.MVc / (double)mvcount)) / (double)mvcount;
788 fps.mv_in_out_count = (double)sum_in_vectors / (double)(mvcount * 2);
790 fps.pcnt_motion = 1.0 * (double)mvcount / cpi->common.MBs;
793 // TODO: handle the case when duration is set to 0, or something less
794 // than the full time between subsequent cpi->source_time_stamp s .
795 fps.duration = cpi->source->ts_end
796 - cpi->source->ts_start;
798 // don't want to do output stats with a stack variable!
799 memcpy(cpi->this_frame_stats,
801 sizeof(FIRSTPASS_STATS));
802 output_stats(cpi, cpi->output_pkt_list, cpi->this_frame_stats);
803 accumulate_stats(cpi->total_stats, &fps);
806 // Copy the previous Last Frame into the GF buffer if specific conditions for doing so are met
807 if ((cm->current_video_frame > 0) &&
808 (cpi->this_frame_stats->pcnt_inter > 0.20) &&
809 ((cpi->this_frame_stats->intra_error / cpi->this_frame_stats->coded_error) > 2.0))
811 vp8_yv12_copy_frame_ptr(lst_yv12, gld_yv12);
814 // swap frame pointers so last frame refers to the frame we just compressed
815 vp8_swap_yv12_buffer(lst_yv12, new_yv12);
816 vp8_yv12_extend_frame_borders(lst_yv12);
818 // Special case for the first frame. Copy into the GF buffer as a second reference.
819 if (cm->current_video_frame == 0)
821 vp8_yv12_copy_frame_ptr(lst_yv12, gld_yv12);
825 // use this to see what the first pass reconstruction looks like
830 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
832 if (cm->current_video_frame == 0)
833 recon_file = fopen(filename, "wb");
835 recon_file = fopen(filename, "ab");
837 if(fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file));
841 cm->current_video_frame++;
844 extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
846 #define BASE_ERRPERMB 150
847 static int estimate_max_q(VP8_COMP *cpi, double section_err, int section_target_bandwitdh)
850 int num_mbs = cpi->common.MBs;
851 int target_norm_bits_per_mb;
853 double err_per_mb = section_err / num_mbs;
854 double correction_factor;
856 double speed_correction = 1.0;
857 double rolling_ratio;
859 double pow_highq = 0.90;
860 double pow_lowq = 0.40;
862 if (section_target_bandwitdh <= 0)
863 return cpi->maxq_max_limit; // Highest value allowed
865 target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20)) ? (512 * section_target_bandwitdh) / num_mbs : 512 * (section_target_bandwitdh / num_mbs);
867 // Calculate a corrective factor based on a rolling ratio of bits spent vs target bits
868 if ((cpi->rolling_target_bits > 0.0) && (cpi->active_worst_quality < cpi->worst_quality))
870 rolling_ratio = (double)cpi->rolling_actual_bits / (double)cpi->rolling_target_bits;
872 //if ( cpi->est_max_qcorrection_factor > rolling_ratio )
873 if (rolling_ratio < 0.95)
874 //cpi->est_max_qcorrection_factor *= adjustment_rate;
875 cpi->est_max_qcorrection_factor -= 0.005;
876 //else if ( cpi->est_max_qcorrection_factor < rolling_ratio )
877 else if (rolling_ratio > 1.05)
878 cpi->est_max_qcorrection_factor += 0.005;
880 //cpi->est_max_qcorrection_factor /= adjustment_rate;
882 cpi->est_max_qcorrection_factor = (cpi->est_max_qcorrection_factor < 0.1) ? 0.1 : (cpi->est_max_qcorrection_factor > 10.0) ? 10.0 : cpi->est_max_qcorrection_factor;
885 // Corrections for higher compression speed settings (reduced compression expected)
886 if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1))
888 if (cpi->oxcf.cpu_used <= 5)
889 speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
891 speed_correction = 1.25;
894 // Correction factor used for Q values >= 20
895 corr_high = pow(err_per_mb / BASE_ERRPERMB, pow_highq);
896 corr_high = (corr_high < 0.05)
897 ? 0.05 : (corr_high > 5.0) ? 5.0 : corr_high;
899 // Try and pick a max Q that will be high enough to encode the
900 // content at the given rate.
901 for (Q = cpi->maxq_min_limit; Q < cpi->maxq_max_limit; Q++)
903 int bits_per_mb_at_this_q;
907 correction_factor = pow(err_per_mb / BASE_ERRPERMB, (pow_lowq + Q * 0.01));
908 correction_factor = (correction_factor < 0.05) ? 0.05 : (correction_factor > 5.0) ? 5.0 : correction_factor;
911 correction_factor = corr_high;
913 bits_per_mb_at_this_q = (int)(.5 + correction_factor * speed_correction * cpi->est_max_qcorrection_factor * cpi->section_max_qfactor * (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0);
914 //bits_per_mb_at_this_q = (int)(.5 + correction_factor * speed_correction * cpi->est_max_qcorrection_factor * (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0);
916 if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
920 // Restriction on active max q for constrained quality mode.
921 if ( (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
922 (Q < cpi->cq_target_quality) )
923 //(Q < cpi->oxcf.cq_level;) )
925 Q = cpi->cq_target_quality;
926 //Q = cpi->oxcf.cq_level;
929 // Adjust maxq_min_limit and maxq_max_limit limits based on
930 // averaga q observed in clip for non kf/gf.arf frames
931 // Give average a chance to settle though.
932 if ( (cpi->ni_frames >
933 ((unsigned int)cpi->total_stats->count >> 8)) &&
934 (cpi->ni_frames > 150) )
936 cpi->maxq_max_limit = ((cpi->ni_av_qi + 32) < cpi->worst_quality)
937 ? (cpi->ni_av_qi + 32) : cpi->worst_quality;
938 cpi->maxq_min_limit = ((cpi->ni_av_qi - 32) > cpi->best_quality)
939 ? (cpi->ni_av_qi - 32) : cpi->best_quality;
944 static int estimate_q(VP8_COMP *cpi, double section_err, int section_target_bandwitdh)
947 int num_mbs = cpi->common.MBs;
948 int target_norm_bits_per_mb;
950 double err_per_mb = section_err / num_mbs;
951 double correction_factor;
953 double speed_correction = 1.0;
954 double pow_highq = 0.90;
955 double pow_lowq = 0.40;
957 target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20)) ? (512 * section_target_bandwitdh) / num_mbs : 512 * (section_target_bandwitdh / num_mbs);
959 // Corrections for higher compression speed settings (reduced compression expected)
960 if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1))
962 if (cpi->oxcf.cpu_used <= 5)
963 speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
965 speed_correction = 1.25;
968 // Correction factor used for Q values >= 20
969 corr_high = pow(err_per_mb / BASE_ERRPERMB, pow_highq);
970 corr_high = (corr_high < 0.05) ? 0.05 : (corr_high > 5.0) ? 5.0 : corr_high;
972 // Try and pick a Q that can encode the content at the given rate.
973 for (Q = 0; Q < MAXQ; Q++)
975 int bits_per_mb_at_this_q;
979 correction_factor = pow(err_per_mb / BASE_ERRPERMB, (pow_lowq + Q * 0.01));
980 correction_factor = (correction_factor < 0.05) ? 0.05 : (correction_factor > 5.0) ? 5.0 : correction_factor;
983 correction_factor = corr_high;
985 bits_per_mb_at_this_q = (int)(.5 + correction_factor * speed_correction * cpi->est_max_qcorrection_factor * (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0);
987 if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
994 // Estimate a worst case Q for a KF group
995 static int estimate_kf_group_q(VP8_COMP *cpi, double section_err, int section_target_bandwitdh, double group_iiratio)
998 int num_mbs = cpi->common.MBs;
999 int target_norm_bits_per_mb = (512 * section_target_bandwitdh) / num_mbs;
1000 int bits_per_mb_at_this_q;
1002 double err_per_mb = section_err / num_mbs;
1003 double err_correction_factor;
1005 double speed_correction = 1.0;
1006 double current_spend_ratio = 1.0;
1008 double pow_highq = (POW1 < 0.6) ? POW1 + 0.3 : 0.90;
1009 double pow_lowq = (POW1 < 0.7) ? POW1 + 0.1 : 0.80;
1011 double iiratio_correction_factor = 1.0;
1013 double combined_correction_factor;
1015 // Trap special case where the target is <= 0
1016 if (target_norm_bits_per_mb <= 0)
1019 // Calculate a corrective factor based on a rolling ratio of bits spent vs target bits
1020 // This is clamped to the range 0.1 to 10.0
1021 if (cpi->long_rolling_target_bits <= 0)
1022 current_spend_ratio = 10.0;
1025 current_spend_ratio = (double)cpi->long_rolling_actual_bits / (double)cpi->long_rolling_target_bits;
1026 current_spend_ratio = (current_spend_ratio > 10.0) ? 10.0 : (current_spend_ratio < 0.1) ? 0.1 : current_spend_ratio;
1029 // Calculate a correction factor based on the quality of prediction in the sequence as indicated by intra_inter error score ratio (IIRatio)
1030 // The idea here is to favour subsampling in the hardest sections vs the easyest.
1031 iiratio_correction_factor = 1.0 - ((group_iiratio - 6.0) * 0.1);
1033 if (iiratio_correction_factor < 0.5)
1034 iiratio_correction_factor = 0.5;
1036 // Corrections for higher compression speed settings (reduced compression expected)
1037 if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1))
1039 if (cpi->oxcf.cpu_used <= 5)
1040 speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
1042 speed_correction = 1.25;
1045 // Combine the various factors calculated above
1046 combined_correction_factor = speed_correction * iiratio_correction_factor * current_spend_ratio;
1048 // Correction factor used for Q values >= 20
1049 corr_high = pow(err_per_mb / BASE_ERRPERMB, pow_highq);
1050 corr_high = (corr_high < 0.05) ? 0.05 : (corr_high > 5.0) ? 5.0 : corr_high;
1052 // Try and pick a Q that should be high enough to encode the content at the given rate.
1053 for (Q = 0; Q < MAXQ; Q++)
1055 // Q values < 20 treated as a special case
1058 err_correction_factor = pow(err_per_mb / BASE_ERRPERMB, (pow_lowq + Q * 0.01));
1059 err_correction_factor = (err_correction_factor < 0.05) ? 0.05 : (err_correction_factor > 5.0) ? 5.0 : err_correction_factor;
1062 err_correction_factor = corr_high;
1064 bits_per_mb_at_this_q = (int)(.5 + err_correction_factor * combined_correction_factor * (double)vp8_bits_per_mb[INTER_FRAME][Q]);
1066 if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
1070 // If we could not hit the target even at Max Q then estimate what Q would have bee required
1071 while ((bits_per_mb_at_this_q > target_norm_bits_per_mb) && (Q < (MAXQ * 2)))
1074 bits_per_mb_at_this_q = (int)(0.96 * bits_per_mb_at_this_q);
1080 FILE *f = fopen("estkf_q.stt", "a");
1081 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,
1082 target_norm_bits_per_mb, err_per_mb, err_correction_factor,
1083 current_spend_ratio, group_iiratio, iiratio_correction_factor,
1084 (double)cpi->buffer_level / (double)cpi->oxcf.optimal_buffer_level, Q);
1091 // For cq mode estimate a cq level that matches the observed
1092 // complexity and data rate.
1093 static int estimate_cq(VP8_COMP *cpi, double section_err, int section_target_bandwitdh)
1096 int num_mbs = cpi->common.MBs;
1097 int target_norm_bits_per_mb;
1099 double err_per_mb = section_err / num_mbs;
1100 double correction_factor;
1102 double speed_correction = 1.0;
1103 double pow_highq = 0.90;
1104 double pow_lowq = 0.40;
1105 double clip_iiratio;
1106 double clip_iifactor;
1108 target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
1109 ? (512 * section_target_bandwitdh) / num_mbs
1110 : 512 * (section_target_bandwitdh / num_mbs);
1112 // Corrections for higher compression speed settings
1113 // (reduced compression expected)
1114 if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1))
1116 if (cpi->oxcf.cpu_used <= 5)
1117 speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
1119 speed_correction = 1.25;
1121 // II ratio correction factor for clip as a whole
1122 clip_iiratio = cpi->total_stats->intra_error /
1123 DOUBLE_DIVIDE_CHECK(cpi->total_stats->coded_error);
1124 clip_iifactor = 1.0 - ((clip_iiratio - 10.0) * 0.025);
1125 if (clip_iifactor < 0.80)
1126 clip_iifactor = 0.80;
1128 // Correction factor used for Q values >= 20
1129 corr_high = pow(err_per_mb / BASE_ERRPERMB, pow_highq);
1130 corr_high = (corr_high < 0.05) ? 0.05 : (corr_high > 5.0) ? 5.0 : corr_high;
1132 // Try and pick a Q that can encode the content at the given rate.
1133 for (Q = 0; Q < MAXQ; Q++)
1135 int bits_per_mb_at_this_q;
1140 pow( err_per_mb / BASE_ERRPERMB, (pow_lowq + Q * 0.01));
1142 correction_factor = (correction_factor < 0.05) ? 0.05
1143 : (correction_factor > 5.0) ? 5.0
1144 : correction_factor;
1147 correction_factor = corr_high;
1149 bits_per_mb_at_this_q =
1150 (int)( .5 + correction_factor *
1153 (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0);
1155 if (bits_per_mb_at_this_q <= target_norm_bits_per_mb)
1162 extern void vp8_new_frame_rate(VP8_COMP *cpi, double framerate);
1164 void vp8_init_second_pass(VP8_COMP *cpi)
1166 FIRSTPASS_STATS this_frame;
1167 FIRSTPASS_STATS *start_pos;
1169 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100);
1171 zero_stats(cpi->total_stats);
1173 if (!cpi->stats_in_end)
1176 *cpi->total_stats = *cpi->stats_in_end;
1178 cpi->total_error_left = cpi->total_stats->ssim_weighted_pred_err;
1179 cpi->total_intra_error_left = cpi->total_stats->intra_error;
1180 cpi->total_coded_error_left = cpi->total_stats->coded_error;
1181 cpi->start_tot_err_left = cpi->total_error_left;
1183 //cpi->bits_left = (long long)(cpi->total_stats->count * cpi->oxcf.target_bandwidth / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.frame_rate));
1184 //cpi->bits_left -= (long long)(cpi->total_stats->count * two_pass_min_rate / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.frame_rate));
1186 // each frame can have a different duration, as the frame rate in the source
1187 // isn't guaranteed to be constant. The frame rate prior to the first frame
1188 // encoded in the second pass is a guess. However the sum duration is not.
1189 // Its calculated based on the actual durations of all frames from the first
1191 vp8_new_frame_rate(cpi, 10000000.0 * cpi->total_stats->count / cpi->total_stats->duration);
1193 cpi->output_frame_rate = cpi->oxcf.frame_rate;
1194 cpi->bits_left = (long long)(cpi->total_stats->duration * cpi->oxcf.target_bandwidth / 10000000.0) ;
1195 cpi->bits_left -= (long long)(cpi->total_stats->duration * two_pass_min_rate / 10000000.0);
1196 cpi->clip_bits_total = cpi->bits_left;
1198 // Calculate a minimum intra value to be used in determining the IIratio
1199 // scores used in the second pass. We have this minimum to make sure
1200 // that clips that are static but "low complexity" in the intra domain
1201 // are still boosted appropriately for KF/GF/ARF
1202 cpi->kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
1203 cpi->gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
1205 avg_stats(cpi->total_stats);
1207 // Scan the first pass file and calculate an average Intra / Inter error score ratio for the sequence
1209 double sum_iiratio = 0.0;
1212 start_pos = cpi->stats_in; // Note starting "file" position
1214 while (input_stats(cpi, &this_frame) != EOF)
1216 IIRatio = this_frame.intra_error / DOUBLE_DIVIDE_CHECK(this_frame.coded_error);
1217 IIRatio = (IIRatio < 1.0) ? 1.0 : (IIRatio > 20.0) ? 20.0 : IIRatio;
1218 sum_iiratio += IIRatio;
1221 cpi->avg_iiratio = sum_iiratio / DOUBLE_DIVIDE_CHECK((double)cpi->total_stats->count);
1223 // Reset file position
1224 reset_fpf_position(cpi, start_pos);
1227 // Scan the first pass file and calculate a modified total error based upon the bias/power function
1228 // used to allocate bits
1230 start_pos = cpi->stats_in; // Note starting "file" position
1232 cpi->modified_error_total = 0.0;
1233 cpi->modified_error_used = 0.0;
1235 while (input_stats(cpi, &this_frame) != EOF)
1237 cpi->modified_error_total += calculate_modified_err(cpi, &this_frame);
1239 cpi->modified_error_left = cpi->modified_error_total;
1241 reset_fpf_position(cpi, start_pos); // Reset file position
1246 void vp8_end_second_pass(VP8_COMP *cpi)
1250 // This function gives and estimate of how badly we believe
1251 // the prediction quality is decaying from frame to frame.
1252 static double get_prediction_decay_rate(VP8_COMP *cpi, FIRSTPASS_STATS *next_frame)
1254 double prediction_decay_rate;
1255 double motion_decay;
1256 double motion_pct = next_frame->pcnt_motion;
1259 // Initial basis is the % mbs inter coded
1260 prediction_decay_rate = next_frame->pcnt_inter;
1262 // High % motion -> somewhat higher decay rate
1263 motion_decay = (1.0 - (motion_pct / 20.0));
1264 if (motion_decay < prediction_decay_rate)
1265 prediction_decay_rate = motion_decay;
1267 // Adjustment to decay rate based on speed of motion
1269 double this_mv_rabs;
1270 double this_mv_cabs;
1271 double distance_factor;
1273 this_mv_rabs = fabs(next_frame->mvr_abs * motion_pct);
1274 this_mv_cabs = fabs(next_frame->mvc_abs * motion_pct);
1276 distance_factor = sqrt((this_mv_rabs * this_mv_rabs) +
1277 (this_mv_cabs * this_mv_cabs)) / 250.0;
1278 distance_factor = ((distance_factor > 1.0)
1279 ? 0.0 : (1.0 - distance_factor));
1280 if (distance_factor < prediction_decay_rate)
1281 prediction_decay_rate = distance_factor;
1284 return prediction_decay_rate;
1287 // Function to test for a condition where a complex transition is followed
1288 // by a static section. For example in slide shows where there is a fade
1289 // between slides. This is to help with more optimal kf and gf positioning.
1290 static int detect_transition_to_still(
1294 double loop_decay_rate,
1295 double decay_accumulator )
1297 BOOL trans_to_still = FALSE;
1299 // Break clause to detect very still sections after motion
1300 // For example a static image after a fade or other transition
1301 // instead of a clean scene cut.
1302 if ( (frame_interval > MIN_GF_INTERVAL) &&
1303 (loop_decay_rate >= 0.999) &&
1304 (decay_accumulator < 0.9) )
1307 FIRSTPASS_STATS * position = cpi->stats_in;
1308 FIRSTPASS_STATS tmp_next_frame;
1311 // Look ahead a few frames to see if static condition
1313 for ( j = 0; j < still_interval; j++ )
1315 if (EOF == input_stats(cpi, &tmp_next_frame))
1318 decay_rate = get_prediction_decay_rate(cpi, &tmp_next_frame);
1319 if ( decay_rate < 0.999 )
1322 // Reset file position
1323 reset_fpf_position(cpi, position);
1325 // Only if it does do we signal a transition to still
1326 if ( j == still_interval )
1327 trans_to_still = TRUE;
1330 return trans_to_still;
1333 // Analyse and define a gf/arf group .
1334 static void define_gf_group(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame)
1336 FIRSTPASS_STATS next_frame;
1337 FIRSTPASS_STATS *start_pos;
1339 double boost_score = 0.0;
1340 double old_boost_score = 0.0;
1341 double gf_group_err = 0.0;
1342 double gf_first_frame_err = 0.0;
1343 double mod_frame_err = 0.0;
1345 double mv_accumulator_rabs = 0.0;
1346 double mv_accumulator_cabs = 0.0;
1347 double mv_ratio_accumulator = 0.0;
1348 double decay_accumulator = 1.0;
1350 double boost_factor = IIFACTOR;
1351 double loop_decay_rate = 1.00; // Starting decay rate
1353 double this_frame_mv_in_out = 0.0;
1354 double mv_in_out_accumulator = 0.0;
1355 double abs_mv_in_out_accumulator = 0.0;
1356 double mod_err_per_mb_accumulator = 0.0;
1358 int max_bits = frame_max_bits(cpi); // Max for a single frame
1360 unsigned int allow_alt_ref =
1361 cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames;
1363 cpi->gf_group_bits = 0;
1364 cpi->gf_decay_rate = 0;
1366 vp8_clear_system_state(); //__asm emms;
1368 start_pos = cpi->stats_in;
1370 vpx_memset(&next_frame, 0, sizeof(next_frame)); // assure clean
1372 // Preload the stats for the next frame.
1373 mod_frame_err = calculate_modified_err(cpi, this_frame);
1375 // Note the error of the frame at the start of the group (this will be
1376 // the GF frame error if we code a normal gf
1377 gf_first_frame_err = mod_frame_err;
1379 // Special treatment if the current frame is a key frame (which is also
1380 // a gf). If it is then its error score (and hence bit allocation) need
1381 // to be subtracted out from the calculation for the GF group
1382 if (cpi->common.frame_type == KEY_FRAME)
1383 gf_group_err -= gf_first_frame_err;
1385 // Scan forward to try and work out how many frames the next gf group
1386 // should contain and what level of boost is appropriate for the GF
1387 // or ARF that will be coded with the group
1390 while (((i < cpi->static_scene_max_gf_interval) ||
1391 ((cpi->frames_to_key - i) < MIN_GF_INTERVAL)) &&
1392 (i < cpi->frames_to_key))
1395 double this_frame_mvr_ratio;
1396 double this_frame_mvc_ratio;
1397 //double motion_pct = next_frame.pcnt_motion;
1400 i++; // Increment the loop counter
1402 // Accumulate error score of frames in this gf group
1403 mod_frame_err = calculate_modified_err(cpi, this_frame);
1405 gf_group_err += mod_frame_err;
1407 mod_err_per_mb_accumulator +=
1408 mod_frame_err / DOUBLE_DIVIDE_CHECK((double)cpi->common.MBs);
1410 if (EOF == input_stats(cpi, &next_frame))
1413 // Accumulate motion stats.
1414 motion_pct = next_frame.pcnt_motion;
1415 mv_accumulator_rabs += fabs(next_frame.mvr_abs * motion_pct);
1416 mv_accumulator_cabs += fabs(next_frame.mvc_abs * motion_pct);
1418 //Accumulate Motion In/Out of frame stats
1419 this_frame_mv_in_out =
1420 next_frame.mv_in_out_count * motion_pct;
1421 mv_in_out_accumulator +=
1422 next_frame.mv_in_out_count * motion_pct;
1423 abs_mv_in_out_accumulator +=
1424 fabs(next_frame.mv_in_out_count * motion_pct);
1426 // If there is a significant amount of motion
1427 if (motion_pct > 0.05)
1429 this_frame_mvr_ratio = fabs(next_frame.mvr_abs) /
1430 DOUBLE_DIVIDE_CHECK(fabs(next_frame.MVr));
1432 this_frame_mvc_ratio = fabs(next_frame.mvc_abs) /
1433 DOUBLE_DIVIDE_CHECK(fabs(next_frame.MVc));
1435 mv_ratio_accumulator +=
1436 (this_frame_mvr_ratio < next_frame.mvr_abs)
1437 ? (this_frame_mvr_ratio * motion_pct)
1438 : next_frame.mvr_abs * motion_pct;
1440 mv_ratio_accumulator +=
1441 (this_frame_mvc_ratio < next_frame.mvc_abs)
1442 ? (this_frame_mvc_ratio * motion_pct)
1443 : next_frame.mvc_abs * motion_pct;
1447 mv_ratio_accumulator += 0.0;
1448 this_frame_mvr_ratio = 1.0;
1449 this_frame_mvc_ratio = 1.0;
1452 // Underlying boost factor is based on inter intra error ratio
1453 r = ( boost_factor *
1454 ( next_frame.intra_error /
1455 DOUBLE_DIVIDE_CHECK(next_frame.coded_error)));
1457 if (next_frame.intra_error > cpi->gf_intra_err_min)
1458 r = (IIKFACTOR2 * next_frame.intra_error /
1459 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
1461 r = (IIKFACTOR2 * cpi->gf_intra_err_min /
1462 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
1464 // Increase boost for frames where new data coming into frame
1465 // (eg zoom out). Slightly reduce boost if there is a net balance
1466 // of motion out of the frame (zoom in).
1467 // The range for this_frame_mv_in_out is -1.0 to +1.0
1468 if (this_frame_mv_in_out > 0.0)
1469 r += r * (this_frame_mv_in_out * 2.0);
1470 // In extreme case boost is halved
1472 r += r * (this_frame_mv_in_out / 2.0);
1477 loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
1479 // Cumulative effect of decay
1480 decay_accumulator = decay_accumulator * loop_decay_rate;
1481 decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
1483 boost_score += (decay_accumulator * r);
1485 // Break clause to detect very still sections after motion
1486 // For example a staic image after a fade or other transition.
1487 if ( detect_transition_to_still( cpi, i, 5,
1488 loop_decay_rate, decay_accumulator ) )
1490 allow_alt_ref = FALSE;
1491 boost_score = old_boost_score;
1495 // Break out conditions.
1497 // Break at cpi->max_gf_interval unless almost totally static
1498 (i >= cpi->max_gf_interval && (decay_accumulator < 0.995)) ||
1500 // Dont break out with a very short interval
1501 (i > MIN_GF_INTERVAL) &&
1502 // Dont break out very close to a key frame
1503 ((cpi->frames_to_key - i) >= MIN_GF_INTERVAL) &&
1504 ((boost_score > 20.0) || (next_frame.pcnt_inter < 0.75)) &&
1505 ((mv_ratio_accumulator > 100.0) ||
1506 (abs_mv_in_out_accumulator > 3.0) ||
1507 (mv_in_out_accumulator < -2.0) ||
1508 ((boost_score - old_boost_score) < 2.0))
1511 boost_score = old_boost_score;
1515 vpx_memcpy(this_frame, &next_frame, sizeof(*this_frame));
1517 old_boost_score = boost_score;
1520 cpi->gf_decay_rate =
1521 (i > 0) ? (int)(100.0 * (1.0 - decay_accumulator)) / i : 0;
1523 // When using CBR apply additional buffer related upper limits
1524 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
1528 // For cbr apply buffer related limits
1529 if (cpi->drop_frames_allowed)
1531 int df_buffer_level = cpi->oxcf.drop_frames_water_mark *
1532 (cpi->oxcf.optimal_buffer_level / 100);
1534 if (cpi->buffer_level > df_buffer_level)
1535 max_boost = ((double)((cpi->buffer_level - df_buffer_level) * 2 / 3) * 16.0) / DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
1539 else if (cpi->buffer_level > 0)
1541 max_boost = ((double)(cpi->buffer_level * 2 / 3) * 16.0) / DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
1548 if (boost_score > max_boost)
1549 boost_score = max_boost;
1552 cpi->gfu_boost = (int)(boost_score * 100.0) >> 4;
1554 // Should we use the alternate refernce frame
1555 if (allow_alt_ref &&
1556 (i >= MIN_GF_INTERVAL) &&
1557 // dont use ARF very near next kf
1558 (i <= (cpi->frames_to_key - MIN_GF_INTERVAL)) &&
1559 (((next_frame.pcnt_inter > 0.75) &&
1560 ((mv_in_out_accumulator / (double)i > -0.2) || (mv_in_out_accumulator > -2.0)) &&
1561 //(cpi->gfu_boost>150) &&
1562 (cpi->gfu_boost > 100) &&
1563 //(cpi->gfu_boost>AF_THRESH2) &&
1564 //((cpi->gfu_boost/i)>AF_THRESH) &&
1565 //(decay_accumulator > 0.5) &&
1566 (cpi->gf_decay_rate <= (ARF_DECAY_THRESH + (cpi->gfu_boost / 200)))
1572 int allocation_chunks;
1573 int Q = (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
1575 int arf_frame_bits = 0;
1578 // Estimate the bits to be allocated to the group as a whole
1579 if ((cpi->kf_group_bits > 0) && (cpi->kf_group_error_left > 0))
1580 group_bits = (int)((double)cpi->kf_group_bits * (gf_group_err / (double)cpi->kf_group_error_left));
1584 // Boost for arf frame
1585 Boost = (cpi->gfu_boost * 3 * GFQ_ADJUSTMENT) / (2 * 100);
1587 allocation_chunks = (i * 100) + Boost;
1589 // Normalize Altboost and allocations chunck down to prevent overflow
1590 while (Boost > 1000)
1593 allocation_chunks /= 2;
1596 // Calculate the number of bits to be spent on the arf based on the boost number
1597 arf_frame_bits = (int)((double)Boost * (group_bits / (double)allocation_chunks));
1599 // Estimate if there are enough bits available to make worthwhile use of an arf.
1600 tmp_q = estimate_q(cpi, mod_frame_err, (int)arf_frame_bits);
1602 // Only use an arf if it is likely we will be able to code it at a lower Q than the surrounding frames.
1603 if (tmp_q < cpi->worst_quality)
1606 int frames_after_arf;
1607 int frames_bwd = cpi->oxcf.arnr_max_frames - 1;
1608 int frames_fwd = cpi->oxcf.arnr_max_frames - 1;
1610 cpi->source_alt_ref_pending = TRUE;
1612 // For alt ref frames the error score for the end frame of the group (the alt ref frame) should not contribute to the group total and hence
1613 // the number of bit allocated to the group. Rather it forms part of the next group (it is the GF at the start of the next group)
1614 gf_group_err -= mod_frame_err;
1616 // Set the interval till the next gf or arf. For ARFs this is the number of frames to be coded before the future frame that is coded as an ARF.
1617 // The future frame itself is part of the next group
1618 cpi->baseline_gf_interval = i - 1;
1620 // Define the arnr filter width for this group of frames:
1621 // We only filter frames that lie within a distance of half
1622 // the GF interval from the ARF frame. We also have to trap
1623 // cases where the filter extends beyond the end of clip.
1624 // Note: this_frame->frame has been updated in the loop
1625 // so it now points at the ARF frame.
1626 half_gf_int = cpi->baseline_gf_interval >> 1;
1627 frames_after_arf = cpi->total_stats->count - this_frame->frame - 1;
1629 switch (cpi->oxcf.arnr_type)
1631 case 1: // Backward filter
1633 if (frames_bwd > half_gf_int)
1634 frames_bwd = half_gf_int;
1637 case 2: // Forward filter
1638 if (frames_fwd > half_gf_int)
1639 frames_fwd = half_gf_int;
1640 if (frames_fwd > frames_after_arf)
1641 frames_fwd = frames_after_arf;
1645 case 3: // Centered filter
1648 if (frames_fwd > frames_after_arf)
1649 frames_fwd = frames_after_arf;
1650 if (frames_fwd > half_gf_int)
1651 frames_fwd = half_gf_int;
1653 frames_bwd = frames_fwd;
1655 // For even length filter there is one more frame backward
1656 // than forward: e.g. len=6 ==> bbbAff, len=7 ==> bbbAfff.
1657 if (frames_bwd < half_gf_int)
1658 frames_bwd += (cpi->oxcf.arnr_max_frames+1) & 0x1;
1662 cpi->active_arnr_frames = frames_bwd + 1 + frames_fwd;
1666 cpi->source_alt_ref_pending = FALSE;
1667 cpi->baseline_gf_interval = i;
1672 cpi->source_alt_ref_pending = FALSE;
1673 cpi->baseline_gf_interval = i;
1677 if (!cpi->source_alt_ref_pending)
1679 // Dont allow conventional gf too near the next kf
1680 if ((cpi->frames_to_key - cpi->baseline_gf_interval) < MIN_GF_INTERVAL)
1682 while (cpi->baseline_gf_interval < cpi->frames_to_key)
1684 if (EOF == input_stats(cpi, this_frame))
1687 cpi->baseline_gf_interval++;
1689 if (cpi->baseline_gf_interval < cpi->frames_to_key)
1690 gf_group_err += calculate_modified_err(cpi, this_frame);
1695 // Now decide how many bits should be allocated to the GF group as a proportion of those remaining in the kf group.
1696 // The final key frame group in the clip is treated as a special case where cpi->kf_group_bits is tied to cpi->bits_left.
1697 // This is also important for short clips where there may only be one key frame.
1698 if (cpi->frames_to_key >= (int)(cpi->total_stats->count - cpi->common.current_video_frame))
1700 cpi->kf_group_bits = (cpi->bits_left > 0) ? cpi->bits_left : 0;
1703 // Calculate the bits to be allocated to the group as a whole
1704 if ((cpi->kf_group_bits > 0) && (cpi->kf_group_error_left > 0))
1705 cpi->gf_group_bits = (int)((double)cpi->kf_group_bits * (gf_group_err / (double)cpi->kf_group_error_left));
1707 cpi->gf_group_bits = 0;
1709 cpi->gf_group_bits = (cpi->gf_group_bits < 0) ? 0 : (cpi->gf_group_bits > cpi->kf_group_bits) ? cpi->kf_group_bits : cpi->gf_group_bits;
1711 // Clip cpi->gf_group_bits based on user supplied data rate variability limit (cpi->oxcf.two_pass_vbrmax_section)
1712 if (cpi->gf_group_bits > max_bits * cpi->baseline_gf_interval)
1713 cpi->gf_group_bits = max_bits * cpi->baseline_gf_interval;
1715 // Reset the file position
1716 reset_fpf_position(cpi, start_pos);
1718 // Update the record of error used so far (only done once per gf group)
1719 cpi->modified_error_used += gf_group_err;
1721 // Assign bits to the arf or gf.
1724 int frames_in_section;
1725 int allocation_chunks;
1726 int Q = (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
1729 if (cpi->source_alt_ref_pending)
1731 Boost = (cpi->gfu_boost * 3 * GFQ_ADJUSTMENT) / (2 * 100);
1732 //Boost += (cpi->baseline_gf_interval * 25);
1733 Boost += (cpi->baseline_gf_interval * 50);
1735 // Set max and minimum boost and hence minimum allocation
1736 if (Boost > ((cpi->baseline_gf_interval + 1) * 200))
1737 Boost = ((cpi->baseline_gf_interval + 1) * 200);
1738 else if (Boost < 125)
1741 frames_in_section = cpi->baseline_gf_interval + 1;
1742 allocation_chunks = (frames_in_section * 100) + Boost;
1744 // Else for standard golden frames
1747 // boost based on inter / intra ratio of subsequent frames
1748 Boost = (cpi->gfu_boost * GFQ_ADJUSTMENT) / 100;
1750 // Set max and minimum boost and hence minimum allocation
1751 if (Boost > (cpi->baseline_gf_interval * 150))
1752 Boost = (cpi->baseline_gf_interval * 150);
1753 else if (Boost < 125)
1756 frames_in_section = cpi->baseline_gf_interval;
1757 allocation_chunks = (frames_in_section * 100) + (Boost - 100);
1760 // Normalize Altboost and allocations chunck down to prevent overflow
1761 while (Boost > 1000)
1764 allocation_chunks /= 2;
1767 // Calculate the number of bits to be spent on the gf or arf based on the boost number
1768 cpi->gf_bits = (int)((double)Boost * (cpi->gf_group_bits / (double)allocation_chunks));
1770 // If the frame that is to be boosted is simpler than the average for
1771 // the gf/arf group then use an alternative calculation
1772 // based on the error score of the frame itself
1773 if (mod_frame_err < gf_group_err / (double)cpi->baseline_gf_interval)
1775 double alt_gf_grp_bits;
1779 (double)cpi->kf_group_bits *
1780 (mod_frame_err * (double)cpi->baseline_gf_interval) /
1781 DOUBLE_DIVIDE_CHECK((double)cpi->kf_group_error_left);
1783 alt_gf_bits = (int)((double)Boost * (alt_gf_grp_bits /
1784 (double)allocation_chunks));
1786 if (cpi->gf_bits > alt_gf_bits)
1788 cpi->gf_bits = alt_gf_bits;
1791 // Else if it is harder than other frames in the group make sure it at
1792 // least receives an allocation in keeping with its relative error
1793 // score, otherwise it may be worse off than an "un-boosted" frame
1797 (int)((double)cpi->kf_group_bits *
1799 DOUBLE_DIVIDE_CHECK((double)cpi->kf_group_error_left));
1801 if (alt_gf_bits > cpi->gf_bits)
1803 cpi->gf_bits = alt_gf_bits;
1807 // Apply an additional limit for CBR
1808 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
1810 if (cpi->gf_bits > (cpi->buffer_level >> 1))
1811 cpi->gf_bits = cpi->buffer_level >> 1;
1814 // Dont allow a negative value for gf_bits
1815 if (cpi->gf_bits < 0)
1818 // Adjust KF group bits and error remainin
1819 cpi->kf_group_error_left -= gf_group_err;
1820 cpi->kf_group_bits -= cpi->gf_group_bits;
1822 if (cpi->kf_group_bits < 0)
1823 cpi->kf_group_bits = 0;
1825 // Note the error score left in the remaining frames of the group.
1826 // 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)
1827 if (!cpi->source_alt_ref_pending && cpi->common.frame_type != KEY_FRAME)
1828 cpi->gf_group_error_left = gf_group_err - gf_first_frame_err;
1830 cpi->gf_group_error_left = gf_group_err;
1832 cpi->gf_group_bits -= cpi->gf_bits;
1834 if (cpi->gf_group_bits < 0)
1835 cpi->gf_group_bits = 0;
1837 // Set aside some bits for a mid gf sequence boost
1838 if ((cpi->gfu_boost > 150) && (cpi->baseline_gf_interval > 5))
1840 int pct_extra = (cpi->gfu_boost - 100) / 50;
1841 pct_extra = (pct_extra > 10) ? 10 : pct_extra;
1843 cpi->mid_gf_extra_bits = (cpi->gf_group_bits * pct_extra) / 100;
1844 cpi->gf_group_bits -= cpi->mid_gf_extra_bits;
1847 cpi->mid_gf_extra_bits = 0;
1849 cpi->gf_bits += cpi->min_frame_bandwidth; // Add in minimum for a frame
1852 if (!cpi->source_alt_ref_pending && (cpi->common.frame_type != KEY_FRAME)) // Normal GF and not a KF
1854 cpi->per_frame_bandwidth = cpi->gf_bits; // Per frame bit target for this frame
1857 // Adjustment to estimate_max_q based on a measure of complexity of the section
1858 if (cpi->common.frame_type != KEY_FRAME)
1860 FIRSTPASS_STATS sectionstats;
1863 zero_stats(§ionstats);
1864 reset_fpf_position(cpi, start_pos);
1866 for (i = 0 ; i < cpi->baseline_gf_interval ; i++)
1868 input_stats(cpi, &next_frame);
1869 accumulate_stats(§ionstats, &next_frame);
1872 avg_stats(§ionstats);
1874 cpi->section_intra_rating =
1875 sectionstats.intra_error /
1876 DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
1878 Ratio = sectionstats.intra_error / DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
1879 //if( (Ratio > 11) ) //&& (sectionstats.pcnt_second_ref < .20) )
1881 cpi->section_max_qfactor = 1.0 - ((Ratio - 10.0) * 0.025);
1883 if (cpi->section_max_qfactor < 0.80)
1884 cpi->section_max_qfactor = 0.80;
1888 // cpi->section_max_qfactor = 1.0;
1890 reset_fpf_position(cpi, start_pos);
1894 // Allocate bits to a normal frame that is neither a gf an arf or a key frame.
1895 static void assign_std_frame_bits(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame)
1897 int target_frame_size; // gf_group_error_left
1899 double modified_err;
1900 double err_fraction; // What portion of the remaining GF group error is used by this frame
1902 int max_bits = frame_max_bits(cpi); // Max for a single frame
1904 // The final few frames have special treatment
1905 if (cpi->frames_till_gf_update_due >= (int)(cpi->total_stats->count - cpi->common.current_video_frame))
1907 cpi->gf_group_bits = (cpi->bits_left > 0) ? cpi->bits_left : 0;;
1910 // Calculate modified prediction error used in bit allocation
1911 modified_err = calculate_modified_err(cpi, this_frame);
1913 if (cpi->gf_group_error_left > 0)
1914 err_fraction = modified_err / cpi->gf_group_error_left; // What portion of the remaining GF group error is used by this frame
1918 target_frame_size = (int)((double)cpi->gf_group_bits * err_fraction); // How many of those bits available for allocation should we give it?
1920 // Clip to target size to 0 - max_bits (or cpi->gf_group_bits) at the top end.
1921 if (target_frame_size < 0)
1922 target_frame_size = 0;
1925 if (target_frame_size > max_bits)
1926 target_frame_size = max_bits;
1928 if (target_frame_size > cpi->gf_group_bits)
1929 target_frame_size = cpi->gf_group_bits;
1932 cpi->gf_group_error_left -= modified_err; // Adjust error remaining
1933 cpi->gf_group_bits -= target_frame_size; // Adjust bits remaining
1935 if (cpi->gf_group_bits < 0)
1936 cpi->gf_group_bits = 0;
1938 target_frame_size += cpi->min_frame_bandwidth; // Add in the minimum number of bits that is set aside for every frame.
1940 // Special case for the frame that lies half way between two gfs
1941 if (cpi->common.frames_since_golden == cpi->baseline_gf_interval / 2)
1942 target_frame_size += cpi->mid_gf_extra_bits;
1944 cpi->per_frame_bandwidth = target_frame_size; // Per frame bit target for this frame
1947 void vp8_second_pass(VP8_COMP *cpi)
1950 int frames_left = (int)(cpi->total_stats->count - cpi->common.current_video_frame);
1952 FIRSTPASS_STATS this_frame;
1953 FIRSTPASS_STATS this_frame_copy;
1955 double this_frame_error;
1956 double this_frame_intra_error;
1957 double this_frame_coded_error;
1959 FIRSTPASS_STATS *start_pos;
1966 vp8_clear_system_state();
1968 if (EOF == input_stats(cpi, &this_frame))
1971 this_frame_error = this_frame.ssim_weighted_pred_err;
1972 this_frame_intra_error = this_frame.intra_error;
1973 this_frame_coded_error = this_frame.coded_error;
1975 start_pos = cpi->stats_in;
1977 // keyframe and section processing !
1978 if (cpi->frames_to_key == 0)
1980 // Define next KF group and assign bits to it
1981 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
1982 find_next_key_frame(cpi, &this_frame_copy);
1984 // 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
1985 // outlandish behaviour if someone does set it when using two pass. It effectively disables GF groups.
1986 // This is temporary code till we decide what should really happen in this case.
1987 if (cpi->oxcf.error_resilient_mode)
1989 cpi->gf_group_bits = cpi->kf_group_bits;
1990 cpi->gf_group_error_left = cpi->kf_group_error_left;
1991 cpi->baseline_gf_interval = cpi->frames_to_key;
1992 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
1993 cpi->source_alt_ref_pending = FALSE;
1998 // Is this a GF / ARF (Note that a KF is always also a GF)
1999 if (cpi->frames_till_gf_update_due == 0)
2001 // Define next gf group and assign bits to it
2002 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2003 define_gf_group(cpi, &this_frame_copy);
2005 // If we are going to code an altref frame at the end of the group and the current frame is not a key frame....
2006 // If the previous group used an arf this frame has already benefited from that arf boost and it should not be given extra bits
2007 // If the previous group was NOT coded using arf we may want to apply some boost to this GF as well
2008 if (cpi->source_alt_ref_pending && (cpi->common.frame_type != KEY_FRAME))
2010 // Assign a standard frames worth of bits from those allocated to the GF group
2011 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2012 assign_std_frame_bits(cpi, &this_frame_copy);
2014 // If appropriate (we are switching into ARF active but it was not previously active) apply a boost for the gf at the start of the group.
2015 //if ( !cpi->source_alt_ref_active && (cpi->gfu_boost > 150) )
2019 int pct_extra = (cpi->gfu_boost - 100) / 50;
2021 pct_extra = (pct_extra > 20) ? 20 : pct_extra;
2023 extra_bits = (cpi->gf_group_bits * pct_extra) / 100;
2024 cpi->gf_group_bits -= extra_bits;
2025 cpi->per_frame_bandwidth += extra_bits;
2030 // Otherwise this is an ordinary frame
2033 // 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
2034 // outlandish behaviour if someone does set it when using two pass. It effectively disables GF groups.
2035 // This is temporary code till we decide what should really happen in this case.
2036 if (cpi->oxcf.error_resilient_mode)
2038 cpi->frames_till_gf_update_due = cpi->frames_to_key;
2040 if (cpi->common.frame_type != KEY_FRAME)
2042 // Assign bits from those allocated to the GF group
2043 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2044 assign_std_frame_bits(cpi, &this_frame_copy);
2049 // Assign bits from those allocated to the GF group
2050 vpx_memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
2051 assign_std_frame_bits(cpi, &this_frame_copy);
2055 // Keep a globally available copy of this and the next frame's iiratio.
2056 cpi->this_iiratio = this_frame_intra_error /
2057 DOUBLE_DIVIDE_CHECK(this_frame_coded_error);
2059 FIRSTPASS_STATS next_frame;
2060 if ( lookup_next_frame_stats(cpi, &next_frame) != EOF )
2062 cpi->next_iiratio = next_frame.intra_error /
2063 DOUBLE_DIVIDE_CHECK(next_frame.coded_error);
2067 // Set nominal per second bandwidth for this frame
2068 cpi->target_bandwidth = cpi->per_frame_bandwidth * cpi->output_frame_rate;
2069 if (cpi->target_bandwidth < 0)
2070 cpi->target_bandwidth = 0;
2072 if (cpi->common.current_video_frame == 0)
2074 cpi->est_max_qcorrection_factor = 1.0;
2076 // Experimental code to try and set a cq_level in constrained
2078 if ( cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY )
2084 (cpi->total_coded_error_left / frames_left),
2085 (int)(cpi->bits_left / frames_left));
2087 cpi->cq_target_quality = cpi->oxcf.cq_level;
2088 if ( est_cq > cpi->cq_target_quality )
2089 cpi->cq_target_quality = est_cq;
2092 // guess at maxq needed in 2nd pass
2093 cpi->maxq_max_limit = cpi->worst_quality;
2094 cpi->maxq_min_limit = cpi->best_quality;
2095 tmp_q = estimate_max_q( cpi,
2096 (cpi->total_coded_error_left / frames_left),
2097 (int)(cpi->bits_left / frames_left));
2099 // Limit the maxq value returned subsequently.
2100 // This increases the risk of overspend or underspend if the initial
2101 // estimate for the clip is bad, but helps prevent excessive
2102 // variation in Q, especially near the end of a clip
2103 // where for example a small overspend may cause Q to crash
2104 cpi->maxq_max_limit = ((tmp_q + 32) < cpi->worst_quality)
2105 ? (tmp_q + 32) : cpi->worst_quality;
2106 cpi->maxq_min_limit = ((tmp_q - 32) > cpi->best_quality)
2107 ? (tmp_q - 32) : cpi->best_quality;
2109 cpi->active_worst_quality = tmp_q;
2110 cpi->ni_av_qi = tmp_q;
2113 // The last few frames of a clip almost always have to few or too many
2114 // bits and for the sake of over exact rate control we dont want to make
2115 // radical adjustments to the allowed quantizer range just to use up a
2116 // few surplus bits or get beneath the target rate.
2117 else if ( (cpi->common.current_video_frame <
2118 (((unsigned int)cpi->total_stats->count * 255)>>8)) &&
2119 ((cpi->common.current_video_frame + cpi->baseline_gf_interval) <
2120 (unsigned int)cpi->total_stats->count) )
2122 if (frames_left < 1)
2125 tmp_q = estimate_max_q(cpi, (cpi->total_coded_error_left / frames_left), (int)(cpi->bits_left / frames_left));
2127 // Move active_worst_quality but in a damped way
2128 if (tmp_q > cpi->active_worst_quality)
2129 cpi->active_worst_quality ++;
2130 else if (tmp_q < cpi->active_worst_quality)
2131 cpi->active_worst_quality --;
2133 cpi->active_worst_quality = ((cpi->active_worst_quality * 3) + tmp_q + 2) / 4;
2136 cpi->frames_to_key --;
2137 cpi->total_error_left -= this_frame_error;
2138 cpi->total_intra_error_left -= this_frame_intra_error;
2139 cpi->total_coded_error_left -= this_frame_coded_error;
2143 static BOOL test_candidate_kf(VP8_COMP *cpi, FIRSTPASS_STATS *last_frame, FIRSTPASS_STATS *this_frame, FIRSTPASS_STATS *next_frame)
2145 BOOL is_viable_kf = FALSE;
2147 // Does the frame satisfy the primary criteria of a key frame
2148 // If so, then examine how well it predicts subsequent frames
2149 if ((this_frame->pcnt_second_ref < 0.10) &&
2150 (next_frame->pcnt_second_ref < 0.10) &&
2151 ((this_frame->pcnt_inter < 0.05) ||
2153 ((this_frame->pcnt_inter - this_frame->pcnt_neutral) < .25) &&
2154 ((this_frame->intra_error / DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) < 2.5) &&
2155 ((fabs(last_frame->coded_error - this_frame->coded_error) / DOUBLE_DIVIDE_CHECK(this_frame->coded_error) > .40) ||
2156 (fabs(last_frame->intra_error - this_frame->intra_error) / DOUBLE_DIVIDE_CHECK(this_frame->intra_error) > .40) ||
2157 ((next_frame->intra_error / DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) > 3.5)
2164 FIRSTPASS_STATS *start_pos;
2166 FIRSTPASS_STATS local_next_frame;
2168 double boost_score = 0.0;
2169 double old_boost_score = 0.0;
2170 double decay_accumulator = 1.0;
2171 double next_iiratio;
2173 vpx_memcpy(&local_next_frame, next_frame, sizeof(*next_frame));
2175 // Note the starting file position so we can reset to it
2176 start_pos = cpi->stats_in;
2178 // Examine how well the key frame predicts subsequent frames
2179 for (i = 0 ; i < 16; i++)
2181 next_iiratio = (IIKFACTOR1 * local_next_frame.intra_error / DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error)) ;
2183 if (next_iiratio > RMAX)
2184 next_iiratio = RMAX;
2186 // Cumulative effect of decay in prediction quality
2187 if (local_next_frame.pcnt_inter > 0.85)
2188 decay_accumulator = decay_accumulator * local_next_frame.pcnt_inter;
2190 decay_accumulator = decay_accumulator * ((0.85 + local_next_frame.pcnt_inter) / 2.0);
2192 //decay_accumulator = decay_accumulator * local_next_frame.pcnt_inter;
2194 // Keep a running total
2195 boost_score += (decay_accumulator * next_iiratio);
2197 // Test various breakout clauses
2198 if ((local_next_frame.pcnt_inter < 0.05) ||
2199 (next_iiratio < 1.5) ||
2200 (((local_next_frame.pcnt_inter -
2201 local_next_frame.pcnt_neutral) < 0.20) &&
2202 (next_iiratio < 3.0)) ||
2203 ((boost_score - old_boost_score) < 0.5) ||
2204 (local_next_frame.intra_error < 200)
2210 old_boost_score = boost_score;
2212 // Get the next frame details
2213 if (EOF == input_stats(cpi, &local_next_frame))
2217 // If there is tolerable prediction for at least the next 3 frames then break out else discard this pottential key frame and move on
2218 if (boost_score > 5.0 && (i > 3))
2219 is_viable_kf = TRUE;
2222 // Reset the file position
2223 reset_fpf_position(cpi, start_pos);
2225 is_viable_kf = FALSE;
2229 return is_viable_kf;
2231 static void find_next_key_frame(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame)
2234 FIRSTPASS_STATS last_frame;
2235 FIRSTPASS_STATS first_frame;
2236 FIRSTPASS_STATS next_frame;
2237 FIRSTPASS_STATS *start_position;
2239 double decay_accumulator = 1.0;
2240 double boost_score = 0;
2241 double old_boost_score = 0.0;
2242 double loop_decay_rate;
2244 double kf_mod_err = 0.0;
2245 double kf_group_err = 0.0;
2246 double kf_group_intra_err = 0.0;
2247 double kf_group_coded_err = 0.0;
2248 double recent_loop_decay[8] = {1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0};
2250 vpx_memset(&next_frame, 0, sizeof(next_frame)); // assure clean
2252 vp8_clear_system_state(); //__asm emms;
2253 start_position = cpi->stats_in;
2255 cpi->common.frame_type = KEY_FRAME;
2257 // is this a forced key frame by interval
2258 cpi->this_key_frame_forced = cpi->next_key_frame_forced;
2260 // Clear the alt ref active flag as this can never be active on a key frame
2261 cpi->source_alt_ref_active = FALSE;
2263 // Kf is always a gf so clear frames till next gf counter
2264 cpi->frames_till_gf_update_due = 0;
2266 cpi->frames_to_key = 1;
2268 // Take a copy of the initial frame details
2269 vpx_memcpy(&first_frame, this_frame, sizeof(*this_frame));
2271 cpi->kf_group_bits = 0; // Total bits avaialable to kf group
2272 cpi->kf_group_error_left = 0; // Group modified error score.
2274 kf_mod_err = calculate_modified_err(cpi, this_frame);
2276 // find the next keyframe
2278 while (cpi->stats_in < cpi->stats_in_end)
2280 // Accumulate kf group error
2281 kf_group_err += calculate_modified_err(cpi, this_frame);
2283 // These figures keep intra and coded error counts for all frames including key frames in the group.
2284 // The effect of the key frame itself can be subtracted out using the first_frame data collected above
2285 kf_group_intra_err += this_frame->intra_error;
2286 kf_group_coded_err += this_frame->coded_error;
2288 // load a the next frame's stats
2289 vpx_memcpy(&last_frame, this_frame, sizeof(*this_frame));
2290 input_stats(cpi, this_frame);
2292 // Provided that we are not at the end of the file...
2293 if (cpi->oxcf.auto_key
2294 && lookup_next_frame_stats(cpi, &next_frame) != EOF)
2296 // Normal scene cut check
2297 if (test_candidate_kf(cpi, &last_frame, this_frame, &next_frame))
2300 // How fast is prediction quality decaying
2301 loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
2303 // We want to know something about the recent past... rather than
2304 // as used elsewhere where we are concened with decay in prediction
2305 // quality since the last GF or KF.
2306 recent_loop_decay[i%8] = loop_decay_rate;
2307 decay_accumulator = 1.0;
2308 for (j = 0; j < 8; j++)
2310 decay_accumulator = decay_accumulator * recent_loop_decay[j];
2313 // Special check for transition or high motion followed by a
2314 // to a static scene.
2315 if ( detect_transition_to_still( cpi, i,
2316 (cpi->key_frame_frequency-i),
2318 decay_accumulator ) )
2324 // Step on to the next frame
2325 cpi->frames_to_key ++;
2327 // If we don't have a real key frame within the next two
2328 // forcekeyframeevery intervals then break out of the loop.
2329 if (cpi->frames_to_key >= 2 *(int)cpi->key_frame_frequency)
2332 cpi->frames_to_key ++;
2337 // If there is a max kf interval set by the user we must obey it.
2338 // We already breakout of the loop above at 2x max.
2339 // This code centers the extra kf if the actual natural
2340 // interval is between 1x and 2x
2341 if (cpi->oxcf.auto_key
2342 && cpi->frames_to_key > (int)cpi->key_frame_frequency )
2344 FIRSTPASS_STATS *current_pos = cpi->stats_in;
2345 FIRSTPASS_STATS tmp_frame;
2347 cpi->frames_to_key /= 2;
2349 // Copy first frame details
2350 vpx_memcpy(&tmp_frame, &first_frame, sizeof(first_frame));
2352 // Reset to the start of the group
2353 reset_fpf_position(cpi, start_position);
2356 kf_group_intra_err = 0;
2357 kf_group_coded_err = 0;
2359 // Rescan to get the correct error data for the forced kf group
2360 for( i = 0; i < cpi->frames_to_key; i++ )
2362 // Accumulate kf group errors
2363 kf_group_err += calculate_modified_err(cpi, &tmp_frame);
2364 kf_group_intra_err += tmp_frame.intra_error;
2365 kf_group_coded_err += tmp_frame.coded_error;
2367 // Load a the next frame's stats
2368 input_stats(cpi, &tmp_frame);
2371 // Reset to the start of the group
2372 reset_fpf_position(cpi, current_pos);
2374 cpi->next_key_frame_forced = TRUE;
2377 cpi->next_key_frame_forced = FALSE;
2379 // Special case for the last frame of the file
2380 if (cpi->stats_in >= cpi->stats_in_end)
2382 // Accumulate kf group error
2383 kf_group_err += calculate_modified_err(cpi, this_frame);
2385 // These figures keep intra and coded error counts for all frames including key frames in the group.
2386 // The effect of the key frame itself can be subtracted out using the first_frame data collected above
2387 kf_group_intra_err += this_frame->intra_error;
2388 kf_group_coded_err += this_frame->coded_error;
2391 // Calculate the number of bits that should be assigned to the kf group.
2392 if ((cpi->bits_left > 0) && (cpi->modified_error_left > 0.0))
2394 // Max for a single normal frame (not key frame)
2395 int max_bits = frame_max_bits(cpi);
2397 // Maximum bits for the kf group
2398 long long max_grp_bits;
2400 // Default allocation based on bits left and relative
2401 // complexity of the section
2402 cpi->kf_group_bits = (long long)( cpi->bits_left *
2404 cpi->modified_error_left ));
2406 // Clip based on maximum per frame rate defined by the user.
2407 max_grp_bits = (long long)max_bits * (long long)cpi->frames_to_key;
2408 if (cpi->kf_group_bits > max_grp_bits)
2409 cpi->kf_group_bits = max_grp_bits;
2411 // Additional special case for CBR if buffer is getting full.
2412 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2414 int opt_buffer_lvl = cpi->oxcf.optimal_buffer_level;
2415 int buffer_lvl = cpi->buffer_level;
2417 // If the buffer is near or above the optimal and this kf group is
2418 // not being allocated much then increase the allocation a bit.
2419 if (buffer_lvl >= opt_buffer_lvl)
2421 int high_water_mark = (opt_buffer_lvl +
2422 cpi->oxcf.maximum_buffer_size) >> 1;
2424 long long av_group_bits;
2426 // Av bits per frame * number of frames
2427 av_group_bits = (long long)cpi->av_per_frame_bandwidth *
2428 (long long)cpi->frames_to_key;
2430 // We are at or above the maximum.
2431 if (cpi->buffer_level >= high_water_mark)
2433 long long min_group_bits;
2435 min_group_bits = av_group_bits +
2436 (long long)(buffer_lvl -
2439 if (cpi->kf_group_bits < min_group_bits)
2440 cpi->kf_group_bits = min_group_bits;
2442 // We are above optimal but below the maximum
2443 else if (cpi->kf_group_bits < av_group_bits)
2445 long long bits_below_av = av_group_bits -
2448 cpi->kf_group_bits +=
2449 (long long)((double)bits_below_av *
2450 (double)(buffer_lvl - opt_buffer_lvl) /
2451 (double)(high_water_mark - opt_buffer_lvl));
2457 cpi->kf_group_bits = 0;
2459 // Reset the first pass file position
2460 reset_fpf_position(cpi, start_position);
2462 // determine how big to make this keyframe based on how well the subsequent frames use inter blocks
2463 decay_accumulator = 1.0;
2465 loop_decay_rate = 1.00; // Starting decay rate
2467 for (i = 0 ; i < cpi->frames_to_key ; i++)
2471 if (EOF == input_stats(cpi, &next_frame))
2474 if (next_frame.intra_error > cpi->kf_intra_err_min)
2475 r = (IIKFACTOR2 * next_frame.intra_error /
2476 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2478 r = (IIKFACTOR2 * cpi->kf_intra_err_min /
2479 DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
2484 // How fast is prediction quality decaying
2485 loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
2487 decay_accumulator = decay_accumulator * loop_decay_rate;
2488 decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
2490 boost_score += (decay_accumulator * r);
2492 if ((i > MIN_GF_INTERVAL) &&
2493 ((boost_score - old_boost_score) < 1.0))
2498 old_boost_score = boost_score;
2503 FIRSTPASS_STATS sectionstats;
2506 zero_stats(§ionstats);
2507 reset_fpf_position(cpi, start_position);
2509 for (i = 0 ; i < cpi->frames_to_key ; i++)
2511 input_stats(cpi, &next_frame);
2512 accumulate_stats(§ionstats, &next_frame);
2515 avg_stats(§ionstats);
2517 cpi->section_intra_rating = sectionstats.intra_error / DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
2519 Ratio = sectionstats.intra_error / DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
2520 // if( (Ratio > 11) ) //&& (sectionstats.pcnt_second_ref < .20) )
2522 cpi->section_max_qfactor = 1.0 - ((Ratio - 10.0) * 0.025);
2524 if (cpi->section_max_qfactor < 0.80)
2525 cpi->section_max_qfactor = 0.80;
2529 // cpi->section_max_qfactor = 1.0;
2532 // When using CBR apply additional buffer fullness related upper limits
2533 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2537 if (cpi->drop_frames_allowed)
2539 int df_buffer_level = cpi->oxcf.drop_frames_water_mark * (cpi->oxcf.optimal_buffer_level / 100);
2541 if (cpi->buffer_level > df_buffer_level)
2542 max_boost = ((double)((cpi->buffer_level - df_buffer_level) * 2 / 3) * 16.0) / DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
2546 else if (cpi->buffer_level > 0)
2548 max_boost = ((double)(cpi->buffer_level * 2 / 3) * 16.0) / DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
2555 if (boost_score > max_boost)
2556 boost_score = max_boost;
2559 // Reset the first pass file position
2560 reset_fpf_position(cpi, start_position);
2562 // Work out how many bits to allocate for the key frame itself
2565 int kf_boost = boost_score;
2566 int allocation_chunks;
2567 int Counter = cpi->frames_to_key;
2569 YV12_BUFFER_CONFIG *lst_yv12 = &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
2570 // Min boost based on kf interval
2573 while ((kf_boost < 48) && (Counter > 0))
2583 kf_boost += ((Counter + 1) >> 1);
2585 if (kf_boost > 48) kf_boost = 48;
2588 // bigger frame sizes need larger kf boosts, smaller frames smaller boosts...
2589 if ((lst_yv12->y_width * lst_yv12->y_height) > (320 * 240))
2590 kf_boost += 2 * (lst_yv12->y_width * lst_yv12->y_height) / (320 * 240);
2591 else if ((lst_yv12->y_width * lst_yv12->y_height) < (320 * 240))
2592 kf_boost -= 4 * (320 * 240) / (lst_yv12->y_width * lst_yv12->y_height);
2594 kf_boost = (int)((double)kf_boost * 100.0) >> 4; // Scale 16 to 100
2596 // Adjustment to boost based on recent average q
2597 //kf_boost = kf_boost * vp8_kf_boost_qadjustment[cpi->ni_av_qi] / 100;
2599 if (kf_boost < 250) // Min KF boost
2602 // We do three calculations for kf size.
2603 // The first is based on the error score for the whole kf group.
2604 // The second (optionaly) on the key frames own error if this is smaller than the average for the group.
2605 // 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
2607 allocation_chunks = ((cpi->frames_to_key - 1) * 100) + kf_boost; // cpi->frames_to_key-1 because key frame itself is taken care of by kf_boost
2609 // Normalize Altboost and allocations chunck down to prevent overflow
2610 while (kf_boost > 1000)
2613 allocation_chunks /= 2;
2616 cpi->kf_group_bits = (cpi->kf_group_bits < 0) ? 0 : cpi->kf_group_bits;
2618 // Calculate the number of bits to be spent on the key frame
2619 cpi->kf_bits = (int)((double)kf_boost * ((double)cpi->kf_group_bits / (double)allocation_chunks));
2621 // Apply an additional limit for CBR
2622 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2624 if (cpi->kf_bits > ((3 * cpi->buffer_level) >> 2))
2625 cpi->kf_bits = (3 * cpi->buffer_level) >> 2;
2628 // If the key frame is actually easier than the average for the
2629 // kf group (which does sometimes happen... eg a blank intro frame)
2630 // Then use an alternate calculation based on the kf error score
2631 // which should give a smaller key frame.
2632 if (kf_mod_err < kf_group_err / cpi->frames_to_key)
2634 double alt_kf_grp_bits =
2635 ((double)cpi->bits_left *
2636 (kf_mod_err * (double)cpi->frames_to_key) /
2637 DOUBLE_DIVIDE_CHECK(cpi->modified_error_left));
2639 alt_kf_bits = (int)((double)kf_boost *
2640 (alt_kf_grp_bits / (double)allocation_chunks));
2642 if (cpi->kf_bits > alt_kf_bits)
2644 cpi->kf_bits = alt_kf_bits;
2647 // Else if it is much harder than other frames in the group make sure
2648 // it at least receives an allocation in keeping with its relative
2653 (int)((double)cpi->bits_left *
2655 DOUBLE_DIVIDE_CHECK(cpi->modified_error_left)));
2657 if (alt_kf_bits > cpi->kf_bits)
2659 cpi->kf_bits = alt_kf_bits;
2663 cpi->kf_group_bits -= cpi->kf_bits;
2664 cpi->kf_bits += cpi->min_frame_bandwidth; // Add in the minimum frame allowance
2666 cpi->per_frame_bandwidth = cpi->kf_bits; // Peer frame bit target for this frame
2667 cpi->target_bandwidth = cpi->kf_bits * cpi->output_frame_rate; // Convert to a per second bitrate
2670 // Note the total error score of the kf group minus the key frame itself
2671 cpi->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
2673 // Adjust the count of total modified error left.
2674 // The count of bits left is adjusted elsewhere based on real coded frame sizes
2675 cpi->modified_error_left -= kf_group_err;
2677 if (cpi->oxcf.allow_spatial_resampling)
2679 int resample_trigger = FALSE;
2680 int last_kf_resampled = FALSE;
2684 int new_width = cpi->oxcf.Width;
2685 int new_height = cpi->oxcf.Height;
2687 int projected_buffer_level = cpi->buffer_level;
2690 double projected_bits_perframe;
2691 double group_iiratio = (kf_group_intra_err - first_frame.intra_error) / (kf_group_coded_err - first_frame.coded_error);
2692 double err_per_frame = kf_group_err / cpi->frames_to_key;
2693 double bits_per_frame;
2694 double av_bits_per_frame;
2695 double effective_size_ratio;
2697 if ((cpi->common.Width != cpi->oxcf.Width) || (cpi->common.Height != cpi->oxcf.Height))
2698 last_kf_resampled = TRUE;
2700 // Set back to unscaled by defaults
2701 cpi->common.horiz_scale = NORMAL;
2702 cpi->common.vert_scale = NORMAL;
2704 // Calculate Average bits per frame.
2705 //av_bits_per_frame = cpi->bits_left/(double)(cpi->total_stats->count - cpi->common.current_video_frame);
2706 av_bits_per_frame = cpi->oxcf.target_bandwidth / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.frame_rate);
2707 //if ( av_bits_per_frame < 0.0 )
2708 // av_bits_per_frame = 0.0
2710 // CBR... Use the clip average as the target for deciding resample
2711 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2713 bits_per_frame = av_bits_per_frame;
2716 // In VBR we want to avoid downsampling in easy section unless we are under extreme pressure
2717 // So use the larger of target bitrate for this sectoion or average bitrate for sequence
2720 bits_per_frame = cpi->kf_group_bits / cpi->frames_to_key; // This accounts for how hard the section is...
2722 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
2723 bits_per_frame = av_bits_per_frame;
2726 // bits_per_frame should comply with our minimum
2727 if (bits_per_frame < (cpi->oxcf.target_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100))
2728 bits_per_frame = (cpi->oxcf.target_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100);
2730 // Work out if spatial resampling is necessary
2731 kf_q = estimate_kf_group_q(cpi, err_per_frame, bits_per_frame, group_iiratio);
2733 // 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
2734 projected_bits_perframe = bits_per_frame;
2737 while (tmp_q > cpi->worst_quality)
2739 projected_bits_perframe *= 1.04;
2743 // Guess at buffer level at the end of the section
2744 projected_buffer_level = cpi->buffer_level - (int)((projected_bits_perframe - av_bits_per_frame) * cpi->frames_to_key);
2748 FILE *f = fopen("Subsamle.stt", "a");
2749 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->frames_to_key, (int)(cpi->kf_group_bits / cpi->frames_to_key), new_height, new_width);
2753 // The trigger for spatial resampling depends on the various parameters such as whether we are streaming (CBR) or VBR.
2754 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
2756 // Trigger resample if we are projected to fall below down sample level or
2757 // resampled last time and are projected to remain below the up sample level
2758 if ((projected_buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100)) ||
2759 (last_kf_resampled && (projected_buffer_level < (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))))
2760 //( ((cpi->buffer_level < (cpi->oxcf.resample_down_water_mark * cpi->oxcf.optimal_buffer_level / 100))) &&
2761 // ((projected_buffer_level < (cpi->oxcf.resample_up_water_mark * cpi->oxcf.optimal_buffer_level / 100))) ))
2762 resample_trigger = TRUE;
2764 resample_trigger = FALSE;
2768 long long clip_bits = (long long)(cpi->total_stats->count * cpi->oxcf.target_bandwidth / DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.frame_rate));
2769 long long over_spend = cpi->oxcf.starting_buffer_level - cpi->buffer_level;
2771 if ((last_kf_resampled && (kf_q > cpi->worst_quality)) || // If triggered last time the threshold for triggering again is reduced
2772 ((kf_q > cpi->worst_quality) && // Projected Q higher than allowed and ...
2773 (over_spend > clip_bits / 20))) // ... Overspend > 5% of total bits
2774 resample_trigger = TRUE;
2776 resample_trigger = FALSE;
2780 if (resample_trigger)
2782 while ((kf_q >= cpi->worst_quality) && (scale_val < 6))
2786 cpi->common.vert_scale = vscale_lookup[scale_val];
2787 cpi->common.horiz_scale = hscale_lookup[scale_val];
2789 Scale2Ratio(cpi->common.horiz_scale, &hr, &hs);
2790 Scale2Ratio(cpi->common.vert_scale, &vr, &vs);
2792 new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2793 new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2795 // Reducing the area to 1/4 does not reduce the complexity (err_per_frame) to 1/4...
2796 // effective_sizeratio attempts to provide a crude correction for this
2797 effective_size_ratio = (double)(new_width * new_height) / (double)(cpi->oxcf.Width * cpi->oxcf.Height);
2798 effective_size_ratio = (1.0 + (3.0 * effective_size_ratio)) / 4.0;
2800 // Now try again and see what Q we get with the smaller image size
2801 kf_q = estimate_kf_group_q(cpi, err_per_frame * effective_size_ratio, bits_per_frame, group_iiratio);
2805 FILE *f = fopen("Subsamle.stt", "a");
2806 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->frames_to_key, (int)(cpi->kf_group_bits / cpi->frames_to_key), new_height, new_width);
2812 if ((cpi->common.Width != new_width) || (cpi->common.Height != new_height))
2814 cpi->common.Width = new_width;
2815 cpi->common.Height = new_height;
2816 vp8_alloc_compressor_data(cpi);