]> git.sesse.net Git - x264/blob - encoder/ratecontrol.c
Merge some of adaptive quant and weightp
[x264] / encoder / ratecontrol.c
1 /*****************************************************************************
2  * ratecontrol.c: h264 encoder library (Rate Control)
3  *****************************************************************************
4  * Copyright (C) 2005-2008 x264 project
5  *
6  * Authors: Loren Merritt <lorenm@u.washington.edu>
7  *          Michael Niedermayer <michaelni@gmx.at>
8  *          Gabriel Bouvigne <gabriel.bouvigne@joost.com>
9  *          Fiona Glaser <fiona@x264.com>
10  *          Måns Rullgård <mru@mru.ath.cx>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 #define _ISOC99_SOURCE
28 #undef NDEBUG // always check asserts, the speed effect is far too small to disable them
29 #include <math.h>
30
31 #include "common/common.h"
32 #include "ratecontrol.h"
33 #include "me.h"
34
35 typedef struct
36 {
37     int pict_type;
38     int frame_type;
39     int kept_as_ref;
40     double qscale;
41     int mv_bits;
42     int tex_bits;
43     int misc_bits;
44     uint64_t expected_bits; /*total expected bits up to the current frame (current one excluded)*/
45     double expected_vbv;
46     double new_qscale;
47     int new_qp;
48     int i_count;
49     int p_count;
50     int s_count;
51     float blurred_complexity;
52     char direct_mode;
53     int16_t weight[2];
54     int16_t i_weight_denom;
55     int refcount[16];
56     int refs;
57     int i_duration;
58     int i_cpb_duration;
59 } ratecontrol_entry_t;
60
61 typedef struct
62 {
63     double coeff;
64     double count;
65     double decay;
66     double offset;
67 } predictor_t;
68
69 struct x264_ratecontrol_t
70 {
71     /* constants */
72     int b_abr;
73     int b_2pass;
74     int b_vbv;
75     int b_vbv_min_rate;
76     double fps;
77     double bitrate;
78     double rate_tolerance;
79     double qcompress;
80     int nmb;                    /* number of macroblocks in a frame */
81     int qp_constant[5];
82
83     /* current frame */
84     ratecontrol_entry_t *rce;
85     int qp;                     /* qp for current frame */
86     float qpm;                  /* qp for current macroblock: precise float for AQ */
87     float qpa_rc;               /* average of macroblocks' qp before aq */
88     float qpa_aq;               /* average of macroblocks' qp after aq */
89     float qp_novbv;             /* QP for the current frame if 1-pass VBV was disabled. */
90     int qp_force;
91
92     /* VBV stuff */
93     double buffer_size;
94     double buffer_fill_final;   /* real buffer as of the last finished frame */
95     double buffer_fill;         /* planned buffer, if all in-progress frames hit their bit budget */
96     double buffer_rate;         /* # of bits added to buffer_fill after each frame */
97     double vbv_max_rate;        /* # of bits added to buffer_fill per second */
98     predictor_t *pred;          /* predict frame size from satd */
99     int single_frame_vbv;
100     double rate_factor_max_increment; /* Don't allow RF above (CRF + this value). */
101
102     /* ABR stuff */
103     int    last_satd;
104     double last_rceq;
105     double cplxr_sum;           /* sum of bits*qscale/rceq */
106     double expected_bits_sum;   /* sum of qscale2bits after rceq, ratefactor, and overflow, only includes finished frames */
107     double wanted_bits_window;  /* target bitrate * window */
108     double cbr_decay;
109     double short_term_cplxsum;
110     double short_term_cplxcount;
111     double rate_factor_constant;
112     double ip_offset;
113     double pb_offset;
114
115     /* 2pass stuff */
116     FILE *p_stat_file_out;
117     char *psz_stat_file_tmpname;
118     FILE *p_mbtree_stat_file_out;
119     char *psz_mbtree_stat_file_tmpname;
120     char *psz_mbtree_stat_file_name;
121     FILE *p_mbtree_stat_file_in;
122
123     int num_entries;            /* number of ratecontrol_entry_ts */
124     ratecontrol_entry_t *entry; /* FIXME: copy needed data and free this once init is done */
125     double last_qscale;
126     double last_qscale_for[5];  /* last qscale for a specific pict type, used for max_diff & ipb factor stuff  */
127     int last_non_b_pict_type;
128     double accum_p_qp;          /* for determining I-frame quant */
129     double accum_p_norm;
130     double last_accum_p_norm;
131     double lmin[5];             /* min qscale by frame type */
132     double lmax[5];
133     double lstep;               /* max change (multiply) in qscale per frame */
134     uint16_t *qp_buffer[2];     /* Global buffers for converting MB-tree quantizer data. */
135     int qpbuf_pos;              /* In order to handle pyramid reordering, QP buffer acts as a stack.
136                                  * This value is the current position (0 or 1). */
137
138     /* MBRC stuff */
139     float frame_size_estimated; /* Access to this variable must be atomic: double is
140                                  * not atomic on all arches we care about */
141     double frame_size_maximum;  /* Maximum frame size due to MinCR */
142     double frame_size_planned;
143     double slice_size_planned;
144     double max_frame_error;
145     predictor_t (*row_pred)[2];
146     predictor_t row_preds[5][2];
147     predictor_t *pred_b_from_p; /* predict B-frame size from P-frame satd */
148     int bframes;                /* # consecutive B-frames before this P-frame */
149     int bframe_bits;            /* total cost of those frames */
150
151     int i_zones;
152     x264_zone_t *zones;
153     x264_zone_t *prev_zone;
154
155     /* hrd stuff */
156     int initial_cpb_removal_delay;
157     int initial_cpb_removal_delay_offset;
158     double nrt_first_access_unit; /* nominal removal time */
159     double previous_cpb_final_arrival_time;
160 };
161
162
163 static int parse_zones( x264_t *h );
164 static int init_pass2(x264_t *);
165 static float rate_estimate_qscale( x264_t *h );
166 static int update_vbv( x264_t *h, int bits );
167 static void update_vbv_plan( x264_t *h, int overhead );
168 static double predict_size( predictor_t *p, double q, double var );
169 static void update_predictor( predictor_t *p, double q, double var, double bits );
170
171 #define CMP_OPT_FIRST_PASS( opt, param_val )\
172 {\
173     if( ( p = strstr( opts, opt "=" ) ) && sscanf( p, opt "=%d" , &i ) && param_val != i )\
174     {\
175         x264_log( h, X264_LOG_ERROR, "different " opt " setting than first pass (%d vs %d)\n", param_val, i );\
176         return -1;\
177     }\
178 }
179
180 /* Terminology:
181  * qp = h.264's quantizer
182  * qscale = linearized quantizer = Lagrange multiplier
183  */
184 static inline double qp2qscale( double qp )
185 {
186     return 0.85 * pow( 2.0, ( qp - 12.0 ) / 6.0 );
187 }
188 static inline double qscale2qp( double qscale )
189 {
190     return 12.0 + 6.0 * log2( qscale/0.85 );
191 }
192
193 /* Texture bitrate is not quite inversely proportional to qscale,
194  * probably due the the changing number of SKIP blocks.
195  * MV bits level off at about qp<=12, because the lambda used
196  * for motion estimation is constant there. */
197 static inline double qscale2bits( ratecontrol_entry_t *rce, double qscale )
198 {
199     if( qscale<0.1 )
200         qscale = 0.1;
201     return (rce->tex_bits + .1) * pow( rce->qscale / qscale, 1.1 )
202            + rce->mv_bits * pow( X264_MAX(rce->qscale, 1) / X264_MAX(qscale, 1), 0.5 )
203            + rce->misc_bits;
204 }
205
206 static ALWAYS_INLINE uint32_t ac_energy_plane( x264_t *h, int mb_x, int mb_y, x264_frame_t *frame, int i )
207 {
208     int w = i ? 8 : 16;
209     int shift = i ? 6 : 8;
210     int stride = frame->i_stride[i];
211     int offset = h->mb.b_interlaced
212         ? w * (mb_x + (mb_y&~1) * stride) + (mb_y&1) * stride
213         : w * (mb_x + mb_y * stride);
214     int pix = i ? PIXEL_8x8 : PIXEL_16x16;
215     stride <<= h->mb.b_interlaced;
216     uint64_t res = h->pixf.var[pix]( frame->plane[i] + offset, stride );
217     uint32_t sum = (uint32_t)res;
218     uint32_t ssd = res >> 32;
219     frame->i_pixel_sum[i] += sum;
220     frame->i_pixel_ssd[i] += ssd;
221     return ssd - (sum * sum >> shift);
222 }
223
224 // Find the total AC energy of the block in all planes.
225 static NOINLINE uint32_t x264_ac_energy_mb( x264_t *h, int mb_x, int mb_y, x264_frame_t *frame )
226 {
227     /* This function contains annoying hacks because GCC has a habit of reordering emms
228      * and putting it after floating point ops.  As a result, we put the emms at the end of the
229      * function and make sure that its always called before the float math.  Noinline makes
230      * sure no reordering goes on. */
231     uint32_t var = ac_energy_plane( h, mb_x, mb_y, frame, 0 );
232     var         += ac_energy_plane( h, mb_x, mb_y, frame, 1 );
233     var         += ac_energy_plane( h, mb_x, mb_y, frame, 2 );
234     x264_emms();
235     return var;
236 }
237
238 void x264_adaptive_quant_frame( x264_t *h, x264_frame_t *frame )
239 {
240     /* constants chosen to result in approximately the same overall bitrate as without AQ.
241      * FIXME: while they're written in 5 significant digits, they're only tuned to 2. */
242     float strength;
243     float avg_adj = 0.f;
244     int width = h->sps->i_mb_width;
245     int height = h->sps->i_mb_height;
246     /* Initialize frame stats */
247     for( int i = 0; i < 3; i++ )
248     {
249         frame->i_pixel_sum[i] = 0;
250         frame->i_pixel_ssd[i] = 0;
251     }
252
253     /* Degenerate cases */
254     if( h->param.rc.i_aq_mode == X264_AQ_NONE || h->param.rc.f_aq_strength == 0 )
255     {
256         /* Need to init it anyways for MB tree */
257         if( h->param.rc.f_aq_strength == 0 )
258         {
259             memset( frame->f_qp_offset, 0, h->mb.i_mb_count * sizeof(float) );
260             memset( frame->f_qp_offset_aq, 0, h->mb.i_mb_count * sizeof(float) );
261             if( h->frames.b_have_lowres )
262                 for( int mb_xy = 0; mb_xy < h->mb.i_mb_count; mb_xy++ )
263                     frame->i_inv_qscale_factor[mb_xy] = 256;
264         }
265         /* Need variance data for weighted prediction */
266         if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE || h->param.analyse.i_weighted_pred == X264_WEIGHTP_SMART )
267         {
268             for( int mb_y = 0; mb_y < height; mb_y++ )
269                 for( int mb_x = 0; mb_x < width; mb_x++ )
270                     x264_ac_energy_mb( h, mb_x, mb_y, frame );
271         }
272         else
273             return;
274     }
275     /* Actual adaptive quantization */
276     else
277     {
278         if( h->param.rc.i_aq_mode == X264_AQ_AUTOVARIANCE )
279         {
280             float avg_adj_pow2 = 0.f;
281             for( int mb_y = 0; mb_y < height; mb_y++ )
282                 for( int mb_x = 0; mb_x < width; mb_x++ )
283                 {
284                     uint32_t energy = x264_ac_energy_mb( h, mb_x, mb_y, frame );
285                     float qp_adj = powf( energy + 1, 0.125f );
286                     frame->f_qp_offset[mb_x + mb_y*h->mb.i_mb_stride] = qp_adj;
287                     avg_adj += qp_adj;
288                     avg_adj_pow2 += qp_adj * qp_adj;
289                 }
290             avg_adj /= h->mb.i_mb_count;
291             avg_adj_pow2 /= h->mb.i_mb_count;
292             strength = h->param.rc.f_aq_strength * avg_adj;
293             avg_adj = avg_adj - 0.5f * (avg_adj_pow2 - 14.f) / avg_adj;
294         }
295         else
296             strength = h->param.rc.f_aq_strength * 1.0397f;
297
298         for( int mb_y = 0; mb_y < height; mb_y++ )
299             for( int mb_x = 0; mb_x < width; mb_x++ )
300             {
301                 float qp_adj;
302                 if( h->param.rc.i_aq_mode == X264_AQ_AUTOVARIANCE )
303                 {
304                     qp_adj = frame->f_qp_offset[mb_x + mb_y*h->mb.i_mb_stride];
305                     qp_adj = strength * (qp_adj - avg_adj);
306                 }
307                 else
308                 {
309                     uint32_t energy = x264_ac_energy_mb( h, mb_x, mb_y, frame );
310                     qp_adj = strength * (x264_log2( X264_MAX(energy, 1) ) - 14.427f);
311                 }
312                 frame->f_qp_offset[mb_x + mb_y*h->mb.i_mb_stride] =
313                 frame->f_qp_offset_aq[mb_x + mb_y*h->mb.i_mb_stride] = qp_adj;
314                 if( h->frames.b_have_lowres )
315                     frame->i_inv_qscale_factor[mb_x + mb_y*h->mb.i_mb_stride] = x264_exp2fix8(qp_adj);
316             }
317     }
318
319     /* Remove mean from SSD calculation */
320     for( int i = 0; i < 3; i++ )
321     {
322         uint64_t ssd = frame->i_pixel_ssd[i];
323         uint64_t sum = frame->i_pixel_sum[i];
324         int w = width*16>>!!i;
325         int h = height*16>>!!i;
326         frame->i_pixel_ssd[i] = ssd - (sum * sum + w * h / 2) / (w * h);
327     }
328 }
329
330 int x264_macroblock_tree_read( x264_t *h, x264_frame_t *frame )
331 {
332     x264_ratecontrol_t *rc = h->rc;
333     uint8_t i_type_actual = rc->entry[frame->i_frame].pict_type;
334
335     if( rc->entry[frame->i_frame].kept_as_ref )
336     {
337         uint8_t i_type;
338         if( rc->qpbuf_pos < 0 )
339         {
340             do
341             {
342                 rc->qpbuf_pos++;
343
344                 if( !fread( &i_type, 1, 1, rc->p_mbtree_stat_file_in ) )
345                     goto fail;
346                 if( fread( rc->qp_buffer[rc->qpbuf_pos], sizeof(uint16_t), h->mb.i_mb_count, rc->p_mbtree_stat_file_in ) != h->mb.i_mb_count )
347                     goto fail;
348
349                 if( i_type != i_type_actual && rc->qpbuf_pos == 1 )
350                 {
351                     x264_log(h, X264_LOG_ERROR, "MB-tree frametype %d doesn't match actual frametype %d.\n", i_type, i_type_actual);
352                     return -1;
353                 }
354             } while( i_type != i_type_actual );
355         }
356
357         for( int i = 0; i < h->mb.i_mb_count; i++ )
358         {
359             frame->f_qp_offset[i] = ((float)(int16_t)endian_fix16( rc->qp_buffer[rc->qpbuf_pos][i] )) * (1/256.0);
360             if( h->frames.b_have_lowres )
361                 frame->i_inv_qscale_factor[i] = x264_exp2fix8(frame->f_qp_offset[i]);
362         }
363         rc->qpbuf_pos--;
364     }
365     else
366         x264_adaptive_quant_frame( h, frame );
367     return 0;
368 fail:
369     x264_log(h, X264_LOG_ERROR, "Incomplete MB-tree stats file.\n");
370     return -1;
371 }
372
373 int x264_reference_build_list_optimal( x264_t *h )
374 {
375     ratecontrol_entry_t *rce = h->rc->rce;
376     x264_frame_t *frames[16];
377     x264_weight_t weights[16][3];
378     int refcount[16];
379
380     if( rce->refs != h->i_ref0 )
381         return -1;
382
383     memcpy( frames, h->fref0, sizeof(frames) );
384     memcpy( refcount, rce->refcount, sizeof(refcount) );
385     memcpy( weights, h->fenc->weight, sizeof(weights) );
386     memset( &h->fenc->weight[1][0], 0, sizeof(x264_weight_t[15][3]) );
387
388     /* For now don't reorder ref 0; it seems to lower quality
389        in most cases due to skips. */
390     for( int ref = 1; ref < h->i_ref0; ref++ )
391     {
392         int max = -1;
393         int bestref = 1;
394
395         for( int i = 1; i < h->i_ref0; i++ )
396             /* Favor lower POC as a tiebreaker. */
397             COPY2_IF_GT( max, refcount[i], bestref, i );
398
399         /* FIXME: If there are duplicates from frames other than ref0 then it is possible
400          * that the optimal ordering doesnt place every duplicate. */
401
402         refcount[bestref] = -1;
403         h->fref0[ref] = frames[bestref];
404         memcpy( h->fenc->weight[ref], weights[bestref], sizeof(weights[bestref]) );
405     }
406
407     return 0;
408 }
409
410 static char *x264_strcat_filename( char *input, char *suffix )
411 {
412     char *output = x264_malloc( strlen( input ) + strlen( suffix ) + 1 );
413     if( !output )
414         return NULL;
415     strcpy( output, input );
416     strcat( output, suffix );
417     return output;
418 }
419
420 void x264_ratecontrol_init_reconfigurable( x264_t *h, int b_init )
421 {
422     x264_ratecontrol_t *rc = h->rc;
423     if( !b_init && rc->b_2pass )
424         return;
425
426     if( h->param.rc.i_rc_method == X264_RC_CRF )
427     {
428         /* Arbitrary rescaling to make CRF somewhat similar to QP.
429          * Try to compensate for MB-tree's effects as well. */
430         double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
431         double mbtree_offset = h->param.rc.b_mb_tree ? (1.0-h->param.rc.f_qcompress)*13.5 : 0;
432         rc->rate_factor_constant = pow( base_cplx, 1 - rc->qcompress )
433                                  / qp2qscale( h->param.rc.f_rf_constant + mbtree_offset );
434     }
435
436     if( h->param.rc.i_vbv_max_bitrate > 0 && h->param.rc.i_vbv_buffer_size > 0 )
437     {
438         if( h->param.rc.i_vbv_buffer_size < (int)(h->param.rc.i_vbv_max_bitrate / rc->fps) )
439         {
440             h->param.rc.i_vbv_buffer_size = h->param.rc.i_vbv_max_bitrate / rc->fps;
441             x264_log( h, X264_LOG_WARNING, "VBV buffer size cannot be smaller than one frame, using %d kbit\n",
442                       h->param.rc.i_vbv_buffer_size );
443         }
444
445         /* We don't support changing the ABR bitrate right now,
446            so if the stream starts as CBR, keep it CBR. */
447         if( rc->b_vbv_min_rate )
448             h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
449
450         int vbv_buffer_size = h->param.rc.i_vbv_buffer_size * 1000;
451         int vbv_max_bitrate = h->param.rc.i_vbv_max_bitrate * 1000;
452
453         /* Init HRD */
454         if( h->param.i_nal_hrd && b_init )
455         {
456             h->sps->vui.hrd.i_cpb_cnt = 1;
457             h->sps->vui.hrd.b_cbr_hrd = h->param.i_nal_hrd == X264_NAL_HRD_CBR;
458             h->sps->vui.hrd.i_time_offset_length = 0;
459
460             #define BR_SHIFT  6
461             #define CPB_SHIFT 4
462
463             int bitrate = 1000*h->param.rc.i_vbv_max_bitrate;
464             int bufsize = 1000*h->param.rc.i_vbv_buffer_size;
465
466             // normalize HRD size and rate to the value / scale notation
467             h->sps->vui.hrd.i_bit_rate_scale = x264_clip3( x264_ctz( bitrate ) - BR_SHIFT, 0, 15 );
468             h->sps->vui.hrd.i_bit_rate_value = bitrate >> ( h->sps->vui.hrd.i_bit_rate_scale + BR_SHIFT );
469             h->sps->vui.hrd.i_bit_rate_unscaled = h->sps->vui.hrd.i_bit_rate_value << ( h->sps->vui.hrd.i_bit_rate_scale + BR_SHIFT );
470             h->sps->vui.hrd.i_cpb_size_scale = x264_clip3( x264_ctz( bufsize ) - CPB_SHIFT, 0, 15 );
471             h->sps->vui.hrd.i_cpb_size_value = bufsize >> ( h->sps->vui.hrd.i_cpb_size_scale + CPB_SHIFT );
472             h->sps->vui.hrd.i_cpb_size_unscaled = h->sps->vui.hrd.i_cpb_size_value << ( h->sps->vui.hrd.i_cpb_size_scale + CPB_SHIFT );
473
474             #undef CPB_SHIFT
475             #undef BR_SHIFT
476
477             // arbitrary
478             #define MAX_DURATION 0.5
479
480             int max_cpb_output_delay = h->param.i_keyint_max * MAX_DURATION * h->sps->vui.i_time_scale / h->sps->vui.i_num_units_in_tick;
481             int max_dpb_output_delay = h->sps->vui.i_max_dec_frame_buffering * MAX_DURATION * h->sps->vui.i_time_scale / h->sps->vui.i_num_units_in_tick;
482             int max_delay = (int)(90000.0 * (double)h->sps->vui.hrd.i_cpb_size_unscaled / h->sps->vui.hrd.i_bit_rate_unscaled + 0.5);
483
484             h->sps->vui.hrd.i_initial_cpb_removal_delay_length = 2 + x264_clip3( 32 - x264_clz( max_delay ), 4, 22 );
485             h->sps->vui.hrd.i_cpb_removal_delay_length = x264_clip3( 32 - x264_clz( max_cpb_output_delay ), 4, 32 );
486             h->sps->vui.hrd.i_dpb_output_delay_length  = x264_clip3( 32 - x264_clz( max_dpb_output_delay ), 4, 32 );
487
488             #undef MAX_DURATION
489
490             vbv_buffer_size = X264_MIN( vbv_buffer_size, h->sps->vui.hrd.i_cpb_size_unscaled );
491             vbv_max_bitrate = X264_MIN( vbv_max_bitrate, h->sps->vui.hrd.i_bit_rate_unscaled );
492         }
493         else if( h->param.i_nal_hrd && !b_init )
494         {
495             x264_log( h, X264_LOG_WARNING, "VBV parameters cannot be changed when NAL HRD is in use\n" );
496             return;
497         }
498
499         rc->buffer_rate = vbv_max_bitrate / rc->fps;
500         rc->vbv_max_rate = vbv_max_bitrate;
501         rc->buffer_size = vbv_buffer_size;
502         rc->single_frame_vbv = rc->buffer_rate * 1.1 > rc->buffer_size;
503         rc->cbr_decay = 1.0 - rc->buffer_rate / rc->buffer_size
504                       * 0.5 * X264_MAX(0, 1.5 - rc->buffer_rate * rc->fps / rc->bitrate);
505         if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.f_rf_constant_max )
506         {
507             rc->rate_factor_max_increment = h->param.rc.f_rf_constant_max - h->param.rc.f_rf_constant;
508             if( rc->rate_factor_max_increment <= 0 )
509             {
510                 x264_log( h, X264_LOG_WARNING, "CRF max must be greater than CRF\n" );
511                 rc->rate_factor_max_increment = 0;
512             }
513         }
514         if( b_init )
515         {
516             if( h->param.rc.f_vbv_buffer_init > 1. )
517                 h->param.rc.f_vbv_buffer_init = x264_clip3f( h->param.rc.f_vbv_buffer_init / h->param.rc.i_vbv_buffer_size, 0, 1 );
518             h->param.rc.f_vbv_buffer_init = x264_clip3f( X264_MAX( h->param.rc.f_vbv_buffer_init, rc->buffer_rate / rc->buffer_size ), 0, 1);
519             rc->buffer_fill_final = rc->buffer_size * h->param.rc.f_vbv_buffer_init;
520             rc->b_vbv = 1;
521             rc->b_vbv_min_rate = !rc->b_2pass
522                           && h->param.rc.i_rc_method == X264_RC_ABR
523                           && h->param.rc.i_vbv_max_bitrate <= h->param.rc.i_bitrate;
524         }
525     }
526 }
527
528 int x264_ratecontrol_new( x264_t *h )
529 {
530     x264_ratecontrol_t *rc;
531
532     x264_emms();
533
534     CHECKED_MALLOCZERO( h->rc, h->param.i_threads * sizeof(x264_ratecontrol_t) );
535     rc = h->rc;
536
537     rc->b_abr = h->param.rc.i_rc_method != X264_RC_CQP && !h->param.rc.b_stat_read;
538     rc->b_2pass = h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.b_stat_read;
539
540     /* FIXME: use integers */
541     if( h->param.i_fps_num > 0 && h->param.i_fps_den > 0 )
542         rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den;
543     else
544         rc->fps = 25.0;
545
546     if( h->param.rc.b_mb_tree )
547     {
548         h->param.rc.f_pb_factor = 1;
549         rc->qcompress = 1;
550     }
551     else
552         rc->qcompress = h->param.rc.f_qcompress;
553
554     rc->bitrate = h->param.rc.i_bitrate * 1000.;
555     rc->rate_tolerance = h->param.rc.f_rate_tolerance;
556     rc->nmb = h->mb.i_mb_count;
557     rc->last_non_b_pict_type = -1;
558     rc->cbr_decay = 1.0;
559
560     if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.b_stat_read )
561     {
562         x264_log(h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n");
563         return -1;
564     }
565
566     x264_ratecontrol_init_reconfigurable( h, 1 );
567
568     if( rc->rate_tolerance < 0.01 )
569     {
570         x264_log(h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n");
571         rc->rate_tolerance = 0.01;
572     }
573
574     h->mb.b_variable_qp = rc->b_vbv || h->param.rc.i_aq_mode;
575
576     if( rc->b_abr )
577     {
578         /* FIXME ABR_INIT_QP is actually used only in CRF */
579 #define ABR_INIT_QP ( h->param.rc.i_rc_method == X264_RC_CRF ? h->param.rc.f_rf_constant : 24 )
580         rc->accum_p_norm = .01;
581         rc->accum_p_qp = ABR_INIT_QP * rc->accum_p_norm;
582         /* estimated ratio that produces a reasonable QP for the first I-frame */
583         rc->cplxr_sum = .01 * pow( 7.0e5, rc->qcompress ) * pow( h->mb.i_mb_count, 0.5 );
584         rc->wanted_bits_window = 1.0 * rc->bitrate / rc->fps;
585         rc->last_non_b_pict_type = SLICE_TYPE_I;
586     }
587
588     rc->ip_offset = 6.0 * log2f( h->param.rc.f_ip_factor );
589     rc->pb_offset = 6.0 * log2f( h->param.rc.f_pb_factor );
590     rc->qp_constant[SLICE_TYPE_P] = h->param.rc.i_qp_constant;
591     rc->qp_constant[SLICE_TYPE_I] = x264_clip3( h->param.rc.i_qp_constant - rc->ip_offset + 0.5, 0, 51 );
592     rc->qp_constant[SLICE_TYPE_B] = x264_clip3( h->param.rc.i_qp_constant + rc->pb_offset + 0.5, 0, 51 );
593     h->mb.ip_offset = rc->ip_offset + 0.5;
594
595     rc->lstep = pow( 2, h->param.rc.i_qp_step / 6.0 );
596     rc->last_qscale = qp2qscale( 26 );
597     int num_preds = h->param.b_sliced_threads * h->param.i_threads + 1;
598     CHECKED_MALLOC( rc->pred, 5 * sizeof(predictor_t) * num_preds );
599     CHECKED_MALLOC( rc->pred_b_from_p, sizeof(predictor_t) );
600     for( int i = 0; i < 5; i++ )
601     {
602         rc->last_qscale_for[i] = qp2qscale( ABR_INIT_QP );
603         rc->lmin[i] = qp2qscale( h->param.rc.i_qp_min );
604         rc->lmax[i] = qp2qscale( h->param.rc.i_qp_max );
605         for( int j = 0; j < num_preds; j++ )
606         {
607             rc->pred[i+j*5].coeff= 2.0;
608             rc->pred[i+j*5].count= 1.0;
609             rc->pred[i+j*5].decay= 0.5;
610             rc->pred[i+j*5].offset= 0.0;
611         }
612         for( int j = 0; j < 2; j++ )
613         {
614             rc->row_preds[i][j].coeff= .25;
615             rc->row_preds[i][j].count= 1.0;
616             rc->row_preds[i][j].decay= 0.5;
617             rc->row_preds[i][j].offset= 0.0;
618         }
619     }
620     *rc->pred_b_from_p = rc->pred[0];
621
622     if( parse_zones( h ) < 0 )
623     {
624         x264_log( h, X264_LOG_ERROR, "failed to parse zones\n" );
625         return -1;
626     }
627
628     /* Load stat file and init 2pass algo */
629     if( h->param.rc.b_stat_read )
630     {
631         char *p, *stats_in, *stats_buf;
632
633         /* read 1st pass stats */
634         assert( h->param.rc.psz_stat_in );
635         stats_buf = stats_in = x264_slurp_file( h->param.rc.psz_stat_in );
636         if( !stats_buf )
637         {
638             x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
639             return -1;
640         }
641         if( h->param.rc.b_mb_tree )
642         {
643             char *mbtree_stats_in = x264_strcat_filename( h->param.rc.psz_stat_in, ".mbtree" );
644             if( !mbtree_stats_in )
645                 return -1;
646             rc->p_mbtree_stat_file_in = fopen( mbtree_stats_in, "rb" );
647             x264_free( mbtree_stats_in );
648             if( !rc->p_mbtree_stat_file_in )
649             {
650                 x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open mbtree stats file\n");
651                 return -1;
652             }
653         }
654
655         /* check whether 1st pass options were compatible with current options */
656         if( !strncmp( stats_buf, "#options:", 9 ) )
657         {
658             int i, j;
659             uint32_t k, l;
660             char *opts = stats_buf;
661             stats_in = strchr( stats_buf, '\n' );
662             if( !stats_in )
663                 return -1;
664             *stats_in = '\0';
665             stats_in++;
666             if( sscanf( opts, "#options: %dx%d", &i, &j ) != 2 )
667             {
668                 x264_log( h, X264_LOG_ERROR, "resolution specified in stats file not valid\n" );
669                 return -1;
670             }
671             else if( h->param.rc.b_mb_tree && (i != h->param.i_width || j != h->param.i_height)  )
672             {
673                 x264_log( h, X264_LOG_ERROR, "MB-tree doesn't support different resolution than 1st pass (%dx%d vs %dx%d)\n",
674                           h->param.i_width, h->param.i_height, i, j );
675                 return -1;
676             }
677
678             if( ( p = strstr( opts, "timebase=" ) ) && sscanf( p, "timebase=%u/%u", &k, &l ) != 2 )
679             {
680                 x264_log( h, X264_LOG_ERROR, "timebase specified in stats file not valid\n" );
681                 return -1;
682             }
683             if( k != h->param.i_timebase_num || l != h->param.i_timebase_den )
684             {
685                 x264_log( h, X264_LOG_ERROR, "timebase mismatch with 1st pass (%u/%u vs %u/%u)\n",
686                           h->param.i_timebase_num, h->param.i_timebase_den, k, l );
687                 return -1;
688             }
689
690             CMP_OPT_FIRST_PASS( "weightp", X264_MAX( 0, h->param.analyse.i_weighted_pred ) );
691             CMP_OPT_FIRST_PASS( "bframes", h->param.i_bframe );
692             CMP_OPT_FIRST_PASS( "b_pyramid", h->param.i_bframe_pyramid );
693             CMP_OPT_FIRST_PASS( "intra_refresh", h->param.b_intra_refresh );
694             CMP_OPT_FIRST_PASS( "keyint", h->param.i_keyint_max );
695
696             if( strstr( opts, "qp=0" ) && h->param.rc.i_rc_method == X264_RC_ABR )
697                 x264_log( h, X264_LOG_WARNING, "1st pass was lossless, bitrate prediction will be inaccurate\n" );
698
699             if( !strstr( opts, "direct=3" ) && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
700             {
701                 x264_log( h, X264_LOG_WARNING, "direct=auto not used on the first pass\n" );
702                 h->mb.b_direct_auto_write = 1;
703             }
704
705             if( ( p = strstr( opts, "b_adapt=" ) ) && sscanf( p, "b_adapt=%d", &i ) && i >= X264_B_ADAPT_NONE && i <= X264_B_ADAPT_TRELLIS )
706                 h->param.i_bframe_adaptive = i;
707             else if( h->param.i_bframe )
708             {
709                 x264_log( h, X264_LOG_ERROR, "b_adapt method specified in stats file not valid\n" );
710                 return -1;
711             }
712
713             if( (h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size) && ( p = strstr( opts, "rc_lookahead=" ) ) && sscanf( p, "rc_lookahead=%d", &i ) )
714                 h->param.rc.i_lookahead = i;
715         }
716
717         /* find number of pics */
718         p = stats_in;
719         int num_entries;
720         for( num_entries = -1; p; num_entries++ )
721             p = strchr( p + 1, ';' );
722         if( !num_entries )
723         {
724             x264_log(h, X264_LOG_ERROR, "empty stats file\n");
725             return -1;
726         }
727         rc->num_entries = num_entries;
728
729         if( h->param.i_frame_total < rc->num_entries && h->param.i_frame_total > 0 )
730         {
731             x264_log( h, X264_LOG_WARNING, "2nd pass has fewer frames than 1st pass (%d vs %d)\n",
732                       h->param.i_frame_total, rc->num_entries );
733         }
734         if( h->param.i_frame_total > rc->num_entries )
735         {
736             x264_log( h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d vs %d)\n",
737                       h->param.i_frame_total, rc->num_entries );
738             return -1;
739         }
740
741         CHECKED_MALLOCZERO( rc->entry, rc->num_entries * sizeof(ratecontrol_entry_t) );
742
743         /* init all to skipped p frames */
744         for( int i = 0; i < rc->num_entries; i++ )
745         {
746             ratecontrol_entry_t *rce = &rc->entry[i];
747             rce->pict_type = SLICE_TYPE_P;
748             rce->qscale = rce->new_qscale = qp2qscale( 20 );
749             rce->misc_bits = rc->nmb + 10;
750             rce->new_qp = 0;
751         }
752
753         /* read stats */
754         p = stats_in;
755         for( int i = 0; i < rc->num_entries; i++ )
756         {
757             ratecontrol_entry_t *rce;
758             int frame_number;
759             char pict_type;
760             int e;
761             char *next;
762             float qp;
763             int ref;
764
765             next= strchr(p, ';');
766             if( next )
767                 *next++ = 0; //sscanf is unbelievably slow on long strings
768             e = sscanf( p, " in:%d ", &frame_number );
769
770             if( frame_number < 0 || frame_number >= rc->num_entries )
771             {
772                 x264_log( h, X264_LOG_ERROR, "bad frame number (%d) at stats line %d\n", frame_number, i );
773                 return -1;
774             }
775             rce = &rc->entry[frame_number];
776             rce->direct_mode = 0;
777
778             e += sscanf( p, " in:%*d out:%*d type:%c dur:%d cpbdur:%d q:%f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c",
779                    &pict_type, &rce->i_duration, &rce->i_cpb_duration, &qp, &rce->tex_bits,
780                    &rce->mv_bits, &rce->misc_bits, &rce->i_count, &rce->p_count,
781                    &rce->s_count, &rce->direct_mode );
782
783             p = strstr( p, "ref:" );
784             if( !p )
785                 goto parse_error;
786             p += 4;
787             for( ref = 0; ref < 16; ref++ )
788             {
789                 if( sscanf( p, " %d", &rce->refcount[ref] ) != 1 )
790                     break;
791                 p = strchr( p+1, ' ' );
792                 if( !p )
793                     goto parse_error;
794             }
795             rce->refs = ref;
796
797             /* find weights */
798             rce->i_weight_denom = -1;
799             char *w = strchr( p, 'w' );
800             if( w )
801                 if( sscanf( w, "w:%hd,%hd,%hd", &rce->i_weight_denom, &rce->weight[0], &rce->weight[1] ) != 3 )
802                     rce->i_weight_denom = -1;
803
804             if( pict_type != 'b' )
805                 rce->kept_as_ref = 1;
806             switch( pict_type )
807             {
808                 case 'I':
809                     rce->frame_type = X264_TYPE_IDR;
810                     rce->pict_type  = SLICE_TYPE_I;
811                     break;
812                 case 'i':
813                     rce->frame_type = X264_TYPE_I;
814                     rce->pict_type  = SLICE_TYPE_I;
815                     break;
816                 case 'P':
817                     rce->frame_type = X264_TYPE_P;
818                     rce->pict_type  = SLICE_TYPE_P;
819                     break;
820                 case 'B':
821                     rce->frame_type = X264_TYPE_BREF;
822                     rce->pict_type  = SLICE_TYPE_B;
823                     break;
824                 case 'b':
825                     rce->frame_type = X264_TYPE_B;
826                     rce->pict_type  = SLICE_TYPE_B;
827                     break;
828                 default:  e = -1; break;
829             }
830             if( e < 12 )
831             {
832 parse_error:
833                 x264_log( h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e );
834                 return -1;
835             }
836             rce->qscale = qp2qscale( qp );
837             p = next;
838         }
839
840         x264_free( stats_buf );
841
842         if( h->param.rc.i_rc_method == X264_RC_ABR )
843         {
844             if( init_pass2( h ) < 0 )
845                 return -1;
846         } /* else we're using constant quant, so no need to run the bitrate allocation */
847     }
848
849     /* Open output file */
850     /* If input and output files are the same, output to a temp file
851      * and move it to the real name only when it's complete */
852     if( h->param.rc.b_stat_write )
853     {
854         char *p;
855         rc->psz_stat_file_tmpname = x264_strcat_filename( h->param.rc.psz_stat_out, ".temp" );
856         if( !rc->psz_stat_file_tmpname )
857             return -1;
858
859         rc->p_stat_file_out = fopen( rc->psz_stat_file_tmpname, "wb" );
860         if( rc->p_stat_file_out == NULL )
861         {
862             x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
863             return -1;
864         }
865
866         p = x264_param2string( &h->param, 1 );
867         if( p )
868             fprintf( rc->p_stat_file_out, "#options: %s\n", p );
869         x264_free( p );
870         if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
871         {
872             rc->psz_mbtree_stat_file_tmpname = x264_strcat_filename( h->param.rc.psz_stat_out, ".mbtree.temp" );
873             rc->psz_mbtree_stat_file_name = x264_strcat_filename( h->param.rc.psz_stat_out, ".mbtree" );
874             if( !rc->psz_mbtree_stat_file_tmpname || !rc->psz_mbtree_stat_file_name )
875                 return -1;
876
877             rc->p_mbtree_stat_file_out = fopen( rc->psz_mbtree_stat_file_tmpname, "wb" );
878             if( rc->p_mbtree_stat_file_out == NULL )
879             {
880                 x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open mbtree stats file\n");
881                 return -1;
882             }
883         }
884     }
885
886     if( h->param.rc.b_mb_tree && (h->param.rc.b_stat_read || h->param.rc.b_stat_write) )
887     {
888         CHECKED_MALLOC( rc->qp_buffer[0], h->mb.i_mb_count * sizeof(uint16_t) );
889         if( h->param.i_bframe_pyramid && h->param.rc.b_stat_read )
890             CHECKED_MALLOC( rc->qp_buffer[1], h->mb.i_mb_count * sizeof(uint16_t) );
891         rc->qpbuf_pos = -1;
892     }
893
894     for( int i = 0; i<h->param.i_threads; i++ )
895     {
896         h->thread[i]->rc = rc+i;
897         if( i )
898         {
899             rc[i] = rc[0];
900             h->thread[i]->param = h->param;
901             h->thread[i]->mb.b_variable_qp = h->mb.b_variable_qp;
902         }
903     }
904
905     return 0;
906 fail:
907     return -1;
908 }
909
910 static int parse_zone( x264_t *h, x264_zone_t *z, char *p )
911 {
912     int len = 0;
913     char *tok, UNUSED *saveptr=NULL;
914     z->param = NULL;
915     z->f_bitrate_factor = 1;
916     if( 3 <= sscanf(p, "%u,%u,q=%u%n", &z->i_start, &z->i_end, &z->i_qp, &len) )
917         z->b_force_qp = 1;
918     else if( 3 <= sscanf(p, "%u,%u,b=%f%n", &z->i_start, &z->i_end, &z->f_bitrate_factor, &len) )
919         z->b_force_qp = 0;
920     else if( 2 <= sscanf(p, "%u,%u%n", &z->i_start, &z->i_end, &len) )
921         z->b_force_qp = 0;
922     else
923     {
924         x264_log( h, X264_LOG_ERROR, "invalid zone: \"%s\"\n", p );
925         return -1;
926     }
927     p += len;
928     if( !*p )
929         return 0;
930     CHECKED_MALLOC( z->param, sizeof(x264_param_t) );
931     memcpy( z->param, &h->param, sizeof(x264_param_t) );
932     z->param->param_free = x264_free;
933     while( (tok = strtok_r( p, ",", &saveptr )) )
934     {
935         char *val = strchr( tok, '=' );
936         if( val )
937         {
938             *val = '\0';
939             val++;
940         }
941         if( x264_param_parse( z->param, tok, val ) )
942         {
943             x264_log( h, X264_LOG_ERROR, "invalid zone param: %s = %s\n", tok, val );
944             return -1;
945         }
946         p = NULL;
947     }
948     return 0;
949 fail:
950     return -1;
951 }
952
953 static int parse_zones( x264_t *h )
954 {
955     x264_ratecontrol_t *rc = h->rc;
956     if( h->param.rc.psz_zones && !h->param.rc.i_zones )
957     {
958         char *psz_zones, *p;
959         CHECKED_MALLOC( psz_zones, strlen( h->param.rc.psz_zones )+1 );
960         strcpy( psz_zones, h->param.rc.psz_zones );
961         h->param.rc.i_zones = 1;
962         for( p = psz_zones; *p; p++ )
963             h->param.rc.i_zones += (*p == '/');
964         CHECKED_MALLOC( h->param.rc.zones, h->param.rc.i_zones * sizeof(x264_zone_t) );
965         p = psz_zones;
966         for( int i = 0; i < h->param.rc.i_zones; i++ )
967         {
968             int i_tok = strcspn( p, "/" );
969             p[i_tok] = 0;
970             if( parse_zone( h, &h->param.rc.zones[i], p ) )
971                 return -1;
972             p += i_tok + 1;
973         }
974         x264_free( psz_zones );
975     }
976
977     if( h->param.rc.i_zones > 0 )
978     {
979         for( int i = 0; i < h->param.rc.i_zones; i++ )
980         {
981             x264_zone_t z = h->param.rc.zones[i];
982             if( z.i_start < 0 || z.i_start > z.i_end )
983             {
984                 x264_log( h, X264_LOG_ERROR, "invalid zone: start=%d end=%d\n",
985                           z.i_start, z.i_end );
986                 return -1;
987             }
988             else if( !z.b_force_qp && z.f_bitrate_factor <= 0 )
989             {
990                 x264_log( h, X264_LOG_ERROR, "invalid zone: bitrate_factor=%f\n",
991                           z.f_bitrate_factor );
992                 return -1;
993             }
994         }
995
996         rc->i_zones = h->param.rc.i_zones + 1;
997         CHECKED_MALLOC( rc->zones, rc->i_zones * sizeof(x264_zone_t) );
998         memcpy( rc->zones+1, h->param.rc.zones, (rc->i_zones-1) * sizeof(x264_zone_t) );
999
1000         // default zone to fall back to if none of the others match
1001         rc->zones[0].i_start = 0;
1002         rc->zones[0].i_end = INT_MAX;
1003         rc->zones[0].b_force_qp = 0;
1004         rc->zones[0].f_bitrate_factor = 1;
1005         CHECKED_MALLOC( rc->zones[0].param, sizeof(x264_param_t) );
1006         memcpy( rc->zones[0].param, &h->param, sizeof(x264_param_t) );
1007         for( int i = 1; i < rc->i_zones; i++ )
1008         {
1009             if( !rc->zones[i].param )
1010                 rc->zones[i].param = rc->zones[0].param;
1011         }
1012     }
1013
1014     return 0;
1015 fail:
1016     return -1;
1017 }
1018
1019 static x264_zone_t *get_zone( x264_t *h, int frame_num )
1020 {
1021     for( int i = h->rc->i_zones - 1; i >= 0; i-- )
1022     {
1023         x264_zone_t *z = &h->rc->zones[i];
1024         if( frame_num >= z->i_start && frame_num <= z->i_end )
1025             return z;
1026     }
1027     return NULL;
1028 }
1029
1030 void x264_ratecontrol_summary( x264_t *h )
1031 {
1032     x264_ratecontrol_t *rc = h->rc;
1033     if( rc->b_abr && h->param.rc.i_rc_method == X264_RC_ABR && rc->cbr_decay > .9999 )
1034     {
1035         double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
1036         double mbtree_offset = h->param.rc.b_mb_tree ? (1.0-h->param.rc.f_qcompress)*13.5 : 0;
1037         x264_log( h, X264_LOG_INFO, "final ratefactor: %.2f\n",
1038                   qscale2qp( pow( base_cplx, 1 - rc->qcompress )
1039                              * rc->cplxr_sum / rc->wanted_bits_window ) - mbtree_offset );
1040     }
1041 }
1042
1043 void x264_ratecontrol_delete( x264_t *h )
1044 {
1045     x264_ratecontrol_t *rc = h->rc;
1046     int b_regular_file;
1047
1048     if( rc->p_stat_file_out )
1049     {
1050         b_regular_file = x264_is_regular_file( rc->p_stat_file_out );
1051         fclose( rc->p_stat_file_out );
1052         if( h->i_frame >= rc->num_entries && b_regular_file )
1053             if( rename( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ) != 0 )
1054             {
1055                 x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
1056                           rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out );
1057             }
1058         x264_free( rc->psz_stat_file_tmpname );
1059     }
1060     if( rc->p_mbtree_stat_file_out )
1061     {
1062         b_regular_file = x264_is_regular_file( rc->p_mbtree_stat_file_out );
1063         fclose( rc->p_mbtree_stat_file_out );
1064         if( h->i_frame >= rc->num_entries && b_regular_file )
1065             if( rename( rc->psz_mbtree_stat_file_tmpname, rc->psz_mbtree_stat_file_name ) != 0 )
1066             {
1067                 x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
1068                           rc->psz_mbtree_stat_file_tmpname, rc->psz_mbtree_stat_file_name );
1069             }
1070         x264_free( rc->psz_mbtree_stat_file_tmpname );
1071         x264_free( rc->psz_mbtree_stat_file_name );
1072     }
1073     if( rc->p_mbtree_stat_file_in )
1074         fclose( rc->p_mbtree_stat_file_in );
1075     x264_free( rc->pred );
1076     x264_free( rc->pred_b_from_p );
1077     x264_free( rc->entry );
1078     x264_free( rc->qp_buffer[0] );
1079     x264_free( rc->qp_buffer[1] );
1080     if( rc->zones )
1081     {
1082         x264_free( rc->zones[0].param );
1083         for( int i = 1; i < rc->i_zones; i++ )
1084             if( rc->zones[i].param != rc->zones[0].param && rc->zones[i].param->param_free )
1085                 rc->zones[i].param->param_free( rc->zones[i].param );
1086         x264_free( rc->zones );
1087     }
1088     x264_free( rc );
1089 }
1090
1091 static void accum_p_qp_update( x264_t *h, float qp )
1092 {
1093     x264_ratecontrol_t *rc = h->rc;
1094     rc->accum_p_qp   *= .95;
1095     rc->accum_p_norm *= .95;
1096     rc->accum_p_norm += 1;
1097     if( h->sh.i_type == SLICE_TYPE_I )
1098         rc->accum_p_qp += qp + rc->ip_offset;
1099     else
1100         rc->accum_p_qp += qp;
1101 }
1102
1103 /* Before encoding a frame, choose a QP for it */
1104 void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
1105 {
1106     x264_ratecontrol_t *rc = h->rc;
1107     ratecontrol_entry_t *rce = NULL;
1108     x264_zone_t *zone = get_zone( h, h->fenc->i_frame );
1109     float q;
1110
1111     x264_emms();
1112
1113     if( zone && (!rc->prev_zone || zone->param != rc->prev_zone->param) )
1114         x264_encoder_reconfig( h, zone->param );
1115     rc->prev_zone = zone;
1116
1117     rc->qp_force = i_force_qp;
1118
1119     if( h->param.rc.b_stat_read )
1120     {
1121         int frame = h->fenc->i_frame;
1122         assert( frame >= 0 && frame < rc->num_entries );
1123         rce = h->rc->rce = &h->rc->entry[frame];
1124
1125         if( h->sh.i_type == SLICE_TYPE_B
1126             && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
1127         {
1128             h->sh.b_direct_spatial_mv_pred = ( rce->direct_mode == 's' );
1129             h->mb.b_direct_auto_read = ( rce->direct_mode == 's' || rce->direct_mode == 't' );
1130         }
1131     }
1132
1133     if( rc->b_vbv )
1134     {
1135         memset( h->fdec->i_row_bits, 0, h->sps->i_mb_height * sizeof(int) );
1136         rc->row_pred = &rc->row_preds[h->sh.i_type];
1137         rc->buffer_rate = h->fenc->i_cpb_duration * rc->vbv_max_rate * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1138         update_vbv_plan( h, overhead );
1139
1140         const x264_level_t *l = x264_levels;
1141         while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
1142             l++;
1143
1144         int mincr = l->mincr;
1145
1146         /* Blu-ray requires this */
1147         if( l->level_idc == 41 && h->param.i_nal_hrd )
1148             mincr = 4;
1149
1150         /* The spec has a bizarre special case for the first frame. */
1151         if( h->i_frame == 0 )
1152         {
1153             //384 * ( Max( PicSizeInMbs, fR * MaxMBPS ) + MaxMBPS * ( tr( 0 ) - tr,n( 0 ) ) ) / MinCR
1154             double fr = 1. / 172;
1155             int pic_size_in_mbs = h->sps->i_mb_width * h->sps->i_mb_height;
1156             rc->frame_size_maximum = 384 * 8 * X264_MAX( pic_size_in_mbs, fr*l->mbps ) / mincr;
1157         }
1158         else
1159         {
1160             //384 * MaxMBPS * ( tr( n ) - tr( n - 1 ) ) / MinCR
1161             rc->frame_size_maximum = 384 * 8 * ((double)h->fenc->i_cpb_duration * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale) * l->mbps / mincr;
1162         }
1163     }
1164
1165     if( h->sh.i_type != SLICE_TYPE_B )
1166         rc->bframes = h->fenc->i_bframes;
1167
1168     if( i_force_qp )
1169     {
1170         q = i_force_qp - 1;
1171     }
1172     else if( rc->b_abr )
1173     {
1174         q = qscale2qp( rate_estimate_qscale( h ) );
1175     }
1176     else if( rc->b_2pass )
1177     {
1178         rce->new_qscale = rate_estimate_qscale( h );
1179         q = qscale2qp( rce->new_qscale );
1180     }
1181     else /* CQP */
1182     {
1183         if( h->sh.i_type == SLICE_TYPE_B && h->fdec->b_kept_as_ref )
1184             q = ( rc->qp_constant[ SLICE_TYPE_B ] + rc->qp_constant[ SLICE_TYPE_P ] ) / 2;
1185         else
1186             q = rc->qp_constant[ h->sh.i_type ];
1187
1188         if( zone )
1189         {
1190             if( zone->b_force_qp )
1191                 q += zone->i_qp - rc->qp_constant[SLICE_TYPE_P];
1192             else
1193                 q -= 6*log2f( zone->f_bitrate_factor );
1194         }
1195     }
1196
1197     q = x264_clip3f( q, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
1198
1199     rc->qpa_rc =
1200     rc->qpa_aq = 0;
1201     rc->qp = x264_clip3( (int)(q + 0.5), 0, 51 );
1202     h->fdec->f_qp_avg_rc =
1203     h->fdec->f_qp_avg_aq =
1204     rc->qpm = q;
1205     if( rce )
1206         rce->new_qp = rc->qp;
1207
1208     accum_p_qp_update( h, rc->qpm );
1209
1210     if( h->sh.i_type != SLICE_TYPE_B )
1211         rc->last_non_b_pict_type = h->sh.i_type;
1212 }
1213
1214 static double predict_row_size( x264_t *h, int y, double qp )
1215 {
1216     /* average between two predictors:
1217      * absolute SATD, and scaled bit cost of the colocated row in the previous frame */
1218     x264_ratecontrol_t *rc = h->rc;
1219     double pred_s = predict_size( rc->row_pred[0], qp2qscale( qp ), h->fdec->i_row_satd[y] );
1220     double pred_t = 0;
1221     if( h->sh.i_type == SLICE_TYPE_I || qp >= h->fref0[0]->f_row_qp[y] )
1222     {
1223         if( h->sh.i_type == SLICE_TYPE_P
1224             && h->fref0[0]->i_type == h->fdec->i_type
1225             && h->fref0[0]->i_row_satd[y] > 0
1226             && (abs(h->fref0[0]->i_row_satd[y] - h->fdec->i_row_satd[y]) < h->fdec->i_row_satd[y]/2))
1227         {
1228             pred_t = h->fref0[0]->i_row_bits[y] * h->fdec->i_row_satd[y] / h->fref0[0]->i_row_satd[y]
1229                      * qp2qscale( h->fref0[0]->f_row_qp[y] ) / qp2qscale( qp );
1230         }
1231         if( pred_t == 0 )
1232             pred_t = pred_s;
1233         return (pred_s + pred_t) / 2;
1234     }
1235     /* Our QP is lower than the reference! */
1236     else
1237     {
1238         double pred_intra = predict_size( rc->row_pred[1], qp2qscale( qp ), h->fdec->i_row_satds[0][0][y] );
1239         /* Sum: better to overestimate than underestimate by using only one of the two predictors. */
1240         return pred_intra + pred_s;
1241     }
1242 }
1243
1244 static double row_bits_so_far( x264_t *h, int y )
1245 {
1246     double bits = 0;
1247     for( int i = h->i_threadslice_start; i <= y; i++ )
1248         bits += h->fdec->i_row_bits[i];
1249     return bits;
1250 }
1251
1252 static double predict_row_size_sum( x264_t *h, int y, double qp )
1253 {
1254     double bits = row_bits_so_far(h, y);
1255     for( int i = y+1; i < h->i_threadslice_end; i++ )
1256         bits += predict_row_size( h, i, qp );
1257     return bits;
1258 }
1259
1260
1261 void x264_ratecontrol_mb( x264_t *h, int bits )
1262 {
1263     x264_ratecontrol_t *rc = h->rc;
1264     const int y = h->mb.i_mb_y;
1265
1266     x264_emms();
1267
1268     h->fdec->i_row_bits[y] += bits;
1269     rc->qpa_rc += rc->qpm;
1270     rc->qpa_aq += h->mb.i_qp;
1271
1272     if( h->mb.i_mb_x != h->sps->i_mb_width - 1 || !rc->b_vbv )
1273         return;
1274
1275     h->fdec->f_row_qp[y] = rc->qpm;
1276
1277     update_predictor( rc->row_pred[0], qp2qscale( rc->qpm ), h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] );
1278     if( h->sh.i_type == SLICE_TYPE_P && rc->qpm < h->fref0[0]->f_row_qp[y] )
1279         update_predictor( rc->row_pred[1], qp2qscale( rc->qpm ), h->fdec->i_row_satds[0][0][y], h->fdec->i_row_bits[y] );
1280
1281     /* tweak quality based on difference from predicted size */
1282     if( y < h->i_threadslice_end-1 )
1283     {
1284         float prev_row_qp = h->fdec->f_row_qp[y];
1285         float qp_min = X264_MAX( prev_row_qp - h->param.rc.i_qp_step, h->param.rc.i_qp_min );
1286         float qp_absolute_max = h->param.rc.i_qp_max;
1287         if( rc->rate_factor_max_increment )
1288             qp_absolute_max = X264_MIN( qp_absolute_max, rc->qp_novbv + rc->rate_factor_max_increment );
1289         float qp_max = X264_MIN( prev_row_qp + h->param.rc.i_qp_step, qp_absolute_max );
1290         float step_size = 0.5;
1291
1292         /* B-frames shouldn't use lower QP than their reference frames. */
1293         if( h->sh.i_type == SLICE_TYPE_B )
1294         {
1295             qp_min = X264_MAX( qp_min, X264_MAX( h->fref0[0]->f_row_qp[y+1], h->fref1[0]->f_row_qp[y+1] ) );
1296             rc->qpm = X264_MAX( rc->qpm, qp_min );
1297         }
1298
1299         float buffer_left_planned = rc->buffer_fill - rc->frame_size_planned;
1300         float slice_size_planned = h->param.b_sliced_threads ? rc->slice_size_planned : rc->frame_size_planned;
1301         float size_of_other_slices = 0;
1302         if( h->param.b_sliced_threads )
1303         {
1304             for( int i = 0; i < h->param.i_threads; i++ )
1305                 if( h != h->thread[i] )
1306                     size_of_other_slices += h->thread[i]->rc->frame_size_estimated;
1307         }
1308         else
1309             rc->max_frame_error = X264_MAX( 0.05, 1.0 / (h->sps->i_mb_width) );
1310
1311         /* More threads means we have to be more cautious in letting ratecontrol use up extra bits. */
1312         float rc_tol = buffer_left_planned / h->param.i_threads * rc->rate_tolerance;
1313         int b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;
1314
1315         /* Don't modify the row QPs until a sufficent amount of the bits of the frame have been processed, in case a flat */
1316         /* area at the top of the frame was measured inaccurately. */
1317         if( row_bits_so_far( h, y ) < 0.05 * slice_size_planned )
1318             return;
1319
1320         if( h->sh.i_type != SLICE_TYPE_I )
1321             rc_tol /= 2;
1322
1323         if( !rc->b_vbv_min_rate )
1324             qp_min = X264_MAX( qp_min, rc->qp_novbv );
1325
1326         while( rc->qpm < qp_max
1327                && ((b1 > rc->frame_size_planned + rc_tol) ||
1328                    (rc->buffer_fill - b1 < buffer_left_planned * 0.5) ||
1329                    (b1 > rc->frame_size_planned && rc->qpm < rc->qp_novbv)) )
1330         {
1331             rc->qpm += step_size;
1332             b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;
1333         }
1334
1335         while( rc->qpm > qp_min
1336                && (rc->qpm > h->fdec->f_row_qp[0] || rc->single_frame_vbv)
1337                && ((b1 < rc->frame_size_planned * 0.8 && rc->qpm <= prev_row_qp)
1338                || b1 < (rc->buffer_fill - rc->buffer_size + rc->buffer_rate) * 1.1) )
1339         {
1340             rc->qpm -= step_size;
1341             b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;
1342         }
1343
1344         /* avoid VBV underflow or MinCR violation */
1345         while( (rc->qpm < qp_absolute_max)
1346                && ((rc->buffer_fill - b1 < rc->buffer_rate * rc->max_frame_error) ||
1347                    (rc->frame_size_maximum - b1 < rc->frame_size_maximum * rc->max_frame_error)))
1348         {
1349             rc->qpm += step_size;
1350             b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;
1351         }
1352
1353         h->rc->frame_size_estimated = predict_row_size_sum( h, y, rc->qpm );
1354     }
1355 }
1356
1357 int x264_ratecontrol_qp( x264_t *h )
1358 {
1359     x264_emms();
1360     return x264_clip3( h->rc->qpm + .5, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
1361 }
1362
1363 int x264_ratecontrol_mb_qp( x264_t *h )
1364 {
1365     x264_emms();
1366     float qp = h->rc->qpm;
1367     if( h->param.rc.i_aq_mode )
1368         /* MB-tree currently doesn't adjust quantizers in unreferenced frames. */
1369         qp += h->fdec->b_kept_as_ref ? h->fenc->f_qp_offset[h->mb.i_mb_xy] : h->fenc->f_qp_offset_aq[h->mb.i_mb_xy];
1370     return x264_clip3( qp + .5, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
1371 }
1372
1373 /* In 2pass, force the same frame types as in the 1st pass */
1374 int x264_ratecontrol_slice_type( x264_t *h, int frame_num )
1375 {
1376     x264_ratecontrol_t *rc = h->rc;
1377     if( h->param.rc.b_stat_read )
1378     {
1379         if( frame_num >= rc->num_entries )
1380         {
1381             /* We could try to initialize everything required for ABR and
1382              * adaptive B-frames, but that would be complicated.
1383              * So just calculate the average QP used so far. */
1384             h->param.rc.i_qp_constant = (h->stat.i_frame_count[SLICE_TYPE_P] == 0) ? 24
1385                                       : 1 + h->stat.f_frame_qp[SLICE_TYPE_P] / h->stat.i_frame_count[SLICE_TYPE_P];
1386             rc->qp_constant[SLICE_TYPE_P] = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
1387             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 );
1388             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 );
1389
1390             x264_log(h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d)\n", rc->num_entries);
1391             x264_log(h, X264_LOG_ERROR, "continuing anyway, at constant QP=%d\n", h->param.rc.i_qp_constant);
1392             if( h->param.i_bframe_adaptive )
1393                 x264_log(h, X264_LOG_ERROR, "disabling adaptive B-frames\n");
1394
1395             for( int i = 0; i < h->param.i_threads; i++ )
1396             {
1397                 h->thread[i]->rc->b_abr = 0;
1398                 h->thread[i]->rc->b_2pass = 0;
1399                 h->thread[i]->param.rc.i_rc_method = X264_RC_CQP;
1400                 h->thread[i]->param.rc.b_stat_read = 0;
1401                 h->thread[i]->param.i_bframe_adaptive = 0;
1402                 h->thread[i]->param.i_scenecut_threshold = 0;
1403                 h->thread[i]->param.rc.b_mb_tree = 0;
1404                 if( h->thread[i]->param.i_bframe > 1 )
1405                     h->thread[i]->param.i_bframe = 1;
1406             }
1407             return X264_TYPE_AUTO;
1408         }
1409         return rc->entry[frame_num].frame_type;
1410     }
1411     else
1412         return X264_TYPE_AUTO;
1413 }
1414
1415 void x264_ratecontrol_set_weights( x264_t *h, x264_frame_t *frm )
1416 {
1417     ratecontrol_entry_t *rce = &h->rc->entry[frm->i_frame];
1418     if( h->param.analyse.i_weighted_pred <= 0 )
1419         return;
1420     if( rce->i_weight_denom >= 0 )
1421         SET_WEIGHT( frm->weight[0][0], 1, rce->weight[0], rce->i_weight_denom, rce->weight[1] );
1422 }
1423
1424 /* After encoding one frame, save stats and update ratecontrol state */
1425 int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
1426 {
1427     x264_ratecontrol_t *rc = h->rc;
1428     const int *mbs = h->stat.frame.i_mb_count;
1429
1430     x264_emms();
1431
1432     h->stat.frame.i_mb_count_skip = mbs[P_SKIP] + mbs[B_SKIP];
1433     h->stat.frame.i_mb_count_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
1434     h->stat.frame.i_mb_count_p = mbs[P_L0] + mbs[P_8x8];
1435     for( int i = B_DIRECT; i < B_8x8; i++ )
1436         h->stat.frame.i_mb_count_p += mbs[i];
1437
1438     h->fdec->f_qp_avg_rc = rc->qpa_rc /= h->mb.i_mb_count;
1439     h->fdec->f_qp_avg_aq = rc->qpa_aq /= h->mb.i_mb_count;
1440
1441     if( h->param.rc.b_stat_write )
1442     {
1443         char c_type = h->sh.i_type==SLICE_TYPE_I ? (h->fenc->i_poc==0 ? 'I' : 'i')
1444                     : h->sh.i_type==SLICE_TYPE_P ? 'P'
1445                     : h->fenc->b_kept_as_ref ? 'B' : 'b';
1446         int dir_frame = h->stat.frame.i_direct_score[1] - h->stat.frame.i_direct_score[0];
1447         int dir_avg = h->stat.i_direct_score[1] - h->stat.i_direct_score[0];
1448         char c_direct = h->mb.b_direct_auto_write ?
1449                         ( dir_frame>0 ? 's' : dir_frame<0 ? 't' :
1450                           dir_avg>0 ? 's' : dir_avg<0 ? 't' : '-' )
1451                         : '-';
1452         if( fprintf( rc->p_stat_file_out,
1453                  "in:%d out:%d type:%c dur:%d cpbdur:%d q:%.2f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c ref:",
1454                  h->fenc->i_frame, h->i_frame,
1455                  c_type, h->fenc->i_duration,
1456                  h->fenc->i_cpb_duration, rc->qpa_rc,
1457                  h->stat.frame.i_tex_bits,
1458                  h->stat.frame.i_mv_bits,
1459                  h->stat.frame.i_misc_bits,
1460                  h->stat.frame.i_mb_count_i,
1461                  h->stat.frame.i_mb_count_p,
1462                  h->stat.frame.i_mb_count_skip,
1463                  c_direct) < 0 )
1464             goto fail;
1465
1466         /* Only write information for reference reordering once. */
1467         int use_old_stats = h->param.rc.b_stat_read && rc->rce->refs > 1;
1468         for( int i = 0; i < (use_old_stats ? rc->rce->refs : h->i_ref0); i++ )
1469         {
1470             int refcount = use_old_stats         ? rc->rce->refcount[i]
1471                          : h->param.b_interlaced ? h->stat.frame.i_mb_count_ref[0][i*2]
1472                                                  + h->stat.frame.i_mb_count_ref[0][i*2+1]
1473                          :                         h->stat.frame.i_mb_count_ref[0][i];
1474             if( fprintf( rc->p_stat_file_out, "%d ", refcount ) < 0 )
1475                 goto fail;
1476         }
1477
1478         if( h->sh.weight[0][0].weightfn )
1479         {
1480             if( fprintf( rc->p_stat_file_out, "w:%"PRId32",%"PRId32",%"PRId32, h->sh.weight[0][0].i_denom, h->sh.weight[0][0].i_scale, h->sh.weight[0][0].i_offset ) < 0 )
1481                 goto fail;
1482         }
1483
1484         if( fprintf( rc->p_stat_file_out, ";\n") < 0 )
1485             goto fail;
1486
1487         /* Don't re-write the data in multi-pass mode. */
1488         if( h->param.rc.b_mb_tree && h->fenc->b_kept_as_ref && !h->param.rc.b_stat_read )
1489         {
1490             uint8_t i_type = h->sh.i_type;
1491             /* Values are stored as big-endian FIX8.8 */
1492             for( int i = 0; i < h->mb.i_mb_count; i++ )
1493                 rc->qp_buffer[0][i] = endian_fix16( h->fenc->f_qp_offset[i]*256.0 );
1494             if( fwrite( &i_type, 1, 1, rc->p_mbtree_stat_file_out ) < 1 )
1495                 goto fail;
1496             if( fwrite( rc->qp_buffer[0], sizeof(uint16_t), h->mb.i_mb_count, rc->p_mbtree_stat_file_out ) < h->mb.i_mb_count )
1497                 goto fail;
1498         }
1499     }
1500
1501     if( rc->b_abr )
1502     {
1503         if( h->sh.i_type != SLICE_TYPE_B )
1504             rc->cplxr_sum += bits * qp2qscale( rc->qpa_rc ) / rc->last_rceq;
1505         else
1506         {
1507             /* Depends on the fact that B-frame's QP is an offset from the following P-frame's.
1508              * Not perfectly accurate with B-refs, but good enough. */
1509             rc->cplxr_sum += bits * qp2qscale( rc->qpa_rc ) / (rc->last_rceq * fabs( h->param.rc.f_pb_factor ));
1510         }
1511         rc->cplxr_sum *= rc->cbr_decay;
1512         double frame_duration = (double)h->fenc->i_duration * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1513
1514         rc->wanted_bits_window += frame_duration * rc->bitrate;
1515         rc->wanted_bits_window *= rc->cbr_decay;
1516     }
1517
1518     if( rc->b_2pass )
1519         rc->expected_bits_sum += qscale2bits( rc->rce, qp2qscale( rc->rce->new_qp ) );
1520
1521     if( h->mb.b_variable_qp )
1522     {
1523         if( h->sh.i_type == SLICE_TYPE_B )
1524         {
1525             rc->bframe_bits += bits;
1526             if( h->fenc->b_last_minigop_bframe )
1527             {
1528                 update_predictor( rc->pred_b_from_p, qp2qscale( rc->qpa_rc ),
1529                                   h->fref1[h->i_ref1-1]->i_satd, rc->bframe_bits / rc->bframes );
1530                 rc->bframe_bits = 0;
1531             }
1532         }
1533     }
1534
1535     *filler = update_vbv( h, bits );
1536
1537     if( h->sps->vui.b_nal_hrd_parameters_present )
1538     {
1539         if( h->fenc->i_frame == 0 )
1540         {
1541             // access unit initialises the HRD
1542             h->fenc->hrd_timing.cpb_initial_arrival_time = 0;
1543             rc->initial_cpb_removal_delay = h->initial_cpb_removal_delay;
1544             rc->initial_cpb_removal_delay_offset = h->initial_cpb_removal_delay_offset;
1545             h->fenc->hrd_timing.cpb_removal_time = rc->nrt_first_access_unit = (double)rc->initial_cpb_removal_delay / 90000;
1546         }
1547         else
1548         {
1549             h->fenc->hrd_timing.cpb_removal_time = rc->nrt_first_access_unit + (double)h->fenc->i_cpb_delay *
1550                                                    h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1551
1552             double cpb_earliest_arrival_time = h->fenc->hrd_timing.cpb_removal_time - (double)rc->initial_cpb_removal_delay / 90000;
1553             if( h->fenc->b_keyframe )
1554             {
1555                  rc->nrt_first_access_unit = h->fenc->hrd_timing.cpb_removal_time;
1556                  rc->initial_cpb_removal_delay = h->initial_cpb_removal_delay;
1557                  rc->initial_cpb_removal_delay_offset = h->initial_cpb_removal_delay_offset;
1558             }
1559             else
1560                  cpb_earliest_arrival_time -= (double)rc->initial_cpb_removal_delay_offset / 90000;
1561
1562             if( h->sps->vui.hrd.b_cbr_hrd )
1563                 h->fenc->hrd_timing.cpb_initial_arrival_time = rc->previous_cpb_final_arrival_time;
1564             else
1565                 h->fenc->hrd_timing.cpb_initial_arrival_time = X264_MAX( rc->previous_cpb_final_arrival_time, cpb_earliest_arrival_time );
1566         }
1567         int filler_bits = *filler ? X264_MAX( (FILLER_OVERHEAD - h->param.b_annexb), *filler )*8 : 0;
1568         // Equation C-6
1569         h->fenc->hrd_timing.cpb_final_arrival_time = rc->previous_cpb_final_arrival_time = h->fenc->hrd_timing.cpb_initial_arrival_time +
1570                                                      (double)(bits + filler_bits) / h->sps->vui.hrd.i_bit_rate_unscaled;
1571
1572         h->fenc->hrd_timing.dpb_output_time = (double)h->fenc->i_dpb_output_delay * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale +
1573                                               h->fenc->hrd_timing.cpb_removal_time;
1574     }
1575
1576     return 0;
1577 fail:
1578     x264_log(h, X264_LOG_ERROR, "ratecontrol_end: stats file could not be written to\n");
1579     return -1;
1580 }
1581
1582 /****************************************************************************
1583  * 2 pass functions
1584  ***************************************************************************/
1585
1586 /**
1587  * modify the bitrate curve from pass1 for one frame
1588  */
1589 static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor, int frame_num)
1590 {
1591     x264_ratecontrol_t *rcc= h->rc;
1592     x264_zone_t *zone = get_zone( h, frame_num );
1593     double q = pow( rce->blurred_complexity, 1 - rcc->qcompress );
1594
1595     // avoid NaN's in the rc_eq
1596     if( !isfinite(q) || rce->tex_bits + rce->mv_bits == 0 )
1597         q = rcc->last_qscale_for[rce->pict_type];
1598     else
1599     {
1600         rcc->last_rceq = q;
1601         q /= rate_factor;
1602         rcc->last_qscale = q;
1603     }
1604
1605     if( zone )
1606     {
1607         if( zone->b_force_qp )
1608             q = qp2qscale( zone->i_qp );
1609         else
1610             q /= zone->f_bitrate_factor;
1611     }
1612
1613     return q;
1614 }
1615
1616 static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
1617 {
1618     x264_ratecontrol_t *rcc = h->rc;
1619     const int pict_type = rce->pict_type;
1620
1621     // force I/B quants as a function of P quants
1622     const double last_p_q    = rcc->last_qscale_for[SLICE_TYPE_P];
1623     const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
1624     if( pict_type == SLICE_TYPE_I )
1625     {
1626         double iq = q;
1627         double pq = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
1628         double ip_factor = fabs( h->param.rc.f_ip_factor );
1629         /* don't apply ip_factor if the following frame is also I */
1630         if( rcc->accum_p_norm <= 0 )
1631             q = iq;
1632         else if( h->param.rc.f_ip_factor < 0 )
1633             q = iq / ip_factor;
1634         else if( rcc->accum_p_norm >= 1 )
1635             q = pq / ip_factor;
1636         else
1637             q = rcc->accum_p_norm * pq / ip_factor + (1 - rcc->accum_p_norm) * iq;
1638     }
1639     else if( pict_type == SLICE_TYPE_B )
1640     {
1641         if( h->param.rc.f_pb_factor > 0 )
1642             q = last_non_b_q;
1643         if( !rce->kept_as_ref )
1644             q *= fabs( h->param.rc.f_pb_factor );
1645     }
1646     else if( pict_type == SLICE_TYPE_P
1647              && rcc->last_non_b_pict_type == SLICE_TYPE_P
1648              && rce->tex_bits == 0 )
1649     {
1650         q = last_p_q;
1651     }
1652
1653     /* last qscale / qdiff stuff */
1654     if( rcc->last_non_b_pict_type == pict_type &&
1655         (pict_type!=SLICE_TYPE_I || rcc->last_accum_p_norm < 1) )
1656     {
1657         double last_q = rcc->last_qscale_for[pict_type];
1658         double max_qscale = last_q * rcc->lstep;
1659         double min_qscale = last_q / rcc->lstep;
1660
1661         if     ( q > max_qscale ) q = max_qscale;
1662         else if( q < min_qscale ) q = min_qscale;
1663     }
1664
1665     rcc->last_qscale_for[pict_type] = q;
1666     if( pict_type != SLICE_TYPE_B )
1667         rcc->last_non_b_pict_type = pict_type;
1668     if( pict_type == SLICE_TYPE_I )
1669     {
1670         rcc->last_accum_p_norm = rcc->accum_p_norm;
1671         rcc->accum_p_norm = 0;
1672         rcc->accum_p_qp = 0;
1673     }
1674     if( pict_type == SLICE_TYPE_P )
1675     {
1676         float mask = 1 - pow( (float)rce->i_count / rcc->nmb, 2 );
1677         rcc->accum_p_qp   = mask * (qscale2qp( q ) + rcc->accum_p_qp);
1678         rcc->accum_p_norm = mask * (1 + rcc->accum_p_norm);
1679     }
1680     return q;
1681 }
1682
1683 static double predict_size( predictor_t *p, double q, double var )
1684 {
1685      return (p->coeff*var + p->offset) / (q*p->count);
1686 }
1687
1688 static void update_predictor( predictor_t *p, double q, double var, double bits )
1689 {
1690     const double range = 1.5;
1691     if( var < 10 )
1692         return;
1693     double old_coeff = p->coeff / p->count;
1694     double new_coeff = bits*q / var;
1695     double new_coeff_clipped = x264_clip3f( new_coeff, old_coeff/range, old_coeff*range );
1696     double new_offset = bits*q - new_coeff_clipped * var;
1697     if( new_offset >= 0 )
1698         new_coeff = new_coeff_clipped;
1699     else
1700         new_offset = 0;
1701     p->count  *= p->decay;
1702     p->coeff  *= p->decay;
1703     p->offset *= p->decay;
1704     p->count  ++;
1705     p->coeff  += new_coeff;
1706     p->offset += new_offset;
1707 }
1708
1709 // update VBV after encoding a frame
1710 static int update_vbv( x264_t *h, int bits )
1711 {
1712     int filler = 0;
1713
1714     x264_ratecontrol_t *rcc = h->rc;
1715     x264_ratecontrol_t *rct = h->thread[0]->rc;
1716
1717     if( rcc->last_satd >= h->mb.i_mb_count )
1718         update_predictor( &rct->pred[h->sh.i_type], qp2qscale( rcc->qpa_rc ), rcc->last_satd, bits );
1719
1720     if( !rcc->b_vbv )
1721         return filler;
1722
1723     rct->buffer_fill_final -= bits;
1724
1725     if( rct->buffer_fill_final < 0 )
1726         x264_log( h, X264_LOG_WARNING, "VBV underflow (frame %d, %.0f bits)\n", h->i_frame, rct->buffer_fill_final );
1727     rct->buffer_fill_final = X264_MAX( rct->buffer_fill_final, 0 );
1728     rct->buffer_fill_final += rcc->buffer_rate;
1729
1730     if( h->sps->vui.hrd.b_cbr_hrd && rct->buffer_fill_final > rcc->buffer_size )
1731     {
1732         filler = ceil( (rct->buffer_fill_final - rcc->buffer_size) / 8 );
1733         rct->buffer_fill_final -= X264_MAX( (FILLER_OVERHEAD - h->param.b_annexb), filler ) * 8;
1734     }
1735     else
1736         rct->buffer_fill_final = X264_MIN( rct->buffer_fill_final, rcc->buffer_size );
1737
1738     return filler;
1739 }
1740
1741 int x264_hrd_fullness( x264_t *h )
1742 {
1743     x264_ratecontrol_t *rct = h->thread[0]->rc;
1744     double cpb_bits = rct->buffer_fill_final;
1745     double bps = h->sps->vui.hrd.i_bit_rate_unscaled;
1746     double cpb_size = h->sps->vui.hrd.i_cpb_size_unscaled;
1747     double cpb_fullness = 90000.0*cpb_bits/bps;
1748
1749     if( cpb_bits < 0 || cpb_bits > cpb_size )
1750     {
1751          x264_log( h, X264_LOG_WARNING, "CPB %s: %.0lf bits in a %.0lf-bit buffer\n",
1752                    cpb_bits < 0 ? "underflow" : "overflow", cpb_bits, cpb_size );
1753     }
1754
1755     h->initial_cpb_removal_delay_offset = 90000.0*(cpb_size - cpb_bits)/bps;
1756
1757     return x264_clip3f( cpb_fullness + 0.5, 0, 90000.0*cpb_size/bps ); // just lie if we are in a weird state
1758 }
1759
1760 // provisionally update VBV according to the planned size of all frames currently in progress
1761 static void update_vbv_plan( x264_t *h, int overhead )
1762 {
1763     x264_ratecontrol_t *rcc = h->rc;
1764     rcc->buffer_fill = h->thread[0]->rc->buffer_fill_final;
1765     if( h->i_thread_frames > 1 )
1766     {
1767         int j = h->rc - h->thread[0]->rc;
1768         for( int i = 1; i < h->i_thread_frames; i++ )
1769         {
1770             x264_t *t = h->thread[ (j+i)%h->i_thread_frames ];
1771             double bits = t->rc->frame_size_planned;
1772             if( !t->b_thread_active )
1773                 continue;
1774             bits  = X264_MAX(bits, t->rc->frame_size_estimated);
1775             rcc->buffer_fill -= bits;
1776             rcc->buffer_fill = X264_MAX( rcc->buffer_fill, 0 );
1777             rcc->buffer_fill += t->rc->buffer_rate;
1778             rcc->buffer_fill = X264_MIN( rcc->buffer_fill, rcc->buffer_size );
1779         }
1780     }
1781     rcc->buffer_fill = X264_MIN( rcc->buffer_fill, rcc->buffer_size );
1782     rcc->buffer_fill -= overhead;
1783 }
1784
1785 // apply VBV constraints and clip qscale to between lmin and lmax
1786 static double clip_qscale( x264_t *h, int pict_type, double q )
1787 {
1788     x264_ratecontrol_t *rcc = h->rc;
1789     double lmin = rcc->lmin[pict_type];
1790     double lmax = rcc->lmax[pict_type];
1791     if( rcc->rate_factor_max_increment )
1792         lmax = X264_MIN( lmax, qp2qscale( rcc->qp_novbv + rcc->rate_factor_max_increment ) );
1793     double q0 = q;
1794
1795     /* B-frames are not directly subject to VBV,
1796      * since they are controlled by the P-frames' QPs. */
1797
1798     if( rcc->b_vbv && rcc->last_satd > 0 )
1799     {
1800         /* Lookahead VBV: raise the quantizer as necessary such that no frames in
1801          * the lookahead overflow and such that the buffer is in a reasonable state
1802          * by the end of the lookahead. */
1803         if( h->param.rc.i_lookahead )
1804         {
1805             int terminate = 0;
1806
1807             /* Avoid an infinite loop. */
1808             for( int iterations = 0; iterations < 1000 && terminate != 3; iterations++ )
1809             {
1810                 double frame_q[3];
1811                 double cur_bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
1812                 double buffer_fill_cur = rcc->buffer_fill - cur_bits;
1813                 double target_fill;
1814                 double total_duration = 0;
1815                 frame_q[0] = h->sh.i_type == SLICE_TYPE_I ? q * h->param.rc.f_ip_factor : q;
1816                 frame_q[1] = frame_q[0] * h->param.rc.f_pb_factor;
1817                 frame_q[2] = frame_q[0] / h->param.rc.f_ip_factor;
1818
1819                 /* Loop over the planned future frames. */
1820                 for( int j = 0; buffer_fill_cur >= 0 && buffer_fill_cur <= rcc->buffer_size; j++ )
1821                 {
1822                     total_duration += h->fenc->f_planned_cpb_duration[j];
1823                     buffer_fill_cur += rcc->vbv_max_rate * h->fenc->f_planned_cpb_duration[j];
1824                     int i_type = h->fenc->i_planned_type[j];
1825                     int i_satd = h->fenc->i_planned_satd[j];
1826                     if( i_type == X264_TYPE_AUTO )
1827                         break;
1828                     i_type = IS_X264_TYPE_I( i_type ) ? SLICE_TYPE_I : IS_X264_TYPE_B( i_type ) ? SLICE_TYPE_B : SLICE_TYPE_P;
1829                     cur_bits = predict_size( &rcc->pred[i_type], frame_q[i_type], i_satd );
1830                     buffer_fill_cur -= cur_bits;
1831                 }
1832                 /* Try to get to get the buffer at least 50% filled, but don't set an impossible goal. */
1833                 target_fill = X264_MIN( rcc->buffer_fill + total_duration * rcc->vbv_max_rate * 0.5, rcc->buffer_size * 0.5 );
1834                 if( buffer_fill_cur < target_fill )
1835                 {
1836                     q *= 1.01;
1837                     terminate |= 1;
1838                     continue;
1839                 }
1840                 /* Try to get the buffer no more than 80% filled, but don't set an impossible goal. */
1841                 target_fill = x264_clip3f( rcc->buffer_fill - total_duration * rcc->vbv_max_rate * 0.5, rcc->buffer_size * 0.8, rcc->buffer_size );
1842                 if( rcc->b_vbv_min_rate && buffer_fill_cur > target_fill )
1843                 {
1844                     q /= 1.01;
1845                     terminate |= 2;
1846                     continue;
1847                 }
1848                 break;
1849             }
1850         }
1851         /* Fallback to old purely-reactive algorithm: no lookahead. */
1852         else
1853         {
1854             if( ( pict_type == SLICE_TYPE_P ||
1855                 ( pict_type == SLICE_TYPE_I && rcc->last_non_b_pict_type == SLICE_TYPE_I ) ) &&
1856                 rcc->buffer_fill/rcc->buffer_size < 0.5 )
1857             {
1858                 q /= x264_clip3f( 2.0*rcc->buffer_fill/rcc->buffer_size, 0.5, 1.0 );
1859             }
1860
1861             /* Now a hard threshold to make sure the frame fits in VBV.
1862              * This one is mostly for I-frames. */
1863             double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
1864             double qf = 1.0;
1865             /* For small VBVs, allow the frame to use up the entire VBV. */
1866             double max_fill_factor = h->param.rc.i_vbv_buffer_size >= 5*h->param.rc.i_vbv_max_bitrate / rcc->fps ? 2 : 1;
1867             /* For single-frame VBVs, request that the frame use up the entire VBV. */
1868             double min_fill_factor = rcc->single_frame_vbv ? 1 : 2;
1869
1870             if( bits > rcc->buffer_fill/max_fill_factor )
1871                 qf = x264_clip3f( rcc->buffer_fill/(max_fill_factor*bits), 0.2, 1.0 );
1872             q /= qf;
1873             bits *= qf;
1874             if( bits < rcc->buffer_rate/min_fill_factor )
1875                 q *= bits*min_fill_factor/rcc->buffer_rate;
1876             q = X264_MAX( q0, q );
1877         }
1878
1879         /* Apply MinCR restrictions */
1880         double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
1881         if( bits > rcc->frame_size_maximum )
1882             q *= bits / rcc->frame_size_maximum;
1883         bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
1884
1885         /* Check B-frame complexity, and use up any bits that would
1886          * overflow before the next P-frame. */
1887         if( h->sh.i_type == SLICE_TYPE_P && !rcc->single_frame_vbv )
1888         {
1889             int nb = rcc->bframes;
1890             double pbbits = bits;
1891             double bbits = predict_size( rcc->pred_b_from_p, q * h->param.rc.f_pb_factor, rcc->last_satd );
1892             double space;
1893             double bframe_cpb_duration = 0;
1894             double minigop_cpb_duration;
1895             for( int i = 0; i < nb; i++ )
1896                 bframe_cpb_duration += h->fenc->f_planned_cpb_duration[1+i];
1897
1898             if( bbits * nb > bframe_cpb_duration * rcc->vbv_max_rate )
1899                 nb = 0;
1900             pbbits += nb * bbits;
1901
1902             minigop_cpb_duration = bframe_cpb_duration + h->fenc->f_planned_cpb_duration[0];
1903             space = rcc->buffer_fill + minigop_cpb_duration*rcc->vbv_max_rate - rcc->buffer_size;
1904             if( pbbits < space )
1905             {
1906                 q *= X264_MAX( pbbits / space, bits / (0.5 * rcc->buffer_size) );
1907             }
1908             q = X264_MAX( q0-5, q );
1909         }
1910
1911         if( !rcc->b_vbv_min_rate )
1912             q = X264_MAX( q0, q );
1913     }
1914
1915     if( lmin==lmax )
1916         return lmin;
1917     else if( rcc->b_2pass )
1918     {
1919         double min2 = log( lmin );
1920         double max2 = log( lmax );
1921         q = (log(q) - min2)/(max2-min2) - 0.5;
1922         q = 1.0/(1.0 + exp( -4*q ));
1923         q = q*(max2-min2) + min2;
1924         return exp( q );
1925     }
1926     else
1927         return x264_clip3f( q, lmin, lmax );
1928 }
1929
1930 // update qscale for 1 frame based on actual bits used so far
1931 static float rate_estimate_qscale( x264_t *h )
1932 {
1933     float q;
1934     x264_ratecontrol_t *rcc = h->rc;
1935     ratecontrol_entry_t rce;
1936     int pict_type = h->sh.i_type;
1937     int64_t total_bits = 8*(h->stat.i_frame_size[SLICE_TYPE_I]
1938                           + h->stat.i_frame_size[SLICE_TYPE_P]
1939                           + h->stat.i_frame_size[SLICE_TYPE_B]);
1940
1941     if( rcc->b_2pass )
1942     {
1943         rce = *rcc->rce;
1944         if( pict_type != rce.pict_type )
1945         {
1946             x264_log( h, X264_LOG_ERROR, "slice=%c but 2pass stats say %c\n",
1947                       slice_type_to_char[pict_type], slice_type_to_char[rce.pict_type] );
1948         }
1949     }
1950
1951     if( pict_type == SLICE_TYPE_B )
1952     {
1953         /* B-frames don't have independent ratecontrol, but rather get the
1954          * average QP of the two adjacent P-frames + an offset */
1955
1956         int i0 = IS_X264_TYPE_I(h->fref0[0]->i_type);
1957         int i1 = IS_X264_TYPE_I(h->fref1[0]->i_type);
1958         int dt0 = abs(h->fenc->i_poc - h->fref0[0]->i_poc);
1959         int dt1 = abs(h->fenc->i_poc - h->fref1[0]->i_poc);
1960         float q0 = h->fref0[0]->f_qp_avg_rc;
1961         float q1 = h->fref1[0]->f_qp_avg_rc;
1962
1963         if( h->fref0[0]->i_type == X264_TYPE_BREF )
1964             q0 -= rcc->pb_offset/2;
1965         if( h->fref1[0]->i_type == X264_TYPE_BREF )
1966             q1 -= rcc->pb_offset/2;
1967
1968         if( i0 && i1 )
1969             q = (q0 + q1) / 2 + rcc->ip_offset;
1970         else if( i0 )
1971             q = q1;
1972         else if( i1 )
1973             q = q0;
1974         else
1975             q = (q0*dt1 + q1*dt0) / (dt0 + dt1);
1976
1977         if( h->fenc->b_kept_as_ref )
1978             q += rcc->pb_offset/2;
1979         else
1980             q += rcc->pb_offset;
1981
1982         if( rcc->b_2pass && rcc->b_vbv )
1983             rcc->frame_size_planned = qscale2bits( &rce, q );
1984         else
1985             rcc->frame_size_planned = predict_size( rcc->pred_b_from_p, q, h->fref1[h->i_ref1-1]->i_satd );
1986         h->rc->frame_size_estimated = rcc->frame_size_planned;
1987
1988         /* For row SATDs */
1989         if( rcc->b_vbv )
1990             rcc->last_satd = x264_rc_analyse_slice( h );
1991         rcc->qp_novbv = q;
1992         return qp2qscale( q );
1993     }
1994     else
1995     {
1996         double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate;
1997
1998         if( rcc->b_2pass )
1999         {
2000             double lmin = rcc->lmin[pict_type];
2001             double lmax = rcc->lmax[pict_type];
2002             int64_t diff;
2003             int64_t predicted_bits = total_bits;
2004             /* Adjust ABR buffer based on distance to the end of the video. */
2005             if( rcc->num_entries > h->i_frame )
2006                 abr_buffer *= 0.5 * sqrt( rcc->num_entries - h->i_frame );
2007
2008             if( rcc->b_vbv )
2009             {
2010                 if( h->i_thread_frames > 1 )
2011                 {
2012                     int j = h->rc - h->thread[0]->rc;
2013                     for( int i = 1; i < h->i_thread_frames; i++ )
2014                     {
2015                         x264_t *t = h->thread[ (j+i)%h->i_thread_frames ];
2016                         double bits = t->rc->frame_size_planned;
2017                         if( !t->b_thread_active )
2018                             continue;
2019                         bits  = X264_MAX(bits, t->rc->frame_size_estimated);
2020                         predicted_bits += (int64_t)bits;
2021                     }
2022                 }
2023             }
2024             else
2025             {
2026                 if( h->i_frame < h->i_thread_frames )
2027                     predicted_bits += (int64_t)h->i_frame * rcc->bitrate / rcc->fps;
2028                 else
2029                     predicted_bits += (int64_t)(h->i_thread_frames - 1) * rcc->bitrate / rcc->fps;
2030             }
2031
2032             diff = predicted_bits - (int64_t)rce.expected_bits;
2033             q = rce.new_qscale;
2034             q /= x264_clip3f((double)(abr_buffer - diff) / abr_buffer, .5, 2);
2035             if( ((h->i_frame + 1 - h->i_thread_frames) >= rcc->fps) &&
2036                 (rcc->expected_bits_sum > 0))
2037             {
2038                 /* Adjust quant based on the difference between
2039                  * achieved and expected bitrate so far */
2040                 double cur_time = (double)h->i_frame / rcc->num_entries;
2041                 double w = x264_clip3f( cur_time*100, 0.0, 1.0 );
2042                 q *= pow( (double)total_bits / rcc->expected_bits_sum, w );
2043             }
2044             if( rcc->b_vbv )
2045             {
2046                 /* Do not overflow vbv */
2047                 double expected_size = qscale2bits( &rce, q );
2048                 double expected_vbv = rcc->buffer_fill + rcc->buffer_rate - expected_size;
2049                 double expected_fullness = rce.expected_vbv / rcc->buffer_size;
2050                 double qmax = q*(2 - expected_fullness);
2051                 double size_constraint = 1 + expected_fullness;
2052                 qmax = X264_MAX( qmax, rce.new_qscale );
2053                 if( expected_fullness < .05 )
2054                     qmax = lmax;
2055                 qmax = X264_MIN(qmax, lmax);
2056                 while( ((expected_vbv < rce.expected_vbv/size_constraint) && (q < qmax)) ||
2057                         ((expected_vbv < 0) && (q < lmax)))
2058                 {
2059                     q *= 1.05;
2060                     expected_size = qscale2bits(&rce, q);
2061                     expected_vbv = rcc->buffer_fill + rcc->buffer_rate - expected_size;
2062                 }
2063                 rcc->last_satd = x264_rc_analyse_slice( h );
2064             }
2065             q = x264_clip3f( q, lmin, lmax );
2066         }
2067         else /* 1pass ABR */
2068         {
2069             /* Calculate the quantizer which would have produced the desired
2070              * average bitrate if it had been applied to all frames so far.
2071              * Then modulate that quant based on the current frame's complexity
2072              * relative to the average complexity so far (using the 2pass RCEQ).
2073              * Then bias the quant up or down if total size so far was far from
2074              * the target.
2075              * Result: Depending on the value of rate_tolerance, there is a
2076              * tradeoff between quality and bitrate precision. But at large
2077              * tolerances, the bit distribution approaches that of 2pass. */
2078
2079             double wanted_bits, overflow = 1;
2080
2081             rcc->last_satd = x264_rc_analyse_slice( h );
2082             rcc->short_term_cplxsum *= 0.5;
2083             rcc->short_term_cplxcount *= 0.5;
2084             rcc->short_term_cplxsum += rcc->last_satd;
2085             rcc->short_term_cplxcount ++;
2086
2087             rce.tex_bits = rcc->last_satd;
2088             rce.blurred_complexity = rcc->short_term_cplxsum / rcc->short_term_cplxcount;
2089             rce.mv_bits = 0;
2090             rce.p_count = rcc->nmb;
2091             rce.i_count = 0;
2092             rce.s_count = 0;
2093             rce.qscale = 1;
2094             rce.pict_type = pict_type;
2095
2096             if( h->param.rc.i_rc_method == X264_RC_CRF )
2097             {
2098                 q = get_qscale( h, &rce, rcc->rate_factor_constant, h->fenc->i_frame );
2099             }
2100             else
2101             {
2102                 q = get_qscale( h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame );
2103
2104                 /* ABR code can potentially be counterproductive in CBR, so just don't bother.
2105                  * Don't run it if the frame complexity is zero either. */
2106                 if( !rcc->b_vbv_min_rate && rcc->last_satd )
2107                 {
2108                     // FIXME is it simpler to keep track of wanted_bits in ratecontrol_end?
2109                     int i_frame_done = h->i_frame + 1 - h->i_thread_frames;
2110                     double time_done = i_frame_done / rcc->fps;
2111                     if( h->param.b_vfr_input && i_frame_done > 0 )
2112                         time_done = ((double)(h->fenc->i_reordered_pts - h->i_reordered_pts_delay)) * h->param.i_timebase_num / h->param.i_timebase_den;
2113                     wanted_bits = time_done * rcc->bitrate;
2114                     if( wanted_bits > 0 )
2115                     {
2116                         abr_buffer *= X264_MAX( 1, sqrt( time_done ) );
2117                         overflow = x264_clip3f( 1.0 + (total_bits - wanted_bits) / abr_buffer, .5, 2 );
2118                         q *= overflow;
2119                     }
2120                 }
2121             }
2122
2123             if( pict_type == SLICE_TYPE_I && h->param.i_keyint_max > 1
2124                 /* should test _next_ pict type, but that isn't decided yet */
2125                 && rcc->last_non_b_pict_type != SLICE_TYPE_I )
2126             {
2127                 q = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
2128                 q /= fabs( h->param.rc.f_ip_factor );
2129             }
2130             else if( h->i_frame > 0 )
2131             {
2132                 /* Asymmetric clipping, because symmetric would prevent
2133                  * overflow control in areas of rapidly oscillating complexity */
2134                 double lmin = rcc->last_qscale_for[pict_type] / rcc->lstep;
2135                 double lmax = rcc->last_qscale_for[pict_type] * rcc->lstep;
2136                 if( overflow > 1.1 && h->i_frame > 3 )
2137                     lmax *= rcc->lstep;
2138                 else if( overflow < 0.9 )
2139                     lmin /= rcc->lstep;
2140
2141                 q = x264_clip3f(q, lmin, lmax);
2142             }
2143             else if( h->param.rc.i_rc_method == X264_RC_CRF && rcc->qcompress != 1 )
2144             {
2145                 q = qp2qscale( ABR_INIT_QP ) / fabs( h->param.rc.f_ip_factor );
2146             }
2147             rcc->qp_novbv = qscale2qp( q );
2148
2149             //FIXME use get_diff_limited_q() ?
2150             q = clip_qscale( h, pict_type, q );
2151         }
2152
2153         rcc->last_qscale_for[pict_type] =
2154         rcc->last_qscale = q;
2155
2156         if( !(rcc->b_2pass && !rcc->b_vbv) && h->fenc->i_frame == 0 )
2157             rcc->last_qscale_for[SLICE_TYPE_P] = q * fabs( h->param.rc.f_ip_factor );
2158
2159         if( rcc->b_2pass && rcc->b_vbv )
2160             rcc->frame_size_planned = qscale2bits(&rce, q);
2161         else
2162             rcc->frame_size_planned = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
2163
2164         /* Always use up the whole VBV in this case. */
2165         if( rcc->single_frame_vbv )
2166             rcc->frame_size_planned = rcc->buffer_rate;
2167         h->rc->frame_size_estimated = rcc->frame_size_planned;
2168         return q;
2169     }
2170 }
2171
2172 void x264_threads_normalize_predictors( x264_t *h )
2173 {
2174     double totalsize = 0;
2175     for( int i = 0; i < h->param.i_threads; i++ )
2176         totalsize += h->thread[i]->rc->slice_size_planned;
2177     double factor = h->rc->frame_size_planned / totalsize;
2178     for( int i = 0; i < h->param.i_threads; i++ )
2179         h->thread[i]->rc->slice_size_planned *= factor;
2180 }
2181
2182 void x264_threads_distribute_ratecontrol( x264_t *h )
2183 {
2184     int row;
2185     x264_ratecontrol_t *rc = h->rc;
2186
2187     /* Initialize row predictors */
2188     if( h->i_frame == 0 )
2189         for( int i = 0; i < h->param.i_threads; i++ )
2190         {
2191             x264_ratecontrol_t *t = h->thread[i]->rc;
2192             memcpy( t->row_preds, rc->row_preds, sizeof(rc->row_preds) );
2193         }
2194
2195     for( int i = 0; i < h->param.i_threads; i++ )
2196     {
2197         x264_t *t = h->thread[i];
2198         memcpy( t->rc, rc, offsetof(x264_ratecontrol_t, row_pred) );
2199         t->rc->row_pred = &t->rc->row_preds[h->sh.i_type];
2200         /* Calculate the planned slice size. */
2201         if( rc->b_vbv && rc->frame_size_planned )
2202         {
2203             int size = 0;
2204             for( row = t->i_threadslice_start; row < t->i_threadslice_end; row++ )
2205                 size += h->fdec->i_row_satd[row];
2206             t->rc->slice_size_planned = predict_size( &rc->pred[h->sh.i_type + (i+1)*5], rc->qpm, size );
2207         }
2208         else
2209             t->rc->slice_size_planned = 0;
2210     }
2211     if( rc->b_vbv && rc->frame_size_planned )
2212     {
2213         x264_threads_normalize_predictors( h );
2214
2215         if( rc->single_frame_vbv )
2216         {
2217             /* Compensate for our max frame error threshold: give more bits (proportionally) to smaller slices. */
2218             for( int i = 0; i < h->param.i_threads; i++ )
2219             {
2220                 x264_t *t = h->thread[i];
2221                 t->rc->max_frame_error = X264_MAX( 0.05, 1.0 / (t->i_threadslice_end - t->i_threadslice_start) );
2222                 t->rc->slice_size_planned += 2 * t->rc->max_frame_error * rc->frame_size_planned;
2223             }
2224             x264_threads_normalize_predictors( h );
2225         }
2226
2227         for( int i = 0; i < h->param.i_threads; i++ )
2228             h->thread[i]->rc->frame_size_estimated = h->thread[i]->rc->slice_size_planned;
2229     }
2230 }
2231
2232 void x264_threads_merge_ratecontrol( x264_t *h )
2233 {
2234     x264_ratecontrol_t *rc = h->rc;
2235     x264_emms();
2236
2237     for( int i = 0; i < h->param.i_threads; i++ )
2238     {
2239         x264_t *t = h->thread[i];
2240         x264_ratecontrol_t *rct = h->thread[i]->rc;
2241         if( h->param.rc.i_vbv_buffer_size )
2242         {
2243             int size = 0;
2244             for( int row = t->i_threadslice_start; row < t->i_threadslice_end; row++ )
2245                 size += h->fdec->i_row_satd[row];
2246             int bits = t->stat.frame.i_mv_bits + t->stat.frame.i_tex_bits + t->stat.frame.i_misc_bits;
2247             int mb_count = (t->i_threadslice_end - t->i_threadslice_start) * h->sps->i_mb_width;
2248             update_predictor( &rc->pred[h->sh.i_type+5*i], qp2qscale( rct->qpa_rc/mb_count ), size, bits );
2249         }
2250         if( !i )
2251             continue;
2252         rc->qpa_rc += rct->qpa_rc;
2253         rc->qpa_aq += rct->qpa_aq;
2254     }
2255 }
2256
2257 void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
2258 {
2259     if( cur != prev )
2260     {
2261 #define COPY(var) memcpy(&cur->rc->var, &prev->rc->var, sizeof(cur->rc->var))
2262         /* these vars are updated in x264_ratecontrol_start()
2263          * so copy them from the context that most recently started (prev)
2264          * to the context that's about to start (cur). */
2265         COPY(accum_p_qp);
2266         COPY(accum_p_norm);
2267         COPY(last_satd);
2268         COPY(last_rceq);
2269         COPY(last_qscale_for);
2270         COPY(last_non_b_pict_type);
2271         COPY(short_term_cplxsum);
2272         COPY(short_term_cplxcount);
2273         COPY(bframes);
2274         COPY(prev_zone);
2275         COPY(qpbuf_pos);
2276         /* these vars can be updated by x264_ratecontrol_init_reconfigurable */
2277         COPY(buffer_rate);
2278         COPY(buffer_size);
2279         COPY(single_frame_vbv);
2280         COPY(cbr_decay);
2281         COPY(b_vbv_min_rate);
2282         COPY(rate_factor_constant);
2283         COPY(bitrate);
2284 #undef COPY
2285     }
2286     if( cur != next )
2287     {
2288 #define COPY(var) next->rc->var = cur->rc->var
2289         /* these vars are updated in x264_ratecontrol_end()
2290          * so copy them from the context that most recently ended (cur)
2291          * to the context that's about to end (next) */
2292         COPY(cplxr_sum);
2293         COPY(expected_bits_sum);
2294         COPY(wanted_bits_window);
2295         COPY(bframe_bits);
2296         COPY(initial_cpb_removal_delay);
2297         COPY(initial_cpb_removal_delay_offset);
2298         COPY(nrt_first_access_unit);
2299         COPY(previous_cpb_final_arrival_time);
2300 #undef COPY
2301     }
2302     //FIXME row_preds[] (not strictly necessary, but would improve prediction)
2303     /* the rest of the variables are either constant or thread-local */
2304 }
2305
2306 static int find_underflow( x264_t *h, double *fills, int *t0, int *t1, int over )
2307 {
2308     /* find an interval ending on an overflow or underflow (depending on whether
2309      * we're adding or removing bits), and starting on the earliest frame that
2310      * can influence the buffer fill of that end frame. */
2311     x264_ratecontrol_t *rcc = h->rc;
2312     const double buffer_min = (over ? .1 : .1) * rcc->buffer_size;
2313     const double buffer_max = .9 * rcc->buffer_size;
2314     double fill = fills[*t0-1];
2315     double parity = over ? 1. : -1.;
2316     int start = -1, end = -1;
2317     for( int i = *t0; i < rcc->num_entries; i++ )
2318     {
2319         fill += (rcc->entry[i].i_cpb_duration * rcc->vbv_max_rate * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale -
2320                  qscale2bits( &rcc->entry[i], rcc->entry[i].new_qscale )) * parity;
2321         fill = x264_clip3f(fill, 0, rcc->buffer_size);
2322         fills[i] = fill;
2323         if( fill <= buffer_min || i == 0 )
2324         {
2325             if( end >= 0 )
2326                 break;
2327             start = i;
2328         }
2329         else if( fill >= buffer_max && start >= 0 )
2330             end = i;
2331     }
2332     *t0 = start;
2333     *t1 = end;
2334     return start >= 0 && end >= 0;
2335 }
2336
2337 static int fix_underflow( x264_t *h, int t0, int t1, double adjustment, double qscale_min, double qscale_max)
2338 {
2339     x264_ratecontrol_t *rcc = h->rc;
2340     double qscale_orig, qscale_new;
2341     int adjusted = 0;
2342     if( t0 > 0 )
2343         t0++;
2344     for( int i = t0; i <= t1; i++ )
2345     {
2346         qscale_orig = rcc->entry[i].new_qscale;
2347         qscale_orig = x264_clip3f( qscale_orig, qscale_min, qscale_max );
2348         qscale_new  = qscale_orig * adjustment;
2349         qscale_new  = x264_clip3f( qscale_new, qscale_min, qscale_max );
2350         rcc->entry[i].new_qscale = qscale_new;
2351         adjusted = adjusted || (qscale_new != qscale_orig);
2352     }
2353     return adjusted;
2354 }
2355
2356 static double count_expected_bits( x264_t *h )
2357 {
2358     x264_ratecontrol_t *rcc = h->rc;
2359     double expected_bits = 0;
2360     for( int i = 0; i < rcc->num_entries; i++ )
2361     {
2362         ratecontrol_entry_t *rce = &rcc->entry[i];
2363         rce->expected_bits = expected_bits;
2364         expected_bits += qscale2bits( rce, rce->new_qscale );
2365     }
2366     return expected_bits;
2367 }
2368
2369 static int vbv_pass2( x264_t *h, double all_available_bits )
2370 {
2371     /* for each interval of buffer_full .. underflow, uniformly increase the qp of all
2372      * frames in the interval until either buffer is full at some intermediate frame or the
2373      * last frame in the interval no longer underflows.  Recompute intervals and repeat.
2374      * Then do the converse to put bits back into overflow areas until target size is met */
2375
2376     x264_ratecontrol_t *rcc = h->rc;
2377     double *fills;
2378     double expected_bits = 0;
2379     double adjustment;
2380     double prev_bits = 0;
2381     int t0, t1;
2382     double qscale_min = qp2qscale( h->param.rc.i_qp_min );
2383     double qscale_max = qp2qscale( h->param.rc.i_qp_max );
2384     int iterations = 0;
2385     int adj_min, adj_max;
2386     CHECKED_MALLOC( fills, (rcc->num_entries+1)*sizeof(double) );
2387
2388     fills++;
2389
2390     /* adjust overall stream size */
2391     do
2392     {
2393         iterations++;
2394         prev_bits = expected_bits;
2395
2396         if( expected_bits )
2397         {   /* not first iteration */
2398             adjustment = X264_MAX(X264_MIN(expected_bits / all_available_bits, 0.999), 0.9);
2399             fills[-1] = rcc->buffer_size * h->param.rc.f_vbv_buffer_init;
2400             t0 = 0;
2401             /* fix overflows */
2402             adj_min = 1;
2403             while(adj_min && find_underflow( h, fills, &t0, &t1, 1 ))
2404             {
2405                 adj_min = fix_underflow( h, t0, t1, adjustment, qscale_min, qscale_max );
2406                 t0 = t1;
2407             }
2408         }
2409
2410         fills[-1] = rcc->buffer_size * (1. - h->param.rc.f_vbv_buffer_init);
2411         t0 = 0;
2412         /* fix underflows -- should be done after overflow, as we'd better undersize target than underflowing VBV */
2413         adj_max = 1;
2414         while( adj_max && find_underflow( h, fills, &t0, &t1, 0 ) )
2415             adj_max = fix_underflow( h, t0, t1, 1.001, qscale_min, qscale_max );
2416
2417         expected_bits = count_expected_bits( h );
2418     } while( (expected_bits < .995*all_available_bits) && ((int64_t)(expected_bits+.5) > (int64_t)(prev_bits+.5)) );
2419
2420     if( !adj_max )
2421         x264_log( h, X264_LOG_WARNING, "vbv-maxrate issue, qpmax or vbv-maxrate too low\n");
2422
2423     /* store expected vbv filling values for tracking when encoding */
2424     for( int i = 0; i < rcc->num_entries; i++ )
2425         rcc->entry[i].expected_vbv = rcc->buffer_size - fills[i];
2426
2427     x264_free( fills-1 );
2428     return 0;
2429 fail:
2430     return -1;
2431 }
2432
2433 static int init_pass2( x264_t *h )
2434 {
2435     x264_ratecontrol_t *rcc = h->rc;
2436     uint64_t all_const_bits = 0;
2437     double duration = 0;
2438     for( int i = 0; i < rcc->num_entries; i++ )
2439         duration += rcc->entry[i].i_duration;
2440     duration *= (double)h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
2441     uint64_t all_available_bits = h->param.rc.i_bitrate * 1000. * duration;
2442     double rate_factor, step_mult;
2443     double qblur = h->param.rc.f_qblur;
2444     double cplxblur = h->param.rc.f_complexity_blur;
2445     const int filter_size = (int)(qblur*4) | 1;
2446     double expected_bits;
2447     double *qscale, *blurred_qscale;
2448
2449     /* find total/average complexity & const_bits */
2450     for( int i = 0; i < rcc->num_entries; i++ )
2451     {
2452         ratecontrol_entry_t *rce = &rcc->entry[i];
2453         all_const_bits += rce->misc_bits;
2454     }
2455
2456     if( all_available_bits < all_const_bits)
2457     {
2458         x264_log( h, X264_LOG_ERROR, "requested bitrate is too low. estimated minimum is %d kbps\n",
2459                  (int)(all_const_bits * rcc->fps / (rcc->num_entries * 1000.)) );
2460         return -1;
2461     }
2462
2463     /* Blur complexities, to reduce local fluctuation of QP.
2464      * We don't blur the QPs directly, because then one very simple frame
2465      * could drag down the QP of a nearby complex frame and give it more
2466      * bits than intended. */
2467     for( int i = 0; i < rcc->num_entries; i++ )
2468     {
2469         ratecontrol_entry_t *rce = &rcc->entry[i];
2470         double weight_sum = 0;
2471         double cplx_sum = 0;
2472         double weight = 1.0;
2473         double gaussian_weight;
2474         /* weighted average of cplx of future frames */
2475         for( int j = 1; j < cplxblur*2 && j < rcc->num_entries-i; j++ )
2476         {
2477             ratecontrol_entry_t *rcj = &rcc->entry[i+j];
2478             weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 );
2479             if( weight < .0001 )
2480                 break;
2481             gaussian_weight = weight * exp( -j*j/200.0 );
2482             weight_sum += gaussian_weight;
2483             cplx_sum += gaussian_weight * (qscale2bits(rcj, 1) - rcj->misc_bits);
2484         }
2485         /* weighted average of cplx of past frames */
2486         weight = 1.0;
2487         for( int j = 0; j <= cplxblur*2 && j <= i; j++ )
2488         {
2489             ratecontrol_entry_t *rcj = &rcc->entry[i-j];
2490             gaussian_weight = weight * exp( -j*j/200.0 );
2491             weight_sum += gaussian_weight;
2492             cplx_sum += gaussian_weight * (qscale2bits( rcj, 1 ) - rcj->misc_bits);
2493             weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 );
2494             if( weight < .0001 )
2495                 break;
2496         }
2497         rce->blurred_complexity = cplx_sum / weight_sum;
2498     }
2499
2500     CHECKED_MALLOC( qscale, sizeof(double)*rcc->num_entries );
2501     if( filter_size > 1 )
2502         CHECKED_MALLOC( blurred_qscale, sizeof(double)*rcc->num_entries );
2503     else
2504         blurred_qscale = qscale;
2505
2506     /* Search for a factor which, when multiplied by the RCEQ values from
2507      * each frame, adds up to the desired total size.
2508      * There is no exact closed-form solution because of VBV constraints and
2509      * because qscale2bits is not invertible, but we can start with the simple
2510      * approximation of scaling the 1st pass by the ratio of bitrates.
2511      * The search range is probably overkill, but speed doesn't matter here. */
2512
2513     expected_bits = 1;
2514     for( int i = 0; i < rcc->num_entries; i++ )
2515     {
2516         double q = get_qscale(h, &rcc->entry[i], 1.0, i);
2517         expected_bits += qscale2bits(&rcc->entry[i], q);
2518         rcc->last_qscale_for[rcc->entry[i].pict_type] = q;
2519     }
2520     step_mult = all_available_bits / expected_bits;
2521
2522     rate_factor = 0;
2523     for( double step = 1E4 * step_mult; step > 1E-7 * step_mult; step *= 0.5)
2524     {
2525         expected_bits = 0;
2526         rate_factor += step;
2527
2528         rcc->last_non_b_pict_type = -1;
2529         rcc->last_accum_p_norm = 1;
2530         rcc->accum_p_norm = 0;
2531
2532         /* find qscale */
2533         for( int i = 0; i < rcc->num_entries; i++ )
2534         {
2535             qscale[i] = get_qscale( h, &rcc->entry[i], rate_factor, i );
2536             rcc->last_qscale_for[rcc->entry[i].pict_type] = qscale[i];
2537         }
2538
2539         /* fixed I/B qscale relative to P */
2540         for( int i = rcc->num_entries-1; i >= 0; i-- )
2541         {
2542             qscale[i] = get_diff_limited_q( h, &rcc->entry[i], qscale[i] );
2543             assert(qscale[i] >= 0);
2544         }
2545
2546         /* smooth curve */
2547         if( filter_size > 1 )
2548         {
2549             assert( filter_size%2 == 1 );
2550             for( int i = 0; i < rcc->num_entries; i++ )
2551             {
2552                 ratecontrol_entry_t *rce = &rcc->entry[i];
2553                 double q = 0.0, sum = 0.0;
2554
2555                 for( int j = 0; j < filter_size; j++ )
2556                 {
2557                     int index = i+j-filter_size/2;
2558                     double d = index-i;
2559                     double coeff = qblur==0 ? 1.0 : exp( -d*d/(qblur*qblur) );
2560                     if( index < 0 || index >= rcc->num_entries )
2561                         continue;
2562                     if( rce->pict_type != rcc->entry[index].pict_type )
2563                         continue;
2564                     q += qscale[index] * coeff;
2565                     sum += coeff;
2566                 }
2567                 blurred_qscale[i] = q/sum;
2568             }
2569         }
2570
2571         /* find expected bits */
2572         for( int i = 0; i < rcc->num_entries; i++ )
2573         {
2574             ratecontrol_entry_t *rce = &rcc->entry[i];
2575             rce->new_qscale = clip_qscale( h, rce->pict_type, blurred_qscale[i] );
2576             assert(rce->new_qscale >= 0);
2577             expected_bits += qscale2bits( rce, rce->new_qscale );
2578         }
2579
2580         if( expected_bits > all_available_bits )
2581             rate_factor -= step;
2582     }
2583
2584     x264_free( qscale );
2585     if( filter_size > 1 )
2586         x264_free( blurred_qscale );
2587
2588     if( rcc->b_vbv )
2589         if( vbv_pass2( h, all_available_bits ) )
2590             return -1;
2591     expected_bits = count_expected_bits( h );
2592
2593     if( fabs( expected_bits/all_available_bits - 1.0 ) > 0.01 )
2594     {
2595         double avgq = 0;
2596         for( int i = 0; i < rcc->num_entries; i++ )
2597             avgq += rcc->entry[i].new_qscale;
2598         avgq = qscale2qp( avgq / rcc->num_entries );
2599
2600         if( expected_bits > all_available_bits || !rcc->b_vbv )
2601             x264_log( h, X264_LOG_WARNING, "Error: 2pass curve failed to converge\n" );
2602         x264_log( h, X264_LOG_WARNING, "target: %.2f kbit/s, expected: %.2f kbit/s, avg QP: %.4f\n",
2603                   (float)h->param.rc.i_bitrate,
2604                   expected_bits * rcc->fps / (rcc->num_entries * 1000.),
2605                   avgq );
2606         if( expected_bits < all_available_bits && avgq < h->param.rc.i_qp_min + 2 )
2607         {
2608             if( h->param.rc.i_qp_min > 0 )
2609                 x264_log( h, X264_LOG_WARNING, "try reducing target bitrate or reducing qp_min (currently %d)\n", h->param.rc.i_qp_min );
2610             else
2611                 x264_log( h, X264_LOG_WARNING, "try reducing target bitrate\n" );
2612         }
2613         else if( expected_bits > all_available_bits && avgq > h->param.rc.i_qp_max - 2 )
2614         {
2615             if( h->param.rc.i_qp_max < 51 )
2616                 x264_log( h, X264_LOG_WARNING, "try increasing target bitrate or increasing qp_max (currently %d)\n", h->param.rc.i_qp_max );
2617             else
2618                 x264_log( h, X264_LOG_WARNING, "try increasing target bitrate\n");
2619         }
2620         else if( !(rcc->b_2pass && rcc->b_vbv) )
2621             x264_log( h, X264_LOG_WARNING, "internal error\n" );
2622     }
2623
2624     return 0;
2625 fail:
2626     return -1;
2627 }