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/attributes.h"
30 #include "ratecontrol.h"
31 #include "mpegvideo.h"
32 #include "libavutil/eval.h"
34 #undef NDEBUG // Always check asserts, the speed effect is far too small to disable them.
38 #define M_E 2.718281828
41 static int init_pass2(MpegEncContext *s);
42 static double get_qscale(MpegEncContext *s, RateControlEntry *rce,
43 double rate_factor, int frame_num);
45 void ff_write_pass1_stats(MpegEncContext *s)
47 snprintf(s->avctx->stats_out, 256,
48 "in:%d out:%d type:%d q:%d itex:%d ptex:%d mv:%d misc:%d "
49 "fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d;\n",
50 s->current_picture_ptr->f.display_picture_number,
51 s->current_picture_ptr->f.coded_picture_number,
53 s->current_picture.f.quality,
60 s->current_picture.mc_mb_var_sum,
61 s->current_picture.mb_var_sum,
62 s->i_count, s->skip_count,
66 static double get_fps(AVCodecContext *avctx)
68 return 1.0 / av_q2d(avctx->time_base) / FFMAX(avctx->ticks_per_frame, 1);
71 static inline double qp2bits(RateControlEntry *rce, double qp)
74 av_log(NULL, AV_LOG_ERROR, "qp<=0.0\n");
76 return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits + 1) / qp;
79 static inline double bits2qp(RateControlEntry *rce, double bits)
82 av_log(NULL, AV_LOG_ERROR, "bits<0.9\n");
84 return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits + 1) / bits;
87 av_cold int ff_rate_control_init(MpegEncContext *s)
89 RateControlContext *rcc = &s->rc_context;
91 static const char * const const_names[] = {
120 static double (* const func1[])(void *, double) = {
125 static const char * const func1_names[] = {
132 if (!s->avctx->rc_max_available_vbv_use && s->avctx->rc_buffer_size) {
133 if (s->avctx->rc_max_rate) {
134 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);
136 s->avctx->rc_max_available_vbv_use = 1.0;
139 res = av_expr_parse(&rcc->rc_eq_eval,
140 s->avctx->rc_eq ? s->avctx->rc_eq : "tex^qComp",
141 const_names, func1_names, func1,
142 NULL, NULL, 0, s->avctx);
144 av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\"\n", s->avctx->rc_eq);
148 for (i = 0; i < 5; i++) {
149 rcc->pred[i].coeff = FF_QP2LAMBDA * 7.0;
150 rcc->pred[i].count = 1.0;
151 rcc->pred[i].decay = 0.4;
153 rcc->i_cplx_sum [i] =
154 rcc->p_cplx_sum [i] =
155 rcc->mv_bits_sum[i] =
156 rcc->qscale_sum [i] =
157 rcc->frame_count[i] = 1; // 1 is better because of 1/0 and such
159 rcc->last_qscale_for[i] = FF_QP2LAMBDA * 5;
161 rcc->buffer_index = s->avctx->rc_initial_buffer_occupancy;
162 if (!rcc->buffer_index)
163 rcc->buffer_index = s->avctx->rc_buffer_size * 3 / 4;
165 if (s->flags & CODEC_FLAG_PASS2) {
169 /* find number of pics */
170 p = s->avctx->stats_in;
172 p = strchr(p + 1, ';');
173 i += s->max_b_frames;
174 if (i <= 0 || i >= INT_MAX / sizeof(RateControlEntry))
176 rcc->entry = av_mallocz(i * sizeof(RateControlEntry));
177 rcc->num_entries = i;
179 /* init all to skipped p frames
180 * (with b frames we might have a not encoded frame at the end FIXME) */
181 for (i = 0; i < rcc->num_entries; i++) {
182 RateControlEntry *rce = &rcc->entry[i];
184 rce->pict_type = rce->new_pict_type = AV_PICTURE_TYPE_P;
185 rce->qscale = rce->new_qscale = FF_QP2LAMBDA * 2;
186 rce->misc_bits = s->mb_num + 10;
187 rce->mb_var_sum = s->mb_num * 100;
191 p = s->avctx->stats_in;
192 for (i = 0; i < rcc->num_entries - s->max_b_frames; i++) {
193 RateControlEntry *rce;
198 next = strchr(p, ';');
200 (*next) = 0; // sscanf in unbelievably slow on looong strings // FIXME copy / do not write
203 e = sscanf(p, " in:%d ", &picture_number);
205 assert(picture_number >= 0);
206 assert(picture_number < rcc->num_entries);
207 rce = &rcc->entry[picture_number];
209 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",
210 &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits,
211 &rce->mv_bits, &rce->misc_bits,
212 &rce->f_code, &rce->b_code,
213 &rce->mc_mb_var_sum, &rce->mb_var_sum,
214 &rce->i_count, &rce->skip_count, &rce->header_bits);
216 av_log(s->avctx, AV_LOG_ERROR,
217 "statistics are damaged at line %d, parser out=%d\n",
225 if (init_pass2(s) < 0)
228 // FIXME maybe move to end
229 if ((s->flags & CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID) {
231 return ff_xvid_rate_control_init(s);
233 av_log(s->avctx, AV_LOG_ERROR,
234 "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");
240 if (!(s->flags & CODEC_FLAG_PASS2)) {
241 rcc->short_term_qsum = 0.001;
242 rcc->short_term_qcount = 0.001;
244 rcc->pass1_rc_eq_output_sum = 0.001;
245 rcc->pass1_wanted_bits = 0.001;
247 if (s->avctx->qblur > 1.0) {
248 av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");
251 /* init stuff with the user specified complexity */
252 if (s->avctx->rc_initial_cplx) {
253 for (i = 0; i < 60 * 30; i++) {
254 double bits = s->avctx->rc_initial_cplx * (i / 10000.0 + 1.0) * s->mb_num;
255 RateControlEntry rce;
257 if (i % ((s->gop_size + 3) / 4) == 0)
258 rce.pict_type = AV_PICTURE_TYPE_I;
259 else if (i % (s->max_b_frames + 1))
260 rce.pict_type = AV_PICTURE_TYPE_B;
262 rce.pict_type = AV_PICTURE_TYPE_P;
264 rce.new_pict_type = rce.pict_type;
265 rce.mc_mb_var_sum = bits * s->mb_num / 100000;
266 rce.mb_var_sum = s->mb_num;
268 rce.qscale = FF_QP2LAMBDA * 2;
273 if (s->pict_type == AV_PICTURE_TYPE_I) {
274 rce.i_count = s->mb_num;
275 rce.i_tex_bits = bits;
279 rce.i_count = 0; // FIXME we do know this approx
281 rce.p_tex_bits = bits * 0.9;
282 rce.mv_bits = bits * 0.1;
284 rcc->i_cplx_sum[rce.pict_type] += rce.i_tex_bits * rce.qscale;
285 rcc->p_cplx_sum[rce.pict_type] += rce.p_tex_bits * rce.qscale;
286 rcc->mv_bits_sum[rce.pict_type] += rce.mv_bits;
287 rcc->frame_count[rce.pict_type]++;
289 get_qscale(s, &rce, rcc->pass1_wanted_bits / rcc->pass1_rc_eq_output_sum, i);
291 // FIXME misbehaves a little for variable fps
292 rcc->pass1_wanted_bits += s->bit_rate / get_fps(s->avctx);
300 av_cold void ff_rate_control_uninit(MpegEncContext *s)
302 RateControlContext *rcc = &s->rc_context;
305 av_expr_free(rcc->rc_eq_eval);
306 av_freep(&rcc->entry);
309 if ((s->flags & CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
310 ff_xvid_rate_control_uninit(s);
314 int ff_vbv_update(MpegEncContext *s, int frame_size)
316 RateControlContext *rcc = &s->rc_context;
317 const double fps = get_fps(s->avctx);
318 const int buffer_size = s->avctx->rc_buffer_size;
319 const double min_rate = s->avctx->rc_min_rate / fps;
320 const double max_rate = s->avctx->rc_max_rate / fps;
322 av_dlog(s, "%d %f %d %f %f\n",
323 buffer_size, rcc->buffer_index, frame_size, min_rate, max_rate);
328 rcc->buffer_index -= frame_size;
329 if (rcc->buffer_index < 0) {
330 av_log(s->avctx, AV_LOG_ERROR, "rc buffer underflow\n");
331 rcc->buffer_index = 0;
334 left = buffer_size - rcc->buffer_index - 1;
335 rcc->buffer_index += av_clip(left, min_rate, max_rate);
337 if (rcc->buffer_index > buffer_size) {
338 int stuffing = ceil((rcc->buffer_index - buffer_size) / 8);
340 if (stuffing < 4 && s->codec_id == AV_CODEC_ID_MPEG4)
342 rcc->buffer_index -= 8 * stuffing;
344 if (s->avctx->debug & FF_DEBUG_RC)
345 av_log(s->avctx, AV_LOG_DEBUG, "stuffing %d bytes\n", stuffing);
354 * Modify the bitrate curve from pass1 for one frame.
356 static double get_qscale(MpegEncContext *s, RateControlEntry *rce,
357 double rate_factor, int frame_num)
359 RateControlContext *rcc = &s->rc_context;
360 AVCodecContext *a = s->avctx;
361 const int pict_type = rce->new_pict_type;
362 const double mb_num = s->mb_num;
366 double const_values[] = {
369 rce->i_tex_bits * rce->qscale,
370 rce->p_tex_bits * rce->qscale,
371 (rce->i_tex_bits + rce->p_tex_bits) * (double)rce->qscale,
372 rce->mv_bits / mb_num,
373 rce->pict_type == AV_PICTURE_TYPE_B ? (rce->f_code + rce->b_code) * 0.5 : rce->f_code,
374 rce->i_count / mb_num,
375 rce->mc_mb_var_sum / mb_num,
376 rce->mb_var_sum / mb_num,
377 rce->pict_type == AV_PICTURE_TYPE_I,
378 rce->pict_type == AV_PICTURE_TYPE_P,
379 rce->pict_type == AV_PICTURE_TYPE_B,
380 rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],
383 rcc->last_qscale_for[AV_PICTURE_TYPE_I],
384 rcc->last_qscale_for[AV_PICTURE_TYPE_P],
385 rcc->last_qscale_for[AV_PICTURE_TYPE_B],
386 rcc->next_non_b_qscale,
388 rcc->i_cplx_sum[AV_PICTURE_TYPE_I] / (double)rcc->frame_count[AV_PICTURE_TYPE_I],
389 rcc->i_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
390 rcc->p_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
391 rcc->p_cplx_sum[AV_PICTURE_TYPE_B] / (double)rcc->frame_count[AV_PICTURE_TYPE_B],
392 (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],
396 bits = av_expr_eval(rcc->rc_eq_eval, const_values, rce);
398 av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);
402 rcc->pass1_rc_eq_output_sum += bits;
406 bits += 1.0; // avoid 1/0 issues
409 for (i = 0; i < s->avctx->rc_override_count; i++) {
410 RcOverride *rco = s->avctx->rc_override;
411 if (rco[i].start_frame > frame_num)
413 if (rco[i].end_frame < frame_num)
417 bits = qp2bits(rce, rco[i].qscale); // FIXME move at end to really force it?
419 bits *= rco[i].quality_factor;
422 q = bits2qp(rce, bits);
425 if (pict_type == AV_PICTURE_TYPE_I && s->avctx->i_quant_factor < 0.0)
426 q = -q * s->avctx->i_quant_factor + s->avctx->i_quant_offset;
427 else if (pict_type == AV_PICTURE_TYPE_B && s->avctx->b_quant_factor < 0.0)
428 q = -q * s->avctx->b_quant_factor + s->avctx->b_quant_offset;
435 static double get_diff_limited_q(MpegEncContext *s, RateControlEntry *rce, double q)
437 RateControlContext *rcc = &s->rc_context;
438 AVCodecContext *a = s->avctx;
439 const int pict_type = rce->new_pict_type;
440 const double last_p_q = rcc->last_qscale_for[AV_PICTURE_TYPE_P];
441 const double last_non_b_q = rcc->last_qscale_for[rcc->last_non_b_pict_type];
443 if (pict_type == AV_PICTURE_TYPE_I &&
444 (a->i_quant_factor > 0.0 || rcc->last_non_b_pict_type == AV_PICTURE_TYPE_P))
445 q = last_p_q * FFABS(a->i_quant_factor) + a->i_quant_offset;
446 else if (pict_type == AV_PICTURE_TYPE_B &&
447 a->b_quant_factor > 0.0)
448 q = last_non_b_q * a->b_quant_factor + a->b_quant_offset;
452 /* last qscale / qdiff stuff */
453 if (rcc->last_non_b_pict_type == pict_type || pict_type != AV_PICTURE_TYPE_I) {
454 double last_q = rcc->last_qscale_for[pict_type];
455 const int maxdiff = FF_QP2LAMBDA * a->max_qdiff;
457 if (q > last_q + maxdiff)
458 q = last_q + maxdiff;
459 else if (q < last_q - maxdiff)
460 q = last_q - maxdiff;
463 rcc->last_qscale_for[pict_type] = q; // Note we cannot do that after blurring
465 if (pict_type != AV_PICTURE_TYPE_B)
466 rcc->last_non_b_pict_type = pict_type;
472 * Get the qmin & qmax for pict_type.
474 static void get_qminmax(int *qmin_ret, int *qmax_ret, MpegEncContext *s, int pict_type)
476 int qmin = s->avctx->lmin;
477 int qmax = s->avctx->lmax;
479 assert(qmin <= qmax);
482 case AV_PICTURE_TYPE_B:
483 qmin = (int)(qmin * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset + 0.5);
484 qmax = (int)(qmax * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset + 0.5);
486 case AV_PICTURE_TYPE_I:
487 qmin = (int)(qmin * FFABS(s->avctx->i_quant_factor) + s->avctx->i_quant_offset + 0.5);
488 qmax = (int)(qmax * FFABS(s->avctx->i_quant_factor) + s->avctx->i_quant_offset + 0.5);
492 qmin = av_clip(qmin, 1, FF_LAMBDA_MAX);
493 qmax = av_clip(qmax, 1, FF_LAMBDA_MAX);
502 static double modify_qscale(MpegEncContext *s, RateControlEntry *rce,
503 double q, int frame_num)
505 RateControlContext *rcc = &s->rc_context;
506 const double buffer_size = s->avctx->rc_buffer_size;
507 const double fps = get_fps(s->avctx);
508 const double min_rate = s->avctx->rc_min_rate / fps;
509 const double max_rate = s->avctx->rc_max_rate / fps;
510 const int pict_type = rce->new_pict_type;
513 get_qminmax(&qmin, &qmax, s, pict_type);
516 if (s->avctx->rc_qmod_freq &&
517 frame_num % s->avctx->rc_qmod_freq == 0 &&
518 pict_type == AV_PICTURE_TYPE_P)
519 q *= s->avctx->rc_qmod_amp;
521 /* buffer overflow/underflow protection */
523 double expected_size = rcc->buffer_index;
527 double d = 2 * (buffer_size - expected_size) / buffer_size;
532 q *= pow(d, 1.0 / s->avctx->rc_buffer_aggressivity);
534 q_limit = bits2qp(rce,
535 FFMAX((min_rate - buffer_size + rcc->buffer_index) *
536 s->avctx->rc_min_vbv_overflow_use, 1));
539 if (s->avctx->debug & FF_DEBUG_RC)
540 av_log(s->avctx, AV_LOG_DEBUG,
541 "limiting QP %f -> %f\n", q, q_limit);
547 double d = 2 * expected_size / buffer_size;
552 q /= pow(d, 1.0 / s->avctx->rc_buffer_aggressivity);
554 q_limit = bits2qp(rce,
555 FFMAX(rcc->buffer_index *
556 s->avctx->rc_max_available_vbv_use,
559 if (s->avctx->debug & FF_DEBUG_RC)
560 av_log(s->avctx, AV_LOG_DEBUG,
561 "limiting QP %f -> %f\n", q, q_limit);
566 av_dlog(s, "q:%f max:%f min:%f size:%f index:%f agr:%f\n",
567 q, max_rate, min_rate, buffer_size, rcc->buffer_index,
568 s->avctx->rc_buffer_aggressivity);
569 if (s->avctx->rc_qsquish == 0.0 || qmin == qmax) {
575 double min2 = log(qmin);
576 double max2 = log(qmax);
579 q = (q - min2) / (max2 - min2) - 0.5;
581 q = 1.0 / (1.0 + exp(q));
582 q = q * (max2 - min2) + min2;
590 // ----------------------------------
593 static double predict_size(Predictor *p, double q, double var)
595 return p->coeff * var / (q * p->count);
598 static void update_predictor(Predictor *p, double q, double var, double size)
600 double new_coeff = size * q / (var + 1);
604 p->count *= p->decay;
605 p->coeff *= p->decay;
607 p->coeff += new_coeff;
610 static void adaptive_quantization(MpegEncContext *s, double q)
613 const float lumi_masking = s->avctx->lumi_masking / (128.0 * 128.0);
614 const float dark_masking = s->avctx->dark_masking / (128.0 * 128.0);
615 const float temp_cplx_masking = s->avctx->temporal_cplx_masking;
616 const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;
617 const float p_masking = s->avctx->p_masking;
618 const float border_masking = s->avctx->border_masking;
619 float bits_sum = 0.0;
620 float cplx_sum = 0.0;
621 float *cplx_tab = s->cplx_tab;
622 float *bits_tab = s->bits_tab;
623 const int qmin = s->avctx->mb_lmin;
624 const int qmax = s->avctx->mb_lmax;
625 Picture *const pic = &s->current_picture;
626 const int mb_width = s->mb_width;
627 const int mb_height = s->mb_height;
629 for (i = 0; i < s->mb_num; i++) {
630 const int mb_xy = s->mb_index2xy[i];
631 float temp_cplx = sqrt(pic->mc_mb_var[mb_xy]); // FIXME merge in pow()
632 float spat_cplx = sqrt(pic->mb_var[mb_xy]);
633 const int lumi = pic->mb_mean[mb_xy];
634 float bits, cplx, factor;
635 int mb_x = mb_xy % s->mb_stride;
636 int mb_y = mb_xy / s->mb_stride;
638 float mb_factor = 0.0;
640 spat_cplx = 4; // FIXME finetune
642 temp_cplx = 4; // FIXME finetune
644 if ((s->mb_type[mb_xy] & CANDIDATE_MB_TYPE_INTRA)) { // FIXME hq mode
646 factor = 1.0 + p_masking;
649 factor = pow(temp_cplx, -temp_cplx_masking);
651 factor *= pow(spat_cplx, -spatial_cplx_masking);
654 factor *= (1.0 - (lumi - 128) * (lumi - 128) * lumi_masking);
656 factor *= (1.0 - (lumi - 128) * (lumi - 128) * dark_masking);
658 if (mb_x < mb_width / 5) {
659 mb_distance = mb_width / 5 - mb_x;
660 mb_factor = (float)mb_distance / (float)(mb_width / 5);
661 } else if (mb_x > 4 * mb_width / 5) {
662 mb_distance = mb_x - 4 * mb_width / 5;
663 mb_factor = (float)mb_distance / (float)(mb_width / 5);
665 if (mb_y < mb_height / 5) {
666 mb_distance = mb_height / 5 - mb_y;
667 mb_factor = FFMAX(mb_factor,
668 (float)mb_distance / (float)(mb_height / 5));
669 } else if (mb_y > 4 * mb_height / 5) {
670 mb_distance = mb_y - 4 * mb_height / 5;
671 mb_factor = FFMAX(mb_factor,
672 (float)mb_distance / (float)(mb_height / 5));
675 factor *= 1.0 - border_masking * mb_factor;
677 if (factor < 0.00001)
680 bits = cplx * factor;
687 /* handle qmin/qmax clipping */
688 if (s->flags & CODEC_FLAG_NORMALIZE_AQP) {
689 float factor = bits_sum / cplx_sum;
690 for (i = 0; i < s->mb_num; i++) {
691 float newq = q * cplx_tab[i] / bits_tab[i];
695 bits_sum -= bits_tab[i];
696 cplx_sum -= cplx_tab[i] * q / qmax;
697 } else if (newq < qmin) {
698 bits_sum -= bits_tab[i];
699 cplx_sum -= cplx_tab[i] * q / qmin;
702 if (bits_sum < 0.001)
704 if (cplx_sum < 0.001)
708 for (i = 0; i < s->mb_num; i++) {
709 const int mb_xy = s->mb_index2xy[i];
710 float newq = q * cplx_tab[i] / bits_tab[i];
713 if (s->flags & CODEC_FLAG_NORMALIZE_AQP) {
714 newq *= bits_sum / cplx_sum;
717 intq = (int)(newq + 0.5);
721 else if (intq < qmin)
723 s->lambda_table[mb_xy] = intq;
727 void ff_get_2pass_fcode(MpegEncContext *s)
729 RateControlContext *rcc = &s->rc_context;
730 RateControlEntry *rce = &rcc->entry[s->picture_number];
732 s->f_code = rce->f_code;
733 s->b_code = rce->b_code;
736 // FIXME rd or at least approx for dquant
738 float ff_rate_estimate_qscale(MpegEncContext *s, int dry_run)
742 float br_compensation;
746 int picture_number = s->picture_number;
748 RateControlContext *rcc = &s->rc_context;
749 AVCodecContext *a = s->avctx;
750 RateControlEntry local_rce, *rce;
754 const int pict_type = s->pict_type;
755 Picture * const pic = &s->current_picture;
759 if ((s->flags & CODEC_FLAG_PASS2) &&
760 s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
761 return ff_xvid_rate_estimate_qscale(s, dry_run);
764 get_qminmax(&qmin, &qmax, s, pict_type);
766 fps = get_fps(s->avctx);
767 /* update predictors */
768 if (picture_number > 2 && !dry_run) {
769 const int last_var = s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum
770 : rcc->last_mc_mb_var_sum;
771 av_assert1(s->frame_bits >= s->stuffing_bits);
772 update_predictor(&rcc->pred[s->last_pict_type],
775 s->frame_bits - s->stuffing_bits);
778 if (s->flags & CODEC_FLAG_PASS2) {
779 assert(picture_number >= 0);
780 if (picture_number >= rcc->num_entries) {
781 av_log(s, AV_LOG_ERROR, "Input is longer than 2-pass log file\n");
784 rce = &rcc->entry[picture_number];
785 wanted_bits = rce->expected_bits;
790 /* FIXME add a dts field to AVFrame and ensure it is set and use it
791 * here instead of reordering but the reordering is simpler for now
792 * until H.264 B-pyramid must be handled. */
793 if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
794 dts_pic = s->current_picture_ptr;
796 dts_pic = s->last_picture_ptr;
798 if (!dts_pic || dts_pic->f.pts == AV_NOPTS_VALUE)
799 wanted_bits = (uint64_t)(s->bit_rate * (double)picture_number / fps);
801 wanted_bits = (uint64_t)(s->bit_rate * (double)dts_pic->f.pts / fps);
804 diff = s->total_bits - wanted_bits;
805 br_compensation = (a->bit_rate_tolerance - diff) / a->bit_rate_tolerance;
806 if (br_compensation <= 0.0)
807 br_compensation = 0.001;
809 var = pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;
811 short_term_q = 0; /* avoid warning */
812 if (s->flags & CODEC_FLAG_PASS2) {
813 if (pict_type != AV_PICTURE_TYPE_I)
814 assert(pict_type == rce->new_pict_type);
816 q = rce->new_qscale / br_compensation;
817 av_dlog(s, "%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale,
818 br_compensation, s->frame_bits, var, pict_type);
821 rce->new_pict_type = pict_type;
822 rce->mc_mb_var_sum = pic->mc_mb_var_sum;
823 rce->mb_var_sum = pic->mb_var_sum;
824 rce->qscale = FF_QP2LAMBDA * 2;
825 rce->f_code = s->f_code;
826 rce->b_code = s->b_code;
829 bits = predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));
830 if (pict_type == AV_PICTURE_TYPE_I) {
831 rce->i_count = s->mb_num;
832 rce->i_tex_bits = bits;
836 rce->i_count = 0; // FIXME we do know this approx
838 rce->p_tex_bits = bits * 0.9;
839 rce->mv_bits = bits * 0.1;
841 rcc->i_cplx_sum[pict_type] += rce->i_tex_bits * rce->qscale;
842 rcc->p_cplx_sum[pict_type] += rce->p_tex_bits * rce->qscale;
843 rcc->mv_bits_sum[pict_type] += rce->mv_bits;
844 rcc->frame_count[pict_type]++;
846 bits = rce->i_tex_bits + rce->p_tex_bits;
847 rate_factor = rcc->pass1_wanted_bits /
848 rcc->pass1_rc_eq_output_sum * br_compensation;
850 q = get_qscale(s, rce, rate_factor, picture_number);
855 q = get_diff_limited_q(s, rce, q);
858 // FIXME type dependent blur like in 2-pass
859 if (pict_type == AV_PICTURE_TYPE_P || s->intra_only) {
860 rcc->short_term_qsum *= a->qblur;
861 rcc->short_term_qcount *= a->qblur;
863 rcc->short_term_qsum += q;
864 rcc->short_term_qcount++;
865 q = short_term_q = rcc->short_term_qsum / rcc->short_term_qcount;
869 q = modify_qscale(s, rce, q, picture_number);
871 rcc->pass1_wanted_bits += s->bit_rate / fps;
876 if (s->avctx->debug & FF_DEBUG_RC) {
877 av_log(s->avctx, AV_LOG_DEBUG,
878 "%c qp:%d<%2.1f<%d %d want:%d total:%d comp:%f st_q:%2.2f "
879 "size:%d var:%d/%d br:%d fps:%d\n",
880 av_get_picture_type_char(pict_type),
881 qmin, q, qmax, picture_number,
882 (int)wanted_bits / 1000, (int)s->total_bits / 1000,
883 br_compensation, short_term_q, s->frame_bits,
884 pic->mb_var_sum, pic->mc_mb_var_sum,
885 s->bit_rate / 1000, (int)fps);
893 if (s->adaptive_quant)
894 adaptive_quantization(s, q);
899 rcc->last_qscale = q;
900 rcc->last_mc_mb_var_sum = pic->mc_mb_var_sum;
901 rcc->last_mb_var_sum = pic->mb_var_sum;
906 // ----------------------------------------------
909 static int init_pass2(MpegEncContext *s)
911 RateControlContext *rcc = &s->rc_context;
912 AVCodecContext *a = s->avctx;
914 double fps = get_fps(s->avctx);
915 double complexity[5] = { 0 }; // approximate bits at quant=1
916 uint64_t const_bits[5] = { 0 }; // quantizer independent bits
917 uint64_t all_const_bits;
918 uint64_t all_available_bits = (uint64_t)(s->bit_rate *
919 (double)rcc->num_entries / fps);
920 double rate_factor = 0;
922 const int filter_size = (int)(a->qblur * 4) | 1;
923 double expected_bits;
924 double *qscale, *blurred_qscale, qscale_sum;
926 /* find complexity & const_bits & decide the pict_types */
927 for (i = 0; i < rcc->num_entries; i++) {
928 RateControlEntry *rce = &rcc->entry[i];
930 rce->new_pict_type = rce->pict_type;
931 rcc->i_cplx_sum[rce->pict_type] += rce->i_tex_bits * rce->qscale;
932 rcc->p_cplx_sum[rce->pict_type] += rce->p_tex_bits * rce->qscale;
933 rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;
934 rcc->frame_count[rce->pict_type]++;
936 complexity[rce->new_pict_type] += (rce->i_tex_bits + rce->p_tex_bits) *
938 const_bits[rce->new_pict_type] += rce->mv_bits + rce->misc_bits;
941 all_const_bits = const_bits[AV_PICTURE_TYPE_I] +
942 const_bits[AV_PICTURE_TYPE_P] +
943 const_bits[AV_PICTURE_TYPE_B];
945 if (all_available_bits < all_const_bits) {
946 av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
950 qscale = av_malloc(sizeof(double) * rcc->num_entries);
951 blurred_qscale = av_malloc(sizeof(double) * rcc->num_entries);
954 for (step = 256 * 256; step > 0.0000001; step *= 0.5) {
958 rcc->buffer_index = s->avctx->rc_buffer_size / 2;
961 for (i = 0; i < rcc->num_entries; i++) {
962 RateControlEntry *rce = &rcc->entry[i];
964 qscale[i] = get_qscale(s, &rcc->entry[i], rate_factor, i);
965 rcc->last_qscale_for[rce->pict_type] = qscale[i];
967 assert(filter_size % 2 == 1);
969 /* fixed I/B QP relative to P mode */
970 for (i = FFMAX(0, rcc->num_entries - 300); i < rcc->num_entries; i++) {
971 RateControlEntry *rce = &rcc->entry[i];
973 qscale[i] = get_diff_limited_q(s, rce, qscale[i]);
976 for (i = rcc->num_entries - 1; i >= 0; i--) {
977 RateControlEntry *rce = &rcc->entry[i];
979 qscale[i] = get_diff_limited_q(s, rce, qscale[i]);
983 for (i = 0; i < rcc->num_entries; i++) {
984 RateControlEntry *rce = &rcc->entry[i];
985 const int pict_type = rce->new_pict_type;
987 double q = 0.0, sum = 0.0;
989 for (j = 0; j < filter_size; j++) {
990 int index = i + j - filter_size / 2;
991 double d = index - i;
992 double coeff = a->qblur == 0 ? 1.0 : exp(-d * d / (a->qblur * a->qblur));
994 if (index < 0 || index >= rcc->num_entries)
996 if (pict_type != rcc->entry[index].new_pict_type)
998 q += qscale[index] * coeff;
1001 blurred_qscale[i] = q / sum;
1004 /* find expected bits */
1005 for (i = 0; i < rcc->num_entries; i++) {
1006 RateControlEntry *rce = &rcc->entry[i];
1009 rce->new_qscale = modify_qscale(s, rce, blurred_qscale[i], i);
1011 bits = qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
1012 bits += 8 * ff_vbv_update(s, bits);
1014 rce->expected_bits = expected_bits;
1015 expected_bits += bits;
1019 "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
1020 expected_bits, (int)all_available_bits, rate_factor);
1021 if (expected_bits > all_available_bits) {
1022 rate_factor -= step;
1027 av_free(blurred_qscale);
1029 /* check bitrate calculations and print info */
1031 for (i = 0; i < rcc->num_entries; i++) {
1032 av_dlog(s, "[lavc rc] entry[%d].new_qscale = %.3f qp = %.3f\n",
1034 rcc->entry[i].new_qscale,
1035 rcc->entry[i].new_qscale / FF_QP2LAMBDA);
1036 qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA,
1037 s->avctx->qmin, s->avctx->qmax);
1039 assert(toobig <= 40);
1040 av_log(s->avctx, AV_LOG_DEBUG,
1041 "[lavc rc] requested bitrate: %d bps expected bitrate: %d bps\n",
1043 (int)(expected_bits / ((double)all_available_bits / s->bit_rate)));
1044 av_log(s->avctx, AV_LOG_DEBUG,
1045 "[lavc rc] estimated target average qp: %.3f\n",
1046 (float)qscale_sum / rcc->num_entries);
1048 av_log(s->avctx, AV_LOG_INFO,
1049 "[lavc rc] Using all of requested bitrate is not "
1050 "necessary for this video with these parameters.\n");
1051 } else if (toobig == 40) {
1052 av_log(s->avctx, AV_LOG_ERROR,
1053 "[lavc rc] Error: bitrate too low for this video "
1054 "with these parameters.\n");
1056 } else if (fabs(expected_bits / all_available_bits - 1.0) > 0.01) {
1057 av_log(s->avctx, AV_LOG_ERROR,
1058 "[lavc rc] Error: 2pass curve failed to converge\n");