]> git.sesse.net Git - x264/blobdiff - encoder/ratecontrol.c
eliminate some divisions
[x264] / encoder / ratecontrol.c
index b11c7c4357f3ae98ce2f871d26a98c73d4058f84..7054c35ad5dc10b9788e543b79a9f5cf90534e7d 100644 (file)
@@ -31,6 +31,7 @@
 #include "common/common.h"
 #include "common/cpu.h"
 #include "ratecontrol.h"
+#include "me.h"
 
 typedef struct
 {
@@ -49,6 +50,8 @@ typedef struct
     int s_count;
     float blurred_complexity;
     char direct_mode;
+    int refcount[16];
+    int refs;
 } ratecontrol_entry_t;
 
 typedef struct
@@ -89,6 +92,7 @@ struct x264_ratecontrol_t
     double buffer_fill;         /* planned buffer, if all in-progress frames hit their bit budget */
     double buffer_rate;         /* # of bits added to buffer_fill after each frame */
     predictor_t *pred;          /* predict frame size from satd */
+    int single_frame_vbv;
 
     /* ABR stuff */
     int    last_satd;
@@ -127,8 +131,8 @@ struct x264_ratecontrol_t
     /* MBRC stuff */
     double frame_size_estimated;
     double frame_size_planned;
-    predictor_t *row_pred;
-    predictor_t row_preds[5];
+    predictor_t (*row_pred)[2];
+    predictor_t row_preds[5][2];
     predictor_t *pred_b_from_p; /* predict B-frame size from P-frame satd */
     int bframes;                /* # consecutive B-frames before this P-frame */
     int bframe_bits;            /* total cost of those frames */
@@ -143,7 +147,7 @@ static int parse_zones( x264_t *h );
 static int init_pass2(x264_t *);
 static float rate_estimate_qscale( x264_t *h );
 static void update_vbv( x264_t *h, int bits );
-static void update_vbv_plan( x264_t *h );
+static void update_vbv_plan( x264_t *h, int overhead );
 static double predict_size( predictor_t *p, double q, double var );
 static void update_predictor( predictor_t *p, double q, double var, double bits );
 
@@ -290,7 +294,11 @@ int x264_macroblock_tree_read( x264_t *h, x264_frame_t *frame )
             goto fail;
 
         for( i = 0; i < h->mb.i_mb_count; i++ )
+        {
             frame->f_qp_offset[i] = ((float)(int16_t)endian_fix16( rc->qp_buffer[i] )) * (1/256.0);
+            if( h->frames.b_have_lowres )
+                frame->i_inv_qscale_factor[i] = x264_exp2fix8(frame->f_qp_offset[i]);
+        }
     }
     else
         x264_adaptive_quant_frame( h, frame );
@@ -300,6 +308,33 @@ fail:
     return -1;
 }
 
