+ /* Lookahead VBV: raise the quantizer as necessary such that no frames in
+ * the lookahead overflow and such that the buffer is in a reasonable state
+ * by the end of the lookahead. */
+ if( h->param.rc.i_lookahead )
+ {
+ int j, iterations, terminate = 0;
+
+ /* Avoid an infinite loop. */
+ for( iterations = 0; iterations < 1000 && terminate != 3; iterations++ )
+ {
+ double frame_q[3];
+ double cur_bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
+ double buffer_fill_cur = rcc->buffer_fill - cur_bits + rcc->buffer_rate;
+ double target_fill;
+ frame_q[0] = h->sh.i_type == SLICE_TYPE_I ? q * h->param.rc.f_ip_factor : q;
+ frame_q[1] = frame_q[0] * h->param.rc.f_pb_factor;
+ frame_q[2] = frame_q[0] / h->param.rc.f_ip_factor;
+
+ /* Loop over the planned future frames. */
+ for( j = 0; buffer_fill_cur >= 0 && buffer_fill_cur <= rcc->buffer_size; j++ )
+ {
+ int i_type = h->fenc->i_planned_type[j];
+ int i_satd = h->fenc->i_planned_satd[j];
+ if( i_type == X264_TYPE_AUTO )
+ break;
+ i_type = IS_X264_TYPE_I( i_type ) ? SLICE_TYPE_I : IS_X264_TYPE_B( i_type ) ? SLICE_TYPE_B : SLICE_TYPE_P;
+ cur_bits = predict_size( &rcc->pred[i_type], frame_q[i_type], i_satd );
+ buffer_fill_cur = buffer_fill_cur - cur_bits + rcc->buffer_rate;
+ }
+ /* Try to get to get the buffer at least 50% filled, but don't set an impossible goal. */
+ target_fill = X264_MIN( rcc->buffer_fill + j * rcc->buffer_rate * 0.5, rcc->buffer_size * 0.5 );
+ if( buffer_fill_cur < target_fill )
+ {
+ q *= 1.01;
+ terminate |= 1;
+ continue;
+ }
+ /* Try to get the buffer no more than 80% filled, but don't set an impossible goal. */
+ target_fill = x264_clip3f( rcc->buffer_fill - j * rcc->buffer_rate * 0.5, rcc->buffer_size * 0.8, rcc->buffer_size );
+ if( rcc->b_vbv_min_rate && buffer_fill_cur > target_fill )
+ {
+ q /= 1.01;
+ terminate |= 2;
+ continue;
+ }
+ break;
+ }
+ }
+ /* Fallback to old purely-reactive algorithm: no lookahead. */
+ else
+ {
+ if( ( pict_type == SLICE_TYPE_P ||
+ ( pict_type == SLICE_TYPE_I && rcc->last_non_b_pict_type == SLICE_TYPE_I ) ) &&
+ rcc->buffer_fill/rcc->buffer_size < 0.5 )
+ {
+ q /= x264_clip3f( 2.0*rcc->buffer_fill/rcc->buffer_size, 0.5, 1.0 );
+ }
+
+ /* Now a hard threshold to make sure the frame fits in VBV.
+ * This one is mostly for I-frames. */
+ double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
+ double qf = 1.0;
+ /* For small VBVs, allow the frame to use up the entire VBV. */
+ double max_fill_factor = h->param.rc.i_vbv_buffer_size >= 5*h->param.rc.i_vbv_max_bitrate / rcc->fps ? 2 : 1;
+ /* For single-frame VBVs, request that the frame use up the entire VBV. */
+ double min_fill_factor = rcc->single_frame_vbv ? 1 : 2;
+
+ if( bits > rcc->buffer_fill/max_fill_factor )
+ qf = x264_clip3f( rcc->buffer_fill/(max_fill_factor*bits), 0.2, 1.0 );
+ q /= qf;
+ bits *= qf;
+ if( bits < rcc->buffer_rate/min_fill_factor )
+ q *= bits*min_fill_factor/rcc->buffer_rate;
+ q = X264_MAX( q0, q );
+ }