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