+ if( pict_type == SLICE_TYPE_B )
+ {
+ rcc->last_satd = 0;
+ if(h->fenc->b_kept_as_ref)
+ q = rcc->last_qscale * sqrtf(h->param.rc.f_pb_factor);
+ else
+ q = rcc->last_qscale * h->param.rc.f_pb_factor;
+ return x264_clip3f(q, lmin, lmax);
+ }
+ else
+ {
+ double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate;
+ if( rcc->b_2pass )
+ {
+ //FIXME adjust abr_buffer based on distance to the end of the video
+ int64_t diff = total_bits - (int64_t)rce.expected_bits;
+ q = rce.new_qscale;
+ q /= x264_clip3f((double)(abr_buffer - diff) / abr_buffer, .5, 2);
+ if( h->fenc->i_frame > 30 )
+ {
+ /* Adjust quant based on the difference between
+ * achieved and expected bitrate so far */
+ double time = (double)h->fenc->i_frame / rcc->num_entries;
+ double w = x264_clip3f( time*100, 0.0, 1.0 );
+ q *= pow( (double)total_bits / rcc->expected_bits_sum, w );
+ }
+ q = x264_clip3f( q, lmin, lmax );
+ }
+ else /* 1pass ABR */
+ {
+ /* Calculate the quantizer which would have produced the desired
+ * average bitrate if it had been applied to all frames so far.
+ * Then modulate that quant based on the current frame's complexity
+ * relative to the average complexity so far (using the 2pass RCEQ).
+ * Then bias the quant up or down if total size so far was far from
+ * the target.
+ * Result: Depending on the value of rate_tolerance, there is a
+ * tradeoff between quality and bitrate precision. But at large
+ * tolerances, the bit distribution approaches that of 2pass. */
+
+ double wanted_bits, overflow, lmin, lmax;
+
+ rcc->last_satd = x264_rc_analyse_slice( h );
+ rcc->short_term_cplxsum *= 0.5;
+ rcc->short_term_cplxcount *= 0.5;
+ rcc->short_term_cplxsum += rcc->last_satd;
+ rcc->short_term_cplxcount ++;
+
+ rce.p_tex_bits = rcc->last_satd;
+ rce.blurred_complexity = rcc->short_term_cplxsum / rcc->short_term_cplxcount;
+ rce.i_tex_bits = 0;
+ rce.mv_bits = 0;
+ rce.p_count = rcc->nmb;
+ rce.i_count = 0;
+ rce.s_count = 0;
+ rce.qscale = 1;
+ rce.pict_type = pict_type;
+ q = get_qscale(h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame);
+
+ wanted_bits = h->fenc->i_frame * rcc->bitrate / rcc->fps;
+ abr_buffer *= X264_MAX( 1, sqrt(h->fenc->i_frame/25) );
+ overflow = x264_clip3f( 1.0 + (total_bits - wanted_bits) / abr_buffer, .5, 2 );
+ q *= overflow;
+
+ if( pict_type == SLICE_TYPE_I
+ /* should test _next_ pict type, but that isn't decided yet */
+ && rcc->last_non_b_pict_type != SLICE_TYPE_I )
+ {
+ q = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
+ q /= fabs( h->param.rc.f_ip_factor );
+ q = clip_qscale( h, pict_type, q );
+ }
+ else
+ {
+ if( h->stat.i_slice_count[SLICE_TYPE_P] < 5 )
+ {
+ float w = h->stat.i_slice_count[SLICE_TYPE_P] / 5.;
+ float q2 = qp2qscale(ABR_INIT_QP);
+ q = q*w + q2*(1-w);
+ }