2 * Rate control for video encoders
4 * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * Rate control for video encoders.
28 #include "libavutil/intmath.h"
31 #include "ratecontrol.h"
32 #include "mpegvideo.h"
33 #include "libavutil/eval.h"
35 #undef NDEBUG // Always check asserts, the speed effect is far too small to disable them.
39 #define M_E 2.718281828
42 static int init_pass2(MpegEncContext *s);
43 static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_factor, int frame_num);
45 void ff_write_pass1_stats(MpegEncContext *s){
46 snprintf(s->avctx->stats_out, 256, "in:%d out:%d type:%d q:%d itex:%d ptex:%d mv:%d misc:%d fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d;\n",
47 s->current_picture_ptr->f.display_picture_number, s->current_picture_ptr->f.coded_picture_number, s->pict_type,
48 s->current_picture.f.quality, s->i_tex_bits, s->p_tex_bits, s->mv_bits, s->misc_bits,
49 s->f_code, s->b_code, s->current_picture.mc_mb_var_sum, s->current_picture.mb_var_sum, s->i_count, s->skip_count, s->header_bits);
52 static double get_fps(AVCodecContext *avctx){
53 return 1.0 / av_q2d(avctx->time_base) / FFMAX(avctx->ticks_per_frame, 1);
56 static inline double qp2bits(RateControlEntry *rce, double qp){
58 av_log(NULL, AV_LOG_ERROR, "qp<=0.0\n");
60 return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits+1)/ qp;
63 static inline double bits2qp(RateControlEntry *rce, double bits){
65 av_log(NULL, AV_LOG_ERROR, "bits<0.9\n");
67 return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits+1)/ bits;
70 int ff_rate_control_init(MpegEncContext *s)
72 RateControlContext *rcc= &s->rc_context;
74 static const char * const const_names[]={
101 static double (* const func1[])(void *, double)={
106 static const char * const func1_names[]={
113 if (!s->avctx->rc_max_available_vbv_use && s->avctx->rc_buffer_size) {
114 if (s->avctx->rc_max_rate) {
115 s->avctx->rc_max_available_vbv_use = av_clipf(s->avctx->rc_max_rate/(s->avctx->rc_buffer_size*get_fps(s->avctx)), 1.0/3, 1.0);
117 s->avctx->rc_max_available_vbv_use = 1.0;
120 res = av_expr_parse(&rcc->rc_eq_eval, s->avctx->rc_eq ? s->avctx->rc_eq : "tex^qComp", const_names, func1_names, func1, NULL, NULL, 0, s->avctx);
122 av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\"\n", s->avctx->rc_eq);
127 rcc->pred[i].coeff= FF_QP2LAMBDA * 7.0;
128 rcc->pred[i].count= 1.0;
130 rcc->pred[i].decay= 0.4;
135 rcc->frame_count[i]= 1; // 1 is better because of 1/0 and such
136 rcc->last_qscale_for[i]=FF_QP2LAMBDA * 5;
138 rcc->buffer_index= s->avctx->rc_initial_buffer_occupancy;
139 if (!rcc->buffer_index)
140 rcc->buffer_index = s->avctx->rc_buffer_size * 3 / 4;
142 if(s->flags&CODEC_FLAG_PASS2){
146 /* find number of pics */
147 p= s->avctx->stats_in;
152 if(i<=0 || i>=INT_MAX / sizeof(RateControlEntry))
154 rcc->entry = av_mallocz(i*sizeof(RateControlEntry));
157 /* init all to skipped p frames (with b frames we might have a not encoded frame at the end FIXME) */
158 for(i=0; i<rcc->num_entries; i++){
159 RateControlEntry *rce= &rcc->entry[i];
160 rce->pict_type= rce->new_pict_type=AV_PICTURE_TYPE_P;
161 rce->qscale= rce->new_qscale=FF_QP2LAMBDA * 2;
162 rce->misc_bits= s->mb_num + 10;
163 rce->mb_var_sum= s->mb_num*100;
167 p= s->avctx->stats_in;
168 for(i=0; i<rcc->num_entries - s->max_b_frames; i++){
169 RateControlEntry *rce;
174 next= strchr(p, ';');
176 (*next)=0; //sscanf in unbelievably slow on looong strings //FIXME copy / do not write
179 e= sscanf(p, " in:%d ", &picture_number);
181 assert(picture_number >= 0);
182 assert(picture_number < rcc->num_entries);
183 rce= &rcc->entry[picture_number];
185 e+=sscanf(p, " in:%*d out:%*d type:%d q:%f itex:%d ptex:%d mv:%d misc:%d fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d",
186 &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits, &rce->mv_bits, &rce->misc_bits,
187 &rce->f_code, &rce->b_code, &rce->mc_mb_var_sum, &rce->mb_var_sum, &rce->i_count, &rce->skip_count, &rce->header_bits);
189 av_log(s->avctx, AV_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);
196 if(init_pass2(s) < 0) return -1;
198 //FIXME maybe move to end
199 if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID) {
201 return ff_xvid_rate_control_init(s);
203 av_log(s->avctx, AV_LOG_ERROR, "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");
209 if(!(s->flags&CODEC_FLAG_PASS2)){
211 rcc->short_term_qsum=0.001;
212 rcc->short_term_qcount=0.001;
214 rcc->pass1_rc_eq_output_sum= 0.001;
215 rcc->pass1_wanted_bits=0.001;
217 if(s->avctx->qblur > 1.0){
218 av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");
221 /* init stuff with the user specified complexity */
222 if(s->avctx->rc_initial_cplx){
223 for(i=0; i<60*30; i++){
224 double bits= s->avctx->rc_initial_cplx * (i/10000.0 + 1.0)*s->mb_num;
225 RateControlEntry rce;
227 if (i%((s->gop_size+3)/4)==0) rce.pict_type= AV_PICTURE_TYPE_I;
228 else if(i%(s->max_b_frames+1)) rce.pict_type= AV_PICTURE_TYPE_B;
229 else rce.pict_type= AV_PICTURE_TYPE_P;
231 rce.new_pict_type= rce.pict_type;
232 rce.mc_mb_var_sum= bits*s->mb_num/100000;
233 rce.mb_var_sum = s->mb_num;
234 rce.qscale = FF_QP2LAMBDA * 2;
239 if(s->pict_type== AV_PICTURE_TYPE_I){
240 rce.i_count = s->mb_num;
241 rce.i_tex_bits= bits;
245 rce.i_count = 0; //FIXME we do know this approx
247 rce.p_tex_bits= bits*0.9;
248 rce.mv_bits= bits*0.1;
250 rcc->i_cplx_sum [rce.pict_type] += rce.i_tex_bits*rce.qscale;
251 rcc->p_cplx_sum [rce.pict_type] += rce.p_tex_bits*rce.qscale;
252 rcc->mv_bits_sum[rce.pict_type] += rce.mv_bits;
253 rcc->frame_count[rce.pict_type] ++;
255 get_qscale(s, &rce, rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum, i);
256 rcc->pass1_wanted_bits+= s->bit_rate/get_fps(s->avctx); //FIXME misbehaves a little for variable fps
265 void ff_rate_control_uninit(MpegEncContext *s)
267 RateControlContext *rcc= &s->rc_context;
270 av_expr_free(rcc->rc_eq_eval);
271 av_freep(&rcc->entry);
274 if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
275 ff_xvid_rate_control_uninit(s);
279 int ff_vbv_update(MpegEncContext *s, int frame_size){
280 RateControlContext *rcc= &s->rc_context;
281 const double fps= get_fps(s->avctx);
282 const int buffer_size= s->avctx->rc_buffer_size;
283 const double min_rate= s->avctx->rc_min_rate/fps;
284 const double max_rate= s->avctx->rc_max_rate/fps;
286 av_dlog(s, "%d %f %d %f %f\n",
287 buffer_size, rcc->buffer_index, frame_size, min_rate, max_rate);
291 rcc->buffer_index-= frame_size;
292 if(rcc->buffer_index < 0){
293 av_log(s->avctx, AV_LOG_ERROR, "rc buffer underflow\n");
294 rcc->buffer_index= 0;
297 left= buffer_size - rcc->buffer_index - 1;
298 rcc->buffer_index += av_clip(left, min_rate, max_rate);
300 if(rcc->buffer_index > buffer_size){
301 int stuffing= ceil((rcc->buffer_index - buffer_size)/8);
303 if(stuffing < 4 && s->codec_id == AV_CODEC_ID_MPEG4)
305 rcc->buffer_index -= 8*stuffing;
307 if(s->avctx->debug & FF_DEBUG_RC)
308 av_log(s->avctx, AV_LOG_DEBUG, "stuffing %d bytes\n", stuffing);
317 * Modify the bitrate curve from pass1 for one frame.
319 static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_factor, int frame_num){
320 RateControlContext *rcc= &s->rc_context;
321 AVCodecContext *a= s->avctx;
323 const int pict_type= rce->new_pict_type;
324 const double mb_num= s->mb_num;
327 double const_values[]={
330 rce->i_tex_bits*rce->qscale,
331 rce->p_tex_bits*rce->qscale,
332 (rce->i_tex_bits + rce->p_tex_bits)*(double)rce->qscale,
334 rce->pict_type == AV_PICTURE_TYPE_B ? (rce->f_code + rce->b_code)*0.5 : rce->f_code,
336 rce->mc_mb_var_sum/mb_num,
337 rce->mb_var_sum/mb_num,
338 rce->pict_type == AV_PICTURE_TYPE_I,
339 rce->pict_type == AV_PICTURE_TYPE_P,
340 rce->pict_type == AV_PICTURE_TYPE_B,
341 rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],
343 /* rcc->last_qscale_for[AV_PICTURE_TYPE_I],
344 rcc->last_qscale_for[AV_PICTURE_TYPE_P],
345 rcc->last_qscale_for[AV_PICTURE_TYPE_B],
346 rcc->next_non_b_qscale,*/
347 rcc->i_cplx_sum[AV_PICTURE_TYPE_I] / (double)rcc->frame_count[AV_PICTURE_TYPE_I],
348 rcc->i_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
349 rcc->p_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
350 rcc->p_cplx_sum[AV_PICTURE_TYPE_B] / (double)rcc->frame_count[AV_PICTURE_TYPE_B],
351 (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],
355 bits = av_expr_eval(rcc->rc_eq_eval, const_values, rce);
357 av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);
361 rcc->pass1_rc_eq_output_sum+= bits;
363 if(bits<0.0) bits=0.0;
364 bits+= 1.0; //avoid 1/0 issues
367 for(i=0; i<s->avctx->rc_override_count; i++){
368 RcOverride *rco= s->avctx->rc_override;
369 if(rco[i].start_frame > frame_num) continue;
370 if(rco[i].end_frame < frame_num) continue;
373 bits= qp2bits(rce, rco[i].qscale); //FIXME move at end to really force it?
375 bits*= rco[i].quality_factor;
378 q= bits2qp(rce, bits);
381 if (pict_type==AV_PICTURE_TYPE_I && s->avctx->i_quant_factor<0.0)
382 q= -q*s->avctx->i_quant_factor + s->avctx->i_quant_offset;
383 else if(pict_type==AV_PICTURE_TYPE_B && s->avctx->b_quant_factor<0.0)
384 q= -q*s->avctx->b_quant_factor + s->avctx->b_quant_offset;
390 static double get_diff_limited_q(MpegEncContext *s, RateControlEntry *rce, double q){
391 RateControlContext *rcc= &s->rc_context;
392 AVCodecContext *a= s->avctx;
393 const int pict_type= rce->new_pict_type;
394 const double last_p_q = rcc->last_qscale_for[AV_PICTURE_TYPE_P];
395 const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
397 if (pict_type==AV_PICTURE_TYPE_I && (a->i_quant_factor>0.0 || rcc->last_non_b_pict_type==AV_PICTURE_TYPE_P))
398 q= last_p_q *FFABS(a->i_quant_factor) + a->i_quant_offset;
399 else if(pict_type==AV_PICTURE_TYPE_B && a->b_quant_factor>0.0)
400 q= last_non_b_q* a->b_quant_factor + a->b_quant_offset;
403 /* last qscale / qdiff stuff */
404 if(rcc->last_non_b_pict_type==pict_type || pict_type!=AV_PICTURE_TYPE_I){
405 double last_q= rcc->last_qscale_for[pict_type];
406 const int maxdiff= FF_QP2LAMBDA * a->max_qdiff;
408 if (q > last_q + maxdiff) q= last_q + maxdiff;
409 else if(q < last_q - maxdiff) q= last_q - maxdiff;
412 rcc->last_qscale_for[pict_type]= q; //Note we cannot do that after blurring
414 if(pict_type!=AV_PICTURE_TYPE_B)
415 rcc->last_non_b_pict_type= pict_type;
421 * Get the qmin & qmax for pict_type.
423 static void get_qminmax(int *qmin_ret, int *qmax_ret, MpegEncContext *s, int pict_type){
424 int qmin= s->avctx->lmin;
425 int qmax= s->avctx->lmax;
427 assert(qmin <= qmax);
429 if(pict_type==AV_PICTURE_TYPE_B){
430 qmin= (int)(qmin*FFABS(s->avctx->b_quant_factor)+s->avctx->b_quant_offset + 0.5);
431 qmax= (int)(qmax*FFABS(s->avctx->b_quant_factor)+s->avctx->b_quant_offset + 0.5);
432 }else if(pict_type==AV_PICTURE_TYPE_I){
433 qmin= (int)(qmin*FFABS(s->avctx->i_quant_factor)+s->avctx->i_quant_offset + 0.5);
434 qmax= (int)(qmax*FFABS(s->avctx->i_quant_factor)+s->avctx->i_quant_offset + 0.5);
437 qmin= av_clip(qmin, 1, FF_LAMBDA_MAX);
438 qmax= av_clip(qmax, 1, FF_LAMBDA_MAX);
440 if(qmax<qmin) qmax= qmin;
446 static double modify_qscale(MpegEncContext *s, RateControlEntry *rce, double q, int frame_num){
447 RateControlContext *rcc= &s->rc_context;
449 const int pict_type= rce->new_pict_type;
450 const double buffer_size= s->avctx->rc_buffer_size;
451 const double fps= get_fps(s->avctx);
452 const double min_rate= s->avctx->rc_min_rate / fps;
453 const double max_rate= s->avctx->rc_max_rate / fps;
455 get_qminmax(&qmin, &qmax, s, pict_type);
458 if(s->avctx->rc_qmod_freq && frame_num%s->avctx->rc_qmod_freq==0 && pict_type==AV_PICTURE_TYPE_P)
459 q*= s->avctx->rc_qmod_amp;
461 /* buffer overflow/underflow protection */
463 double expected_size= rcc->buffer_index;
467 double d= 2*(buffer_size - expected_size)/buffer_size;
469 else if(d<0.0001) d=0.0001;
470 q*= pow(d, 1.0/s->avctx->rc_buffer_aggressivity);
472 q_limit= bits2qp(rce, FFMAX((min_rate - buffer_size + rcc->buffer_index) * s->avctx->rc_min_vbv_overflow_use, 1));
474 if(s->avctx->debug&FF_DEBUG_RC){
475 av_log(s->avctx, AV_LOG_DEBUG, "limiting QP %f -> %f\n", q, q_limit);
482 double d= 2*expected_size/buffer_size;
484 else if(d<0.0001) d=0.0001;
485 q/= pow(d, 1.0/s->avctx->rc_buffer_aggressivity);
487 q_limit= bits2qp(rce, FFMAX(rcc->buffer_index * s->avctx->rc_max_available_vbv_use, 1));
489 if(s->avctx->debug&FF_DEBUG_RC){
490 av_log(s->avctx, AV_LOG_DEBUG, "limiting QP %f -> %f\n", q, q_limit);
496 av_dlog(s, "q:%f max:%f min:%f size:%f index:%f agr:%f\n",
497 q, max_rate, min_rate, buffer_size, rcc->buffer_index,
498 s->avctx->rc_buffer_aggressivity);
499 if(s->avctx->rc_qsquish==0.0 || qmin==qmax){
501 else if(q>qmax) q=qmax;
503 double min2= log(qmin);
504 double max2= log(qmax);
507 q= (q - min2)/(max2-min2) - 0.5;
509 q= 1.0/(1.0 + exp(q));
510 q= q*(max2-min2) + min2;
518 //----------------------------------
521 static double predict_size(Predictor *p, double q, double var)
523 return p->coeff*var / (q*p->count);
526 static void update_predictor(Predictor *p, double q, double var, double size)
528 double new_coeff= size*q / (var + 1);
534 p->coeff+= new_coeff;
537 static void adaptive_quantization(MpegEncContext *s, double q){
539 const float lumi_masking= s->avctx->lumi_masking / (128.0*128.0);
540 const float dark_masking= s->avctx->dark_masking / (128.0*128.0);
541 const float temp_cplx_masking= s->avctx->temporal_cplx_masking;
542 const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;
543 const float p_masking = s->avctx->p_masking;
544 const float border_masking = s->avctx->border_masking;
547 float *cplx_tab = s->cplx_tab;
548 float *bits_tab = s->bits_tab;
549 const int qmin= s->avctx->mb_lmin;
550 const int qmax= s->avctx->mb_lmax;
551 Picture * const pic= &s->current_picture;
552 const int mb_width = s->mb_width;
553 const int mb_height = s->mb_height;
555 for(i=0; i<s->mb_num; i++){
556 const int mb_xy= s->mb_index2xy[i];
557 float temp_cplx= sqrt(pic->mc_mb_var[mb_xy]); //FIXME merge in pow()
558 float spat_cplx= sqrt(pic->mb_var[mb_xy]);
559 const int lumi= pic->mb_mean[mb_xy];
560 float bits, cplx, factor;
561 int mb_x = mb_xy % s->mb_stride;
562 int mb_y = mb_xy / s->mb_stride;
564 float mb_factor = 0.0;
565 if(spat_cplx < 4) spat_cplx= 4; //FIXME finetune
566 if(temp_cplx < 4) temp_cplx= 4; //FIXME finetune
568 if((s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTRA)){//FIXME hq mode
570 factor= 1.0 + p_masking;
573 factor= pow(temp_cplx, - temp_cplx_masking);
575 factor*=pow(spat_cplx, - spatial_cplx_masking);
578 factor*= (1.0 - (lumi-128)*(lumi-128)*lumi_masking);
580 factor*= (1.0 - (lumi-128)*(lumi-128)*dark_masking);
582 if(mb_x < mb_width/5){
583 mb_distance = mb_width/5 - mb_x;
584 mb_factor = (float)mb_distance / (float)(mb_width/5);
585 }else if(mb_x > 4*mb_width/5){
586 mb_distance = mb_x - 4*mb_width/5;
587 mb_factor = (float)mb_distance / (float)(mb_width/5);
589 if(mb_y < mb_height/5){
590 mb_distance = mb_height/5 - mb_y;
591 mb_factor = FFMAX(mb_factor, (float)mb_distance / (float)(mb_height/5));
592 }else if(mb_y > 4*mb_height/5){
593 mb_distance = mb_y - 4*mb_height/5;
594 mb_factor = FFMAX(mb_factor, (float)mb_distance / (float)(mb_height/5));
597 factor*= 1.0 - border_masking*mb_factor;
599 if(factor<0.00001) factor= 0.00001;
608 /* handle qmin/qmax clipping */
609 if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
610 float factor= bits_sum/cplx_sum;
611 for(i=0; i<s->mb_num; i++){
612 float newq= q*cplx_tab[i]/bits_tab[i];
616 bits_sum -= bits_tab[i];
617 cplx_sum -= cplx_tab[i]*q/qmax;
619 else if(newq < qmin){
620 bits_sum -= bits_tab[i];
621 cplx_sum -= cplx_tab[i]*q/qmin;
624 if(bits_sum < 0.001) bits_sum= 0.001;
625 if(cplx_sum < 0.001) cplx_sum= 0.001;
628 for(i=0; i<s->mb_num; i++){
629 const int mb_xy= s->mb_index2xy[i];
630 float newq= q*cplx_tab[i]/bits_tab[i];
633 if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
634 newq*= bits_sum/cplx_sum;
637 intq= (int)(newq + 0.5);
639 if (intq > qmax) intq= qmax;
640 else if(intq < qmin) intq= qmin;
641 s->lambda_table[mb_xy]= intq;
645 void ff_get_2pass_fcode(MpegEncContext *s){
646 RateControlContext *rcc= &s->rc_context;
647 int picture_number= s->picture_number;
648 RateControlEntry *rce;
650 rce= &rcc->entry[picture_number];
651 s->f_code= rce->f_code;
652 s->b_code= rce->b_code;
655 //FIXME rd or at least approx for dquant
657 float ff_rate_estimate_qscale(MpegEncContext *s, int dry_run)
661 float br_compensation;
665 int picture_number= s->picture_number;
667 RateControlContext *rcc= &s->rc_context;
668 AVCodecContext *a= s->avctx;
669 RateControlEntry local_rce, *rce;
673 const int pict_type= s->pict_type;
674 Picture * const pic= &s->current_picture;
678 if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
679 return ff_xvid_rate_estimate_qscale(s, dry_run);
682 get_qminmax(&qmin, &qmax, s, pict_type);
684 fps= get_fps(s->avctx);
685 /* update predictors */
686 if(picture_number>2 && !dry_run){
687 const int last_var= s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum : rcc->last_mc_mb_var_sum;
688 av_assert1(s->frame_bits >= s->stuffing_bits);
689 update_predictor(&rcc->pred[s->last_pict_type], rcc->last_qscale, sqrt(last_var), s->frame_bits - s->stuffing_bits);
692 if(s->flags&CODEC_FLAG_PASS2){
693 assert(picture_number>=0);
694 if(picture_number >= rcc->num_entries) {
695 av_log(s, AV_LOG_ERROR, "Input is longer than 2-pass log file\n");
698 rce= &rcc->entry[picture_number];
699 wanted_bits= rce->expected_bits;
704 //FIXME add a dts field to AVFrame and ensure its set and use it here instead of reordering
705 //but the reordering is simpler for now until h.264 b pyramid must be handeld
706 if(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
707 dts_pic= s->current_picture_ptr;
709 dts_pic= s->last_picture_ptr;
711 if (!dts_pic || dts_pic->f.pts == AV_NOPTS_VALUE)
712 wanted_bits= (uint64_t)(s->bit_rate*(double)picture_number/fps);
714 wanted_bits = (uint64_t)(s->bit_rate*(double)dts_pic->f.pts / fps);
717 diff= s->total_bits - wanted_bits;
718 br_compensation= (a->bit_rate_tolerance - diff)/a->bit_rate_tolerance;
719 if(br_compensation<=0.0) br_compensation=0.001;
721 var= pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;
723 short_term_q = 0; /* avoid warning */
724 if(s->flags&CODEC_FLAG_PASS2){
725 if(pict_type!=AV_PICTURE_TYPE_I)
726 assert(pict_type == rce->new_pict_type);
728 q= rce->new_qscale / br_compensation;
729 av_dlog(s, "%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale,
730 br_compensation, s->frame_bits, var, pict_type);
733 rce->new_pict_type= pict_type;
734 rce->mc_mb_var_sum= pic->mc_mb_var_sum;
735 rce->mb_var_sum = pic-> mb_var_sum;
736 rce->qscale = FF_QP2LAMBDA * 2;
737 rce->f_code = s->f_code;
738 rce->b_code = s->b_code;
741 bits= predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));
742 if(pict_type== AV_PICTURE_TYPE_I){
743 rce->i_count = s->mb_num;
744 rce->i_tex_bits= bits;
748 rce->i_count = 0; //FIXME we do know this approx
750 rce->p_tex_bits= bits*0.9;
752 rce->mv_bits= bits*0.1;
754 rcc->i_cplx_sum [pict_type] += rce->i_tex_bits*rce->qscale;
755 rcc->p_cplx_sum [pict_type] += rce->p_tex_bits*rce->qscale;
756 rcc->mv_bits_sum[pict_type] += rce->mv_bits;
757 rcc->frame_count[pict_type] ++;
759 bits= rce->i_tex_bits + rce->p_tex_bits;
760 rate_factor= rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum * br_compensation;
762 q= get_qscale(s, rce, rate_factor, picture_number);
767 q= get_diff_limited_q(s, rce, q);
770 if(pict_type==AV_PICTURE_TYPE_P || s->intra_only){ //FIXME type dependent blur like in 2-pass
771 rcc->short_term_qsum*=a->qblur;
772 rcc->short_term_qcount*=a->qblur;
774 rcc->short_term_qsum+= q;
775 rcc->short_term_qcount++;
776 q= short_term_q= rcc->short_term_qsum/rcc->short_term_qcount;
780 q= modify_qscale(s, rce, q, picture_number);
782 rcc->pass1_wanted_bits+= s->bit_rate/fps;
787 if(s->avctx->debug&FF_DEBUG_RC){
788 av_log(s->avctx, AV_LOG_DEBUG, "%c qp:%d<%2.1f<%d %d want:%d total:%d comp:%f st_q:%2.2f size:%d var:%d/%d br:%d fps:%d\n",
789 av_get_picture_type_char(pict_type), qmin, q, qmax, picture_number, (int)wanted_bits/1000, (int)s->total_bits/1000,
790 br_compensation, short_term_q, s->frame_bits, pic->mb_var_sum, pic->mc_mb_var_sum, s->bit_rate/1000, (int)fps
795 else if(q>qmax) q=qmax;
797 if(s->adaptive_quant)
798 adaptive_quantization(s, q);
804 rcc->last_mc_mb_var_sum= pic->mc_mb_var_sum;
805 rcc->last_mb_var_sum= pic->mb_var_sum;
810 //----------------------------------------------
813 static int init_pass2(MpegEncContext *s)
815 RateControlContext *rcc= &s->rc_context;
816 AVCodecContext *a= s->avctx;
818 double fps= get_fps(s->avctx);
819 double complexity[5]={0,0,0,0,0}; // aproximate bits at quant=1
820 uint64_t const_bits[5]={0,0,0,0,0}; // quantizer independent bits
821 uint64_t all_const_bits;
822 uint64_t all_available_bits= (uint64_t)(s->bit_rate*(double)rcc->num_entries/fps);
823 double rate_factor=0;
825 //int last_i_frame=-10000000;
826 const int filter_size= (int)(a->qblur*4) | 1;
827 double expected_bits;
828 double *qscale, *blurred_qscale, qscale_sum;
830 /* find complexity & const_bits & decide the pict_types */
831 for(i=0; i<rcc->num_entries; i++){
832 RateControlEntry *rce= &rcc->entry[i];
834 rce->new_pict_type= rce->pict_type;
835 rcc->i_cplx_sum [rce->pict_type] += rce->i_tex_bits*rce->qscale;
836 rcc->p_cplx_sum [rce->pict_type] += rce->p_tex_bits*rce->qscale;
837 rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;
838 rcc->frame_count[rce->pict_type] ++;
840 complexity[rce->new_pict_type]+= (rce->i_tex_bits+ rce->p_tex_bits)*(double)rce->qscale;
841 const_bits[rce->new_pict_type]+= rce->mv_bits + rce->misc_bits;
843 all_const_bits= const_bits[AV_PICTURE_TYPE_I] + const_bits[AV_PICTURE_TYPE_P] + const_bits[AV_PICTURE_TYPE_B];
845 if(all_available_bits < all_const_bits){
846 av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
850 qscale= av_malloc(sizeof(double)*rcc->num_entries);
851 blurred_qscale= av_malloc(sizeof(double)*rcc->num_entries);
854 for(step=256*256; step>0.0000001; step*=0.5){
858 rcc->buffer_index= s->avctx->rc_buffer_size/2;
861 for(i=0; i<rcc->num_entries; i++){
862 RateControlEntry *rce= &rcc->entry[i];
863 qscale[i]= get_qscale(s, &rcc->entry[i], rate_factor, i);
864 rcc->last_qscale_for[rce->pict_type] = qscale[i];
866 assert(filter_size%2==1);
868 /* fixed I/B QP relative to P mode */
869 for(i=FFMAX(0, rcc->num_entries-300); i<rcc->num_entries; i++){
870 RateControlEntry *rce= &rcc->entry[i];
872 qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
875 for(i=rcc->num_entries-1; i>=0; i--){
876 RateControlEntry *rce= &rcc->entry[i];
878 qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
882 for(i=0; i<rcc->num_entries; i++){
883 RateControlEntry *rce= &rcc->entry[i];
884 const int pict_type= rce->new_pict_type;
886 double q=0.0, sum=0.0;
888 for(j=0; j<filter_size; j++){
889 int index= i+j-filter_size/2;
891 double coeff= a->qblur==0 ? 1.0 : exp(-d*d/(a->qblur * a->qblur));
893 if(index < 0 || index >= rcc->num_entries) continue;
894 if(pict_type != rcc->entry[index].new_pict_type) continue;
895 q+= qscale[index] * coeff;
898 blurred_qscale[i]= q/sum;
901 /* find expected bits */
902 for(i=0; i<rcc->num_entries; i++){
903 RateControlEntry *rce= &rcc->entry[i];
905 rce->new_qscale= modify_qscale(s, rce, blurred_qscale[i], i);
906 bits= qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
907 bits += 8*ff_vbv_update(s, bits);
909 rce->expected_bits= expected_bits;
910 expected_bits += bits;
914 "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
915 expected_bits, (int)all_available_bits, rate_factor);
916 if(expected_bits > all_available_bits) {
922 av_free(blurred_qscale);
924 /* check bitrate calculations and print info */
926 for(i=0; i<rcc->num_entries; i++){
927 av_dlog(s, "[lavc rc] entry[%d].new_qscale = %.3f qp = %.3f\n",
929 rcc->entry[i].new_qscale,
930 rcc->entry[i].new_qscale / FF_QP2LAMBDA);
931 qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA, s->avctx->qmin, s->avctx->qmax);
933 assert(toobig <= 40);
934 av_log(s->avctx, AV_LOG_DEBUG,
935 "[lavc rc] requested bitrate: %d bps expected bitrate: %d bps\n",
937 (int)(expected_bits / ((double)all_available_bits/s->bit_rate)));
938 av_log(s->avctx, AV_LOG_DEBUG,
939 "[lavc rc] estimated target average qp: %.3f\n",
940 (float)qscale_sum / rcc->num_entries);
942 av_log(s->avctx, AV_LOG_INFO,
943 "[lavc rc] Using all of requested bitrate is not "
944 "necessary for this video with these parameters.\n");
945 } else if (toobig == 40) {
946 av_log(s->avctx, AV_LOG_ERROR,
947 "[lavc rc] Error: bitrate too low for this video "
948 "with these parameters.\n");
950 } else if (fabs(expected_bits/all_available_bits - 1.0) > 0.01) {
951 av_log(s->avctx, AV_LOG_ERROR,
952 "[lavc rc] Error: 2pass curve failed to converge\n");