+int x264_reference_build_list_optimal( x264_t *h )
+{
+    ratecontrol_entry_t *rce = h->rc->rce;
+    x264_frame_t *frames[16];
+    int ref, i;
+
+    if( rce->refs != h->i_ref0 )
+        return -1;
+
+    memcpy( frames, h->fref0, sizeof(frames) );
+
+    /* For now don't reorder ref 0; it seems to lower quality
+       in most cases due to skips. */
+    for( ref = 1; ref < h->i_ref0; ref++ )
+    {
+        int max = -1;
+        int bestref = 1;
+        for( i = 1; i < h->i_ref0; i++ )
+            /* Favor lower POC as a tiebreaker. */
+            COPY2_IF_GT( max, rce->refcount[i], bestref, i );
+        rce->refcount[bestref] = -1;
+        h->fref0[ref] = frames[bestref];
+    }
+
+    return 0;
+}
+
 static char *x264_strcat_filename( char *input, char *suffix )
 {
     char *output = x264_malloc( strlen( input ) + strlen( suffix ) + 1 );
@@ -313,7 +348,7 @@ static char *x264_strcat_filename( char *input, char *suffix )
 int x264_ratecontrol_new( x264_t *h )
 {
     x264_ratecontrol_t *rc;
-    int i;
+    int i, j;
 
     x264_emms();
 
@@ -368,16 +403,18 @@ int x264_ratecontrol_new( x264_t *h )
     else if( h->param.rc.i_vbv_max_bitrate > 0 &&
              h->param.rc.i_vbv_buffer_size > 0 )
     {
-        if( h->param.rc.i_vbv_buffer_size < 3 * h->param.rc.i_vbv_max_bitrate / rc->fps )
+        if( h->param.rc.i_vbv_buffer_size < (int)(h->param.rc.i_vbv_max_bitrate / rc->fps) )
         {
-            h->param.rc.i_vbv_buffer_size = 3 * h->param.rc.i_vbv_max_bitrate / rc->fps;
-            x264_log( h, X264_LOG_WARNING, "VBV buffer size too small, using %d kbit\n",
+            h->param.rc.i_vbv_buffer_size = h->param.rc.i_vbv_max_bitrate / rc->fps;
+            x264_log( h, X264_LOG_WARNING, "VBV buffer size cannot be smaller than one frame, using %d kbit\n",
                       h->param.rc.i_vbv_buffer_size );
         }
         if( h->param.rc.f_vbv_buffer_init > 1. )
             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 );
         rc->buffer_rate = h->param.rc.i_vbv_max_bitrate * 1000. / rc->fps;
         rc->buffer_size = h->param.rc.i_vbv_buffer_size * 1000.;
+        rc->single_frame_vbv = rc->buffer_rate * 1.1 > rc->buffer_size;
+        h->param.rc.f_vbv_buffer_init = X264_MAX( h->param.rc.f_vbv_buffer_init, rc->buffer_rate / rc->buffer_size );
         rc->buffer_fill_final = rc->buffer_size * h->param.rc.f_vbv_buffer_init;
         rc->cbr_decay = 1.0 - rc->buffer_rate / rc->buffer_size
                       * 0.5 * X264_MAX(0, 1.5 - rc->buffer_rate * rc->fps / rc->bitrate);
@@ -440,10 +477,13 @@ int x264_ratecontrol_new( x264_t *h )
         rc->pred[i].count= 1.0;
         rc->pred[i].decay= 0.5;
         rc->pred[i].offset= 0.0;
-        rc->row_preds[i].coeff= .25;
-        rc->row_preds[i].count= 1.0;
-        rc->row_preds[i].decay= 0.5;
-        rc->row_preds[i].offset= 0.0;
+        for( j = 0; j < 2; j++ )
+        {
+            rc->row_preds[i][j].coeff= .25;
+            rc->row_preds[i][j].count= 1.0;
+            rc->row_preds[i][j].decay= 0.5;
+            rc->row_preds[i][j].offset= 0.0;
+        }
     }
     *rc->pred_b_from_p = rc->pred[0];
 
@@ -575,6 +615,7 @@ int x264_ratecontrol_new( x264_t *h )
             int e;
             char *next;
             float qp;
+            int ref;
 
             next= strchr(p, ';');
             if(next)
@@ -597,6 +638,20 @@ int x264_ratecontrol_new( x264_t *h )
                    &rce->mv_bits, &rce->misc_bits, &rce->i_count, &rce->p_count,
                    &rce->s_count, &rce->direct_mode);
 
+            p = strstr( p, "ref:" );
+            if( !p )
+                goto parse_error;
+            p += 4;
+            for( ref = 0; ref < 16; ref++ )
+            {
+                if( sscanf( p, " %d", &rce->refcount[ref] ) != 1 )
+                    break;
+                p = strchr( p+1, ' ' );
+                if( !p )
+                    goto parse_error;
+            }
+            rce->refs = ref;
+
             switch(pict_type)
             {
                 case 'I': rce->kept_as_ref = 1;
@@ -608,6 +663,7 @@ int x264_ratecontrol_new( x264_t *h )
             }
             if(e < 10)
             {
+parse_error:
                 x264_log(h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);
                 return -1;
             }
@@ -806,7 +862,7 @@ void x264_ratecontrol_summary( x264_t *h )
     if( rc->b_abr && h->param.rc.i_rc_method == X264_RC_ABR && rc->cbr_decay > .9999 )
     {
         double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
-        double mbtree_offset = h->param.rc.b_mb_tree ? (1.0-h->param.rc.f_qcompress)*12.5 : 0;
+        double mbtree_offset = h->param.rc.b_mb_tree ? (1.0-h->param.rc.f_qcompress)*13.5 : 0;
         x264_log( h, X264_LOG_INFO, "final ratefactor: %.2f\n",
                   qscale2qp( pow( base_cplx, 1 - rc->qcompress )
                              * rc->cplxr_sum / rc->wanted_bits_window ) - mbtree_offset );
@@ -841,6 +897,8 @@ void x264_ratecontrol_delete( x264_t *h )
         x264_free( rc->psz_mbtree_stat_file_tmpname );
         x264_free( rc->psz_mbtree_stat_file_name );
     }
+    if( rc->p_mbtree_stat_file_in )
+        fclose( rc->p_mbtree_stat_file_in );
     x264_free( rc->pred );
     x264_free( rc->pred_b_from_p );
     x264_free( rc->entry );
@@ -885,7 +943,7 @@ static void accum_p_qp_update( x264_t *h, float qp )
 }
 
 /* Before encoding a frame, choose a QP for it */
