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