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