-void x264_ratecontrol_start( x264_t *h, int i_force_qp )
+void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
 {
     x264_ratecontrol_t *rc = h->rc;
     ratecontrol_entry_t *rce = NULL;
@@ -918,7 +976,7 @@ void x264_ratecontrol_start( x264_t *h, int i_force_qp )
     {
         memset( h->fdec->i_row_bits, 0, h->sps->i_mb_height * sizeof(int) );
         rc->row_pred = &rc->row_preds[h->sh.i_type];
-        update_vbv_plan( h );
+        update_vbv_plan( h, overhead );
     }
 
     if( h->sh.i_type != SLICE_TYPE_B )
@@ -976,20 +1034,31 @@ static double predict_row_size( x264_t *h, int y, int qp )
     /* average between two predictors:
      * absolute SATD, and scaled bit cost of the colocated row in the previous frame */
     x264_ratecontrol_t *rc = h->rc;
-    double pred_s = predict_size( rc->row_pred, qp2qscale(qp), h->fdec->i_row_satd[y] );
+    double pred_s = predict_size( rc->row_pred[0], qp2qscale(qp), h->fdec->i_row_satd[y] );
     double pred_t = 0;
-    if( h->sh.i_type != SLICE_TYPE_I
-        && h->fref0[0]->i_type == h->fdec->i_type
-        && h->fref0[0]->i_row_satd[y] > 0
-        && (abs(h->fref0[0]->i_row_satd[y] - h->fdec->i_row_satd[y]) < h->fdec->i_row_satd[y]/2))
+    if( h->sh.i_type == SLICE_TYPE_I || qp >= h->fref0[0]->i_row_qp[y] )
     {
-        pred_t = h->fref0[0]->i_row_bits[y] * h->fdec->i_row_satd[y] / h->fref0[0]->i_row_satd[y]
-                 * qp2qscale(h->fref0[0]->i_row_qp[y]) / qp2qscale(qp);
+        if( h->sh.i_type == SLICE_TYPE_P
+            && h->fref0[0]->i_type == h->fdec->i_type
+            && h->fref0[0]->i_row_satd[y] > 0
+            && (abs(h->fref0[0]->i_row_satd[y] - h->fdec->i_row_satd[y]) < h->fdec->i_row_satd[y]/2))
+        {
+            pred_t = h->fref0[0]->i_row_bits[y] * h->fdec->i_row_satd[y] / h->fref0[0]->i_row_satd[y]
+                     * qp2qscale(h->fref0[0]->i_row_qp[y]) / qp2qscale(qp);
+        }
+        if( pred_t == 0 )
+            pred_t = pred_s;
+        return (pred_s + pred_t) / 2;
+    }
+    /* Our QP is lower than the reference! */
+    else
+    {
+        double newq = qp2qscale(qp);
+        double oldq = qp2qscale(h->fref0[0]->i_row_qp[y]);
+        double pred_intra = predict_size( rc->row_pred[1], (1 - newq / oldq) * newq, h->fdec->i_row_satds[0][0][y] );
+        /* Sum: better to overestimate than underestimate by using only one of the two predictors. */
+        return pred_intra + pred_s;
     }
-    if( pred_t == 0 )
-        pred_t = pred_s;
-
-    return (pred_s + pred_t) / 2;
 }
 
 static double row_bits_so_far( x264_t *h, int y )
