]> git.sesse.net Git - x264/blob - encoder/ratecontrol.c
dce7d331badb07a7b7b6f023e469481182fa24c5
[x264] / encoder / ratecontrol.c
1 /***************************************************-*- coding: iso-8859-1 -*-
2  * ratecontrol.c: h264 encoder library (Rate Control)
3  *****************************************************************************
4  * Copyright (C) 2005 x264 project
5  * $Id: ratecontrol.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
6  *
7  * Authors: Loren Merritt <lorenm@u.washington.edu>
8  *          Michael Niedermayer <michaelni@gmx.at>
9  *          Måns Rullgård <mru@mru.ath.cx>
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 <stdio.h>
29 #include <string.h>
30 #include <math.h>
31 #include <limits.h>
32 #include <assert.h>
33
34 #include "common/common.h"
35 #include "common/cpu.h"
36 #include "ratecontrol.h"
37
38 #if defined(SYS_OPENBSD)
39 #define isfinite finite
40 #endif
41 #if defined(_MSC_VER)
42 #define isfinite _finite
43 #endif
44 #if defined(_MSC_VER) || defined(SYS_SunOS) || defined(SYS_MACOSX)
45 #define sqrtf sqrt
46 #endif
47 #ifdef WIN32 // POSIX says that rename() removes the destination, but win32 doesn't.
48 #define rename(src,dst) (unlink(dst), rename(src,dst))
49 #endif
50
51 typedef struct
52 {
53     int pict_type;
54     int kept_as_ref;
55     float qscale;
56     int mv_bits;
57     int i_tex_bits;
58     int p_tex_bits;
59     int misc_bits;
60     uint64_t expected_bits;
61     float new_qscale;
62     int new_qp;
63     int i_count;
64     int p_count;
65     int s_count;
66     float blurred_complexity;
67     char direct_mode;
68 } ratecontrol_entry_t;
69
70 typedef struct
71 {
72     double coeff;
73     double count;
74     double decay;
75 } predictor_t;
76
77 struct x264_ratecontrol_t
78 {
79     /* constants */
80     int b_abr;
81     int b_2pass;
82     int b_vbv;
83     int b_vbv_min_rate;
84     double fps;
85     double bitrate;
86     double rate_tolerance;
87     int nmb;                    /* number of macroblocks in a frame */
88     int qp_constant[5];
89
90     /* current frame */
91     ratecontrol_entry_t *rce;
92     int qp;                     /* qp for current frame */
93     int qpm;                    /* qp for current macroblock */
94     float qpa;                  /* average of macroblocks' qp */
95     int qp_force;
96
97     /* VBV stuff */
98     double buffer_size;
99     double buffer_fill_final;   /* real buffer as of the last finished frame */
100     double buffer_fill;         /* planned buffer, if all in-progress frames hit their bit budget */
101     double buffer_rate;         /* # of bits added to buffer_fill after each frame */
102     predictor_t *pred;          /* predict frame size from satd */
103
104     /* ABR stuff */
105     int    last_satd;
106     double last_rceq;
107     double cplxr_sum;           /* sum of bits*qscale/rceq */
108     double expected_bits_sum;   /* sum of qscale2bits after rceq, ratefactor, and overflow */
109     double wanted_bits_window;  /* target bitrate * window */
110     double cbr_decay;
111     double short_term_cplxsum;
112     double short_term_cplxcount;
113     double rate_factor_constant;
114     double ip_offset;
115     double pb_offset;
116
117     /* 2pass stuff */
118     FILE *p_stat_file_out;
119     char *psz_stat_file_tmpname;
120
121     int num_entries;            /* number of ratecontrol_entry_ts */
122     ratecontrol_entry_t *entry; /* FIXME: copy needed data and free this once init is done */
123     double last_qscale;
124     double last_qscale_for[5];  /* last qscale for a specific pict type, used for max_diff & ipb factor stuff  */
125     int last_non_b_pict_type;
126     double accum_p_qp;          /* for determining I-frame quant */
127     double accum_p_norm;
128     double last_accum_p_norm;
129     double lmin[5];             /* min qscale by frame type */
130     double lmax[5];
131     double lstep;               /* max change (multiply) in qscale per frame */
132     double i_cplx_sum[5];       /* estimated total texture bits in intra MBs at qscale=1 */
133     double p_cplx_sum[5];
134     double mv_bits_sum[5];
135     int frame_count[5];         /* number of frames of each type */
136
137     /* MBRC stuff */
138     double frame_size_planned;
139     predictor_t *row_pred;
140     predictor_t row_preds[5];
141     predictor_t *pred_b_from_p; /* predict B-frame size from P-frame satd */
142     int bframes;                /* # consecutive B-frames before this P-frame */
143     int bframe_bits;            /* total cost of those frames */
144
145     int i_zones;
146     x264_zone_t *zones;
147 };
148
149
150 static int parse_zones( x264_t *h );
151 static int init_pass2(x264_t *);
152 static float rate_estimate_qscale( x264_t *h );
153 static void update_vbv( x264_t *h, int bits );
154 static void update_vbv_plan( x264_t *h );
155 static double predict_size( predictor_t *p, double q, double var );
156 static void update_predictor( predictor_t *p, double q, double var, double bits );
157 int  x264_rc_analyse_slice( x264_t *h );
158
159 /* Terminology:
160  * qp = h.264's quantizer
161  * qscale = linearized quantizer = Lagrange multiplier
162  */
163 static inline double qp2qscale(double qp)
164 {
165     return 0.85 * pow(2.0, ( qp - 12.0 ) / 6.0);
166 }
167 static inline double qscale2qp(double qscale)
168 {
169     return 12.0 + 6.0 * log(qscale/0.85) / log(2.0);
170 }
171
172 /* Texture bitrate is not quite inversely proportional to qscale,
173  * probably due the the changing number of SKIP blocks.
174  * MV bits level off at about qp<=12, because the lambda used
175  * for motion estimation is constant there. */
176 static inline double qscale2bits(ratecontrol_entry_t *rce, double qscale)
177 {
178     if(qscale<0.1)
179         qscale = 0.1;
180     return (rce->i_tex_bits + rce->p_tex_bits + .1) * pow( rce->qscale / qscale, 1.1 )
181            + rce->mv_bits * pow( X264_MAX(rce->qscale, 1) / X264_MAX(qscale, 1), 0.5 )
182            + rce->misc_bits;
183 }
184
185
186 int x264_ratecontrol_new( x264_t *h )
187 {
188     x264_ratecontrol_t *rc;
189     int i;
190
191     x264_cpu_restore( h->param.cpu );
192
193     rc = h->rc = x264_malloc( h->param.i_threads * sizeof(x264_ratecontrol_t) );
194     memset( rc, 0, h->param.i_threads * sizeof(x264_ratecontrol_t) );
195
196     rc->b_abr = h->param.rc.i_rc_method != X264_RC_CQP && !h->param.rc.b_stat_read;
197     rc->b_2pass = h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.b_stat_read;
198     
199     /* FIXME: use integers */
200     if(h->param.i_fps_num > 0 && h->param.i_fps_den > 0)
201         rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den;
202     else
203         rc->fps = 25.0;
204
205     rc->bitrate = h->param.rc.i_bitrate * 1000;
206     rc->rate_tolerance = h->param.rc.f_rate_tolerance;
207     rc->nmb = h->mb.i_mb_count;
208     rc->last_non_b_pict_type = -1;
209     rc->cbr_decay = 1.0;
210
211     if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.b_stat_read )
212     {
213         x264_log(h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n");
214         return -1;
215     }
216     if( h->param.rc.i_vbv_buffer_size )
217     {
218         if( h->param.rc.i_rc_method == X264_RC_CQP )
219             x264_log(h, X264_LOG_WARNING, "VBV is incompatible with constant QP, ignored.\n");
220         else if( h->param.rc.i_vbv_max_bitrate == 0 )
221         {
222             x264_log( h, X264_LOG_DEBUG, "VBV maxrate unspecified, assuming CBR\n" );
223             h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
224         }
225     }
226     if( h->param.rc.i_vbv_max_bitrate < h->param.rc.i_bitrate &&
227         h->param.rc.i_vbv_max_bitrate > 0)
228         x264_log(h, X264_LOG_WARNING, "max bitrate less than average bitrate, ignored.\n");
229     else if( h->param.rc.i_vbv_max_bitrate > 0 &&
230              h->param.rc.i_vbv_buffer_size > 0 )
231     {
232         if( h->param.rc.i_vbv_buffer_size < 3 * h->param.rc.i_vbv_max_bitrate / rc->fps )
233         {
234             h->param.rc.i_vbv_buffer_size = 3 * h->param.rc.i_vbv_max_bitrate / rc->fps;
235             x264_log( h, X264_LOG_WARNING, "VBV buffer size too small, using %d kbit\n",
236                       h->param.rc.i_vbv_buffer_size );
237         }
238         rc->buffer_rate = h->param.rc.i_vbv_max_bitrate * 1000 / rc->fps;
239         rc->buffer_size = h->param.rc.i_vbv_buffer_size * 1000;
240         rc->buffer_fill_final = rc->buffer_size * h->param.rc.f_vbv_buffer_init;
241         rc->cbr_decay = 1.0 - rc->buffer_rate / rc->buffer_size
242                       * 0.5 * X264_MAX(0, 1.5 - rc->buffer_rate * rc->fps / rc->bitrate);
243         rc->b_vbv = 1;
244         rc->b_vbv_min_rate = !rc->b_2pass
245                           && h->param.rc.i_rc_method == X264_RC_ABR
246                           && h->param.rc.i_vbv_max_bitrate <= h->param.rc.i_bitrate;
247     }
248     else if( h->param.rc.i_vbv_max_bitrate )
249     {
250         x264_log(h, X264_LOG_WARNING, "VBV maxrate specified, but no bufsize.\n");
251         h->param.rc.i_vbv_max_bitrate = 0;
252     }
253     if(rc->rate_tolerance < 0.01) {
254         x264_log(h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n");
255         rc->rate_tolerance = 0.01;
256     }
257
258     h->mb.b_variable_qp = rc->b_vbv && !rc->b_2pass;
259
260     if( rc->b_abr )
261     {
262         /* FIXME ABR_INIT_QP is actually used only in CRF */
263 #define ABR_INIT_QP ( h->param.rc.i_rc_method == X264_RC_CRF ? h->param.rc.f_rf_constant : 24 )
264         rc->accum_p_norm = .01;
265         rc->accum_p_qp = ABR_INIT_QP * rc->accum_p_norm;
266         /* estimated ratio that produces a reasonable QP for the first I-frame */
267         rc->cplxr_sum = .01 * pow( 7.0e5, h->param.rc.f_qcompress ) * pow( h->mb.i_mb_count, 0.5 );
268         rc->wanted_bits_window = 1.0 * rc->bitrate / rc->fps;
269         rc->last_non_b_pict_type = SLICE_TYPE_I;
270     }
271
272     if( h->param.rc.i_rc_method == X264_RC_CRF )
273     {
274         /* arbitrary rescaling to make CRF somewhat similar to QP */
275         double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
276         rc->rate_factor_constant = pow( base_cplx, 1 - h->param.rc.f_qcompress )
277                                  / qp2qscale( h->param.rc.f_rf_constant );
278     }
279
280     rc->ip_offset = 6.0 * log(h->param.rc.f_ip_factor) / log(2.0);
281     rc->pb_offset = 6.0 * log(h->param.rc.f_pb_factor) / log(2.0);
282     rc->qp_constant[SLICE_TYPE_P] = h->param.rc.i_qp_constant;
283     rc->qp_constant[SLICE_TYPE_I] = x264_clip3( h->param.rc.i_qp_constant - rc->ip_offset + 0.5, 0, 51 );
284     rc->qp_constant[SLICE_TYPE_B] = x264_clip3( h->param.rc.i_qp_constant + rc->pb_offset + 0.5, 0, 51 );
285
286     rc->lstep = pow( 2, h->param.rc.i_qp_step / 6.0 );
287     rc->last_qscale = qp2qscale(26);
288     rc->pred = x264_malloc( 5*sizeof(predictor_t) );
289     rc->pred_b_from_p = x264_malloc( sizeof(predictor_t) );
290     for( i = 0; i < 5; i++ )
291     {
292         rc->last_qscale_for[i] = qp2qscale( ABR_INIT_QP );
293         rc->lmin[i] = qp2qscale( h->param.rc.i_qp_min );
294         rc->lmax[i] = qp2qscale( h->param.rc.i_qp_max );
295         rc->pred[i].coeff= 2.0;
296         rc->pred[i].count= 1.0;
297         rc->pred[i].decay= 0.5;
298         rc->row_preds[i].coeff= .25;
299         rc->row_preds[i].count= 1.0;
300         rc->row_preds[i].decay= 0.5;
301     }
302     *rc->pred_b_from_p = rc->pred[0];
303
304     if( parse_zones( h ) < 0 )
305         return -1;
306
307     /* Load stat file and init 2pass algo */
308     if( h->param.rc.b_stat_read )
309     {
310         char *p, *stats_in, *stats_buf;
311
312         /* read 1st pass stats */
313         assert( h->param.rc.psz_stat_in );
314         stats_buf = stats_in = x264_slurp_file( h->param.rc.psz_stat_in );
315         if( !stats_buf )
316         {
317             x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
318             return -1;
319         }
320
321         /* check whether 1st pass options were compatible with current options */
322         if( !strncmp( stats_buf, "#options:", 9 ) )
323         {
324             int i;
325             char *opts = stats_buf;
326             stats_in = strchr( stats_buf, '\n' );
327             if( !stats_in )
328                 return -1;
329             *stats_in = '\0';
330             stats_in++;
331
332             if( ( p = strstr( opts, "bframes=" ) ) && sscanf( p, "bframes=%d", &i )
333                 && h->param.i_bframe != i )
334             {
335                 x264_log( h, X264_LOG_ERROR, "different number of B-frames than 1st pass (%d vs %d)\n",
336                           h->param.i_bframe, i );
337                 return -1;
338             }
339
340             /* since B-adapt doesn't (yet) take into account B-pyramid,
341              * the converse is not a problem */
342             if( strstr( opts, "b_pyramid=1" ) && !h->param.b_bframe_pyramid )
343                 x264_log( h, X264_LOG_WARNING, "1st pass used B-pyramid, 2nd doesn't\n" );
344
345             if( ( p = strstr( opts, "keyint=" ) ) && sscanf( p, "keyint=%d", &i )
346                 && h->param.i_keyint_max != i )
347                 x264_log( h, X264_LOG_WARNING, "different keyint than 1st pass (%d vs %d)\n",
348                           h->param.i_keyint_max, i );
349
350             if( strstr( opts, "qp=0" ) && h->param.rc.i_rc_method == X264_RC_ABR )
351                 x264_log( h, X264_LOG_WARNING, "1st pass was lossless, bitrate prediction will be inaccurate\n" );
352         }
353
354         /* find number of pics */
355         p = stats_in;
356         for(i=-1; p; i++)
357             p = strchr(p+1, ';');
358         if(i==0)
359         {
360             x264_log(h, X264_LOG_ERROR, "empty stats file\n");
361             return -1;
362         }
363         rc->num_entries = i;
364
365         if( h->param.i_frame_total < rc->num_entries && h->param.i_frame_total > 0 )
366         {
367             x264_log( h, X264_LOG_WARNING, "2nd pass has fewer frames than 1st pass (%d vs %d)\n",
368                       h->param.i_frame_total, rc->num_entries );
369         }
370         if( h->param.i_frame_total > rc->num_entries + h->param.i_bframe )
371         {
372             x264_log( h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d vs %d)\n",
373                       h->param.i_frame_total, rc->num_entries );
374             return -1;
375         }
376
377         /* FIXME: ugly padding because VfW drops delayed B-frames */
378         rc->num_entries += h->param.i_bframe;
379
380         rc->entry = (ratecontrol_entry_t*) x264_malloc(rc->num_entries * sizeof(ratecontrol_entry_t));
381         memset(rc->entry, 0, rc->num_entries * sizeof(ratecontrol_entry_t));
382
383         /* init all to skipped p frames */
384         for(i=0; i<rc->num_entries; i++){
385             ratecontrol_entry_t *rce = &rc->entry[i];
386             rce->pict_type = SLICE_TYPE_P;
387             rce->qscale = rce->new_qscale = qp2qscale(20);
388             rce->misc_bits = rc->nmb + 10;
389             rce->new_qp = 0;
390         }
391
392         /* read stats */
393         p = stats_in;
394         for(i=0; i < rc->num_entries - h->param.i_bframe; i++){
395             ratecontrol_entry_t *rce;
396             int frame_number;
397             char pict_type;
398             int e;
399             char *next;
400             float qp;
401
402             next= strchr(p, ';');
403             if(next){
404                 (*next)=0; //sscanf is unbelievably slow on looong strings
405                 next++;
406             }
407             e = sscanf(p, " in:%d ", &frame_number);
408
409             if(frame_number < 0 || frame_number >= rc->num_entries)
410             {
411                 x264_log(h, X264_LOG_ERROR, "bad frame number (%d) at stats line %d\n", frame_number, i);
412                 return -1;
413             }
414             rce = &rc->entry[frame_number];
415             rce->direct_mode = 0;
416
417             e += sscanf(p, " in:%*d out:%*d type:%c q:%f itex:%d ptex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c",
418                    &pict_type, &qp, &rce->i_tex_bits, &rce->p_tex_bits,
419                    &rce->mv_bits, &rce->misc_bits, &rce->i_count, &rce->p_count,
420                    &rce->s_count, &rce->direct_mode);
421
422             switch(pict_type){
423                 case 'I': rce->kept_as_ref = 1;
424                 case 'i': rce->pict_type = SLICE_TYPE_I; break;
425                 case 'P': rce->pict_type = SLICE_TYPE_P; break;
426                 case 'B': rce->kept_as_ref = 1;
427                 case 'b': rce->pict_type = SLICE_TYPE_B; break;
428                 default:  e = -1; break;
429             }
430             if(e < 10){
431                 x264_log(h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);
432                 return -1;
433             }
434             rce->qscale = qp2qscale(qp);
435             p = next;
436         }
437
438         x264_free(stats_buf);
439
440         if(h->param.rc.i_rc_method == X264_RC_ABR)
441         {
442             if(init_pass2(h) < 0) return -1;
443         } /* else we're using constant quant, so no need to run the bitrate allocation */
444     }
445
446     /* Open output file */
447     /* If input and output files are the same, output to a temp file
448      * and move it to the real name only when it's complete */
449     if( h->param.rc.b_stat_write )
450     {
451         char *p;
452
453         rc->psz_stat_file_tmpname = x264_malloc( strlen(h->param.rc.psz_stat_out) + 6 );
454         strcpy( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out );
455         strcat( rc->psz_stat_file_tmpname, ".temp" );
456
457         rc->p_stat_file_out = fopen( rc->psz_stat_file_tmpname, "wb" );
458         if( rc->p_stat_file_out == NULL )
459         {
460             x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
461             return -1;
462         }
463
464         p = x264_param2string( &h->param, 1 );
465         fprintf( rc->p_stat_file_out, "#options: %s\n", p );
466         x264_free( p );
467     }
468
469     for( i=1; i<h->param.i_threads; i++ )
470     {
471         h->thread[i]->rc = rc+i;
472         rc[i] = rc[0];
473     }
474
475     return 0;
476 }
477
478 static int parse_zones( x264_t *h )
479 {
480     x264_ratecontrol_t *rc = h->rc;
481     int i;
482     if( h->param.rc.psz_zones && !h->param.rc.i_zones )
483     {
484         char *p;
485         h->param.rc.i_zones = 1;
486         for( p = h->param.rc.psz_zones; *p; p++ )
487             h->param.rc.i_zones += (*p == '/');
488         h->param.rc.zones = x264_malloc( h->param.rc.i_zones * sizeof(x264_zone_t) );
489         p = h->param.rc.psz_zones;
490         for( i = 0; i < h->param.rc.i_zones; i++)
491         {
492             x264_zone_t *z = &h->param.rc.zones[i];
493             if( 3 == sscanf(p, "%u,%u,q=%u", &z->i_start, &z->i_end, &z->i_qp) )
494                 z->b_force_qp = 1;
495             else if( 3 == sscanf(p, "%u,%u,b=%f", &z->i_start, &z->i_end, &z->f_bitrate_factor) )
496                 z->b_force_qp = 0;
497             else
498             {
499                 char *slash = strchr(p, '/');
500                 if(slash) *slash = '\0';
501                 x264_log( h, X264_LOG_ERROR, "invalid zone: \"%s\"\n", p );
502                 return -1;
503             }
504             p = strchr(p, '/') + 1;
505         }
506     }
507
508     if( h->param.rc.i_zones > 0 )
509     {
510         for( i = 0; i < h->param.rc.i_zones; i++ )
511         {
512             x264_zone_t z = h->param.rc.zones[i];
513             if( z.i_start < 0 || z.i_start > z.i_end )
514             {
515                 x264_log( h, X264_LOG_ERROR, "invalid zone: start=%d end=%d\n",
516                           z.i_start, z.i_end );
517                 return -1;
518             }
519             else if( !z.b_force_qp && z.f_bitrate_factor <= 0 )
520             {
521                 x264_log( h, X264_LOG_ERROR, "invalid zone: bitrate_factor=%f\n",
522                           z.f_bitrate_factor );
523                 return -1;
524             }
525         }
526
527         rc->i_zones = h->param.rc.i_zones;
528         rc->zones = x264_malloc( rc->i_zones * sizeof(x264_zone_t) );
529         memcpy( rc->zones, h->param.rc.zones, rc->i_zones * sizeof(x264_zone_t) );
530     }
531
532     return 0;
533 }
534
535 x264_zone_t *get_zone( x264_t *h, int frame_num )
536 {
537     int i;
538     for( i = h->rc->i_zones-1; i >= 0; i-- )
539     {
540         x264_zone_t *z = &h->rc->zones[i];
541         if( frame_num >= z->i_start && frame_num <= z->i_end )
542             return z;
543     }
544     return NULL;
545 }
546
547 void x264_ratecontrol_summary( x264_t *h )
548 {
549     x264_ratecontrol_t *rc = h->rc;
550     if( rc->b_abr && h->param.rc.i_rc_method == X264_RC_ABR && rc->cbr_decay > .9999 )
551     {
552         double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
553         x264_log( h, X264_LOG_INFO, "final ratefactor: %.2f\n", 
554                   qscale2qp( pow( base_cplx, 1 - h->param.rc.f_qcompress )
555                              * rc->cplxr_sum / rc->wanted_bits_window ) );
556     }
557 }
558
559 void x264_ratecontrol_delete( x264_t *h )
560 {
561     x264_ratecontrol_t *rc = h->rc;
562
563     if( rc->p_stat_file_out )
564     {
565         fclose( rc->p_stat_file_out );
566         if( h->i_frame >= rc->num_entries - h->param.i_bframe )
567             if( rename( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ) != 0 )
568             {
569                 x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
570                           rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out );
571             }
572         x264_free( rc->psz_stat_file_tmpname );
573     }
574     x264_free( rc->pred );
575     x264_free( rc->pred_b_from_p );
576     x264_free( rc->entry );
577     x264_free( rc->zones );
578     x264_free( rc );
579 }
580
581 static void accum_p_qp_update( x264_t *h, float qp )
582 {
583     x264_ratecontrol_t *rc = h->rc;
584     rc->accum_p_qp   *= .95;
585     rc->accum_p_norm *= .95;
586     rc->accum_p_norm += 1;
587     if( h->sh.i_type == SLICE_TYPE_I )
588         rc->accum_p_qp += qp + rc->ip_offset;
589     else
590         rc->accum_p_qp += qp;
591 }
592
593 /* Before encoding a frame, choose a QP for it */
594 void x264_ratecontrol_start( x264_t *h, int i_force_qp )
595 {
596     x264_ratecontrol_t *rc = h->rc;
597     ratecontrol_entry_t *rce = NULL;
598     float q;
599
600     x264_cpu_restore( h->param.cpu );
601
602     rc->qp_force = i_force_qp;
603
604     if( h->param.rc.b_stat_read )
605     {
606         int frame = h->fenc->i_frame;
607         assert( frame >= 0 && frame < rc->num_entries );
608         rce = h->rc->rce = &h->rc->entry[frame];
609
610         if( h->sh.i_type == SLICE_TYPE_B
611             && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
612         {
613             h->sh.b_direct_spatial_mv_pred = ( rce->direct_mode == 's' );
614             h->mb.b_direct_auto_read = ( rce->direct_mode == 's' || rce->direct_mode == 't' );
615         }
616     }
617
618     if( rc->b_vbv )
619     {
620         memset( h->fdec->i_row_bits, 0, h->sps->i_mb_height * sizeof(int) );
621         rc->row_pred = &rc->row_preds[h->sh.i_type];
622         update_vbv_plan( h );
623     }
624
625     if( h->sh.i_type != SLICE_TYPE_B )
626     {
627         rc->bframes = 0;
628         while( h->frames.current[rc->bframes] && IS_X264_TYPE_B(h->frames.current[rc->bframes]->i_type) )
629             rc->bframes++;
630     }
631
632     rc->qpa = 0;
633
634     if( i_force_qp )
635     {
636         q = i_force_qp - 1;
637     }
638     else if( rc->b_abr )
639     {
640         q = qscale2qp( rate_estimate_qscale( h ) );
641     }
642     else if( rc->b_2pass )
643     {
644         rce->new_qscale = rate_estimate_qscale( h );
645         q = qscale2qp( rce->new_qscale );
646     }
647     else /* CQP */
648     {
649         x264_zone_t *zone = get_zone( h, h->fenc->i_frame );
650         if( h->sh.i_type == SLICE_TYPE_B && h->fdec->b_kept_as_ref )
651             q = ( rc->qp_constant[ SLICE_TYPE_B ] + rc->qp_constant[ SLICE_TYPE_P ] ) / 2;
652         else
653             q = rc->qp_constant[ h->sh.i_type ];
654
655         if( zone )
656         {
657             if( zone->b_force_qp )
658                 q += zone->i_qp - rc->qp_constant[SLICE_TYPE_P];
659             else
660                 q -= 6*log(zone->f_bitrate_factor)/log(2);
661         }
662     }
663
664     h->fdec->f_qp_avg =
665     rc->qpm =
666     rc->qp = x264_clip3( (int)(q + 0.5), 0, 51 );
667     if( rce )
668         rce->new_qp = rc->qp;
669
670     /* accum_p_qp needs to be here so that future frames can benefit from the
671      * data before this frame is done. but this only works because threading
672      * guarantees to not re-encode any frames. so the non-threaded case does
673      * accum_p_qp later. */
674     if( h->param.i_threads > 1 )
675         accum_p_qp_update( h, rc->qp );
676
677     if( h->sh.i_type != SLICE_TYPE_B )
678         rc->last_non_b_pict_type = h->sh.i_type;
679 }
680
681 double predict_row_size( x264_t *h, int y, int qp )
682 {
683     /* average between two predictors:
684      * absolute SATD, and scaled bit cost of the colocated row in the previous frame */
685     x264_ratecontrol_t *rc = h->rc;
686     double pred_s = predict_size( rc->row_pred, qp2qscale(qp), h->fdec->i_row_satd[y] );
687     double pred_t = 0;
688     if( h->sh.i_type != SLICE_TYPE_I 
689         && h->fref0[0]->i_type == h->fdec->i_type
690         && h->fref0[0]->i_row_satd[y] > 0 )
691     {
692         pred_t = h->fref0[0]->i_row_bits[y] * h->fdec->i_row_satd[y] / h->fref0[0]->i_row_satd[y]
693                  * qp2qscale(h->fref0[0]->i_row_qp[y]) / qp2qscale(qp);
694     }
695     if( pred_t == 0 )
696         pred_t = pred_s;
697
698     return (pred_s + pred_t) / 2;
699 }
700
701 double predict_row_size_sum( x264_t *h, int y, int qp )
702 {
703     int i;
704     double bits = 0;
705     for( i = 0; i <= y; i++ )
706         bits += h->fdec->i_row_bits[i];
707     for( i = y+1; i < h->sps->i_mb_height; i++ )
708         bits += predict_row_size( h, i, qp );
709     return bits;
710 }
711
712 void x264_ratecontrol_mb( x264_t *h, int bits )
713 {
714     x264_ratecontrol_t *rc = h->rc;
715     const int y = h->mb.i_mb_y;
716
717     x264_cpu_restore( h->param.cpu );
718
719     h->fdec->i_row_bits[y] += bits;
720     rc->qpa += rc->qpm;
721
722     if( h->mb.i_mb_x != h->sps->i_mb_width - 1 || !h->mb.b_variable_qp )
723         return;
724
725     h->fdec->i_row_qp[y] = rc->qpm;
726
727     if( h->sh.i_type == SLICE_TYPE_B )
728     {
729         /* B-frames shouldn't use lower QP than their reference frames */
730         if( y < h->sps->i_mb_height-1 )
731         {
732             rc->qpm = X264_MAX( rc->qp,
733                       X264_MIN( h->fref0[0]->i_row_qp[y+1],
734                                 h->fref1[0]->i_row_qp[y+1] ));
735         }
736     }
737     else
738     {
739         update_predictor( rc->row_pred, qp2qscale(rc->qpm), h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] );
740
741         /* tweak quality based on difference from predicted size */
742         if( y < h->sps->i_mb_height-1 && h->stat.i_slice_count[h->sh.i_type] > 0 )
743         {
744             int prev_row_qp = h->fdec->i_row_qp[y];
745             int b0 = predict_row_size_sum( h, y, rc->qpm );
746             int b1 = b0;
747             int i_qp_max = X264_MIN( prev_row_qp + h->param.rc.i_qp_step, h->param.rc.i_qp_max );
748             int i_qp_min = X264_MAX( prev_row_qp - h->param.rc.i_qp_step, h->param.rc.i_qp_min );
749             float buffer_left_planned = rc->buffer_fill - rc->frame_size_planned;
750
751             if( !rc->b_vbv_min_rate )
752                 i_qp_min = X264_MAX( i_qp_min, h->sh.i_qp );
753
754             while( rc->qpm < i_qp_max
755                    && (b1 > rc->frame_size_planned * 1.15
756                     || (rc->buffer_fill - b1 < buffer_left_planned * 0.5)))
757             {
758                 rc->qpm ++;
759                 b1 = predict_row_size_sum( h, y, rc->qpm );
760             }
761
762             while( rc->qpm > i_qp_min
763                    && buffer_left_planned > rc->buffer_size * 0.4
764                    && ((b1 < rc->frame_size_planned * 0.8 && rc->qpm <= prev_row_qp)
765                      || b1 < (rc->buffer_fill - rc->buffer_size + rc->buffer_rate) * 1.1) )
766             {
767                 rc->qpm --;
768                 b1 = predict_row_size_sum( h, y, rc->qpm );
769             }
770         }
771     }
772 }
773
774 int x264_ratecontrol_qp( x264_t *h )
775 {
776     return h->rc->qpm;
777 }
778
779 /* In 2pass, force the same frame types as in the 1st pass */
780 int x264_ratecontrol_slice_type( x264_t *h, int frame_num )
781 {
782     x264_ratecontrol_t *rc = h->rc;
783     if( h->param.rc.b_stat_read )
784     {
785         if( frame_num >= rc->num_entries )
786         {
787             /* We could try to initialize everything required for ABR and
788              * adaptive B-frames, but that would be complicated.
789              * So just calculate the average QP used so far. */
790
791             h->param.rc.i_qp_constant = (h->stat.i_slice_count[SLICE_TYPE_P] == 0) ? 24
792                                       : 1 + h->stat.i_slice_qp[SLICE_TYPE_P] / h->stat.i_slice_count[SLICE_TYPE_P];
793             rc->qp_constant[SLICE_TYPE_P] = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
794             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 );
795             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 );
796
797             x264_log(h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d)\n", rc->num_entries);
798             x264_log(h, X264_LOG_ERROR, "continuing anyway, at constant QP=%d\n", h->param.rc.i_qp_constant);
799             if( h->param.b_bframe_adaptive )
800                 x264_log(h, X264_LOG_ERROR, "disabling adaptive B-frames\n");
801
802             rc->b_abr = 0;
803             rc->b_2pass = 0;
804             h->param.rc.i_rc_method = X264_RC_CQP;
805             h->param.rc.b_stat_read = 0;
806             h->param.b_bframe_adaptive = 0;
807             if( h->param.i_bframe > 1 )
808                 h->param.i_bframe = 1;
809             return X264_TYPE_P;
810         }
811         switch( rc->entry[frame_num].pict_type )
812         {
813             case SLICE_TYPE_I:
814                 return rc->entry[frame_num].kept_as_ref ? X264_TYPE_IDR : X264_TYPE_I;
815
816             case SLICE_TYPE_B:
817                 return rc->entry[frame_num].kept_as_ref ? X264_TYPE_BREF : X264_TYPE_B;
818
819             case SLICE_TYPE_P:
820             default:
821                 return X264_TYPE_P;
822         }
823     }
824     else
825     {
826         return X264_TYPE_AUTO;
827     }
828 }
829
830 /* After encoding one frame, save stats and update ratecontrol state */
831 void x264_ratecontrol_end( x264_t *h, int bits )
832 {
833     x264_ratecontrol_t *rc = h->rc;
834     const int *mbs = h->stat.frame.i_mb_count;
835     int i;
836
837     x264_cpu_restore( h->param.cpu );
838
839     h->stat.frame.i_mb_count_skip = mbs[P_SKIP] + mbs[B_SKIP];
840     h->stat.frame.i_mb_count_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
841     h->stat.frame.i_mb_count_p = mbs[P_L0] + mbs[P_8x8];
842     for( i = B_DIRECT; i < B_8x8; i++ )
843         h->stat.frame.i_mb_count_p += mbs[i];
844
845     if( h->mb.b_variable_qp )
846         rc->qpa /= h->mb.i_mb_count;
847     else
848         rc->qpa = rc->qp;
849     h->fdec->f_qp_avg = rc->qpa;
850
851     if( h->param.rc.b_stat_write )
852     {
853         char c_type = h->sh.i_type==SLICE_TYPE_I ? (h->fenc->i_poc==0 ? 'I' : 'i')
854                     : h->sh.i_type==SLICE_TYPE_P ? 'P'
855                     : h->fenc->b_kept_as_ref ? 'B' : 'b';
856         int dir_frame = h->stat.frame.i_direct_score[1] - h->stat.frame.i_direct_score[0];
857         int dir_avg = h->stat.i_direct_score[1] - h->stat.i_direct_score[0];
858         char c_direct = h->mb.b_direct_auto_write ?
859                         ( dir_frame>0 ? 's' : dir_frame<0 ? 't' : 
860                           dir_avg>0 ? 's' : dir_avg<0 ? 't' : '-' )
861                         : '-';
862         fprintf( rc->p_stat_file_out,
863                  "in:%d out:%d type:%c q:%.2f itex:%d ptex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c;\n",
864                  h->fenc->i_frame, h->i_frame,
865                  c_type, rc->qpa,
866                  h->stat.frame.i_itex_bits, h->stat.frame.i_ptex_bits,
867                  h->stat.frame.i_hdr_bits, h->stat.frame.i_misc_bits,
868                  h->stat.frame.i_mb_count_i,
869                  h->stat.frame.i_mb_count_p,
870                  h->stat.frame.i_mb_count_skip,
871                  c_direct);
872     }
873
874     if( rc->b_abr )
875     {
876         if( h->sh.i_type != SLICE_TYPE_B )
877             rc->cplxr_sum += bits * qp2qscale(rc->qpa) / rc->last_rceq;
878         else
879         {
880             /* Depends on the fact that B-frame's QP is an offset from the following P-frame's.
881              * Not perfectly accurate with B-refs, but good enough. */
882             rc->cplxr_sum += bits * qp2qscale(rc->qpa) / (rc->last_rceq * fabs(h->param.rc.f_pb_factor));
883         }
884         rc->cplxr_sum *= rc->cbr_decay;
885         rc->wanted_bits_window += rc->bitrate / rc->fps;
886         rc->wanted_bits_window *= rc->cbr_decay;
887
888         if( h->param.i_threads == 1 )
889             accum_p_qp_update( h, rc->qpa );
890     }
891
892     if( rc->b_2pass )
893     {
894         rc->expected_bits_sum += qscale2bits( rc->rce, qp2qscale(rc->rce->new_qp) );
895     }
896
897     if( h->mb.b_variable_qp )
898     {
899         if( h->sh.i_type == SLICE_TYPE_B )
900         {
901             rc->bframe_bits += bits;
902             if( !h->frames.current[0] || !IS_X264_TYPE_B(h->frames.current[0]->i_type) )
903             {
904                 update_predictor( rc->pred_b_from_p, qp2qscale(rc->qpa),
905                                   h->fref1[h->i_ref1-1]->i_satd, rc->bframe_bits / rc->bframes );
906                 rc->bframe_bits = 0;
907             }
908         }
909     }
910
911     update_vbv( h, bits );
912 }
913
914 /****************************************************************************
915  * 2 pass functions
916  ***************************************************************************/
917
918 double x264_eval( char *s, double *const_value, const char **const_name,
919                   double (**func1)(void *, double), const char **func1_name,
920                   double (**func2)(void *, double, double), char **func2_name,
921                   void *opaque );
922
923 /**
924  * modify the bitrate curve from pass1 for one frame
925  */
926 static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor, int frame_num)
927 {
928     x264_ratecontrol_t *rcc= h->rc;
929     const int pict_type = rce->pict_type;
930     double q;
931     x264_zone_t *zone = get_zone( h, frame_num );
932
933     double const_values[]={
934         rce->i_tex_bits * rce->qscale,
935         rce->p_tex_bits * rce->qscale,
936         (rce->i_tex_bits + rce->p_tex_bits) * rce->qscale,
937         rce->mv_bits * rce->qscale,
938         (double)rce->i_count / rcc->nmb,
939         (double)rce->p_count / rcc->nmb,
940         (double)rce->s_count / rcc->nmb,
941         rce->pict_type == SLICE_TYPE_I,
942         rce->pict_type == SLICE_TYPE_P,
943         rce->pict_type == SLICE_TYPE_B,
944         h->param.rc.f_qcompress,
945         rcc->i_cplx_sum[SLICE_TYPE_I] / rcc->frame_count[SLICE_TYPE_I],
946         rcc->i_cplx_sum[SLICE_TYPE_P] / rcc->frame_count[SLICE_TYPE_P],
947         rcc->p_cplx_sum[SLICE_TYPE_P] / rcc->frame_count[SLICE_TYPE_P],
948         rcc->p_cplx_sum[SLICE_TYPE_B] / rcc->frame_count[SLICE_TYPE_B],
949         (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / rcc->frame_count[pict_type],
950         rce->blurred_complexity,
951         0
952     };
953     static const char *const_names[]={
954         "iTex",
955         "pTex",
956         "tex",
957         "mv",
958         "iCount",
959         "pCount",
960         "sCount",
961         "isI",
962         "isP",
963         "isB",
964         "qComp",
965         "avgIITex",
966         "avgPITex",
967         "avgPPTex",
968         "avgBPTex",
969         "avgTex",
970         "blurCplx",
971         NULL
972     };
973     static double (*func1[])(void *, double)={
974 //      (void *)bits2qscale,
975         (void *)qscale2bits,
976         NULL
977     };
978     static const char *func1_names[]={
979 //      "bits2qp",
980         "qp2bits",
981         NULL
982     };
983
984     q = x264_eval((char*)h->param.rc.psz_rc_eq, const_values, const_names, func1, func1_names, NULL, NULL, rce);
985
986     // avoid NaN's in the rc_eq
987     if(!isfinite(q) || rce->i_tex_bits + rce->p_tex_bits + rce->mv_bits == 0)
988         q = rcc->last_qscale;
989     else {
990         rcc->last_rceq = q;
991         q /= rate_factor;
992         rcc->last_qscale = q;
993     }
994
995     if( zone )
996     {
997         if( zone->b_force_qp )
998             q = qp2qscale(zone->i_qp);
999         else
1000             q /= zone->f_bitrate_factor;
1001     }
1002
1003     return q;
1004 }
1005
1006 static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
1007 {
1008     x264_ratecontrol_t *rcc = h->rc;
1009     const int pict_type = rce->pict_type;
1010
1011     // force I/B quants as a function of P quants
1012     const double last_p_q    = rcc->last_qscale_for[SLICE_TYPE_P];
1013     const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
1014     if( pict_type == SLICE_TYPE_I )
1015     {
1016         double iq = q;
1017         double pq = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
1018         double ip_factor = fabs( h->param.rc.f_ip_factor );
1019         /* don't apply ip_factor if the following frame is also I */
1020         if( rcc->accum_p_norm <= 0 )
1021             q = iq;
1022         else if( h->param.rc.f_ip_factor < 0 )
1023             q = iq / ip_factor;
1024         else if( rcc->accum_p_norm >= 1 )
1025             q = pq / ip_factor;
1026         else
1027             q = rcc->accum_p_norm * pq / ip_factor + (1 - rcc->accum_p_norm) * iq;
1028     }
1029     else if( pict_type == SLICE_TYPE_B )
1030     {
1031         if( h->param.rc.f_pb_factor > 0 )
1032             q = last_non_b_q;
1033         if( !rce->kept_as_ref )
1034             q *= fabs( h->param.rc.f_pb_factor );
1035     }
1036     else if( pict_type == SLICE_TYPE_P
1037              && rcc->last_non_b_pict_type == SLICE_TYPE_P
1038              && rce->i_tex_bits + rce->p_tex_bits == 0 )
1039     {
1040         q = last_p_q;
1041     }
1042
1043     /* last qscale / qdiff stuff */
1044     if(rcc->last_non_b_pict_type==pict_type
1045        && (pict_type!=SLICE_TYPE_I || rcc->last_accum_p_norm < 1))
1046     {
1047         double last_q = rcc->last_qscale_for[pict_type];
1048         double max_qscale = last_q * rcc->lstep;
1049         double min_qscale = last_q / rcc->lstep;
1050
1051         if     (q > max_qscale) q = max_qscale;
1052         else if(q < min_qscale) q = min_qscale;
1053     }
1054
1055     rcc->last_qscale_for[pict_type] = q;
1056     if(pict_type!=SLICE_TYPE_B)
1057         rcc->last_non_b_pict_type = pict_type;
1058     if(pict_type==SLICE_TYPE_I)
1059     {
1060         rcc->last_accum_p_norm = rcc->accum_p_norm;
1061         rcc->accum_p_norm = 0;
1062         rcc->accum_p_qp = 0;
1063     }
1064     if(pict_type==SLICE_TYPE_P)
1065     {
1066         float mask = 1 - pow( (float)rce->i_count / rcc->nmb, 2 );
1067         rcc->accum_p_qp   = mask * (qscale2qp(q) + rcc->accum_p_qp);
1068         rcc->accum_p_norm = mask * (1 + rcc->accum_p_norm);
1069     }
1070     return q;
1071 }
1072
1073 static double predict_size( predictor_t *p, double q, double var )
1074 {
1075      return p->coeff*var / (q*p->count);
1076 }
1077
1078 static void update_predictor( predictor_t *p, double q, double var, double bits )
1079 {
1080     if( var < 10 )
1081         return;
1082     p->count *= p->decay;
1083     p->coeff *= p->decay;
1084     p->count ++;
1085     p->coeff += bits*q / var;
1086 }
1087
1088 // update VBV after encoding a frame
1089 static void update_vbv( x264_t *h, int bits )
1090 {
1091     x264_ratecontrol_t *rcc = h->rc;
1092     x264_ratecontrol_t *rct = h->thread[0]->rc;
1093
1094     if( rcc->last_satd >= h->mb.i_mb_count )
1095         update_predictor( &rct->pred[h->sh.i_type], qp2qscale(rcc->qpa), rcc->last_satd, bits );
1096
1097     if( !rcc->b_vbv )
1098         return;
1099
1100     rct->buffer_fill_final += rct->buffer_rate - bits;
1101     if( rct->buffer_fill_final < 0 && !rct->b_2pass )
1102         x264_log( h, X264_LOG_WARNING, "VBV underflow (%.0f bits)\n", rct->buffer_fill_final );
1103     rct->buffer_fill_final = x264_clip3( rct->buffer_fill_final, 0, rct->buffer_size );
1104 }
1105
1106 // provisionally update VBV according to the planned size of all frames currently in progress
1107 static void update_vbv_plan( x264_t *h )
1108 {
1109     x264_ratecontrol_t *rcc = h->rc;
1110     rcc->buffer_fill = h->thread[0]->rc->buffer_fill_final;
1111     if( h->param.i_threads > 1 )
1112     {
1113         int j = h->rc - h->thread[0]->rc;
1114         int i;
1115         for( i=1; i<h->param.i_threads; i++ )
1116         {
1117             x264_t *t = h->thread[ (j+i)%h->param.i_threads ];
1118             double bits = t->rc->frame_size_planned;
1119             if( !t->b_thread_active )
1120                 continue;
1121             rcc->buffer_fill += rcc->buffer_rate - bits;
1122             rcc->buffer_fill = x264_clip3( rcc->buffer_fill, 0, rcc->buffer_size );
1123         }
1124     }
1125 }
1126
1127 // apply VBV constraints and clip qscale to between lmin and lmax
1128 static double clip_qscale( x264_t *h, int pict_type, double q )
1129 {
1130     x264_ratecontrol_t *rcc = h->rc;
1131     double lmin = rcc->lmin[pict_type];
1132     double lmax = rcc->lmax[pict_type];
1133     double q0 = q;
1134
1135     /* B-frames are not directly subject to VBV,
1136      * since they are controlled by the P-frames' QPs.
1137      * FIXME: in 2pass we could modify previous frames' QP too,
1138      *        instead of waiting for the buffer to fill */
1139     if( rcc->b_vbv &&
1140         ( pict_type == SLICE_TYPE_P ||
1141           ( pict_type == SLICE_TYPE_I && rcc->last_non_b_pict_type == SLICE_TYPE_I ) ) )
1142     {
1143         if( rcc->buffer_fill/rcc->buffer_size < 0.5 )
1144             q /= x264_clip3f( 2.0*rcc->buffer_fill/rcc->buffer_size, 0.5, 1.0 );
1145     }
1146
1147     if( rcc->b_vbv && rcc->last_satd > 0 )
1148     {
1149         /* Now a hard threshold to make sure the frame fits in VBV.
1150          * This one is mostly for I-frames. */
1151         double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
1152         double qf = 1.0;
1153         if( bits > rcc->buffer_fill/2 )
1154             qf = x264_clip3f( rcc->buffer_fill/(2*bits), 0.2, 1.0 );
1155         q /= qf;
1156         bits *= qf;
1157         if( bits < rcc->buffer_rate/2 )
1158             q *= bits*2/rcc->buffer_rate;
1159         q = X264_MAX( q0, q );
1160
1161         /* Check B-frame complexity, and use up any bits that would
1162          * overflow before the next P-frame. */
1163         if( h->sh.i_type == SLICE_TYPE_P )
1164         {
1165             int nb = rcc->bframes;
1166             double pbbits = bits;
1167             double bbits = predict_size( rcc->pred_b_from_p, q * h->param.rc.f_pb_factor, rcc->last_satd );
1168             double space;
1169
1170             if( bbits > rcc->buffer_rate )
1171                 nb = 0;
1172             pbbits += nb * bbits;
1173
1174             space = rcc->buffer_fill + (1+nb)*rcc->buffer_rate - rcc->buffer_size;
1175             if( pbbits < space )
1176             {
1177                 q *= X264_MAX( pbbits / space,
1178                                bits / (0.5 * rcc->buffer_size) );
1179             }
1180             q = X264_MAX( q0-5, q );
1181         }
1182
1183         if( !rcc->b_vbv_min_rate )
1184             q = X264_MAX( q0, q );
1185     }
1186
1187     if(lmin==lmax)
1188         return lmin;
1189     else if(rcc->b_2pass)
1190     {
1191         double min2 = log(lmin);
1192         double max2 = log(lmax);
1193         q = (log(q) - min2)/(max2-min2) - 0.5;
1194         q = 1.0/(1.0 + exp(-4*q));
1195         q = q*(max2-min2) + min2;
1196         return exp(q);
1197     }
1198     else
1199         return x264_clip3f(q, lmin, lmax);
1200 }
1201
1202 // update qscale for 1 frame based on actual bits used so far
1203 static float rate_estimate_qscale( x264_t *h )
1204 {
1205     float q;
1206     x264_ratecontrol_t *rcc = h->rc;
1207     ratecontrol_entry_t rce;
1208     int pict_type = h->sh.i_type;
1209     double lmin = rcc->lmin[pict_type];
1210     double lmax = rcc->lmax[pict_type];
1211     int64_t total_bits = 8*(h->stat.i_slice_size[SLICE_TYPE_I]
1212                           + h->stat.i_slice_size[SLICE_TYPE_P]
1213                           + h->stat.i_slice_size[SLICE_TYPE_B]);
1214
1215     if( rcc->b_2pass )
1216     {
1217         rce = *rcc->rce;
1218         if(pict_type != rce.pict_type)
1219         {
1220             x264_log(h, X264_LOG_ERROR, "slice=%c but 2pass stats say %c\n",
1221                      slice_type_to_char[pict_type], slice_type_to_char[rce.pict_type]);
1222         }
1223     }
1224
1225     if( pict_type == SLICE_TYPE_B )
1226     {
1227         /* B-frames don't have independent ratecontrol, but rather get the
1228          * average QP of the two adjacent P-frames + an offset */
1229
1230         int i0 = IS_X264_TYPE_I(h->fref0[0]->i_type);
1231         int i1 = IS_X264_TYPE_I(h->fref1[0]->i_type);
1232         int dt0 = abs(h->fenc->i_poc - h->fref0[0]->i_poc);
1233         int dt1 = abs(h->fenc->i_poc - h->fref1[0]->i_poc);
1234         float q0 = h->fref0[0]->f_qp_avg;
1235         float q1 = h->fref1[0]->f_qp_avg;
1236
1237         if( h->fref0[0]->i_type == X264_TYPE_BREF )
1238             q0 -= rcc->pb_offset/2;
1239         if( h->fref1[0]->i_type == X264_TYPE_BREF )
1240             q1 -= rcc->pb_offset/2;
1241
1242         if(i0 && i1)
1243             q = (q0 + q1) / 2 + rcc->ip_offset;
1244         else if(i0)
1245             q = q1;
1246         else if(i1)
1247             q = q0;
1248         else
1249             q = (q0*dt1 + q1*dt0) / (dt0 + dt1);
1250
1251         if(h->fenc->b_kept_as_ref)
1252             q += rcc->pb_offset/2;
1253         else
1254             q += rcc->pb_offset;
1255
1256         rcc->frame_size_planned = predict_size( rcc->pred_b_from_p, q, h->fref1[h->i_ref1-1]->i_satd );
1257         rcc->last_satd = 0;
1258         return qp2qscale(q);
1259     }
1260     else
1261     {
1262         double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate;
1263         if( rcc->b_2pass )
1264         {
1265             //FIXME adjust abr_buffer based on distance to the end of the video
1266             int64_t diff = total_bits - (int64_t)rce.expected_bits;
1267             q = rce.new_qscale;
1268             q /= x264_clip3f((double)(abr_buffer - diff) / abr_buffer, .5, 2);
1269             if( h->fenc->i_frame > 30 )
1270             {
1271                 /* Adjust quant based on the difference between
1272                  * achieved and expected bitrate so far */
1273                 double time = (double)h->fenc->i_frame / rcc->num_entries;
1274                 double w = x264_clip3f( time*100, 0.0, 1.0 );
1275                 q *= pow( (double)total_bits / rcc->expected_bits_sum, w );
1276             }
1277             q = x264_clip3f( q, lmin, lmax );
1278         }
1279         else /* 1pass ABR */
1280         {
1281             /* Calculate the quantizer which would have produced the desired
1282              * average bitrate if it had been applied to all frames so far.
1283              * Then modulate that quant based on the current frame's complexity
1284              * relative to the average complexity so far (using the 2pass RCEQ).
1285              * Then bias the quant up or down if total size so far was far from
1286              * the target.
1287              * Result: Depending on the value of rate_tolerance, there is a
1288              * tradeoff between quality and bitrate precision. But at large
1289              * tolerances, the bit distribution approaches that of 2pass. */
1290
1291             double wanted_bits, overflow=1, lmin, lmax;
1292
1293             rcc->last_satd = x264_rc_analyse_slice( h );
1294             rcc->short_term_cplxsum *= 0.5;
1295             rcc->short_term_cplxcount *= 0.5;
1296             rcc->short_term_cplxsum += rcc->last_satd;
1297             rcc->short_term_cplxcount ++;
1298
1299             rce.p_tex_bits = rcc->last_satd;
1300             rce.blurred_complexity = rcc->short_term_cplxsum / rcc->short_term_cplxcount;
1301             rce.i_tex_bits = 0;
1302             rce.mv_bits = 0;
1303             rce.p_count = rcc->nmb;
1304             rce.i_count = 0;
1305             rce.s_count = 0;
1306             rce.qscale = 1;
1307             rce.pict_type = pict_type;
1308
1309             if( h->param.rc.i_rc_method == X264_RC_CRF )
1310             {
1311                 q = get_qscale( h, &rce, rcc->rate_factor_constant, h->fenc->i_frame );
1312             }
1313             else
1314             {
1315                 int i_frame_done = h->fenc->i_frame + 1 - h->param.i_threads;
1316
1317                 q = get_qscale( h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame );
1318
1319                 // FIXME is it simpler to keep track of wanted_bits in ratecontrol_end?
1320                 wanted_bits = i_frame_done * rcc->bitrate / rcc->fps;
1321                 if( wanted_bits > 0 )
1322                 {
1323                     abr_buffer *= X264_MAX( 1, sqrt(i_frame_done/25) );
1324                     overflow = x264_clip3f( 1.0 + (total_bits - wanted_bits) / abr_buffer, .5, 2 );
1325                     q *= overflow;
1326                 }
1327             }
1328
1329             if( pict_type == SLICE_TYPE_I && h->param.i_keyint_max > 1
1330                 /* should test _next_ pict type, but that isn't decided yet */
1331                 && rcc->last_non_b_pict_type != SLICE_TYPE_I )
1332             {
1333                 q = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
1334                 q /= fabs( h->param.rc.f_ip_factor );
1335             }
1336             else if( h->i_frame > 0 )
1337             {
1338                 /* Asymmetric clipping, because symmetric would prevent
1339                  * overflow control in areas of rapidly oscillating complexity */
1340                 lmin = rcc->last_qscale_for[pict_type] / rcc->lstep;
1341                 lmax = rcc->last_qscale_for[pict_type] * rcc->lstep;
1342                 if( overflow > 1.1 && h->i_frame > 3 )
1343                     lmax *= rcc->lstep;
1344                 else if( overflow < 0.9 )
1345                     lmin /= rcc->lstep;
1346
1347                 q = x264_clip3f(q, lmin, lmax);
1348             }
1349             else if( h->param.rc.i_rc_method == X264_RC_CRF )
1350             {
1351                 q = qp2qscale( ABR_INIT_QP ) / fabs( h->param.rc.f_ip_factor );
1352             }
1353
1354             //FIXME use get_diff_limited_q() ?
1355             q = clip_qscale( h, pict_type, q );
1356         }
1357
1358         rcc->last_qscale_for[pict_type] =
1359         rcc->last_qscale = q;
1360
1361         if( !rcc->b_2pass && h->fenc->i_frame == 0 )
1362             rcc->last_qscale_for[SLICE_TYPE_P] = q;
1363
1364         rcc->frame_size_planned = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
1365         return q;
1366     }
1367 }
1368
1369 void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
1370 {
1371     if( cur != prev )
1372     {
1373 #define COPY(var) memcpy(&cur->rc->var, &prev->rc->var, sizeof(cur->rc->var))
1374         /* these vars are updated in x264_ratecontrol_start()
1375          * so copy them from the context that most recently started (prev)
1376          * to the context that's about to start (cur).
1377          */
1378         COPY(accum_p_qp);
1379         COPY(accum_p_norm);
1380         COPY(last_satd);
1381         COPY(last_rceq);
1382         COPY(last_qscale_for);
1383         COPY(last_non_b_pict_type);
1384         COPY(short_term_cplxsum);
1385         COPY(short_term_cplxcount);
1386         COPY(bframes);
1387 #undef COPY
1388     }
1389     if( cur != next )
1390     {
1391 #define COPY(var) next->rc->var = cur->rc->var
1392         /* these vars are updated in x264_ratecontrol_end()
1393          * so copy them from the context that most recently ended (cur)
1394          * to the context that's about to end (next)
1395          */
1396         COPY(cplxr_sum);
1397         COPY(expected_bits_sum);
1398         COPY(wanted_bits_window);
1399         COPY(bframe_bits);
1400 #undef COPY
1401     }
1402     //FIXME row_preds[] (not strictly necessary, but would improve prediction)
1403     /* the rest of the variables are either constant or thread-local */
1404 }
1405
1406 static int init_pass2( x264_t *h )
1407 {
1408     x264_ratecontrol_t *rcc = h->rc;
1409     uint64_t all_const_bits = 0;
1410     uint64_t all_available_bits = (uint64_t)(h->param.rc.i_bitrate * 1000 * (double)rcc->num_entries / rcc->fps);
1411     double rate_factor, step, step_mult;
1412     double qblur = h->param.rc.f_qblur;
1413     double cplxblur = h->param.rc.f_complexity_blur;
1414     const int filter_size = (int)(qblur*4) | 1;
1415     double expected_bits;
1416     double *qscale, *blurred_qscale;
1417     int i;
1418
1419     /* find total/average complexity & const_bits */
1420     for(i=0; i<rcc->num_entries; i++){
1421         ratecontrol_entry_t *rce = &rcc->entry[i];
1422         all_const_bits += rce->misc_bits;
1423         rcc->i_cplx_sum[rce->pict_type] += rce->i_tex_bits * rce->qscale;
1424         rcc->p_cplx_sum[rce->pict_type] += rce->p_tex_bits * rce->qscale;
1425         rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits * rce->qscale;
1426         rcc->frame_count[rce->pict_type] ++;
1427     }
1428
1429     if( all_available_bits < all_const_bits)
1430     {
1431         x264_log(h, X264_LOG_ERROR, "requested bitrate is too low. estimated minimum is %d kbps\n",
1432                  (int)(all_const_bits * rcc->fps / (rcc->num_entries * 1000)));
1433         return -1;
1434     }
1435
1436     /* Blur complexities, to reduce local fluctuation of QP.
1437      * We don't blur the QPs directly, because then one very simple frame
1438      * could drag down the QP of a nearby complex frame and give it more
1439      * bits than intended. */
1440     for(i=0; i<rcc->num_entries; i++){
1441         ratecontrol_entry_t *rce = &rcc->entry[i];
1442         double weight_sum = 0;
1443         double cplx_sum = 0;
1444         double weight = 1.0;
1445         int j;
1446         /* weighted average of cplx of future frames */
1447         for(j=1; j<cplxblur*2 && j<rcc->num_entries-i; j++){
1448             ratecontrol_entry_t *rcj = &rcc->entry[i+j];
1449             weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 );
1450             if(weight < .0001)
1451                 break;
1452             weight_sum += weight;
1453             cplx_sum += weight * (qscale2bits(rcj, 1) - rcj->misc_bits);
1454         }
1455         /* weighted average of cplx of past frames */
1456         weight = 1.0;
1457         for(j=0; j<=cplxblur*2 && j<=i; j++){
1458             ratecontrol_entry_t *rcj = &rcc->entry[i-j];
1459             weight_sum += weight;
1460             cplx_sum += weight * (qscale2bits(rcj, 1) - rcj->misc_bits);
1461             weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 );
1462             if(weight < .0001)
1463                 break;
1464         }
1465         rce->blurred_complexity = cplx_sum / weight_sum;
1466     }
1467
1468     qscale = x264_malloc(sizeof(double)*rcc->num_entries);
1469     if(filter_size > 1)
1470         blurred_qscale = x264_malloc(sizeof(double)*rcc->num_entries);
1471     else
1472         blurred_qscale = qscale;
1473
1474     /* Search for a factor which, when multiplied by the RCEQ values from
1475      * each frame, adds up to the desired total size.
1476      * There is no exact closed-form solution because of VBV constraints and
1477      * because qscale2bits is not invertible, but we can start with the simple
1478      * approximation of scaling the 1st pass by the ratio of bitrates.
1479      * The search range is probably overkill, but speed doesn't matter here. */
1480
1481     expected_bits = 1;
1482     for(i=0; i<rcc->num_entries; i++)
1483         expected_bits += qscale2bits(&rcc->entry[i], get_qscale(h, &rcc->entry[i], 1.0, i));
1484     step_mult = all_available_bits / expected_bits;
1485
1486     rate_factor = 0;
1487     for(step = 1E4 * step_mult; step > 1E-7 * step_mult; step *= 0.5){
1488         expected_bits = 0;
1489         rate_factor += step;
1490
1491         rcc->last_non_b_pict_type = -1;
1492         rcc->last_accum_p_norm = 1;
1493         rcc->accum_p_norm = 0;
1494         rcc->buffer_fill = rcc->buffer_size * h->param.rc.f_vbv_buffer_init;
1495
1496         /* find qscale */
1497         for(i=0; i<rcc->num_entries; i++){
1498             qscale[i] = get_qscale(h, &rcc->entry[i], rate_factor, i);
1499         }
1500
1501         /* fixed I/B qscale relative to P */
1502         for(i=rcc->num_entries-1; i>=0; i--){
1503             qscale[i] = get_diff_limited_q(h, &rcc->entry[i], qscale[i]);
1504             assert(qscale[i] >= 0);
1505         }
1506
1507         /* smooth curve */
1508         if(filter_size > 1){
1509             assert(filter_size%2==1);
1510             for(i=0; i<rcc->num_entries; i++){
1511                 ratecontrol_entry_t *rce = &rcc->entry[i];
1512                 int j;
1513                 double q=0.0, sum=0.0;
1514
1515                 for(j=0; j<filter_size; j++){
1516                     int index = i+j-filter_size/2;
1517                     double d = index-i;
1518                     double coeff = qblur==0 ? 1.0 : exp(-d*d/(qblur*qblur));
1519                     if(index < 0 || index >= rcc->num_entries) continue;
1520                     if(rce->pict_type != rcc->entry[index].pict_type) continue;
1521                     q += qscale[index] * coeff;
1522                     sum += coeff;
1523                 }
1524                 blurred_qscale[i] = q/sum;
1525             }
1526         }
1527
1528         /* find expected bits */
1529         for(i=0; i<rcc->num_entries; i++){
1530             ratecontrol_entry_t *rce = &rcc->entry[i];
1531             double bits;
1532             rce->new_qscale = clip_qscale(h, rce->pict_type, blurred_qscale[i]);
1533             assert(rce->new_qscale >= 0);
1534             bits = qscale2bits(rce, rce->new_qscale);
1535
1536             rce->expected_bits = expected_bits;
1537             expected_bits += bits;
1538             update_vbv(h, bits);
1539             rcc->buffer_fill = rcc->buffer_fill_final;
1540         }
1541
1542 //printf("expected:%llu available:%llu factor:%lf avgQ:%lf\n", (uint64_t)expected_bits, all_available_bits, rate_factor);
1543         if(expected_bits > all_available_bits) rate_factor -= step;
1544     }
1545
1546     x264_free(qscale);
1547     if(filter_size > 1)
1548         x264_free(blurred_qscale);
1549
1550     if(fabs(expected_bits/all_available_bits - 1.0) > 0.01)
1551     {
1552         double avgq = 0;
1553         for(i=0; i<rcc->num_entries; i++)
1554             avgq += rcc->entry[i].new_qscale;
1555         avgq = qscale2qp(avgq / rcc->num_entries);
1556
1557         x264_log(h, X264_LOG_WARNING, "Error: 2pass curve failed to converge\n");
1558         x264_log(h, X264_LOG_WARNING, "target: %.2f kbit/s, expected: %.2f kbit/s, avg QP: %.4f\n",
1559                  (float)h->param.rc.i_bitrate,
1560                  expected_bits * rcc->fps / (rcc->num_entries * 1000.),
1561                  avgq);
1562         if(expected_bits < all_available_bits && avgq < h->param.rc.i_qp_min + 2)
1563         {
1564             if(h->param.rc.i_qp_min > 0)
1565                 x264_log(h, X264_LOG_WARNING, "try reducing target bitrate or reducing qp_min (currently %d)\n", h->param.rc.i_qp_min);
1566             else
1567                 x264_log(h, X264_LOG_WARNING, "try reducing target bitrate\n");
1568         }
1569         else if(expected_bits > all_available_bits && avgq > h->param.rc.i_qp_max - 2)
1570         {
1571             if(h->param.rc.i_qp_max < 51)
1572                 x264_log(h, X264_LOG_WARNING, "try increasing target bitrate or increasing qp_max (currently %d)\n", h->param.rc.i_qp_max);
1573             else
1574                 x264_log(h, X264_LOG_WARNING, "try increasing target bitrate\n");
1575         }
1576         else
1577             x264_log(h, X264_LOG_WARNING, "internal error\n");
1578     }
1579
1580     return 0;
1581 }
1582
1583