1 /*****************************************************************************
2 * ratecontrol.c: h264 encoder library (Rate Control)
3 *****************************************************************************
4 * Copyright (C) 2005-2008 x264 project
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>
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.
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.
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 *****************************************************************************/
27 #define _ISOC99_SOURCE
28 #undef NDEBUG // always check asserts, the speed effect is far too small to disable them
31 #include "common/common.h"
32 #include "ratecontrol.h"
44 uint64_t expected_bits; /*total expected bits up to the current frame (current one excluded)*/
51 float blurred_complexity;
54 int16_t i_weight_denom;
59 } ratecontrol_entry_t;
69 struct x264_ratecontrol_t
78 double rate_tolerance;
80 int nmb; /* number of macroblocks in a 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. */
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 */
100 double rate_factor_max_increment; /* Don't allow RF above (CRF + this value). */
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 */
109 double short_term_cplxsum;
110 double short_term_cplxcount;
111 double rate_factor_constant;
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;
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 */
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 */
130 double last_accum_p_norm;
131 double lmin[5]; /* min qscale by frame type */
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). */
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 */
153 x264_zone_t *prev_zone;
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;
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 );
171 #define CMP_OPT_FIRST_PASS( opt, param_val )\
173 if( ( p = strstr( opts, opt "=" ) ) && sscanf( p, opt "=%d" , &i ) && param_val != i )\
175 x264_log( h, X264_LOG_ERROR, "different " opt " setting than first pass (%d vs %d)\n", param_val, i );\
181 * qp = h.264's quantizer
182 * qscale = linearized quantizer = Lagrange multiplier
184 static inline double qp2qscale( double qp )
186 return 0.85 * pow( 2.0, ( qp - 12.0 ) / 6.0 );
188 static inline double qscale2qp( double qscale )
190 return 12.0 + 6.0 * log2( qscale/0.85 );
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 )
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 )
206 static ALWAYS_INLINE uint32_t ac_energy_plane( x264_t *h, int mb_x, int mb_y, x264_frame_t *frame, int i )
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);
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 )
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 );
238 void x264_adaptive_quant_frame( x264_t *h, x264_frame_t *frame )
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. */
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++ )
249 frame->i_pixel_sum[i] = 0;
250 frame->i_pixel_ssd[i] = 0;
253 /* Degenerate cases */
254 if( h->param.rc.i_aq_mode == X264_AQ_NONE || h->param.rc.f_aq_strength == 0 )
256 /* Need to init it anyways for MB tree */
257 if( h->param.rc.f_aq_strength == 0 )
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;
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 )
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 );
275 /* Actual adaptive quantization */
278 if( h->param.rc.i_aq_mode == X264_AQ_AUTOVARIANCE )
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++ )
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;
288 avg_adj_pow2 += qp_adj * qp_adj;
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;
296 strength = h->param.rc.f_aq_strength * 1.0397f;
298 for( int mb_y = 0; mb_y < height; mb_y++ )
299 for( int mb_x = 0; mb_x < width; mb_x++ )
302 if( h->param.rc.i_aq_mode == X264_AQ_AUTOVARIANCE )
304 qp_adj = frame->f_qp_offset[mb_x + mb_y*h->mb.i_mb_stride];
305 qp_adj = strength * (qp_adj - avg_adj);
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);
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);
319 /* Remove mean from SSD calculation */
320 for( int i = 0; i < 3; i++ )
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);
330 int x264_macroblock_tree_read( x264_t *h, x264_frame_t *frame )
332 x264_ratecontrol_t *rc = h->rc;
333 uint8_t i_type_actual = rc->entry[frame->i_frame].pict_type;
335 if( rc->entry[frame->i_frame].kept_as_ref )
338 if( rc->qpbuf_pos < 0 )
344 if( !fread( &i_type, 1, 1, rc->p_mbtree_stat_file_in ) )
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 )
349 if( i_type != i_type_actual && rc->qpbuf_pos == 1 )
351 x264_log(h, X264_LOG_ERROR, "MB-tree frametype %d doesn't match actual frametype %d.\n", i_type, i_type_actual);
354 } while( i_type != i_type_actual );
357 for( int i = 0; i < h->mb.i_mb_count; i++ )
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]);
366 x264_adaptive_quant_frame( h, frame );
369 x264_log(h, X264_LOG_ERROR, "Incomplete MB-tree stats file.\n");
373 int x264_reference_build_list_optimal( x264_t *h )
375 ratecontrol_entry_t *rce = h->rc->rce;
376 x264_frame_t *frames[16];
377 x264_weight_t weights[16][3];
380 if( rce->refs != h->i_ref0 )
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]) );
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++ )
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 );
399 /* FIXME: If there are duplicates from frames other than ref0 then it is possible
400 * that the optimal ordering doesnt place every duplicate. */
402 refcount[bestref] = -1;
403 h->fref0[ref] = frames[bestref];
404 memcpy( h->fenc->weight[ref], weights[bestref], sizeof(weights[bestref]) );
410 static char *x264_strcat_filename( char *input, char *suffix )
412 char *output = x264_malloc( strlen( input ) + strlen( suffix ) + 1 );
415 strcpy( output, input );
416 strcat( output, suffix );
420 void x264_ratecontrol_init_reconfigurable( x264_t *h, int b_init )
422 x264_ratecontrol_t *rc = h->rc;
423 if( !b_init && rc->b_2pass )
426 if( h->param.rc.i_rc_method == X264_RC_CRF )
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 );
436 if( h->param.rc.i_vbv_max_bitrate > 0 && h->param.rc.i_vbv_buffer_size > 0 )
438 if( h->param.rc.i_vbv_buffer_size < (int)(h->param.rc.i_vbv_max_bitrate / rc->fps) )
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 );
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;
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;
454 if( h->param.i_nal_hrd && b_init )
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;
463 int bitrate = 1000*h->param.rc.i_vbv_max_bitrate;
464 int bufsize = 1000*h->param.rc.i_vbv_buffer_size;
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 );
478 #define MAX_DURATION 0.5
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);
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 );
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 );
493 else if( h->param.i_nal_hrd && !b_init )
495 x264_log( h, X264_LOG_WARNING, "VBV parameters cannot be changed when NAL HRD is in use\n" );
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 )
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 )
510 x264_log( h, X264_LOG_WARNING, "CRF max must be greater than CRF\n" );
511 rc->rate_factor_max_increment = 0;
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;
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;
528 int x264_ratecontrol_new( x264_t *h )
530 x264_ratecontrol_t *rc;
534 CHECKED_MALLOCZERO( h->rc, h->param.i_threads * sizeof(x264_ratecontrol_t) );
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;
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;
546 if( h->param.rc.b_mb_tree )
548 h->param.rc.f_pb_factor = 1;
552 rc->qcompress = h->param.rc.f_qcompress;
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;
560 if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.b_stat_read )
562 x264_log(h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n");
566 x264_ratecontrol_init_reconfigurable( h, 1 );
568 if( rc->rate_tolerance < 0.01 )
570 x264_log(h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n");
571 rc->rate_tolerance = 0.01;
574 h->mb.b_variable_qp = rc->b_vbv || h->param.rc.i_aq_mode;
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;
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;
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++ )
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++ )
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;
612 for( int j = 0; j < 2; j++ )
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;
620 *rc->pred_b_from_p = rc->pred[0];
622 if( parse_zones( h ) < 0 )
624 x264_log( h, X264_LOG_ERROR, "failed to parse zones\n" );
628 /* Load stat file and init 2pass algo */
629 if( h->param.rc.b_stat_read )
631 char *p, *stats_in, *stats_buf;
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 );
638 x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
641 if( h->param.rc.b_mb_tree )
643 char *mbtree_stats_in = x264_strcat_filename( h->param.rc.psz_stat_in, ".mbtree" );
644 if( !mbtree_stats_in )
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 )
650 x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open mbtree stats file\n");
655 /* check whether 1st pass options were compatible with current options */
656 if( !strncmp( stats_buf, "#options:", 9 ) )
660 char *opts = stats_buf;
661 stats_in = strchr( stats_buf, '\n' );
666 if( sscanf( opts, "#options: %dx%d", &i, &j ) != 2 )
668 x264_log( h, X264_LOG_ERROR, "resolution specified in stats file not valid\n" );
671 else if( h->param.rc.b_mb_tree && (i != h->param.i_width || j != h->param.i_height) )
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 );
678 if( ( p = strstr( opts, "timebase=" ) ) && sscanf( p, "timebase=%u/%u", &k, &l ) != 2 )
680 x264_log( h, X264_LOG_ERROR, "timebase specified in stats file not valid\n" );
683 if( k != h->param.i_timebase_num || l != h->param.i_timebase_den )
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 );
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 );
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" );
699 if( !strstr( opts, "direct=3" ) && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
701 x264_log( h, X264_LOG_WARNING, "direct=auto not used on the first pass\n" );
702 h->mb.b_direct_auto_write = 1;
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 )
709 x264_log( h, X264_LOG_ERROR, "b_adapt method specified in stats file not valid\n" );
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;
717 /* find number of pics */
720 for( num_entries = -1; p; num_entries++ )
721 p = strchr( p + 1, ';' );
724 x264_log(h, X264_LOG_ERROR, "empty stats file\n");
727 rc->num_entries = num_entries;
729 if( h->param.i_frame_total < rc->num_entries && h->param.i_frame_total > 0 )
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 );
734 if( h->param.i_frame_total > rc->num_entries )
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 );
741 CHECKED_MALLOCZERO( rc->entry, rc->num_entries * sizeof(ratecontrol_entry_t) );
743 /* init all to skipped p frames */
744 for( int i = 0; i < rc->num_entries; i++ )
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;
755 for( int i = 0; i < rc->num_entries; i++ )
757 ratecontrol_entry_t *rce;
765 next= strchr(p, ';');
767 *next++ = 0; //sscanf is unbelievably slow on long strings
768 e = sscanf( p, " in:%d ", &frame_number );
770 if( frame_number < 0 || frame_number >= rc->num_entries )
772 x264_log( h, X264_LOG_ERROR, "bad frame number (%d) at stats line %d\n", frame_number, i );
775 rce = &rc->entry[frame_number];
776 rce->direct_mode = 0;
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 );
783 p = strstr( p, "ref:" );
787 for( ref = 0; ref < 16; ref++ )
789 if( sscanf( p, " %d", &rce->refcount[ref] ) != 1 )
791 p = strchr( p+1, ' ' );
798 rce->i_weight_denom = -1;
799 char *w = strchr( p, '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;
804 if( pict_type != 'b' )
805 rce->kept_as_ref = 1;
809 rce->frame_type = X264_TYPE_IDR;
810 rce->pict_type = SLICE_TYPE_I;
813 rce->frame_type = X264_TYPE_I;
814 rce->pict_type = SLICE_TYPE_I;
817 rce->frame_type = X264_TYPE_P;
818 rce->pict_type = SLICE_TYPE_P;
821 rce->frame_type = X264_TYPE_BREF;
822 rce->pict_type = SLICE_TYPE_B;
825 rce->frame_type = X264_TYPE_B;
826 rce->pict_type = SLICE_TYPE_B;
828 default: e = -1; break;
833 x264_log( h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e );
836 rce->qscale = qp2qscale( qp );
840 x264_free( stats_buf );
842 if( h->param.rc.i_rc_method == X264_RC_ABR )
844 if( init_pass2( h ) < 0 )
846 } /* else we're using constant quant, so no need to run the bitrate allocation */
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 )
855 rc->psz_stat_file_tmpname = x264_strcat_filename( h->param.rc.psz_stat_out, ".temp" );
856 if( !rc->psz_stat_file_tmpname )
859 rc->p_stat_file_out = fopen( rc->psz_stat_file_tmpname, "wb" );
860 if( rc->p_stat_file_out == NULL )
862 x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
866 p = x264_param2string( &h->param, 1 );
868 fprintf( rc->p_stat_file_out, "#options: %s\n", p );
870 if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
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 )
877 rc->p_mbtree_stat_file_out = fopen( rc->psz_mbtree_stat_file_tmpname, "wb" );
878 if( rc->p_mbtree_stat_file_out == NULL )
880 x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open mbtree stats file\n");
886 if( h->param.rc.b_mb_tree && (h->param.rc.b_stat_read || h->param.rc.b_stat_write) )
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) );
894 for( int i = 0; i<h->param.i_threads; i++ )
896 h->thread[i]->rc = rc+i;
900 h->thread[i]->param = h->param;
901 h->thread[i]->mb.b_variable_qp = h->mb.b_variable_qp;
910 static int parse_zone( x264_t *h, x264_zone_t *z, char *p )
913 char *tok, UNUSED *saveptr=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) )
918 else if( 3 <= sscanf(p, "%u,%u,b=%f%n", &z->i_start, &z->i_end, &z->f_bitrate_factor, &len) )
920 else if( 2 <= sscanf(p, "%u,%u%n", &z->i_start, &z->i_end, &len) )
924 x264_log( h, X264_LOG_ERROR, "invalid zone: \"%s\"\n", p );
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 )) )
935 char *val = strchr( tok, '=' );
941 if( x264_param_parse( z->param, tok, val ) )
943 x264_log( h, X264_LOG_ERROR, "invalid zone param: %s = %s\n", tok, val );
953 static int parse_zones( x264_t *h )
955 x264_ratecontrol_t *rc = h->rc;
956 if( h->param.rc.psz_zones && !h->param.rc.i_zones )
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) );
966 for( int i = 0; i < h->param.rc.i_zones; i++ )
968 int i_tok = strcspn( p, "/" );
970 if( parse_zone( h, &h->param.rc.zones[i], p ) )
974 x264_free( psz_zones );
977 if( h->param.rc.i_zones > 0 )
979 for( int i = 0; i < h->param.rc.i_zones; i++ )
981 x264_zone_t z = h->param.rc.zones[i];
982 if( z.i_start < 0 || z.i_start > z.i_end )
984 x264_log( h, X264_LOG_ERROR, "invalid zone: start=%d end=%d\n",
985 z.i_start, z.i_end );
988 else if( !z.b_force_qp && z.f_bitrate_factor <= 0 )
990 x264_log( h, X264_LOG_ERROR, "invalid zone: bitrate_factor=%f\n",
991 z.f_bitrate_factor );
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) );
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++ )
1009 if( !rc->zones[i].param )
1010 rc->zones[i].param = rc->zones[0].param;
1019 static x264_zone_t *get_zone( x264_t *h, int frame_num )
1021 for( int i = h->rc->i_zones - 1; i >= 0; i-- )
1023 x264_zone_t *z = &h->rc->zones[i];
1024 if( frame_num >= z->i_start && frame_num <= z->i_end )
1030 void x264_ratecontrol_summary( x264_t *h )
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 )
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 );
1043 void x264_ratecontrol_delete( x264_t *h )
1045 x264_ratecontrol_t *rc = h->rc;
1048 if( rc->p_stat_file_out )
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 )
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 );
1058 x264_free( rc->psz_stat_file_tmpname );
1060 if( rc->p_mbtree_stat_file_out )
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 )
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 );
1070 x264_free( rc->psz_mbtree_stat_file_tmpname );
1071 x264_free( rc->psz_mbtree_stat_file_name );
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] );
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 );
1091 static void accum_p_qp_update( x264_t *h, float qp )
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;
1100 rc->accum_p_qp += qp;
1103 /* Before encoding a frame, choose a QP for it */
1104 void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
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 );
1113 if( zone && (!rc->prev_zone || zone->param != rc->prev_zone->param) )
1114 x264_encoder_reconfig( h, zone->param );
1115 rc->prev_zone = zone;
1117 rc->qp_force = i_force_qp;
1119 if( h->param.rc.b_stat_read )
1121 int frame = h->fenc->i_frame;
1122 assert( frame >= 0 && frame < rc->num_entries );
1123 rce = h->rc->rce = &h->rc->entry[frame];
1125 if( h->sh.i_type == SLICE_TYPE_B
1126 && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
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' );
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 );
1140 const x264_level_t *l = x264_levels;
1141 while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
1144 int mincr = l->mincr;
1146 /* Blu-ray requires this */
1147 if( l->level_idc == 41 && h->param.i_nal_hrd )
1150 /* The spec has a bizarre special case for the first frame. */
1151 if( h->i_frame == 0 )
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;
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;
1165 if( h->sh.i_type != SLICE_TYPE_B )
1166 rc->bframes = h->fenc->i_bframes;
1172 else if( rc->b_abr )
1174 q = qscale2qp( rate_estimate_qscale( h ) );
1176 else if( rc->b_2pass )
1178 rce->new_qscale = rate_estimate_qscale( h );
1179 q = qscale2qp( rce->new_qscale );
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;
1186 q = rc->qp_constant[ h->sh.i_type ];
1190 if( zone->b_force_qp )
1191 q += zone->i_qp - rc->qp_constant[SLICE_TYPE_P];
1193 q -= 6*log2f( zone->f_bitrate_factor );
1197 q = x264_clip3f( q, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
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 =
1206 rce->new_qp = rc->qp;
1208 accum_p_qp_update( h, rc->qpm );
1210 if( h->sh.i_type != SLICE_TYPE_B )
1211 rc->last_non_b_pict_type = h->sh.i_type;
1214 static double predict_row_size( x264_t *h, int y, double qp )
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] );
1221 if( h->sh.i_type == SLICE_TYPE_I || qp >= h->fref0[0]->f_row_qp[y] )
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))
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 );
1233 return (pred_s + pred_t) / 2;
1235 /* Our QP is lower than the reference! */
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;
1244 static double row_bits_so_far( x264_t *h, int y )
1247 for( int i = h->i_threadslice_start; i <= y; i++ )
1248 bits += h->fdec->i_row_bits[i];
1252 static double predict_row_size_sum( x264_t *h, int y, double qp )
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 );
1261 void x264_ratecontrol_mb( x264_t *h, int bits )
1263 x264_ratecontrol_t *rc = h->rc;
1264 const int y = h->mb.i_mb_y;
1268 h->fdec->i_row_bits[y] += bits;
1269 rc->qpa_rc += rc->qpm;
1270 rc->qpa_aq += h->mb.i_qp;
1272 if( h->mb.i_mb_x != h->sps->i_mb_width - 1 || !rc->b_vbv )
1275 h->fdec->f_row_qp[y] = rc->qpm;
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] );
1281 /* tweak quality based on difference from predicted size */
1282 if( y < h->i_threadslice_end-1 )
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;
1292 /* B-frames shouldn't use lower QP than their reference frames. */
1293 if( h->sh.i_type == SLICE_TYPE_B )
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 );
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 )
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;
1309 rc->max_frame_error = X264_MAX( 0.05, 1.0 / (h->sps->i_mb_width) );
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;
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 )
1320 if( h->sh.i_type != SLICE_TYPE_I )
1323 if( !rc->b_vbv_min_rate )
1324 qp_min = X264_MAX( qp_min, rc->qp_novbv );
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)) )
1331 rc->qpm += step_size;
1332 b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;
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) )
1340 rc->qpm -= step_size;
1341 b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;
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)))
1349 rc->qpm += step_size;
1350 b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;
1353 h->rc->frame_size_estimated = predict_row_size_sum( h, y, rc->qpm );
1357 int x264_ratecontrol_qp( x264_t *h )
1360 return x264_clip3( h->rc->qpm + .5, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
1363 int x264_ratecontrol_mb_qp( x264_t *h )
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 );
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 )
1376 x264_ratecontrol_t *rc = h->rc;
1377 if( h->param.rc.b_stat_read )
1379 if( frame_num >= rc->num_entries )
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 );
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");
1395 for( int i = 0; i < h->param.i_threads; i++ )
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;
1407 return X264_TYPE_AUTO;
1409 return rc->entry[frame_num].frame_type;
1412 return X264_TYPE_AUTO;
1415 void x264_ratecontrol_set_weights( x264_t *h, x264_frame_t *frm )
1417 ratecontrol_entry_t *rce = &h->rc->entry[frm->i_frame];
1418 if( h->param.analyse.i_weighted_pred <= 0 )
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] );
1424 /* After encoding one frame, save stats and update ratecontrol state */
1425 int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
1427 x264_ratecontrol_t *rc = h->rc;
1428 const int *mbs = h->stat.frame.i_mb_count;
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];
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;
1441 if( h->param.rc.b_stat_write )
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' : '-' )
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,
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++ )
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 )
1478 if( h->sh.weight[0][0].weightfn )
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 )
1484 if( fprintf( rc->p_stat_file_out, ";\n") < 0 )
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 )
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 )
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 )
1503 if( h->sh.i_type != SLICE_TYPE_B )
1504 rc->cplxr_sum += bits * qp2qscale( rc->qpa_rc ) / rc->last_rceq;
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 ));
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;
1514 rc->wanted_bits_window += frame_duration * rc->bitrate;
1515 rc->wanted_bits_window *= rc->cbr_decay;
1519 rc->expected_bits_sum += qscale2bits( rc->rce, qp2qscale( rc->rce->new_qp ) );
1521 if( h->mb.b_variable_qp )
1523 if( h->sh.i_type == SLICE_TYPE_B )
1525 rc->bframe_bits += bits;
1526 if( h->fenc->b_last_minigop_bframe )
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;
1535 *filler = update_vbv( h, bits );
1537 if( h->sps->vui.b_nal_hrd_parameters_present )
1539 if( h->fenc->i_frame == 0 )
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;
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;
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 )
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;
1560 cpb_earliest_arrival_time -= (double)rc->initial_cpb_removal_delay_offset / 90000;
1562 if( h->sps->vui.hrd.b_cbr_hrd )
1563 h->fenc->hrd_timing.cpb_initial_arrival_time = rc->previous_cpb_final_arrival_time;
1565 h->fenc->hrd_timing.cpb_initial_arrival_time = X264_MAX( rc->previous_cpb_final_arrival_time, cpb_earliest_arrival_time );
1567 int filler_bits = *filler ? X264_MAX( (FILLER_OVERHEAD - h->param.b_annexb), *filler )*8 : 0;
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;
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;
1578 x264_log(h, X264_LOG_ERROR, "ratecontrol_end: stats file could not be written to\n");
1582 /****************************************************************************
1584 ***************************************************************************/
1587 * modify the bitrate curve from pass1 for one frame
1589 static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor, int frame_num)
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 );
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];
1602 rcc->last_qscale = q;
1607 if( zone->b_force_qp )
1608 q = qp2qscale( zone->i_qp );
1610 q /= zone->f_bitrate_factor;
1616 static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
1618 x264_ratecontrol_t *rcc = h->rc;
1619 const int pict_type = rce->pict_type;
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 )
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 )
1632 else if( h->param.rc.f_ip_factor < 0 )
1634 else if( rcc->accum_p_norm >= 1 )
1637 q = rcc->accum_p_norm * pq / ip_factor + (1 - rcc->accum_p_norm) * iq;
1639 else if( pict_type == SLICE_TYPE_B )
1641 if( h->param.rc.f_pb_factor > 0 )
1643 if( !rce->kept_as_ref )
1644 q *= fabs( h->param.rc.f_pb_factor );
1646 else if( pict_type == SLICE_TYPE_P
1647 && rcc->last_non_b_pict_type == SLICE_TYPE_P
1648 && rce->tex_bits == 0 )
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) )
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;
1661 if ( q > max_qscale ) q = max_qscale;
1662 else if( q < min_qscale ) q = min_qscale;
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 )
1670 rcc->last_accum_p_norm = rcc->accum_p_norm;
1671 rcc->accum_p_norm = 0;
1672 rcc->accum_p_qp = 0;
1674 if( pict_type == SLICE_TYPE_P )
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);
1683 static double predict_size( predictor_t *p, double q, double var )
1685 return (p->coeff*var + p->offset) / (q*p->count);
1688 static void update_predictor( predictor_t *p, double q, double var, double bits )
1690 const double range = 1.5;
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;
1701 p->count *= p->decay;
1702 p->coeff *= p->decay;
1703 p->offset *= p->decay;
1705 p->coeff += new_coeff;
1706 p->offset += new_offset;
1709 // update VBV after encoding a frame
1710 static int update_vbv( x264_t *h, int bits )
1714 x264_ratecontrol_t *rcc = h->rc;
1715 x264_ratecontrol_t *rct = h->thread[0]->rc;
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 );
1723 rct->buffer_fill_final -= bits;
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;
1730 if( h->sps->vui.hrd.b_cbr_hrd && rct->buffer_fill_final > rcc->buffer_size )
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;
1736 rct->buffer_fill_final = X264_MIN( rct->buffer_fill_final, rcc->buffer_size );
1741 int x264_hrd_fullness( x264_t *h )
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;
1749 if( cpb_bits < 0 || cpb_bits > cpb_size )
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 );
1755 h->initial_cpb_removal_delay_offset = 90000.0*(cpb_size - cpb_bits)/bps;
1757 return x264_clip3f( cpb_fullness + 0.5, 0, 90000.0*cpb_size/bps ); // just lie if we are in a weird state
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 )
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 )
1767 int j = h->rc - h->thread[0]->rc;
1768 for( int i = 1; i < h->i_thread_frames; i++ )
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 )
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 );
1781 rcc->buffer_fill = X264_MIN( rcc->buffer_fill, rcc->buffer_size );
1782 rcc->buffer_fill -= overhead;
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 )
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 ) );
1795 /* B-frames are not directly subject to VBV,
1796 * since they are controlled by the P-frames' QPs. */
1798 if( rcc->b_vbv && rcc->last_satd > 0 )
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 )
1807 /* Avoid an infinite loop. */
1808 for( int iterations = 0; iterations < 1000 && terminate != 3; iterations++ )
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;
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;
1819 /* Loop over the planned future frames. */
1820 for( int j = 0; buffer_fill_cur >= 0 && buffer_fill_cur <= rcc->buffer_size; j++ )
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 )
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;
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 )
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 )
1851 /* Fallback to old purely-reactive algorithm: no lookahead. */
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 )
1858 q /= x264_clip3f( 2.0*rcc->buffer_fill/rcc->buffer_size, 0.5, 1.0 );
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 );
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;
1870 if( bits > rcc->buffer_fill/max_fill_factor )
1871 qf = x264_clip3f( rcc->buffer_fill/(max_fill_factor*bits), 0.2, 1.0 );
1874 if( bits < rcc->buffer_rate/min_fill_factor )
1875 q *= bits*min_fill_factor/rcc->buffer_rate;
1876 q = X264_MAX( q0, q );
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 );
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 )
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 );
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];
1898 if( bbits * nb > bframe_cpb_duration * rcc->vbv_max_rate )
1900 pbbits += nb * bbits;
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 )
1906 q *= X264_MAX( pbbits / space, bits / (0.5 * rcc->buffer_size) );
1908 q = X264_MAX( q0-5, q );
1911 if( !rcc->b_vbv_min_rate )
1912 q = X264_MAX( q0, q );
1917 else if( rcc->b_2pass )
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;
1927 return x264_clip3f( q, lmin, lmax );
1930 // update qscale for 1 frame based on actual bits used so far
1931 static float rate_estimate_qscale( x264_t *h )
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]);
1944 if( pict_type != rce.pict_type )
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] );
1951 if( pict_type == SLICE_TYPE_B )
1953 /* B-frames don't have independent ratecontrol, but rather get the
1954 * average QP of the two adjacent P-frames + an offset */
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;
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;
1969 q = (q0 + q1) / 2 + rcc->ip_offset;
1975 q = (q0*dt1 + q1*dt0) / (dt0 + dt1);
1977 if( h->fenc->b_kept_as_ref )
1978 q += rcc->pb_offset/2;
1980 q += rcc->pb_offset;
1982 if( rcc->b_2pass && rcc->b_vbv )
1983 rcc->frame_size_planned = qscale2bits( &rce, q );
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;
1990 rcc->last_satd = x264_rc_analyse_slice( h );
1992 return qp2qscale( q );
1996 double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate;
2000 double lmin = rcc->lmin[pict_type];
2001 double lmax = rcc->lmax[pict_type];
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 );
2010 if( h->i_thread_frames > 1 )
2012 int j = h->rc - h->thread[0]->rc;
2013 for( int i = 1; i < h->i_thread_frames; i++ )
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 )
2019 bits = X264_MAX(bits, t->rc->frame_size_estimated);
2020 predicted_bits += (int64_t)bits;
2026 if( h->i_frame < h->i_thread_frames )
2027 predicted_bits += (int64_t)h->i_frame * rcc->bitrate / rcc->fps;
2029 predicted_bits += (int64_t)(h->i_thread_frames - 1) * rcc->bitrate / rcc->fps;
2032 diff = predicted_bits - (int64_t)rce.expected_bits;
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))
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 );
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 )
2055 qmax = X264_MIN(qmax, lmax);
2056 while( ((expected_vbv < rce.expected_vbv/size_constraint) && (q < qmax)) ||
2057 ((expected_vbv < 0) && (q < lmax)))
2060 expected_size = qscale2bits(&rce, q);
2061 expected_vbv = rcc->buffer_fill + rcc->buffer_rate - expected_size;
2063 rcc->last_satd = x264_rc_analyse_slice( h );
2065 q = x264_clip3f( q, lmin, lmax );
2067 else /* 1pass ABR */
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
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. */
2079 double wanted_bits, overflow = 1;
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 ++;
2087 rce.tex_bits = rcc->last_satd;
2088 rce.blurred_complexity = rcc->short_term_cplxsum / rcc->short_term_cplxcount;
2090 rce.p_count = rcc->nmb;
2094 rce.pict_type = pict_type;
2096 if( h->param.rc.i_rc_method == X264_RC_CRF )
2098 q = get_qscale( h, &rce, rcc->rate_factor_constant, h->fenc->i_frame );
2102 q = get_qscale( h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame );
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 )
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 )
2116 abr_buffer *= X264_MAX( 1, sqrt( time_done ) );
2117 overflow = x264_clip3f( 1.0 + (total_bits - wanted_bits) / abr_buffer, .5, 2 );
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 )
2127 q = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
2128 q /= fabs( h->param.rc.f_ip_factor );
2130 else if( h->i_frame > 0 )
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 )
2138 else if( overflow < 0.9 )
2141 q = x264_clip3f(q, lmin, lmax);
2143 else if( h->param.rc.i_rc_method == X264_RC_CRF && rcc->qcompress != 1 )
2145 q = qp2qscale( ABR_INIT_QP ) / fabs( h->param.rc.f_ip_factor );
2147 rcc->qp_novbv = qscale2qp( q );
2149 //FIXME use get_diff_limited_q() ?
2150 q = clip_qscale( h, pict_type, q );
2153 rcc->last_qscale_for[pict_type] =
2154 rcc->last_qscale = q;
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 );
2159 if( rcc->b_2pass && rcc->b_vbv )
2160 rcc->frame_size_planned = qscale2bits(&rce, q);
2162 rcc->frame_size_planned = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
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;
2172 void x264_threads_normalize_predictors( x264_t *h )
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;
2182 void x264_threads_distribute_ratecontrol( x264_t *h )
2185 x264_ratecontrol_t *rc = h->rc;
2187 /* Initialize row predictors */
2188 if( h->i_frame == 0 )
2189 for( int i = 0; i < h->param.i_threads; i++ )
2191 x264_ratecontrol_t *t = h->thread[i]->rc;
2192 memcpy( t->row_preds, rc->row_preds, sizeof(rc->row_preds) );
2195 for( int i = 0; i < h->param.i_threads; i++ )
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 )
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 );
2209 t->rc->slice_size_planned = 0;
2211 if( rc->b_vbv && rc->frame_size_planned )
2213 x264_threads_normalize_predictors( h );
2215 if( rc->single_frame_vbv )
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++ )
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;
2224 x264_threads_normalize_predictors( h );
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;
2232 void x264_threads_merge_ratecontrol( x264_t *h )
2234 x264_ratecontrol_t *rc = h->rc;
2237 for( int i = 0; i < h->param.i_threads; i++ )
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 )
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 );
2252 rc->qpa_rc += rct->qpa_rc;
2253 rc->qpa_aq += rct->qpa_aq;
2257 void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
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). */
2269 COPY(last_qscale_for);
2270 COPY(last_non_b_pict_type);
2271 COPY(short_term_cplxsum);
2272 COPY(short_term_cplxcount);
2276 /* these vars can be updated by x264_ratecontrol_init_reconfigurable */
2279 COPY(single_frame_vbv);
2281 COPY(b_vbv_min_rate);
2282 COPY(rate_factor_constant);
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) */
2293 COPY(expected_bits_sum);
2294 COPY(wanted_bits_window);
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);
2302 //FIXME row_preds[] (not strictly necessary, but would improve prediction)
2303 /* the rest of the variables are either constant or thread-local */
2306 static int find_underflow( x264_t *h, double *fills, int *t0, int *t1, int over )
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++ )
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);
2323 if( fill <= buffer_min || i == 0 )
2329 else if( fill >= buffer_max && start >= 0 )
2334 return start >= 0 && end >= 0;
2337 static int fix_underflow( x264_t *h, int t0, int t1, double adjustment, double qscale_min, double qscale_max)
2339 x264_ratecontrol_t *rcc = h->rc;
2340 double qscale_orig, qscale_new;
2344 for( int i = t0; i <= t1; i++ )
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);
2356 static double count_expected_bits( x264_t *h )
2358 x264_ratecontrol_t *rcc = h->rc;
2359 double expected_bits = 0;
2360 for( int i = 0; i < rcc->num_entries; i++ )
2362 ratecontrol_entry_t *rce = &rcc->entry[i];
2363 rce->expected_bits = expected_bits;
2364 expected_bits += qscale2bits( rce, rce->new_qscale );
2366 return expected_bits;
2369 static int vbv_pass2( x264_t *h, double all_available_bits )
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 */
2376 x264_ratecontrol_t *rcc = h->rc;
2378 double expected_bits = 0;
2380 double prev_bits = 0;
2382 double qscale_min = qp2qscale( h->param.rc.i_qp_min );
2383 double qscale_max = qp2qscale( h->param.rc.i_qp_max );
2385 int adj_min, adj_max;
2386 CHECKED_MALLOC( fills, (rcc->num_entries+1)*sizeof(double) );
2390 /* adjust overall stream size */
2394 prev_bits = 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;
2403 while(adj_min && find_underflow( h, fills, &t0, &t1, 1 ))
2405 adj_min = fix_underflow( h, t0, t1, adjustment, qscale_min, qscale_max );
2410 fills[-1] = rcc->buffer_size * (1. - h->param.rc.f_vbv_buffer_init);
2412 /* fix underflows -- should be done after overflow, as we'd better undersize target than underflowing VBV */
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 );
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)) );
2421 x264_log( h, X264_LOG_WARNING, "vbv-maxrate issue, qpmax or vbv-maxrate too low\n");
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];
2427 x264_free( fills-1 );
2433 static int init_pass2( x264_t *h )
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;
2449 /* find total/average complexity & const_bits */
2450 for( int i = 0; i < rcc->num_entries; i++ )
2452 ratecontrol_entry_t *rce = &rcc->entry[i];
2453 all_const_bits += rce->misc_bits;
2456 if( all_available_bits < all_const_bits)
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.)) );
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++ )
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++ )
2477 ratecontrol_entry_t *rcj = &rcc->entry[i+j];
2478 weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 );
2479 if( weight < .0001 )
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);
2485 /* weighted average of cplx of past frames */
2487 for( int j = 0; j <= cplxblur*2 && j <= i; j++ )
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 )
2497 rce->blurred_complexity = cplx_sum / weight_sum;
2500 CHECKED_MALLOC( qscale, sizeof(double)*rcc->num_entries );
2501 if( filter_size > 1 )
2502 CHECKED_MALLOC( blurred_qscale, sizeof(double)*rcc->num_entries );
2504 blurred_qscale = qscale;
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. */
2514 for( int i = 0; i < rcc->num_entries; i++ )
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;
2520 step_mult = all_available_bits / expected_bits;
2523 for( double step = 1E4 * step_mult; step > 1E-7 * step_mult; step *= 0.5)
2526 rate_factor += step;
2528 rcc->last_non_b_pict_type = -1;
2529 rcc->last_accum_p_norm = 1;
2530 rcc->accum_p_norm = 0;
2533 for( int i = 0; i < rcc->num_entries; i++ )
2535 qscale[i] = get_qscale( h, &rcc->entry[i], rate_factor, i );
2536 rcc->last_qscale_for[rcc->entry[i].pict_type] = qscale[i];
2539 /* fixed I/B qscale relative to P */
2540 for( int i = rcc->num_entries-1; i >= 0; i-- )
2542 qscale[i] = get_diff_limited_q( h, &rcc->entry[i], qscale[i] );
2543 assert(qscale[i] >= 0);
2547 if( filter_size > 1 )
2549 assert( filter_size%2 == 1 );
2550 for( int i = 0; i < rcc->num_entries; i++ )
2552 ratecontrol_entry_t *rce = &rcc->entry[i];
2553 double q = 0.0, sum = 0.0;
2555 for( int j = 0; j < filter_size; j++ )
2557 int index = i+j-filter_size/2;
2559 double coeff = qblur==0 ? 1.0 : exp( -d*d/(qblur*qblur) );
2560 if( index < 0 || index >= rcc->num_entries )
2562 if( rce->pict_type != rcc->entry[index].pict_type )
2564 q += qscale[index] * coeff;
2567 blurred_qscale[i] = q/sum;
2571 /* find expected bits */
2572 for( int i = 0; i < rcc->num_entries; i++ )
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 );
2580 if( expected_bits > all_available_bits )
2581 rate_factor -= step;
2584 x264_free( qscale );
2585 if( filter_size > 1 )
2586 x264_free( blurred_qscale );
2589 if( vbv_pass2( h, all_available_bits ) )
2591 expected_bits = count_expected_bits( h );
2593 if( fabs( expected_bits/all_available_bits - 1.0 ) > 0.01 )
2596 for( int i = 0; i < rcc->num_entries; i++ )
2597 avgq += rcc->entry[i].new_qscale;
2598 avgq = qscale2qp( avgq / rcc->num_entries );
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.),
2606 if( expected_bits < all_available_bits && avgq < h->param.rc.i_qp_min + 2 )
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 );
2611 x264_log( h, X264_LOG_WARNING, "try reducing target bitrate\n" );
2613 else if( expected_bits > all_available_bits && avgq > h->param.rc.i_qp_max - 2 )
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 );
2618 x264_log( h, X264_LOG_WARNING, "try increasing target bitrate\n");
2620 else if( !(rcc->b_2pass && rcc->b_vbv) )
2621 x264_log( h, X264_LOG_WARNING, "internal error\n" );