@@ -1027,80 +1096,75 @@ void x264_ratecontrol_mb( x264_t *h, int bits )
 
     h->fdec->i_row_qp[y] = rc->qpm;
 
-    if( h->sh.i_type == SLICE_TYPE_B )
+    update_predictor( rc->row_pred[0], qp2qscale(rc->qpm), h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] );
+    if( h->sh.i_type == SLICE_TYPE_P && rc->qpm < h->fref0[0]->i_row_qp[y] )
     {
-        /* B-frames shouldn't use lower QP than their reference frames.
-         * This code is a bit overzealous in limiting B-frame quantizers, but it helps avoid
-         * underflows due to the fact that B-frames are not explicitly covered by VBV. */
-        if( y < h->sps->i_mb_height-1 )
-        {
-            int i_estimated;
-            int avg_qp = X264_MIN(h->fref0[0]->i_row_qp[y+1], h->fref1[0]->i_row_qp[y+1])
-                       + rc->pb_offset * ((h->fenc->i_type == X264_TYPE_BREF) ? 0.5 : 1);
-            rc->qpm = X264_MIN(X264_MAX( rc->qp, avg_qp), 51); //avg_qp could go higher than 51 due to pb_offset
-            i_estimated = row_bits_so_far(h, y); //FIXME: compute full estimated size
-            if (i_estimated > h->rc->frame_size_planned)
-                x264_ratecontrol_set_estimated_size(h, i_estimated);
-        }
+        double newq = qp2qscale(rc->qpm);
+        double oldq = qp2qscale(h->fref0[0]->i_row_qp[y]);
+        update_predictor( rc->row_pred[1], (1 - newq / oldq) * newq, h->fdec->i_row_satds[0][0][y], h->fdec->i_row_bits[y] );
     }
-    else
+
+    /* tweak quality based on difference from predicted size */
+    if( y < h->sps->i_mb_height-1 )
     {
-        update_predictor( rc->row_pred, qp2qscale(rc->qpm), h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] );
+        int prev_row_qp = h->fdec->i_row_qp[y];
+        int i_qp_max = X264_MIN( prev_row_qp + h->param.rc.i_qp_step, h->param.rc.i_qp_max );
+        int i_qp_min = X264_MAX( prev_row_qp - h->param.rc.i_qp_step, h->param.rc.i_qp_min );
+
+        /* B-frames shouldn't use lower QP than their reference frames. */
+        if( h->sh.i_type == SLICE_TYPE_B )
+        {
+            i_qp_min = X264_MAX( i_qp_min, X264_MAX( h->fref0[0]->i_row_qp[y+1], h->fref1[0]->i_row_qp[y+1] ) );
+            rc->qpm = X264_MAX( rc->qpm, i_qp_min );
+        }
+
+        int b0 = predict_row_size_sum( h, y, rc->qpm );
+        int b1 = b0;
+        float buffer_left_planned = rc->buffer_fill - rc->frame_size_planned;
+
+        /* More threads means we have to be more cautious in letting ratecontrol use up extra bits. */
+        float rc_tol = buffer_left_planned / h->param.i_threads * rc->rate_tolerance;
+
+        /* Don't modify the row QPs until a sufficent amount of the bits of the frame have been processed, in case a flat */
+        /* area at the top of the frame was measured inaccurately. */
+        if( row_bits_so_far(h,y) < 0.05 * rc->frame_size_planned )
+            return;
+
+        if( h->sh.i_type != SLICE_TYPE_I )
+            rc_tol /= 2;
+
+        if( !rc->b_vbv_min_rate )
+            i_qp_min = X264_MAX( i_qp_min, h->sh.i_qp );
 
