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
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
44 double rate_factor, int frame_num);
45
47 {
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",
65 }
66
68 {
70 }
71
73 {
74 if (qp <= 0.0) {
76 }
78 }
79
81 {
82 if (bits < 0.9) {
84 }
86 }
87
89 {
91 int i, res;
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) = {
124 NULL
125 };
127 "bits2qp",
128 "qp2bits",
129 NULL
130 };
131 emms_c();
132
136 } else
138 }
139
142 const_names, func1_names,
func1,
143 NULL, NULL, 0, s->
avctx);
144 if (res < 0) {
146 return res;
147 }
148
149 for (i = 0; i < 5; i++) {
153
158 rcc->
frame_count[i] = 1;
// 1 is better because of 1/0 and such
159
161 }
165
167 int i;
168 char *p;
169
170 /* find number of pics */
172 for (i = -1; p; i++)
173 p = strchr(p + 1, ';');
176 return -1;
179
180 /* init all to skipped p frames
181 * (with b frames we might have a not encoded frame at the end FIXME) */
184
189 }
190
191 /* read stats */
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",
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
227 return -1;
228
229 // FIXME maybe move to end
231 #if CONFIG_LIBXVID
233 #else
235 "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");
236 return -1;
237 #endif
238 }
239 }
240
244
247
250 return -1;
251 }
252 /* init stuff with the user specified complexity */
254 for (i = 0; i < 60 * 30; i++) {
257
258 if (i % ((s->
gop_size + 3) / 4) == 0)
262 else
264
268
273
279 } else {
280 rce.
i_count = 0;
// FIXME we do know this approx
284 }
289
291
292 // FIXME misbehaves a little for variable fps
294 }
295 }
296 }
297
298 return 0;
299 }
300
302 {
304 emms_c();
305
308
309 #if CONFIG_LIBXVID
312 #endif
313 }
314
316 {
322
324 buffer_size, rcc->
buffer_index, frame_size, min_rate, max_rate);
325
326 if (buffer_size) {
327 int left;
328
333 av_log(s->
avctx,
AV_LOG_ERROR,
"max bitrate possibly too small or try trellis with large lmax or increase qmax\n");
334 }
336 }
337
340
342 int stuffing = ceil((rcc->
buffer_index - buffer_size) / 8);
343
345 stuffing = 4;
347
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 {
366 const double mb_num = s->
mb_num;
368 int i;
369
386 #if 0
390 rcc->next_non_b_qscale,
391 #endif
397 0
398 };
399
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 */
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
424 }
425
427
428 /* I/B difference */
433 if (q < 1)
434 q = 1;
435
436 return q;
437 }
438
440 {
446
453 if (q < 1)
454 q = 1;
455
456 /* last qscale / qdiff stuff */
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
471
472 return q;
473 }
474
475 /**
476 * Get the qmin & qmax for pict_type.
477 */
479 {
482
483 assert(qmin <= qmax);
484
485 switch (pict_type) {
489 break;
493 break;
494 }
495
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 {
515 int qmin, qmax;
516
518
519 /* modulation */
524
525 /* buffer overflow/underflow protection */
526 if (buffer_size) {
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;
537
541
542 if (q > q_limit) {
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;
557
561 1));
562 if (q < q_limit) {
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",
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
598 {
600 }
601
603 {
604 double new_coeff = size * q / (var + 1);
605 if (var < 10)
606 return;
607
611 p->
coeff += new_coeff;
612 }
613
615 {
616 int i;
623 float bits_sum = 0.0;
624 float cplx_sum = 0.0;
632
633 for (i = 0; i < s->
mb_num; 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];
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
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
685 cplx_sum += cplx;
687 cplx_tab[i] = cplx;
689 }
690
691 /* handle qmin/qmax clipping */
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];
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++) {
714 float newq = q * cplx_tab[i] / bits_tab[i];
715 int intq;
716
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;
728 }
729 }
730
732 {
735
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;
751 int64_t wanted_bits;
756 double rate_factor;
757 int64_t var;
760 emms_c();
761
762 #if CONFIG_LIBXVID
766 #endif
767
769
771 /* update predictors */
772 if (picture_number > 2 && !dry_run) {
773 const int64_t last_var =
779 sqrt(last_var),
781 }
782
784 assert(picture_number >= 0);
787 return -1;
788 }
789 rce = &rcc->
entry[picture_number];
791 } else {
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. */
800 else
802
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
811 if (br_compensation <= 0.0)
812 br_compensation = 0.001;
813
815
816 short_term_q = 0; /* avoid warning */
820
823 br_compensation, s->
frame_bits, var, pict_type);
824 } else {
833
840 } else {
841 rce->
i_count = 0;
// FIXME we do know this approx
845 }
850
854
855 q =
get_qscale(s, rce, rate_factor, picture_number);
856 if (q < 0)
857 return -1;
858
859 assert(q > 0.0);
861 assert(q > 0.0);
862
863 // FIXME type dependent blur like in 2-pass
867
871 }
872 assert(q > 0.0);
873
875
877
878 assert(q > 0.0);
879 }
880
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",
886 qmin, q, qmax, picture_number,
887 (
int)wanted_bits / 1000, (
int)s->
total_bits / 1000,
891 }
892
893 if (q < qmin)
894 q = qmin;
895 else if (q > qmax)
896 q = qmax;
897
900 else
901 q = (int)(q + 0.5);
902
903 if (!dry_run) {
907 }
908 return q;
909 }
910
911 // ----------------------------------------------
912 // 2-Pass code
913
915 {
918 int i, toobig;
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 *
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 */
934
940
944 }
945
949
950 if (all_available_bits < all_const_bits) {
952 return -1;
953 }
954
957 toobig = 0;
958
959 for (step = 256 * 256; step > 0.0000001; step *= 0.5) {
960 expected_bits = 0;
961 rate_factor += step;
962
964
965 /* find qscale */
968
971 }
972 assert(filter_size % 2 == 1);
973
974 /* fixed I/B QP relative to P mode */
977
979 }
980
983
985 }
986
987 /* smooth curve */
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;
998
1000 continue;
1002 continue;
1005 }
1006 blurred_qscale[i] = q / sum;
1007 }
1008
1009 /* find expected bits */
1013
1015
1018
1020 expected_bits +=
bits;
1021 }
1022
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 }
1033
1034 /* check bitrate calculations and print info */
1035 qscale_sum = 0.0;
1037 av_dlog(s,
"[lavc rc] entry[%d].new_qscale = %.3f qp = %.3f\n",
1038 i,
1043 }
1044 assert(toobig <= 40);
1046 "[lavc rc] requested bitrate: %d bps expected bitrate: %d bps\n",
1048 (
int)(expected_bits / ((
double)all_available_bits / s->
bit_rate)));
1050 "[lavc rc] estimated target average qp: %.3f\n",
1052 if (toobig == 0) {
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 }