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