-        /* tweak quality based on difference from predicted size */
-        if( y < h->sps->i_mb_height-1 && h->stat.i_frame_count[h->sh.i_type] > 0 )
+        while( rc->qpm < i_qp_max
+               && ((b1 > rc->frame_size_planned + rc_tol) ||
+                   (rc->buffer_fill - b1 < buffer_left_planned * 0.5) ||
+                   (b1 > rc->frame_size_planned && rc->qpm < rc->qp_novbv)) )
         {
-            int prev_row_qp = h->fdec->i_row_qp[y];
-            int b0 = predict_row_size_sum( h, y, rc->qpm );
-            int b1 = b0;
-            int i_qp_max = X264_MIN( prev_row_qp + h->param.rc.i_qp_step, h->param.rc.i_qp_max );
-            int i_qp_min = X264_MAX( prev_row_qp - h->param.rc.i_qp_step, h->param.rc.i_qp_min );
-            float buffer_left_planned = rc->buffer_fill - rc->frame_size_planned;
-            /* More threads means we have to be more cautious in letting ratecontrol use up extra bits.
-             * In 2-pass mode we can be more trusting of the planned frame sizes, since they were decided
-             * by actual encoding instead of SATD prediction. */
-            float rc_tol = h->param.rc.b_stat_read ? (buffer_left_planned / rc->buffer_size) * rc->frame_size_planned
-                                                   : (buffer_left_planned / h->param.i_threads);
-
-            /* Don't modify the row QPs until a sufficent amount of the bits of the frame have been processed, in case a flat */
-            /* area at the top of the frame was measured inaccurately. */
-            if(row_bits_so_far(h,y) < 0.05 * rc->frame_size_planned)
-                return;
-
-            if(h->sh.i_type != SLICE_TYPE_I)
-                rc_tol /= 2;
-
-            if( !rc->b_vbv_min_rate )
-                i_qp_min = X264_MAX( i_qp_min, h->sh.i_qp );
-
-            while( rc->qpm < i_qp_max
-                   && ((b1 > rc->frame_size_planned + rc_tol) ||
-                       (rc->buffer_fill - b1 < buffer_left_planned * 0.5) ||
-                       (b1 > rc->frame_size_planned && rc->qpm < rc->qp_novbv)) )
-            {
-                rc->qpm ++;
-                b1 = predict_row_size_sum( h, y, rc->qpm );
-            }
+            rc->qpm ++;
+            b1 = predict_row_size_sum( h, y, rc->qpm );
+        }
 
-            /* avoid VBV underflow */
-            while( (rc->qpm < h->param.rc.i_qp_max)
-                   && (rc->buffer_fill - b1 < rc->buffer_size * 0.005))
-            {
-                rc->qpm ++;
-                b1 = predict_row_size_sum( h, y, rc->qpm );
-            }
+        while( rc->qpm > i_qp_min
+               && (rc->qpm > h->fdec->i_row_qp[0] || rc->single_frame_vbv)
+               && ((b1 < rc->frame_size_planned * 0.8 && rc->qpm <= prev_row_qp)
+               || b1 < (rc->buffer_fill - rc->buffer_size + rc->buffer_rate) * 1.1) )
+        {
+            rc->qpm --;
+            b1 = predict_row_size_sum( h, y, rc->qpm );
+        }
 
-            while( rc->qpm > i_qp_min
-                   && rc->qpm > h->fdec->i_row_qp[0]
-                   && ((b1 < rc->frame_size_planned * 0.8 && rc->qpm <= prev_row_qp)
-                     || b1 < (rc->buffer_fill - rc->buffer_size + rc->buffer_rate) * 1.1) )
-            {
-                rc->qpm --;
-                b1 = predict_row_size_sum( h, y, rc->qpm );
-            }
-            x264_ratecontrol_set_estimated_size(h, b1);
+        /* avoid VBV underflow */
+        while( (rc->qpm < h->param.rc.i_qp_max)
+               && (rc->buffer_fill - b1 < rc->buffer_rate * 0.05 ) )
+        {
+            rc->qpm ++;
+            b1 = predict_row_size_sum( h, y, rc->qpm );
         }
