FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
ratecontrol.c
Go to the documentation of this file.
1 /*
2  * Rate control for video encoders
3  *
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
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.
12  *
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.
17  *
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
21  */
22 
23 /**
24  * @file
25  * Rate control for video encoders.
26  */
27 
28 #include "avcodec.h"
29 #include "ratecontrol.h"
30 #include "mpegvideo.h"
31 #include "libavutil/eval.h"
32 
33 #undef NDEBUG // Always check asserts, the speed effect is far too small to disable them.
34 #include <assert.h>
35 
36 #ifndef M_E
37 #define M_E 2.718281828
38 #endif
39 
40 static int init_pass2(MpegEncContext *s);
41 static double get_qscale(MpegEncContext *s, RateControlEntry *rce,
42  double rate_factor, int frame_num);
43 
45 {
46  snprintf(s->avctx->stats_out, 256,
47  "in:%d out:%d type:%d q:%d itex:%d ptex:%d mv:%d misc:%d "
48  "fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d;\n",
51  s->pict_type,
53  s->i_tex_bits,
54  s->p_tex_bits,
55  s->mv_bits,
56  s->misc_bits,
57  s->f_code,
58  s->b_code,
61  s->i_count, s->skip_count,
62  s->header_bits);
63 }
64 
65 static double get_fps(AVCodecContext *avctx)
66 {
67  return 1.0 / av_q2d(avctx->time_base) / FFMAX(avctx->ticks_per_frame, 1);
68 }
69 
70 static inline double qp2bits(RateControlEntry *rce, double qp)
71 {
72  if (qp <= 0.0) {
73  av_log(NULL, AV_LOG_ERROR, "qp<=0.0\n");
74  }
75  return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits + 1) / qp;
76 }
77 
78 static inline double bits2qp(RateControlEntry *rce, double bits)
79 {
80  if (bits < 0.9) {
81  av_log(NULL, AV_LOG_ERROR, "bits<0.9\n");
82  }
83  return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits + 1) / bits;
84 }
85 
87 {
88  RateControlContext *rcc = &s->rc_context;
89  int i, res;
90  static const char * const const_names[] = {
91  "PI",
92  "E",
93  "iTex",
94  "pTex",
95  "tex",
96  "mv",
97  "fCode",
98  "iCount",
99  "mcVar",
100  "var",
101  "isI",
102  "isP",
103  "isB",
104  "avgQP",
105  "qComp",
106 #if 0
107  "lastIQP",
108  "lastPQP",
109  "lastBQP",
110  "nextNonBQP",
111 #endif
112  "avgIITex",
113  "avgPITex",
114  "avgPPTex",
115  "avgBPTex",
116  "avgTex",
117  NULL
118  };
119  static double (* const func1[])(void *, double) = {
120  (void *)bits2qp,
121  (void *)qp2bits,
122  NULL
123  };
124  static const char * const func1_names[] = {
125  "bits2qp",
126  "qp2bits",
127  NULL
128  };
129  emms_c();
130 
132  if (s->avctx->rc_max_rate) {
133  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);
134  } else
136  }
137 
138  res = av_expr_parse(&rcc->rc_eq_eval,
139  s->avctx->rc_eq ? s->avctx->rc_eq : "tex^qComp",
140  const_names, func1_names, func1,
141  NULL, NULL, 0, s->avctx);
142  if (res < 0) {
143  av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\"\n", s->avctx->rc_eq);
144  return res;
145  }
146 
147  for (i = 0; i < 5; i++) {
148  rcc->pred[i].coeff = FF_QP2LAMBDA * 7.0;
149  rcc->pred[i].count = 1.0;
150  rcc->pred[i].decay = 0.4;
151 
152  rcc->i_cplx_sum [i] =
153  rcc->p_cplx_sum [i] =
154  rcc->mv_bits_sum[i] =
155  rcc->qscale_sum [i] =
156  rcc->frame_count[i] = 1; // 1 is better because of 1/0 and such
157 
158  rcc->last_qscale_for[i] = FF_QP2LAMBDA * 5;
159  }
161  if (!rcc->buffer_index)
162  rcc->buffer_index = s->avctx->rc_buffer_size * 3 / 4;
163 
164  if (s->flags & CODEC_FLAG_PASS2) {
165  int i;
166  char *p;
167 
168  /* find number of pics */
169  p = s->avctx->stats_in;
170  for (i = -1; p; i++)
171  p = strchr(p + 1, ';');
172  i += s->max_b_frames;
173  if (i <= 0 || i >= INT_MAX / sizeof(RateControlEntry))
174  return -1;
175  rcc->entry = av_mallocz(i * sizeof(RateControlEntry));
176  rcc->num_entries = i;
177 
178  /* init all to skipped p frames
179  * (with b frames we might have a not encoded frame at the end FIXME) */
180  for (i = 0; i < rcc->num_entries; i++) {
181  RateControlEntry *rce = &rcc->entry[i];
182 
184  rce->qscale = rce->new_qscale = FF_QP2LAMBDA * 2;
185  rce->misc_bits = s->mb_num + 10;
186  rce->mb_var_sum = s->mb_num * 100;
187  }
188 
189  /* read stats */
190  p = s->avctx->stats_in;
191  for (i = 0; i < rcc->num_entries - s->max_b_frames; i++) {
192  RateControlEntry *rce;
193  int picture_number;
194  int e;
195  char *next;
196 
197  next = strchr(p, ';');
198  if (next) {
199  (*next) = 0; // sscanf in unbelievably slow on looong strings // FIXME copy / do not write
200  next++;
201  }
202  e = sscanf(p, " in:%d ", &picture_number);
203 
204  assert(picture_number >= 0);
205  assert(picture_number < rcc->num_entries);
206  rce = &rcc->entry[picture_number];
207 
208  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",
209  &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits,
210  &rce->mv_bits, &rce->misc_bits,
211  &rce->f_code, &rce->b_code,
212  &rce->mc_mb_var_sum, &rce->mb_var_sum,
213  &rce->i_count, &rce->skip_count, &rce->header_bits);
214  if (e != 14) {
216  "statistics are damaged at line %d, parser out=%d\n",
217  i, e);
218  return -1;
219  }
220 
221  p = next;
222  }
223 
224  if (init_pass2(s) < 0)
225  return -1;
226 
227  // FIXME maybe move to end
229 #if CONFIG_LIBXVID
230  return ff_xvid_rate_control_init(s);
231 #else
233  "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");
234  return -1;
235 #endif
236  }
237  }
238 
239  if (!(s->flags & CODEC_FLAG_PASS2)) {
240  rcc->short_term_qsum = 0.001;
241  rcc->short_term_qcount = 0.001;
242 
243  rcc->pass1_rc_eq_output_sum = 0.001;
244  rcc->pass1_wanted_bits = 0.001;
245 
246  if (s->avctx->qblur > 1.0) {
247  av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");
248  return -1;
249  }
250  /* init stuff with the user specified complexity */
251  if (s->avctx->rc_initial_cplx) {
252  for (i = 0; i < 60 * 30; i++) {
253  double bits = s->avctx->rc_initial_cplx * (i / 10000.0 + 1.0) * s->mb_num;
254  RateControlEntry rce;
255 
256  if (i % ((s->gop_size + 3) / 4) == 0)
258  else if (i % (s->max_b_frames + 1))
260  else
262 
263  rce.new_pict_type = rce.pict_type;
264  rce.mc_mb_var_sum = bits * s->mb_num / 100000;
265  rce.mb_var_sum = s->mb_num;
266 
267  rce.qscale = FF_QP2LAMBDA * 2;
268  rce.f_code = 2;
269  rce.b_code = 1;
270  rce.misc_bits = 1;
271 
272  if (s->pict_type == AV_PICTURE_TYPE_I) {
273  rce.i_count = s->mb_num;
274  rce.i_tex_bits = bits;
275  rce.p_tex_bits = 0;
276  rce.mv_bits = 0;
277  } else {
278  rce.i_count = 0; // FIXME we do know this approx
279  rce.i_tex_bits = 0;
280  rce.p_tex_bits = bits * 0.9;
281  rce.mv_bits = bits * 0.1;
282  }
283  rcc->i_cplx_sum[rce.pict_type] += rce.i_tex_bits * rce.qscale;
284  rcc->p_cplx_sum[rce.pict_type] += rce.p_tex_bits * rce.qscale;
285  rcc->mv_bits_sum[rce.pict_type] += rce.mv_bits;
286  rcc->frame_count[rce.pict_type]++;
287 
288  get_qscale(s, &rce, rcc->pass1_wanted_bits / rcc->pass1_rc_eq_output_sum, i);
289 
290  // FIXME misbehaves a little for variable fps
291  rcc->pass1_wanted_bits += s->bit_rate / get_fps(s->avctx);
292  }
293  }
294  }
295 
296  return 0;
297 }
298 
300 {
301  RateControlContext *rcc = &s->rc_context;
302  emms_c();
303 
304  av_expr_free(rcc->rc_eq_eval);
305  av_freep(&rcc->entry);
306 
307 #if CONFIG_LIBXVID
310 #endif
311 }
312 
314 {
315  RateControlContext *rcc = &s->rc_context;
316  const double fps = get_fps(s->avctx);
317  const int buffer_size = s->avctx->rc_buffer_size;
318  const double min_rate = s->avctx->rc_min_rate / fps;
319  const double max_rate = s->avctx->rc_max_rate / fps;
320 
321  av_dlog(s, "%d %f %d %f %f\n",
322  buffer_size, rcc->buffer_index, frame_size, min_rate, max_rate);
323 
324  if (buffer_size) {
325  int left;
326 
327  rcc->buffer_index -= frame_size;
328  if (rcc->buffer_index < 0) {
329  av_log(s->avctx, AV_LOG_ERROR, "rc buffer underflow\n");
330  rcc->buffer_index = 0;
331  }
332 
333  left = buffer_size - rcc->buffer_index - 1;
334  rcc->buffer_index += av_clip(left, min_rate, max_rate);
335 
336  if (rcc->buffer_index > buffer_size) {
337  int stuffing = ceil((rcc->buffer_index - buffer_size) / 8);
338 
339  if (stuffing < 4 && s->codec_id == AV_CODEC_ID_MPEG4)
340  stuffing = 4;
341  rcc->buffer_index -= 8 * stuffing;
342 
343  if (s->avctx->debug & FF_DEBUG_RC)
344  av_log(s->avctx, AV_LOG_DEBUG, "stuffing %d bytes\n", stuffing);
345 
346  return stuffing;
347  }
348  }
349  return 0;
350 }
351 
352 /**
353  * Modify the bitrate curve from pass1 for one frame.
354  */
356  double rate_factor, int frame_num)
357 {
358  RateControlContext *rcc = &s->rc_context;
359  AVCodecContext *a = s->avctx;
360  const int pict_type = rce->new_pict_type;
361  const double mb_num = s->mb_num;
362  double q, bits;
363  int i;
364 
365  double const_values[] = {
366  M_PI,
367  M_E,
368  rce->i_tex_bits * rce->qscale,
369  rce->p_tex_bits * rce->qscale,
370  (rce->i_tex_bits + rce->p_tex_bits) * (double)rce->qscale,
371  rce->mv_bits / mb_num,
372  rce->pict_type == AV_PICTURE_TYPE_B ? (rce->f_code + rce->b_code) * 0.5 : rce->f_code,
373  rce->i_count / mb_num,
374  rce->mc_mb_var_sum / mb_num,
375  rce->mb_var_sum / mb_num,
379  rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],
380  a->qcompress,
381 #if 0
385  rcc->next_non_b_qscale,
386 #endif
391  (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],
392  0
393  };
394 
395  bits = av_expr_eval(rcc->rc_eq_eval, const_values, rce);
396  if (isnan(bits)) {
397  av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);
398  return -1;
399  }
400 
402  bits *= rate_factor;
403  if (bits < 0.0)
404  bits = 0.0;
405  bits += 1.0; // avoid 1/0 issues
406 
407  /* user override */
408  for (i = 0; i < s->avctx->rc_override_count; i++) {
409  RcOverride *rco = s->avctx->rc_override;
410  if (rco[i].start_frame > frame_num)
411  continue;
412  if (rco[i].end_frame < frame_num)
413  continue;
414 
415  if (rco[i].qscale)
416  bits = qp2bits(rce, rco[i].qscale); // FIXME move at end to really force it?
417  else
418  bits *= rco[i].quality_factor;
419  }
420 
421  q = bits2qp(rce, bits);
422 
423  /* I/B difference */
424  if (pict_type == AV_PICTURE_TYPE_I && s->avctx->i_quant_factor < 0.0)
425  q = -q * s->avctx->i_quant_factor + s->avctx->i_quant_offset;
426  else if (pict_type == AV_PICTURE_TYPE_B && s->avctx->b_quant_factor < 0.0)
427  q = -q * s->avctx->b_quant_factor + s->avctx->b_quant_offset;
428  if (q < 1)
429  q = 1;
430 
431  return q;
432 }
433 
434 static double get_diff_limited_q(MpegEncContext *s, RateControlEntry *rce, double q)
435 {
436  RateControlContext *rcc = &s->rc_context;
437  AVCodecContext *a = s->avctx;
438  const int pict_type = rce->new_pict_type;
439  const double last_p_q = rcc->last_qscale_for[AV_PICTURE_TYPE_P];
440  const double last_non_b_q = rcc->last_qscale_for[rcc->last_non_b_pict_type];
441 
442  if (pict_type == AV_PICTURE_TYPE_I &&
444  q = last_p_q * FFABS(a->i_quant_factor) + a->i_quant_offset;
445  else if (pict_type == AV_PICTURE_TYPE_B &&
446  a->b_quant_factor > 0.0)
447  q = last_non_b_q * a->b_quant_factor + a->b_quant_offset;
448  if (q < 1)
449  q = 1;
450 
451  /* last qscale / qdiff stuff */
452  if (rcc->last_non_b_pict_type == pict_type || pict_type != AV_PICTURE_TYPE_I) {
453  double last_q = rcc->last_qscale_for[pict_type];
454  const int maxdiff = FF_QP2LAMBDA * a->max_qdiff;
455 
456  if (q > last_q + maxdiff)
457  q = last_q + maxdiff;
458  else if (q < last_q - maxdiff)
459  q = last_q - maxdiff;
460  }
461 
462  rcc->last_qscale_for[pict_type] = q; // Note we cannot do that after blurring
463 
464  if (pict_type != AV_PICTURE_TYPE_B)
465  rcc->last_non_b_pict_type = pict_type;
466 
467  return q;
468 }
469 
470 /**
471  * Get the qmin & qmax for pict_type.
472  */
473 static void get_qminmax(int *qmin_ret, int *qmax_ret, MpegEncContext *s, int pict_type)
474 {
475  int qmin = s->avctx->lmin;
476  int qmax = s->avctx->lmax;
477 
478  assert(qmin <= qmax);
479 
480  switch (pict_type) {
481  case AV_PICTURE_TYPE_B:
482  qmin = (int)(qmin * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset + 0.5);
483  qmax = (int)(qmax * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset + 0.5);
484  break;
485  case AV_PICTURE_TYPE_I:
486  qmin = (int)(qmin * FFABS(s->avctx->i_quant_factor) + s->avctx->i_quant_offset + 0.5);
487  qmax = (int)(qmax * FFABS(s->avctx->i_quant_factor) + s->avctx->i_quant_offset + 0.5);
488  break;
489  }
490 
491  qmin = av_clip(qmin, 1, FF_LAMBDA_MAX);
492  qmax = av_clip(qmax, 1, FF_LAMBDA_MAX);
493 
494  if (qmax < qmin)
495  qmax = qmin;
496 
497  *qmin_ret = qmin;
498  *qmax_ret = qmax;
499 }
500 
502  double q, int frame_num)
503 {
504  RateControlContext *rcc = &s->rc_context;
505  const double buffer_size = s->avctx->rc_buffer_size;
506  const double fps = get_fps(s->avctx);
507  const double min_rate = s->avctx->rc_min_rate / fps;
508  const double max_rate = s->avctx->rc_max_rate / fps;
509  const int pict_type = rce->new_pict_type;
510  int qmin, qmax;
511 
512  get_qminmax(&qmin, &qmax, s, pict_type);
513 
514  /* modulation */
515  if (s->avctx->rc_qmod_freq &&
516  frame_num % s->avctx->rc_qmod_freq == 0 &&
517  pict_type == AV_PICTURE_TYPE_P)
518  q *= s->avctx->rc_qmod_amp;
519 
520  /* buffer overflow/underflow protection */
521  if (buffer_size) {
522  double expected_size = rcc->buffer_index;
523  double q_limit;
524 
525  if (min_rate) {
526  double d = 2 * (buffer_size - expected_size) / buffer_size;
527  if (d > 1.0)
528  d = 1.0;
529  else if (d < 0.0001)
530  d = 0.0001;
531  q *= pow(d, 1.0 / s->avctx->rc_buffer_aggressivity);
532 
533  q_limit = bits2qp(rce,
534  FFMAX((min_rate - buffer_size + rcc->buffer_index) *
536 
537  if (q > q_limit) {
538  if (s->avctx->debug & FF_DEBUG_RC)
540  "limiting QP %f -> %f\n", q, q_limit);
541  q = q_limit;
542  }
543  }
544 
545  if (max_rate) {
546  double d = 2 * expected_size / buffer_size;
547  if (d > 1.0)
548  d = 1.0;
549  else if (d < 0.0001)
550  d = 0.0001;
551  q /= pow(d, 1.0 / s->avctx->rc_buffer_aggressivity);
552 
553  q_limit = bits2qp(rce,
554  FFMAX(rcc->buffer_index *
556  1));
557  if (q < q_limit) {
558  if (s->avctx->debug & FF_DEBUG_RC)
560  "limiting QP %f -> %f\n", q, q_limit);
561  q = q_limit;
562  }
563  }
564  }
565  av_dlog(s, "q:%f max:%f min:%f size:%f index:%f agr:%f\n",
566  q, max_rate, min_rate, buffer_size, rcc->buffer_index,
568  if (s->avctx->rc_qsquish == 0.0 || qmin == qmax) {
569  if (q < qmin)
570  q = qmin;
571  else if (q > qmax)
572  q = qmax;
573  } else {
574  double min2 = log(qmin);
575  double max2 = log(qmax);
576 
577  q = log(q);
578  q = (q - min2) / (max2 - min2) - 0.5;
579  q *= -4.0;
580  q = 1.0 / (1.0 + exp(q));
581  q = q * (max2 - min2) + min2;
582 
583  q = exp(q);
584  }
585 
586  return q;
587 }
588 
589 // ----------------------------------
590 // 1 Pass Code
591 
592 static double predict_size(Predictor *p, double q, double var)
593 {
594  return p->coeff * var / (q * p->count);
595 }
596 
597 static void update_predictor(Predictor *p, double q, double var, double size)
598 {
599  double new_coeff = size * q / (var + 1);
600  if (var < 10)
601  return;
602 
603  p->count *= p->decay;
604  p->coeff *= p->decay;
605  p->count++;
606  p->coeff += new_coeff;
607 }
608 
609 static void adaptive_quantization(MpegEncContext *s, double q)
610 {
611  int i;
612  const float lumi_masking = s->avctx->lumi_masking / (128.0 * 128.0);
613  const float dark_masking = s->avctx->dark_masking / (128.0 * 128.0);
614  const float temp_cplx_masking = s->avctx->temporal_cplx_masking;
615  const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;
616  const float p_masking = s->avctx->p_masking;
617  const float border_masking = s->avctx->border_masking;
618  float bits_sum = 0.0;
619  float cplx_sum = 0.0;
620  float *cplx_tab = s->cplx_tab;
621  float *bits_tab = s->bits_tab;
622  const int qmin = s->avctx->mb_lmin;
623  const int qmax = s->avctx->mb_lmax;
624  Picture *const pic = &s->current_picture;
625  const int mb_width = s->mb_width;
626  const int mb_height = s->mb_height;
627 
628  for (i = 0; i < s->mb_num; i++) {
629  const int mb_xy = s->mb_index2xy[i];
630  float temp_cplx = sqrt(pic->mc_mb_var[mb_xy]); // FIXME merge in pow()
631  float spat_cplx = sqrt(pic->mb_var[mb_xy]);
632  const int lumi = pic->mb_mean[mb_xy];
633  float bits, cplx, factor;
634  int mb_x = mb_xy % s->mb_stride;
635  int mb_y = mb_xy / s->mb_stride;
636  int mb_distance;
637  float mb_factor = 0.0;
638  if (spat_cplx < 4)
639  spat_cplx = 4; // FIXME finetune
640  if (temp_cplx < 4)
641  temp_cplx = 4; // FIXME finetune
642 
643  if ((s->mb_type[mb_xy] & CANDIDATE_MB_TYPE_INTRA)) { // FIXME hq mode
644  cplx = spat_cplx;
645  factor = 1.0 + p_masking;
646  } else {
647  cplx = temp_cplx;
648  factor = pow(temp_cplx, -temp_cplx_masking);
649  }
650  factor *= pow(spat_cplx, -spatial_cplx_masking);
651 
652  if (lumi > 127)
653  factor *= (1.0 - (lumi - 128) * (lumi - 128) * lumi_masking);
654  else
655  factor *= (1.0 - (lumi - 128) * (lumi - 128) * dark_masking);
656 
657  if (mb_x < mb_width / 5) {
658  mb_distance = mb_width / 5 - mb_x;
659  mb_factor = (float)mb_distance / (float)(mb_width / 5);
660  } else if (mb_x > 4 * mb_width / 5) {
661  mb_distance = mb_x - 4 * mb_width / 5;
662  mb_factor = (float)mb_distance / (float)(mb_width / 5);
663  }
664  if (mb_y < mb_height / 5) {
665  mb_distance = mb_height / 5 - mb_y;
666  mb_factor = FFMAX(mb_factor,
667  (float)mb_distance / (float)(mb_height / 5));
668  } else if (mb_y > 4 * mb_height / 5) {
669  mb_distance = mb_y - 4 * mb_height / 5;
670  mb_factor = FFMAX(mb_factor,
671  (float)mb_distance / (float)(mb_height / 5));
672  }
673 
674  factor *= 1.0 - border_masking * mb_factor;
675 
676  if (factor < 0.00001)
677  factor = 0.00001;
678 
679  bits = cplx * factor;
680  cplx_sum += cplx;
681  bits_sum += bits;
682  cplx_tab[i] = cplx;
683  bits_tab[i] = bits;
684  }
685 
686  /* handle qmin/qmax clipping */
687  if (s->flags & CODEC_FLAG_NORMALIZE_AQP) {
688  float factor = bits_sum / cplx_sum;
689  for (i = 0; i < s->mb_num; i++) {
690  float newq = q * cplx_tab[i] / bits_tab[i];
691  newq *= factor;
692 
693  if (newq > qmax) {
694  bits_sum -= bits_tab[i];
695  cplx_sum -= cplx_tab[i] * q / qmax;
696  } else if (newq < qmin) {
697  bits_sum -= bits_tab[i];
698  cplx_sum -= cplx_tab[i] * q / qmin;
699  }
700  }
701  if (bits_sum < 0.001)
702  bits_sum = 0.001;
703  if (cplx_sum < 0.001)
704  cplx_sum = 0.001;
705  }
706 
707  for (i = 0; i < s->mb_num; i++) {
708  const int mb_xy = s->mb_index2xy[i];
709  float newq = q * cplx_tab[i] / bits_tab[i];
710  int intq;
711 
712  if (s->flags & CODEC_FLAG_NORMALIZE_AQP) {
713  newq *= bits_sum / cplx_sum;
714  }
715 
716  intq = (int)(newq + 0.5);
717 
718  if (intq > qmax)
719  intq = qmax;
720  else if (intq < qmin)
721  intq = qmin;
722  s->lambda_table[mb_xy] = intq;
723  }
724 }
725 
727 {
728  RateControlContext *rcc = &s->rc_context;
729  RateControlEntry *rce = &rcc->entry[s->picture_number];
730 
731  s->f_code = rce->f_code;
732  s->b_code = rce->b_code;
733 }
734 
735 // FIXME rd or at least approx for dquant
736 
738 {
739  float q;
740  int qmin, qmax;
741  float br_compensation;
742  double diff;
743  double short_term_q;
744  double fps;
745  int picture_number = s->picture_number;
746  int64_t wanted_bits;
747  RateControlContext *rcc = &s->rc_context;
748  AVCodecContext *a = s->avctx;
749  RateControlEntry local_rce, *rce;
750  double bits;
751  double rate_factor;
752  int var;
753  const int pict_type = s->pict_type;
754  Picture * const pic = &s->current_picture;
755  emms_c();
756 
757 #if CONFIG_LIBXVID
758  if ((s->flags & CODEC_FLAG_PASS2) &&
760  return ff_xvid_rate_estimate_qscale(s, dry_run);
761 #endif
762 
763  get_qminmax(&qmin, &qmax, s, pict_type);
764 
765  fps = get_fps(s->avctx);
766  /* update predictors */
767  if (picture_number > 2 && !dry_run) {
768  const int last_var = s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum
769  : rcc->last_mc_mb_var_sum;
772  rcc->last_qscale,
773  sqrt(last_var),
774  s->frame_bits - s->stuffing_bits);
775  }
776 
777  if (s->flags & CODEC_FLAG_PASS2) {
778  assert(picture_number >= 0);
779  if (picture_number >= rcc->num_entries) {
780  av_log(s, AV_LOG_ERROR, "Input is longer than 2-pass log file\n");
781  return -1;
782  }
783  rce = &rcc->entry[picture_number];
784  wanted_bits = rce->expected_bits;
785  } else {
786  Picture *dts_pic;
787  rce = &local_rce;
788 
789  /* FIXME add a dts field to AVFrame and ensure it is set and use it
790  * here instead of reordering but the reordering is simpler for now
791  * until H.264 B-pyramid must be handled. */
792  if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
793  dts_pic = s->current_picture_ptr;
794  else
795  dts_pic = s->last_picture_ptr;
796 
797  if (!dts_pic || dts_pic->f.pts == AV_NOPTS_VALUE)
798  wanted_bits = (uint64_t)(s->bit_rate * (double)picture_number / fps);
799  else
800  wanted_bits = (uint64_t)(s->bit_rate * (double)dts_pic->f.pts / fps);
801  }
802 
803  diff = s->total_bits - wanted_bits;
804  br_compensation = (a->bit_rate_tolerance - diff) / a->bit_rate_tolerance;
805  if (br_compensation <= 0.0)
806  br_compensation = 0.001;
807 
808  var = pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;
809 
810  short_term_q = 0; /* avoid warning */
811  if (s->flags & CODEC_FLAG_PASS2) {
812  if (pict_type != AV_PICTURE_TYPE_I)
813  assert(pict_type == rce->new_pict_type);
814 
815  q = rce->new_qscale / br_compensation;
816  av_dlog(s, "%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale,
817  br_compensation, s->frame_bits, var, pict_type);
818  } else {
819  rce->pict_type =
820  rce->new_pict_type = pict_type;
821  rce->mc_mb_var_sum = pic->mc_mb_var_sum;
822  rce->mb_var_sum = pic->mb_var_sum;
823  rce->qscale = FF_QP2LAMBDA * 2;
824  rce->f_code = s->f_code;
825  rce->b_code = s->b_code;
826  rce->misc_bits = 1;
827 
828  bits = predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));
829  if (pict_type == AV_PICTURE_TYPE_I) {
830  rce->i_count = s->mb_num;
831  rce->i_tex_bits = bits;
832  rce->p_tex_bits = 0;
833  rce->mv_bits = 0;
834  } else {
835  rce->i_count = 0; // FIXME we do know this approx
836  rce->i_tex_bits = 0;
837  rce->p_tex_bits = bits * 0.9;
838  rce->mv_bits = bits * 0.1;
839  }
840  rcc->i_cplx_sum[pict_type] += rce->i_tex_bits * rce->qscale;
841  rcc->p_cplx_sum[pict_type] += rce->p_tex_bits * rce->qscale;
842  rcc->mv_bits_sum[pict_type] += rce->mv_bits;
843  rcc->frame_count[pict_type]++;
844 
845  bits = rce->i_tex_bits + rce->p_tex_bits;
846  rate_factor = rcc->pass1_wanted_bits /
847  rcc->pass1_rc_eq_output_sum * br_compensation;
848 
849  q = get_qscale(s, rce, rate_factor, picture_number);
850  if (q < 0)
851  return -1;
852 
853  assert(q > 0.0);
854  q = get_diff_limited_q(s, rce, q);
855  assert(q > 0.0);
856 
857  // FIXME type dependent blur like in 2-pass
858  if (pict_type == AV_PICTURE_TYPE_P || s->intra_only) {
859  rcc->short_term_qsum *= a->qblur;
860  rcc->short_term_qcount *= a->qblur;
861 
862  rcc->short_term_qsum += q;
863  rcc->short_term_qcount++;
864  q = short_term_q = rcc->short_term_qsum / rcc->short_term_qcount;
865  }
866  assert(q > 0.0);
867 
868  q = modify_qscale(s, rce, q, picture_number);
869 
870  rcc->pass1_wanted_bits += s->bit_rate / fps;
871 
872  assert(q > 0.0);
873  }
874 
875  if (s->avctx->debug & FF_DEBUG_RC) {
877  "%c qp:%d<%2.1f<%d %d want:%d total:%d comp:%f st_q:%2.2f "
878  "size:%d var:%d/%d br:%d fps:%d\n",
879  av_get_picture_type_char(pict_type),
880  qmin, q, qmax, picture_number,
881  (int)wanted_bits / 1000, (int)s->total_bits / 1000,
882  br_compensation, short_term_q, s->frame_bits,
883  pic->mb_var_sum, pic->mc_mb_var_sum,
884  s->bit_rate / 1000, (int)fps);
885  }
886 
887  if (q < qmin)
888  q = qmin;
889  else if (q > qmax)
890  q = qmax;
891 
892  if (s->adaptive_quant)
893  adaptive_quantization(s, q);
894  else
895  q = (int)(q + 0.5);
896 
897  if (!dry_run) {
898  rcc->last_qscale = q;
899  rcc->last_mc_mb_var_sum = pic->mc_mb_var_sum;
900  rcc->last_mb_var_sum = pic->mb_var_sum;
901  }
902  return q;
903 }
904 
905 // ----------------------------------------------
906 // 2-Pass code
907 
909 {
910  RateControlContext *rcc = &s->rc_context;
911  AVCodecContext *a = s->avctx;
912  int i, toobig;
913  double fps = get_fps(s->avctx);
914  double complexity[5] = { 0 }; // approximate bits at quant=1
915  uint64_t const_bits[5] = { 0 }; // quantizer independent bits
916  uint64_t all_const_bits;
917  uint64_t all_available_bits = (uint64_t)(s->bit_rate *
918  (double)rcc->num_entries / fps);
919  double rate_factor = 0;
920  double step;
921  const int filter_size = (int)(a->qblur * 4) | 1;
922  double expected_bits;
923  double *qscale, *blurred_qscale, qscale_sum;
924 
925  /* find complexity & const_bits & decide the pict_types */
926  for (i = 0; i < rcc->num_entries; i++) {
927  RateControlEntry *rce = &rcc->entry[i];
928 
929  rce->new_pict_type = rce->pict_type;
930  rcc->i_cplx_sum[rce->pict_type] += rce->i_tex_bits * rce->qscale;
931  rcc->p_cplx_sum[rce->pict_type] += rce->p_tex_bits * rce->qscale;
932  rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;
933  rcc->frame_count[rce->pict_type]++;
934 
935  complexity[rce->new_pict_type] += (rce->i_tex_bits + rce->p_tex_bits) *
936  (double)rce->qscale;
937  const_bits[rce->new_pict_type] += rce->mv_bits + rce->misc_bits;
938  }
939 
940  all_const_bits = const_bits[AV_PICTURE_TYPE_I] +
941  const_bits[AV_PICTURE_TYPE_P] +
942  const_bits[AV_PICTURE_TYPE_B];
943 
944  if (all_available_bits < all_const_bits) {
945  av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
946  return -1;
947  }
948 
949  qscale = av_malloc(sizeof(double) * rcc->num_entries);
950  blurred_qscale = av_malloc(sizeof(double) * rcc->num_entries);
951  toobig = 0;
952 
953  for (step = 256 * 256; step > 0.0000001; step *= 0.5) {
954  expected_bits = 0;
955  rate_factor += step;
956 
957  rcc->buffer_index = s->avctx->rc_buffer_size / 2;
958 
959  /* find qscale */
960  for (i = 0; i < rcc->num_entries; i++) {
961  RateControlEntry *rce = &rcc->entry[i];
962 
963  qscale[i] = get_qscale(s, &rcc->entry[i], rate_factor, i);
964  rcc->last_qscale_for[rce->pict_type] = qscale[i];
965  }
966  assert(filter_size % 2 == 1);
967 
968  /* fixed I/B QP relative to P mode */
969  for (i = FFMAX(0, rcc->num_entries - 300); i < rcc->num_entries; i++) {
970  RateControlEntry *rce = &rcc->entry[i];
971 
972  qscale[i] = get_diff_limited_q(s, rce, qscale[i]);
973  }
974 
975  for (i = rcc->num_entries - 1; i >= 0; i--) {
976  RateControlEntry *rce = &rcc->entry[i];
977 
978  qscale[i] = get_diff_limited_q(s, rce, qscale[i]);
979  }
980 
981  /* smooth curve */
982  for (i = 0; i < rcc->num_entries; i++) {
983  RateControlEntry *rce = &rcc->entry[i];
984  const int pict_type = rce->new_pict_type;
985  int j;
986  double q = 0.0, sum = 0.0;
987 
988  for (j = 0; j < filter_size; j++) {
989  int index = i + j - filter_size / 2;
990  double d = index - i;
991  double coeff = a->qblur == 0 ? 1.0 : exp(-d * d / (a->qblur * a->qblur));
992 
993  if (index < 0 || index >= rcc->num_entries)
994  continue;
995  if (pict_type != rcc->entry[index].new_pict_type)
996  continue;
997  q += qscale[index] * coeff;
998  sum += coeff;
999  }
1000  blurred_qscale[i] = q / sum;
1001  }
1002 
1003  /* find expected bits */
1004  for (i = 0; i < rcc->num_entries; i++) {
1005  RateControlEntry *rce = &rcc->entry[i];
1006  double bits;
1007 
1008  rce->new_qscale = modify_qscale(s, rce, blurred_qscale[i], i);
1009 
1010  bits = qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
1011  bits += 8 * ff_vbv_update(s, bits);
1012 
1013  rce->expected_bits = expected_bits;
1014  expected_bits += bits;
1015  }
1016 
1017  av_dlog(s->avctx,
1018  "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
1019  expected_bits, (int)all_available_bits, rate_factor);
1020  if (expected_bits > all_available_bits) {
1021  rate_factor -= step;
1022  ++toobig;
1023  }
1024  }
1025  av_free(qscale);
1026  av_free(blurred_qscale);
1027 
1028  /* check bitrate calculations and print info */
1029  qscale_sum = 0.0;
1030  for (i = 0; i < rcc->num_entries; i++) {
1031  av_dlog(s, "[lavc rc] entry[%d].new_qscale = %.3f qp = %.3f\n",
1032  i,
1033  rcc->entry[i].new_qscale,
1034  rcc->entry[i].new_qscale / FF_QP2LAMBDA);
1035  qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA,
1036  s->avctx->qmin, s->avctx->qmax);
1037  }
1038  assert(toobig <= 40);
1040  "[lavc rc] requested bitrate: %d bps expected bitrate: %d bps\n",
1041  s->bit_rate,
1042  (int)(expected_bits / ((double)all_available_bits / s->bit_rate)));
1044  "[lavc rc] estimated target average qp: %.3f\n",
1045  (float)qscale_sum / rcc->num_entries);
1046  if (toobig == 0) {
1047  av_log(s->avctx, AV_LOG_INFO,
1048  "[lavc rc] Using all of requested bitrate is not "
1049  "necessary for this video with these parameters.\n");
1050  } else if (toobig == 40) {
1052  "[lavc rc] Error: bitrate too low for this video "
1053  "with these parameters.\n");
1054  return -1;
1055  } else if (fabs(expected_bits / all_available_bits - 1.0) > 0.01) {
1057  "[lavc rc] Error: 2pass curve failed to converge\n");
1058  return -1;
1059  }
1060 
1061  return 0;
1062 }