]> git.sesse.net Git - x264/blob - encoder/ratecontrol.c
* all: 2pass patch by Loren Merritt <lorenm AT u.washington DOT edu>
[x264] / encoder / ratecontrol.c
1 /***************************************************-*- coding: iso-8859-1 -*-
2  * ratecontrol.c: h264 encoder library (Rate Control)
3  *****************************************************************************
4  * Copyright (C) 2003 Laurent Aimar
5  * $Id: ratecontrol.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
6  *
7  * Authors: Måns Rullgård <mru@mru.ath.cx>
8  * 2 pass code: Michael Niedermayer <michaelni@gmx.at>
9  *              Loren Merritt
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 #define _ISOC99_SOURCE
27 #undef NDEBUG // always check asserts, the speed effect is far too small to disable them
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <math.h>
32 #include <limits.h>
33 #include <assert.h>
34
35 #include "../core/common.h"
36 #include "../core/cpu.h"
37 #include "../core/macroblock.h"
38 #include "ratecontrol.h"
39
40 #ifdef SYS_MACOSX
41 #define exp2f(x) ( (float) exp2( (x) ) )
42 #endif
43
44
45 typedef struct
46 {
47     int pict_type;
48     float qscale;
49     int mv_bits;
50     int i_tex_bits;
51     int p_tex_bits;
52     int misc_bits;
53     uint64_t expected_bits;
54     int new_pict_type;
55     float new_qscale;
56     int new_qp;
57     int i_count;
58     int p_count;
59     int s_count;
60     int f_code;
61     int b_code;
62 } ratecontrol_entry_t;
63
64 struct x264_ratecontrol_t
65 {
66     /* constants */
67     double fps;
68     int gop_size;
69     int bitrate;
70     int nmb;                    /* number of macroblocks in a frame */
71     int buffer_size;
72     int rcbufrate;
73     int init_qp;
74
75     /* 1st pass stuff */
76     int gop_qp;
77     int buffer_fullness;
78     int frames;                 /* frames in current gop */
79     int pframes;
80     int slice_type;
81     int mb;                     /* MBs processed in current frame */
82     int bits_gop;               /* allocated bits current gop */
83     int bits_last_gop;          /* bits consumed in gop */
84     int qp;                     /* qp for current frame */
85     int qpm;                    /* qp for next MB */
86     int qpa;                    /* average qp for last frame */
87     int qps;
88     int qp_avg_p;               /* average QP for P frames */
89     int qp_last_p;
90     int fbits;                  /* bits allocated for current frame */
91     int ufbits;                 /* bits used for current frame */
92     int nzcoeffs;               /* # of 0-quantized coefficients */
93     int ncoeffs;                /* total # of coefficients */
94     int overhead;
95
96     /* 2pass stuff */
97     FILE *p_stat_file_out;
98
99     int num_entries;            /* number of ratecontrol_entry_ts */
100     ratecontrol_entry_t *entry;
101     double last_qscale;
102     double last_qscale_for[5];  /* last qscale for a specific pict type, used for max_diff & ipb factor stuff  */
103     int last_non_b_pict_type;
104     double lmin[5];                /* min qscale by frame type */
105     double lmax[5];
106     double i_cplx_sum[5];       /* estimated total texture bits in intra MBs at qscale=1 */
107     double p_cplx_sum[5];
108     double mv_bits_sum[5];
109     int frame_count[5];         /* number of frames of each type */
110 };
111
112
113 static int init_pass2(x264_t *);
114 static float rate_estimate_qscale( x264_t *h, int pict_type );
115
116 /* Terminology:
117  * qp = h.264's quantizer
118  * qscale = an arbitrary linear scale, mappable to qp
119  */
120 static inline double qp2qscale(double qp)
121 {
122     return 0.85 * pow(2.0, ( qp - 12.0 ) / 6.0);
123 }
124 static inline double qscale2qp(double qscale)
125 {
126     return 12.0 + 6.0 * log(qscale/0.85) / log(2.0);
127 }
128
129 static inline double qscale2bits(ratecontrol_entry_t *rce, double qscale)
130 {
131     if(qscale<=0.0)
132     {
133         fprintf(stderr, "qscale<=0.0\n");
134         qscale = 0.1;
135     }
136     return (double)(rce->i_tex_bits + rce->p_tex_bits + 1) * rce->qscale / qscale;
137 }
138
139 static inline double bits2qscale(ratecontrol_entry_t *rce, double bits)
140 {
141     if(bits<0.9)
142     {
143         fprintf(stderr, "bits<0.9\n");
144         bits = 1.0;
145     }
146     return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits + 1) / bits;
147 }
148
149
150 int x264_ratecontrol_new( x264_t *h )
151 {
152     x264_ratecontrol_t *rc;
153     float bpp;
154     int i;
155
156     /* Needed(?) for 2 pass */
157     x264_cpu_restore( h->param.cpu );
158
159     h->rc = rc = x264_malloc( sizeof( x264_ratecontrol_t ) );
160     memset(rc, 0, sizeof(*rc));
161
162     /* FIXME: use integers */
163     if(h->param.i_fps_num > 0 && h->param.i_fps_den > 0)
164         rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den;
165     else
166         rc->fps = 25.0;
167
168     rc->gop_size = h->param.i_iframe;
169     rc->bitrate = h->param.rc.i_bitrate * 1000;
170     rc->nmb = ((h->param.i_width + 15) / 16) * ((h->param.i_height + 15) / 16);
171
172     rc->qp = h->param.rc.i_qp_constant;
173     rc->qpa = rc->qp;
174     rc->qpm = rc->qp;
175
176     rc->buffer_size = h->param.rc.i_rc_buffer_size * 1000;
177     rc->buffer_fullness = h->param.rc.i_rc_init_buffer;
178     rc->rcbufrate = rc->bitrate / rc->fps;
179
180     if(rc->buffer_size < rc->rcbufrate){
181         x264_log(h, X264_LOG_WARNING, "rc buffer size %i too small\n",
182                  rc->buffer_size);
183         rc->buffer_size = 0;
184     }
185
186     if(rc->buffer_size <= 0)
187         rc->buffer_size = rc->bitrate / 2;
188
189     if(rc->buffer_fullness > rc->buffer_size || rc->buffer_fullness < 0){
190         x264_log(h, X264_LOG_WARNING, "invalid initial buffer fullness %i\n",
191                  rc->buffer_fullness);
192         rc->buffer_fullness = 0;
193     }
194
195     bpp = rc->bitrate / (rc->fps * h->param.i_width * h->param.i_height);
196     if(bpp <= 0.6)
197         rc->init_qp = 31;
198     else if(bpp <= 1.4)
199         rc->init_qp = 25;
200     else if(bpp <= 2.4)
201         rc->init_qp = 20;
202     else
203         rc->init_qp = 10;
204     rc->gop_qp = rc->init_qp;
205
206     rc->bits_last_gop = 0;
207
208     x264_log(h, X264_LOG_DEBUG, "%f fps, %i bps, bufsize %i\n",
209              rc->fps, rc->bitrate, rc->buffer_size);
210
211
212     for( i = 0; i < 5; i++ )
213     {
214         rc->last_qscale_for[i] = qp2qscale(26);
215         rc->lmin[i] = qp2qscale( h->param.rc.i_qp_min );
216         rc->lmax[i] = qp2qscale( h->param.rc.i_qp_max );
217     }
218 #if 0 // FIXME: do we want to assign lmin/lmax based on ip_factor, or leave them all the same?
219     rc->lmin[SLICE_TYPE_I] /= fabs(h->param.f_ip_factor);
220     rc->lmax[SLICE_TYPE_I] /= fabs(h->param.f_ip_factor);
221     rc->lmin[SLICE_TYPE_B] *= fabs(h->param.f_pb_factor);
222     rc->lmax[SLICE_TYPE_B] *= fabs(h->param.f_pb_factor);
223 #endif
224
225     /* Load stat file and init 2pass algo */
226     if( h->param.rc.b_stat_read )
227     {
228         int stats_size;
229         char *p, *stats_in;
230         FILE *stats_file;
231
232         /* read 1st pass stats */
233         assert( h->param.rc.psz_stat_in );
234         stats_file = fopen( h->param.rc.psz_stat_in, "r");
235         if(!stats_file)
236         {
237             x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
238             return -1;
239         }
240         // FIXME: error checking
241         fseek(stats_file, 0, SEEK_END);
242         stats_size = ftell(stats_file);
243         fseek(stats_file, 0, SEEK_SET);
244         stats_in = x264_malloc(stats_size+10);
245         fread(stats_in, 1, stats_size, stats_file);
246         fclose(stats_file);
247
248         /* find number of pics */
249         p = stats_in;
250         for(i=-1; p; i++){
251             p = strchr(p+1, ';');
252         }
253         i += h->param.i_bframe;
254         rc->entry = (ratecontrol_entry_t*) x264_malloc(i*sizeof(ratecontrol_entry_t));
255         memset(rc->entry, 0, i*sizeof(ratecontrol_entry_t));
256         rc->num_entries= i;
257
258         /* init all to skipped p frames */
259         for(i=0; i<rc->num_entries; i++){
260             ratecontrol_entry_t *rce = &rc->entry[i];
261             rce->pict_type = rce->new_pict_type = SLICE_TYPE_P;
262             rce->qscale = rce->new_qscale = qp2qscale(20);
263             rce->misc_bits = rc->nmb + 10;
264             rce->new_qp = 0;
265         }
266
267         /* read stats */
268         p = stats_in;
269         for(i=0; i < rc->num_entries - h->param.i_bframe; i++){
270             ratecontrol_entry_t *rce;
271             int picture_number;
272             int e;
273             char *next;
274             float qp;
275
276             next= strchr(p, ';');
277             if(next){
278                 (*next)=0; //sscanf is unbelievably slow on looong strings
279                 next++;
280             }
281             e = sscanf(p, " in:%d ", &picture_number);
282
283             assert(picture_number >= 0);
284             assert(picture_number < rc->num_entries);
285             rce = &rc->entry[picture_number];
286
287             e += sscanf(p, " in:%*d out:%*d type:%d q:%f itex:%d ptex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d",
288                    &rce->pict_type, &qp, &rce->i_tex_bits, &rce->p_tex_bits,
289                    &rce->mv_bits, &rce->misc_bits, &rce->i_count, &rce->p_count, &rce->s_count);
290             if(e != 10){
291                 x264_log(h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);
292                 return -1;
293             }
294             rce->qscale = qp2qscale(qp);
295             p = next;
296         }
297
298         x264_free(stats_in);
299
300         if(init_pass2(h) < 0) return -1;
301     }
302
303     /* Open output file */
304     if( h->param.rc.b_stat_write )
305     {
306         rc->p_stat_file_out = fopen( h->param.rc.psz_stat_out, "w" );
307         if( rc->p_stat_file_out == NULL )
308         {
309             x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
310             return -1;
311         }
312     }
313
314     return 0;
315 }
316
317 void x264_ratecontrol_delete( x264_t *h )
318 {
319     x264_ratecontrol_t *rc = h->rc;
320
321     if( rc->p_stat_file_out )
322         fclose( rc->p_stat_file_out );
323     if( rc->entry )
324         x264_free(rc->entry);
325     x264_free( rc );
326 }
327
328 void x264_ratecontrol_start( x264_t *h, int i_slice_type )
329 {
330     x264_ratecontrol_t *rc = h->rc;
331     int gframes, iframes, pframes, bframes;
332     int minbits, maxbits;
333     int gbits, fbits;
334     int zn = 0;
335     float kp;
336     int gbuf;
337
338     rc->slice_type = i_slice_type;
339
340     /* Needed ? */
341     x264_cpu_restore( h->param.cpu );
342
343     if( h->param.rc.b_stat_read )
344     {
345         int frame = h->fenc->i_frame;
346         ratecontrol_entry_t *rce = &h->rc->entry[frame];
347
348         assert( frame >= 0 && frame < rc->num_entries );
349
350         rce->new_qscale = rate_estimate_qscale( h, i_slice_type );
351         rc->qpm = rc->qp = rce->new_qp = (int)(qscale2qp(rce->new_qscale) + 0.5);
352         return;
353     }
354     else if( !h->param.rc.b_cbr )
355     {
356         return;
357     }
358
359     switch(i_slice_type){
360     case SLICE_TYPE_I:
361         gbuf = rc->buffer_fullness + (rc->gop_size-1) * rc->rcbufrate;
362         rc->bits_gop = gbuf - rc->buffer_size / 2;
363
364         if(!rc->mb && rc->pframes){
365             int qp = (float) rc->qp_avg_p / rc->pframes + 0.5;
366 #if 0 /* JM does this without explaining why */
367             int gdq = (float) rc->gop_size / 15 + 0.5;
368             if(gdq > 2)
369                 gdq = 2;
370             qp -= gdq;
371             if(qp > rc->qp_last_p - 2)
372                 qp--;
373 #endif
374             qp = x264_clip3(qp, rc->gop_qp - 4, rc->gop_qp + 4);
375             qp =
376                 x264_clip3(qp, h->param.rc.i_qp_min, h->param.rc.i_qp_max);
377             rc->gop_qp = qp;
378         } else if(rc->frames > 4){
379             rc->gop_qp = rc->init_qp;
380         }
381
382         kp = h->param.rc.f_ip_factor * h->param.rc.f_pb_factor;
383
384         x264_log(h, X264_LOG_DEBUG,"gbuf=%i bits_gop=%i frames=%i gop_qp=%i\n",
385                  gbuf, rc->bits_gop, rc->frames, rc->gop_qp);
386
387         rc->bits_last_gop = 0;
388         rc->frames = 0;
389         rc->pframes = 0;
390         rc->qp_avg_p = 0;
391         break;
392
393     case SLICE_TYPE_P:
394         kp = h->param.rc.f_pb_factor;
395         break;
396
397     case SLICE_TYPE_B:
398         kp = 1.0;
399         break;
400
401     default:
402         x264_log(h, X264_LOG_WARNING, "ratecontrol: unknown slice type %i\n",
403                  i_slice_type);
404         kp = 1.0;
405         break;
406     }
407
408     gframes = rc->gop_size - rc->frames;
409     iframes = gframes / rc->gop_size;
410     pframes = gframes / (h->param.i_bframe + 1) - iframes;
411     bframes = gframes - pframes - iframes;
412
413     gbits = rc->bits_gop - rc->bits_last_gop;
414     fbits = kp * gbits /
415         (h->param.rc.f_ip_factor * h->param.rc.f_pb_factor * iframes +
416          h->param.rc.f_pb_factor * pframes + bframes);
417
418     minbits = rc->buffer_fullness + rc->rcbufrate - rc->buffer_size;
419     if(minbits < 0)
420         minbits = 0;
421     maxbits = rc->buffer_fullness;
422     rc->fbits = x264_clip3(fbits, minbits, maxbits);
423
424     if(i_slice_type == SLICE_TYPE_I){
425         rc->qp = rc->gop_qp;
426     } else if(rc->ncoeffs && rc->ufbits){
427         int dqp, nonzc;
428
429         nonzc = (rc->ncoeffs - rc->nzcoeffs);
430         if(nonzc == 0)
431             zn = rc->ncoeffs;
432         else if(rc->fbits < INT_MAX / nonzc)
433             zn = rc->ncoeffs - rc->fbits * nonzc / rc->ufbits;
434         else
435             zn = 0;
436         zn = x264_clip3(zn, 0, rc->ncoeffs);
437         dqp = h->param.rc.i_rc_sens * exp2f((float) rc->qpa / 6) *
438             (zn - rc->nzcoeffs) / rc->nzcoeffs;
439         dqp = x264_clip3(dqp, -h->param.rc.i_qp_step, h->param.rc.i_qp_step);
440         rc->qp = rc->qpa + dqp;
441     }
442
443     if(rc->fbits > 0.9 * maxbits)
444         rc->qp += 2;
445     else if(rc->fbits > 0.8 * maxbits)
446         rc->qp += 1;
447     else if(rc->fbits < 1.1 * minbits)
448         rc->qp -= 2;
449     else if(rc->fbits < 1.2 * minbits)
450         rc->qp -= 1;
451
452     rc->qp = x264_clip3(rc->qp, h->param.rc.i_qp_min, h->param.rc.i_qp_max);
453     rc->qpm = rc->qp;
454
455     x264_log(h, X264_LOG_DEBUG, "fbits=%i, qp=%i, z=%i, min=%i, max=%i\n",
456              rc->fbits, rc->qpm, zn, minbits, maxbits);
457
458     rc->fbits -= rc->overhead;
459     rc->ufbits = 0;
460     rc->ncoeffs = 0;
461     rc->nzcoeffs = 0;
462     rc->mb = 0;
463     rc->qps = 0;
464 }
465
466 void x264_ratecontrol_mb( x264_t *h, int bits )
467 {
468     x264_ratecontrol_t *rc = h->rc;
469     int rbits;
470     int zn, enz, nonz;
471     int rcoeffs;
472     int dqp;
473     int i;
474
475     if( !h->param.rc.b_cbr || h->param.rc.b_stat_read )
476         return;
477
478     x264_cpu_restore( h->param.cpu );
479
480     rc->qps += rc->qpm;
481     rc->ufbits += bits;
482     rc->mb++;
483
484     for(i = 0; i < 16 + 8; i++)
485         rc->nzcoeffs += 16 - h->mb.cache.non_zero_count[x264_scan8[i]];
486     rc->ncoeffs += 16 * (16 + 8);
487
488     if(rc->mb < rc->nmb / 16)
489         return;
490     else if(rc->mb == rc->nmb)
491         return;
492
493     rcoeffs = (rc->nmb - rc->mb) * 16 * 24;
494     rbits = rc->fbits - rc->ufbits;
495 /*     if(rbits < 0) */
496 /*      rbits = 0; */
497
498 /*     zn = (rc->nmb - rc->mb) * 16 * 24; */
499     nonz = (rc->ncoeffs - rc->nzcoeffs);
500     if(nonz == 0)
501         zn = rcoeffs;
502     else if(rc->ufbits && rbits < INT_MAX / nonz)
503         zn = rcoeffs - rbits * nonz / rc->ufbits;
504     else
505         zn = 0;
506     zn = x264_clip3(zn, 0, rcoeffs);
507     enz = rc->nzcoeffs * (rc->nmb - rc->mb) / rc->mb;
508     dqp = (float) 2*h->param.rc.i_rc_sens * exp2f((float) rc->qps / rc->mb / 6) *
509         (zn - enz) / enz;
510     rc->qpm = x264_clip3(rc->qpm + dqp, rc->qp - 3, rc->qp + 3);
511     if(rbits <= 0)
512         rc->qpm++;
513     rc->qpm = x264_clip3(rc->qpm, h->param.rc.i_qp_min, h->param.rc.i_qp_max);
514 }
515
516 int  x264_ratecontrol_qp( x264_t *h )
517 {
518     return h->rc->qpm;
519 }
520
521 int x264_ratecontrol_slice_type( x264_t *h, int frame_num )
522 {
523     if( h->param.rc.b_stat_read )
524     {
525         assert(frame_num < h->rc->num_entries);
526         switch( h->rc->entry[frame_num].new_pict_type )
527         {
528             case SLICE_TYPE_I:
529                 return X264_TYPE_I;
530
531             case SLICE_TYPE_B:
532                 return X264_TYPE_B;
533
534             case SLICE_TYPE_P:
535             default:
536                 return X264_TYPE_P;
537         }
538     }
539     else
540     {
541         return X264_TYPE_AUTO;
542     }
543 }
544
545 void x264_ratecontrol_end( x264_t *h, int bits )
546 {
547     x264_ratecontrol_t *rc = h->rc;
548
549     if( h->param.rc.b_stat_write )
550     {
551         fprintf( rc->p_stat_file_out,
552                  "in:%d out:%d type:%d q:%.3f itex:%d ptex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d;\n",
553                  h->fenc->i_frame, h->i_frame-1,
554                  rc->slice_type, (float)rc->qpm,
555                  h->stat.frame.i_itex_bits, h->stat.frame.i_ptex_bits,
556                  h->stat.frame.i_hdr_bits, h->stat.frame.i_misc_bits,
557                  h->stat.frame.i_mb_count[I_4x4] + h->stat.frame.i_mb_count[I_16x16],
558                  h->stat.frame.i_mb_count[P_L0]  + h->stat.frame.i_mb_count[P_8x8],
559                  h->stat.frame.i_mb_count[P_SKIP]);
560     }
561
562     if( !h->param.rc.b_cbr || h->param.rc.b_stat_read )
563         return;
564
565     rc->buffer_fullness += rc->rcbufrate - bits;
566     if(rc->buffer_fullness < 0){
567         x264_log(h, X264_LOG_WARNING, "buffer underflow %i\n",
568                  rc->buffer_fullness);
569         rc->buffer_fullness = 0;
570     }
571
572     rc->qpa = rc->qps / rc->mb;
573     if(rc->slice_type == SLICE_TYPE_P){
574         rc->qp_avg_p += rc->qpa;
575         rc->qp_last_p = rc->qpa;
576         rc->pframes++;
577     } else if(rc->slice_type == SLICE_TYPE_I){
578         float err = (float) rc->ufbits / rc->fbits;
579         if(err > 1.1)
580             rc->gop_qp++;
581         else if(err < 0.9)
582             rc->gop_qp--;
583     }
584
585     rc->overhead = bits - rc->ufbits;
586
587     x264_log(h, X264_LOG_DEBUG, "bits=%i, qp=%i, z=%i, zr=%6.3f, buf=%i\n",
588              bits, rc->qpa, rc->nzcoeffs, (float) rc->nzcoeffs / rc->ncoeffs,
589              rc->buffer_fullness);
590
591     rc->bits_last_gop += bits;
592     rc->frames++;
593     rc->mb = 0;
594 }
595
596 /****************************************************************************
597  * 2 pass functions
598  ***************************************************************************/
599 double x264_eval( char *s, double *const_value, const char **const_name,
600                   double (**func1)(void *, double), const char **func1_name,
601                   double (**func2)(void *, double, double), char **func2_name,
602                   void *opaque );
603
604 /**
605  * modifies the bitrate curve from pass1 for one frame
606  */
607 static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor)
608 {
609     x264_ratecontrol_t *rcc= h->rc;
610     double bits;
611     //double q, avg_cplx;
612     const int pict_type = rce->new_pict_type;
613
614     x264_cpu_restore( h->param.cpu );
615
616     //avg_cplx = (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / rcc->frame_count[pict_type];
617
618     double const_values[]={
619         rce->i_tex_bits * rce->qscale,
620         rce->p_tex_bits * rce->qscale,
621         (rce->i_tex_bits + rce->p_tex_bits) * rce->qscale,
622         rce->mv_bits / rcc->nmb,
623         (double)rce->i_count / rcc->nmb,
624         (double)rce->p_count / rcc->nmb,
625         (double)rce->s_count / rcc->nmb,
626         rce->pict_type == SLICE_TYPE_I,
627         rce->pict_type == SLICE_TYPE_P,
628         rce->pict_type == SLICE_TYPE_B,
629         h->param.rc.f_qcompress,
630         rcc->i_cplx_sum[SLICE_TYPE_I] / rcc->frame_count[SLICE_TYPE_I],
631         rcc->i_cplx_sum[SLICE_TYPE_P] / rcc->frame_count[SLICE_TYPE_P],
632         rcc->p_cplx_sum[SLICE_TYPE_P] / rcc->frame_count[SLICE_TYPE_P],
633         rcc->p_cplx_sum[SLICE_TYPE_B] / rcc->frame_count[SLICE_TYPE_B],
634         (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / rcc->frame_count[pict_type],
635         0
636     };
637     static const char *const_names[]={
638         "iTex",
639         "pTex",
640         "tex",
641         "mv",
642         "iCount",
643         "pCount",
644         "sCount",
645         "isI",
646         "isP",
647         "isB",
648         "qComp",
649         "avgIITex",
650         "avgPITex",
651         "avgPPTex",
652         "avgBPTex",
653         "avgTex",
654         NULL
655     };
656     static double (*func1[])(void *, double)={
657         (void *)bits2qscale,
658         (void *)qscale2bits,
659         NULL
660     };
661     static const char *func1_names[]={
662         "bits2qp",
663         "qp2bits",
664         NULL
665     };
666
667     bits = x264_eval((char*)h->param.rc.psz_rc_eq, const_values, const_names, func1, func1_names, NULL, NULL, rce);
668
669     bits *= rate_factor;
670     if(bits<0.0) bits=0.0;
671     bits += 1.0; //avoid 1/0 issues
672
673     /* I/B difference */
674     if( pict_type==SLICE_TYPE_I && h->param.rc.f_ip_factor > 0 )
675         bits *= h->param.rc.f_ip_factor;
676     else if( pict_type==SLICE_TYPE_B && h->param.rc.f_pb_factor > 0 )
677         bits /= h->param.rc.f_pb_factor;
678
679     return bits2qscale(rce, bits);
680 }
681
682 static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
683 {
684     x264_ratecontrol_t *rcc = h->rc;
685     const int pict_type = rce->new_pict_type;
686
687     // force I/B quants as a function of P quants
688     const double last_p_q    = rcc->last_qscale_for[SLICE_TYPE_P];
689     const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
690     if( pict_type == SLICE_TYPE_I && h->param.rc.f_ip_factor < 0 )
691         q = last_p_q     / -h->param.rc.f_ip_factor;
692     else if(pict_type==SLICE_TYPE_B && h->param.rc.f_pb_factor < 0)
693         q = last_non_b_q * -h->param.rc.f_pb_factor;
694
695     /* last qscale / qdiff stuff */
696     if(rcc->last_non_b_pict_type==pict_type || pict_type!=SLICE_TYPE_I)
697     {
698         double last_q = rcc->last_qscale_for[pict_type];
699         const double max_qscale = qp2qscale(qscale2qp(last_q) + h->param.rc.i_qp_step);
700         const double min_qscale = qp2qscale(qscale2qp(last_q) - h->param.rc.i_qp_step);
701
702         if     (q > max_qscale) q = max_qscale;
703         else if(q < min_qscale) q = min_qscale;
704     }
705
706     rcc->last_qscale_for[pict_type] = q; //Note we can't do that after blurring
707     if(pict_type!=SLICE_TYPE_B)
708         rcc->last_non_b_pict_type = pict_type;
709     return q;
710 }
711
712 static double modify_qscale( x264_t *h, ratecontrol_entry_t *rce, double q )
713 {
714     x264_ratecontrol_t *rcc = h->rc;
715     const int pict_type = rce->new_pict_type;
716     double lmin = rcc->lmin[pict_type];
717     double lmax = rcc->lmax[pict_type];
718
719     if(lmin==lmax /* || !h->param.b_qsquish */){
720         if     (q<lmin) q = lmin;
721         else if(q>lmax) q = lmax;
722     }else{
723         double min2 = log(lmin);
724         double max2 = log(lmax);
725
726         q = log(q);
727         q = (q - min2)/(max2-min2) - 0.5;
728         q *= -4.0;
729         q = 1.0/(1.0 + exp(q));
730         q = q*(max2-min2) + min2;
731
732         q = exp(q);
733     }
734     return q;
735 }
736
737 // update qscale for 1 frame based on actual bits used so far
738 static float rate_estimate_qscale(x264_t *h, int pict_type)
739 {
740     float q;
741     float br_compensation;
742     double diff;
743     int picture_number = h->fenc->i_frame;
744     x264_ratecontrol_t *rcc = h->rc;
745     ratecontrol_entry_t *rce;
746     double lmin = rcc->lmin[pict_type];
747     double lmax = rcc->lmax[pict_type];
748     int64_t wanted_bits;
749     int64_t total_bits = 8*(h->stat.i_slice_size[SLICE_TYPE_I]
750                           + h->stat.i_slice_size[SLICE_TYPE_P]
751                           + h->stat.i_slice_size[SLICE_TYPE_B]);
752
753 //printf("input_pic_num:%d pic_num:%d frame_rate:%d\n", s->input_picture_number, s->picture_number, s->frame_rate);
754
755     rce = &rcc->entry[picture_number];
756
757     if(pict_type!=SLICE_TYPE_I)
758         assert(pict_type == rce->new_pict_type);
759
760     wanted_bits = rce->expected_bits;
761
762     diff = total_bits - wanted_bits;
763     br_compensation = (rcc->buffer_size - diff) / rcc->buffer_size;
764     if(br_compensation<=0.0) br_compensation=0.001;
765
766     q = rce->new_qscale / br_compensation;
767
768     if     (q<lmin) q=lmin;
769     else if(q>lmax) q=lmax;
770
771     rcc->last_qscale = q;
772     return q;
773 }
774
775 static int init_pass2( x264_t *h )
776 {
777     x264_ratecontrol_t *rcc = h->rc;
778     uint64_t all_const_bits = 0;
779     uint64_t all_available_bits = (uint64_t)(h->param.rc.i_bitrate * 1000 * (double)rcc->num_entries / rcc->fps);
780     double rate_factor, step, step_mult;
781     double qblur = h->param.rc.f_qblur;
782     const int filter_size = (int)(qblur*4) | 1;
783     double expected_bits;
784     double *qscale, *blurred_qscale;
785     int i;
786
787     /* find total/average complexity & const_bits */
788     for(i=0; i<rcc->num_entries; i++){
789         ratecontrol_entry_t *rce = &rcc->entry[i];
790         rce->new_pict_type = rce->pict_type;
791         all_const_bits += rce->mv_bits + rce->misc_bits;
792         rcc->i_cplx_sum[rce->new_pict_type] += rce->i_tex_bits * rce->qscale;
793         rcc->p_cplx_sum[rce->new_pict_type] += rce->p_tex_bits * rce->qscale;
794         rcc->mv_bits_sum[rce->new_pict_type] += rce->mv_bits;
795         rcc->frame_count[rce->new_pict_type] ++;
796     }
797
798     if( all_available_bits < all_const_bits)
799     {
800         x264_log(h, X264_LOG_ERROR, "requested bitrate is too low. estimated minimum is %d kbps\n",
801                  (int)(all_const_bits * rcc->fps / (rcc->num_entries * 1000)));
802         return -1;
803     }
804
805     qscale = x264_malloc(sizeof(double)*rcc->num_entries);
806     if(filter_size > 1)
807         blurred_qscale = x264_malloc(sizeof(double)*rcc->num_entries);
808     else
809         blurred_qscale = qscale;
810
811     expected_bits = 0;
812     for(i=0; i<rcc->num_entries; i++)
813         expected_bits += qscale2bits(&rcc->entry[i], get_qscale(h, &rcc->entry[i], 1.0));
814     step_mult = all_available_bits / expected_bits;
815
816     rate_factor = 0;
817     for(step = 1E4 * step_mult; step > 1E-7 * step_mult; step*=0.5){
818         expected_bits = 0;
819         rate_factor += step;
820
821         /* find qscale */
822         for(i=0; i<rcc->num_entries; i++){
823             qscale[i] = get_qscale(h, &rcc->entry[i], rate_factor);
824         }
825
826         /* fixed I/B QP relative to P mode */
827         for(i=rcc->num_entries-1; i>=0; i--){
828             qscale[i] = get_diff_limited_q(h, &rcc->entry[i], qscale[i]);
829             assert(qscale[i] >= 0);
830         }
831
832         /* smooth curve */
833         if(filter_size > 1){
834             assert(filter_size%2==1);
835             for(i=0; i<rcc->num_entries; i++){
836                 ratecontrol_entry_t *rce = &rcc->entry[i];
837                 const int pict_type = rce->new_pict_type;
838                 int j;
839                 double q=0.0, sum=0.0;
840
841                 for(j=0; j<filter_size; j++){
842                     int index = i+j-filter_size/2;
843                     double d = index-i;
844                     double coeff = qblur==0 ? 1.0 : exp(-d*d/(qblur*qblur));
845                     if(index < 0 || index >= rcc->num_entries) continue;
846                     if(pict_type != rcc->entry[index].new_pict_type) continue;
847                     q += qscale[index] * coeff;
848                     sum += coeff;
849                 }
850                 blurred_qscale[i] = q/sum;
851             }
852         }
853
854         /* find expected bits */
855         for(i=0; i<rcc->num_entries; i++){
856             ratecontrol_entry_t *rce = &rcc->entry[i];
857             double bits;
858             rce->new_qscale = modify_qscale(h, rce, blurred_qscale[i]);
859             assert(rce->new_qscale >= 0);
860             bits = qscale2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
861
862             rce->expected_bits = expected_bits;
863             expected_bits += bits;
864         }
865
866 //printf("expected:%f available:%d factor:%f\n", expected_bits, (int)all_available_bits, rate_factor);
867         if(expected_bits > all_available_bits) rate_factor -= step;
868     }
869
870     x264_free(qscale);
871     if(filter_size > 1)
872         x264_free(blurred_qscale);
873
874     if(fabs(expected_bits/all_available_bits - 1.0) > 0.01 )
875     {
876         x264_log( h, X264_LOG_ERROR, "Error: 2pass curve failed to converge\n");
877         return -1;
878     }
879
880     return 0;
881 }
882
883