+
+        x264_ratecontrol_set_estimated_size(h, b1);
     }
+
     /* loses the fractional part of the frame-wise qp */
     rc->f_qpm = rc->qpm;
 }
@@ -1196,7 +1260,7 @@ int x264_ratecontrol_end( x264_t *h, int bits )
                           dir_avg>0 ? 's' : dir_avg<0 ? 't' : '-' )
                         : '-';
         if( fprintf( rc->p_stat_file_out,
-                 "in:%d out:%d type:%c q:%.2f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c;\n",
+                 "in:%d out:%d type:%c q:%.2f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c ref:",
                  h->fenc->i_frame, h->i_frame,
                  c_type, rc->qpa_rc,
                  h->stat.frame.i_tex_bits,
@@ -1206,7 +1270,19 @@ int x264_ratecontrol_end( x264_t *h, int bits )
                  h->stat.frame.i_mb_count_p,
                  h->stat.frame.i_mb_count_skip,
                  c_direct) < 0 )
-             goto fail;
+            goto fail;
+
+        for( i = 0; i < h->i_ref0; i++ )
+        {
+            int refcount = h->param.b_interlaced ? h->stat.frame.i_mb_count_ref[0][i*2]
+                                                 + h->stat.frame.i_mb_count_ref[0][i*2+1] :
+                                                   h->stat.frame.i_mb_count_ref[0][i];
+            if( fprintf( rc->p_stat_file_out, "%d ", refcount ) < 0 )
+                goto fail;
+        }
+
+        if( fprintf( rc->p_stat_file_out, ";\n" ) < 0 )
+            goto fail;
 
         /* Don't re-write the data in multi-pass mode. */
         if( h->param.rc.b_mb_tree && h->fenc->b_kept_as_ref && !h->param.rc.b_stat_read )
@@ -1405,17 +1481,19 @@ static void update_vbv( x264_t *h, int bits )
     if( !rcc->b_vbv )
         return;
 
-    rct->buffer_fill_final += rct->buffer_rate - bits;
+    rct->buffer_fill_final -= bits;
     if( rct->buffer_fill_final < 0 )
-        x264_log( h, X264_LOG_WARNING, "VBV underflow (%.0f bits)\n", rct->buffer_fill_final );
-    rct->buffer_fill_final = x264_clip3f( rct->buffer_fill_final, 0, rct->buffer_size );
+        x264_log( h, X264_LOG_WARNING, "VBV underflow (frame %d, %.0f bits)\n", h->i_frame, rct->buffer_fill_final );
+    rct->buffer_fill_final = X264_MAX( rct->buffer_fill_final, 0 );
+    rct->buffer_fill_final += rct->buffer_rate;
+    rct->buffer_fill_final = X264_MIN( rct->buffer_fill_final, rct->buffer_size );
 }
 
 // provisionally update VBV according to the planned size of all frames currently in progress
-static void update_vbv_plan( x264_t *h )
+static void update_vbv_plan( x264_t *h, int overhead )
 {
     x264_ratecontrol_t *rcc = h->rc;
-    rcc->buffer_fill = h->thread[0]->rc->buffer_fill_final;
+    rcc->buffer_fill = h->thread[0]->rc->buffer_fill_final - overhead;
     if( h->param.i_threads > 1 )
     {
         int j = h->rc - h->thread[0]->rc;
@@ -1427,8 +1505,10 @@ static void update_vbv_plan( x264_t *h )
             if( !t->b_thread_active )
                 continue;
             bits  = X264_MAX(bits, x264_ratecontrol_get_estimated_size(t));
-            rcc->buffer_fill += rcc->buffer_rate - bits;
-            rcc->buffer_fill = x264_clip3( rcc->buffer_fill, 0, rcc->buffer_size );
+            rcc->buffer_fill -= bits;
+            rcc->buffer_fill = X264_MAX( rcc->buffer_fill, 0 );
+            rcc->buffer_fill += rcc->buffer_rate;
+            rcc->buffer_fill = X264_MIN( rcc->buffer_fill, rcc->buffer_size );
         }
     }
 }
@@ -1508,34 +1588,37 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
              * 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;
-            if( bits > rcc->buffer_fill/2 )
-                qf = x264_clip3f( rcc->buffer_fill/(2*bits), 0.2, 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/2 )
-                q *= bits*2/rcc->buffer_rate;
+            if( bits < rcc->buffer_rate/min_fill_factor )
+                q *= bits*min_fill_factor/rcc->buffer_rate;
             q = X264_MAX( q0, q );
         }
 
         /* Check B-frame complexity, and use up any bits that would
          * overflow before the next P-frame. */
-        if( h->sh.i_type == SLICE_TYPE_P )
+        if( h->sh.i_type == SLICE_TYPE_P && !rcc->single_frame_vbv )
         {
             int nb = rcc->bframes;
             double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
             double pbbits = bits;
             double bbits = predict_size( rcc->pred_b_from_p, q * h->param.rc.f_pb_factor, rcc->last_satd );
             double space;
-
-            if( bbits > rcc->buffer_rate )
+            if( bbits > rcc->buffer_rate  )
                 nb = 0;
             pbbits += nb * bbits;
 
             space = rcc->buffer_fill + (1+nb)*rcc->buffer_rate - rcc->buffer_size;
             if( pbbits < space )
             {
-                q *= X264_MAX( pbbits / space,
-                               bits / (0.5 * rcc->buffer_size) );
+                q *= X264_MAX( pbbits / space, bits / (0.5 * rcc->buffer_size) );
             }
             q = X264_MAX( q0-5, q );
         }
@@ -1613,9 +1696,15 @@ static float rate_estimate_qscale( x264_t *h )
         else
             q += rcc->pb_offset;
 
-        rcc->frame_size_planned = predict_size( rcc->pred_b_from_p, q, h->fref1[h->i_ref1-1]->i_satd );
+        if( rcc->b_2pass && rcc->b_vbv )
+            rcc->frame_size_planned = qscale2bits( &rce, q );
+        else
+            rcc->frame_size_planned = predict_size( rcc->pred_b_from_p, q, h->fref1[h->i_ref1-1]->i_satd );
         x264_ratecontrol_set_estimated_size(h, rcc->frame_size_planned);
-        rcc->last_satd = 0;
+
+        /* For row SATDs */
+        if( rcc->b_vbv )
+            rcc->last_satd = x264_rc_analyse_slice( h );
         return qp2qscale(q);
     }
     else
@@ -1684,7 +1773,7 @@ static float rate_estimate_qscale( x264_t *h )
                     expected_size = qscale2bits(&rce, q);
                     expected_vbv = rcc->buffer_fill + rcc->buffer_rate - expected_size;
                 }
-                rcc->last_satd = x264_stack_align( x264_rc_analyse_slice, h );
+                rcc->last_satd = x264_rc_analyse_slice( h );
             }
             q = x264_clip3f( q, lmin, lmax );
         }
@@ -1702,7 +1791,7 @@ static float rate_estimate_qscale( x264_t *h )
 
             double wanted_bits, overflow=1, lmin, lmax;
 
-            rcc->last_satd = x264_stack_align( x264_rc_analyse_slice, h );
+            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;
@@ -1934,7 +2023,7 @@ static int vbv_pass2( x264_t *h )
             adj_max = fix_underflow(h, t0, t1, 1.001, qscale_min, qscale_max);
 
         expected_bits = count_expected_bits(h);
-    } while((expected_bits < .995*all_available_bits) && ((int)(expected_bits+.5) > (int)(prev_bits+.5)) );
+    } while((expected_bits < .995*all_available_bits) && ((int64_t)(expected_bits+.5) > (int64_t)(prev_bits+.5)) );
 
     if (!adj_max)
         x264_log( h, X264_LOG_WARNING, "vbv-maxrate issue, qpmax or vbv-maxrate too low\n");