]> git.sesse.net Git - x264/blobdiff - encoder/ratecontrol.c
Slightly faster predictor_difference_mmxext
[x264] / encoder / ratecontrol.c
index 72d3c37219f2ebf7082ed0592745d8db06f4e861..0e3e99ab080a36d7572faad50cd7658faa185dd9 100644 (file)
 #include "common/common.h"
 #include "common/cpu.h"
 #include "ratecontrol.h"
+#include "me.h"
 
 typedef struct
 {
     int pict_type;
+    int frame_type;
     int kept_as_ref;
-    float qscale;
+    double qscale;
     int mv_bits;
     int tex_bits;
     int misc_bits;
     uint64_t expected_bits; /*total expected bits up to the current frame (current one excluded)*/
     double expected_vbv;
-    float new_qscale;
+    double new_qscale;
     int new_qp;
     int i_count;
     int p_count;
     int s_count;
     float blurred_complexity;
     char direct_mode;
+    int16_t weight[2];
+    int16_t i_weight_denom;
+    int refcount[16];
+    int refs;
 } ratecontrol_entry_t;
 
 typedef struct
@@ -89,6 +95,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;
@@ -122,13 +129,16 @@ struct x264_ratecontrol_t
     double lmin[5];             /* min qscale by frame type */
     double lmax[5];
     double lstep;               /* max change (multiply) in qscale per frame */
-    uint16_t *qp_buffer; /* Global buffer for converting MB-tree quantizer data. */
+    uint16_t *qp_buffer[2];     /* Global buffers for converting MB-tree quantizer data. */
+    int qpbuf_pos;              /* In order to handle pyramid reordering, QP buffer acts as a stack.
+                                 * This value is the current position (0 or 1). */
 
     /* MBRC stuff */
     double frame_size_estimated;
     double frame_size_planned;
-    predictor_t *row_pred;
-    predictor_t row_preds[5];
+    double slice_size_planned;
+    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 */
@@ -141,12 +151,21 @@ struct x264_ratecontrol_t
 
 static int parse_zones( x264_t *h );
 static int init_pass2(x264_t *);
-static float rate_estimate_qscale( x264_t *h, int overhead );
+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, 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 );
 
+#define CMP_OPT_FIRST_PASS( opt, param_val )\
+{\
+    if( ( p = strstr( opts, opt "=" ) ) && sscanf( p, opt "=%d" , &i ) && param_val != i )\
+    {\
+        x264_log( h, X264_LOG_ERROR, "different " opt " setting than first pass (%d vs %d)\n", param_val, i );\
+        return -1;\
+    }\
+}
+
 /* Terminology:
  * qp = h.264's quantizer
  * qscale = linearized quantizer = Lagrange multiplier
@@ -173,6 +192,22 @@ static inline double qscale2bits(ratecontrol_entry_t *rce, double qscale)
            + rce->misc_bits;
 }
 
+static ALWAYS_INLINE uint32_t ac_energy_plane( x264_t *h, int mb_x, int mb_y, x264_frame_t *frame, int i )
+{
+    int w = i ? 8 : 16;
+    int shift = i ? 6 : 8;
+    int stride = frame->i_stride[i];
+    int offset = h->mb.b_interlaced
+        ? w * (mb_x + (mb_y&~1) * stride) + (mb_y&1) * stride
+        : w * (mb_x + mb_y * stride);
+    int pix = i ? PIXEL_8x8 : PIXEL_16x16;
+    stride <<= h->mb.b_interlaced;
+    uint64_t res = h->pixf.var[pix]( frame->plane[i] + offset, stride );
+    uint32_t sum = (uint32_t)res;
+    uint32_t sqr = res >> 32;
+    return sqr - (sum * sum >> shift);
+}
+
 // Find the total AC energy of the block in all planes.
 static NOINLINE uint32_t ac_energy_mb( x264_t *h, int mb_x, int mb_y, x264_frame_t *frame )
 {
@@ -180,18 +215,9 @@ static NOINLINE uint32_t ac_energy_mb( x264_t *h, int mb_x, int mb_y, x264_frame
      * and putting it after floating point ops.  As a result, we put the emms at the end of the
      * function and make sure that its always called before the float math.  Noinline makes
      * sure no reordering goes on. */
-    uint32_t var = 0, i;
-    for( i = 0; i < 3; i++ )
-    {
-        int w = i ? 8 : 16;
-        int stride = frame->i_stride[i];
-        int offset = h->mb.b_interlaced
-            ? w * (mb_x + (mb_y&~1) * stride) + (mb_y&1) * stride
-            : w * (mb_x + mb_y * stride);
-        int pix = i ? PIXEL_8x8 : PIXEL_16x16;
-        stride <<= h->mb.b_interlaced;
-        var += h->pixf.var[pix]( frame->plane[i]+offset, stride );
-    }
+    uint32_t var = ac_energy_plane( h, mb_x, mb_y, frame, 0 );
+    var         += ac_energy_plane( h, mb_x, mb_y, frame, 1 );
+    var         += ac_energy_plane( h, mb_x, mb_y, frame, 2 );
     x264_emms();
     return var;
 }
@@ -264,7 +290,9 @@ void x264_adaptive_quant_frame( x264_t *h, x264_frame_t *frame )
 void x264_adaptive_quant( x264_t *h )
 {
     x264_emms();
-    h->mb.i_qp = x264_clip3( h->rc->f_qpm + h->fenc->f_qp_offset[h->mb.i_mb_xy] + .5, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
+    /* MB-tree currently doesn't adjust quantizers in unreferenced frames. */
+    float qp_offset = 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];
+    h->mb.i_qp = x264_clip3( h->rc->f_qpm + qp_offset + .5, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
 }
 
 int x264_macroblock_tree_read( x264_t *h, x264_frame_t *frame )
@@ -273,24 +301,35 @@ int x264_macroblock_tree_read( x264_t *h, x264_frame_t *frame )
     uint8_t i_type_actual = rc->entry[frame->i_frame].pict_type;
     int i;
 
-    if( i_type_actual != SLICE_TYPE_B )
+    if( rc->entry[frame->i_frame].kept_as_ref )
     {
         uint8_t i_type;
+        if( rc->qpbuf_pos < 0 )
+        {
+            do
+            {
+                rc->qpbuf_pos++;
 
-        if( !fread( &i_type, 1, 1, rc->p_mbtree_stat_file_in ) )
-            goto fail;
+                if( !fread( &i_type, 1, 1, rc->p_mbtree_stat_file_in ) )
+                    goto fail;
+                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 )
+                    goto fail;
 
-        if( i_type != i_type_actual )
-        {
-            x264_log(h, X264_LOG_ERROR, "MB-tree frametype %d doesn't match actual frametype %d.\n", i_type,i_type_actual);
-            return -1;
+                if( i_type != i_type_actual && rc->qpbuf_pos == 1 )
+                {
+                    x264_log(h, X264_LOG_ERROR, "MB-tree frametype %d doesn't match actual frametype %d.\n", i_type, i_type_actual);
+                    return -1;
+                }
+            } while( i_type != i_type_actual );
         }
 
-        if( fread( rc->qp_buffer, sizeof(uint16_t), h->mb.i_mb_count, rc->p_mbtree_stat_file_in ) != h->mb.i_mb_count )
-            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);
+        {
+            frame->f_qp_offset[i] = ((float)(int16_t)endian_fix16( rc->qp_buffer[rc->qpbuf_pos][i] )) * (1/256.0);
+            if( h->frames.b_have_lowres )
+                frame->i_inv_qscale_factor[i] = x264_exp2fix8(frame->f_qp_offset[i]);
+        }
+        rc->qpbuf_pos--;
     }
     else
         x264_adaptive_quant_frame( h, frame );
@@ -300,6 +339,45 @@ fail:
     return -1;
 }
 
+int x264_reference_build_list_optimal( x264_t *h )
+{
+    ratecontrol_entry_t *rce = h->rc->rce;
+    x264_frame_t *frames[16];
+    x264_weight_t weights[16][3];
+    int refcount[16];
+    int ref, i;
+
+    if( rce->refs != h->i_ref0 )
+        return -1;
+
+    memcpy( frames, h->fref0, sizeof(frames) );
+    memcpy( refcount, rce->refcount, sizeof(refcount) );
+    memcpy( weights, h->fenc->weight, sizeof(weights) );
+    memset( &h->fenc->weight[1][0], 0, sizeof(x264_weight_t[15][3]) );
+
+    /* 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++ )
+            if( !frames[i]->b_duplicate || frames[i]->i_frame != h->fref0[ref-1]->i_frame )
+                /* Favor lower POC as a tiebreaker. */
+                COPY2_IF_GT( max, refcount[i], bestref, i );
+
+        /* FIXME: If there are duplicates from frames other than ref0 then it is possible
+         * that the optimal ordering doesnt place every duplicate. */
+
+        refcount[bestref] = -1;
+        h->fref0[ref] = frames[bestref];
+        memcpy( h->fenc->weight[ref], weights[bestref], sizeof(weights[bestref]) );
+    }
+
+    return 0;
+}
+
 static char *x264_strcat_filename( char *input, char *suffix )
 {
     char *output = x264_malloc( strlen( input ) + strlen( suffix ) + 1 );
@@ -310,10 +388,57 @@ static char *x264_strcat_filename( char *input, char *suffix )
     return output;
 }
 
+void x264_ratecontrol_init_reconfigurable( x264_t *h, int b_init )
+{
+    x264_ratecontrol_t *rc = h->rc;
+    if( !b_init && rc->b_2pass )
+        return;
+
+    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 < (int)(h->param.rc.i_vbv_max_bitrate / rc->fps) )
+        {
+            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 );
+        }
+
+        /* We don't support changing the ABR bitrate right now,
+           so if the stream starts as CBR, keep it CBR. */
+        if( rc->b_vbv_min_rate )
+            h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
+        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;
+        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);
+        if( b_init )
+        {
+            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 );
+            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->b_vbv = 1;
+            rc->b_vbv_min_rate = !rc->b_2pass
+                          && h->param.rc.i_rc_method == X264_RC_ABR
+                          && h->param.rc.i_vbv_max_bitrate <= h->param.rc.i_bitrate;
+        }
+    }
+    if( h->param.rc.i_rc_method == X264_RC_CRF )
+    {
+        /* Arbitrary rescaling to make CRF somewhat similar to QP.
+         * Try to compensate for MB-tree's effects as well. */
+        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)*13.5 : 0;
+        rc->rate_factor_constant = pow( base_cplx, 1 - rc->qcompress )
+                                 / qp2qscale( h->param.rc.f_rf_constant + mbtree_offset );
+    }
+}
+
 int x264_ratecontrol_new( x264_t *h )
 {
     x264_ratecontrol_t *rc;
-    int i;
+    int i, j;
 
     x264_emms();
 
@@ -348,50 +473,10 @@ int x264_ratecontrol_new( x264_t *h )
         x264_log(h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n");
         return -1;
     }
-    if( h->param.rc.i_vbv_buffer_size )
-    {
-        if( h->param.rc.i_rc_method == X264_RC_CQP )
-        {
-            x264_log(h, X264_LOG_WARNING, "VBV is incompatible with constant QP, ignored.\n");
-            h->param.rc.i_vbv_max_bitrate = 0;
-            h->param.rc.i_vbv_buffer_size = 0;
-        }
-        else if( h->param.rc.i_vbv_max_bitrate == 0 )
-        {
-            x264_log( h, X264_LOG_DEBUG, "VBV maxrate unspecified, assuming CBR\n" );
-            h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
-        }
-    }
-    if( h->param.rc.i_vbv_max_bitrate < h->param.rc.i_bitrate &&
-        h->param.rc.i_vbv_max_bitrate > 0)
-        x264_log(h, X264_LOG_WARNING, "max bitrate less than average bitrate, ignored.\n");
-    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 )
-        {
-            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 );
-        }
-        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->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);
-        rc->b_vbv = 1;
-        rc->b_vbv_min_rate = !rc->b_2pass
-                          && h->param.rc.i_rc_method == X264_RC_ABR
-                          && h->param.rc.i_vbv_max_bitrate <= h->param.rc.i_bitrate;
-    }
-    else if( h->param.rc.i_vbv_max_bitrate )
-    {
-        x264_log(h, X264_LOG_WARNING, "VBV maxrate specified, but no bufsize.\n");
-        h->param.rc.i_vbv_max_bitrate = 0;
-    }
-    if(rc->rate_tolerance < 0.01)
+
+    x264_ratecontrol_init_reconfigurable( h, 1 );
+
+    if( rc->rate_tolerance < 0.01 )
     {
         x264_log(h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n");
         rc->rate_tolerance = 0.01;
@@ -411,21 +496,12 @@ int x264_ratecontrol_new( x264_t *h )
         rc->last_non_b_pict_type = SLICE_TYPE_I;
     }
 
-    if( h->param.rc.i_rc_method == X264_RC_CRF )
-    {
-        /* Arbitrary rescaling to make CRF somewhat similar to QP.
-         * Try to compensate for MB-tree's effects as well. */
-        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)*13.5 : 0;
-        rc->rate_factor_constant = pow( base_cplx, 1 - rc->qcompress )
-                                 / qp2qscale( h->param.rc.f_rf_constant + mbtree_offset );
-    }
-
     rc->ip_offset = 6.0 * log(h->param.rc.f_ip_factor) / log(2.0);
     rc->pb_offset = 6.0 * log(h->param.rc.f_pb_factor) / log(2.0);
     rc->qp_constant[SLICE_TYPE_P] = h->param.rc.i_qp_constant;
     rc->qp_constant[SLICE_TYPE_I] = x264_clip3( h->param.rc.i_qp_constant - rc->ip_offset + 0.5, 0, 51 );
     rc->qp_constant[SLICE_TYPE_B] = x264_clip3( h->param.rc.i_qp_constant + rc->pb_offset + 0.5, 0, 51 );
+    h->mb.ip_offset = rc->ip_offset + 0.5;
 
     rc->lstep = pow( 2, h->param.rc.i_qp_step / 6.0 );
     rc->last_qscale = qp2qscale(26);
@@ -440,10 +516,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];
 
@@ -483,31 +562,30 @@ int x264_ratecontrol_new( x264_t *h )
         /* check whether 1st pass options were compatible with current options */
         if( !strncmp( stats_buf, "#options:", 9 ) )
         {
-            int i;
+            int i, j;
             char *opts = stats_buf;
             stats_in = strchr( stats_buf, '\n' );
             if( !stats_in )
                 return -1;
             *stats_in = '\0';
             stats_in++;
-
-            if( ( p = strstr( opts, "bframes=" ) ) && sscanf( p, "bframes=%d", &i )
-                && h->param.i_bframe != i )
+            if( sscanf( opts, "#options: %dx%d", &i, &j ) != 2 )
             {
-                x264_log( h, X264_LOG_ERROR, "different number of B-frames than 1st pass (%d vs %d)\n",
-                          h->param.i_bframe, i );
+                x264_log( h, X264_LOG_ERROR, "resolution specified in stats file not valid\n" );
+                return -1;
+            }
+            else if( h->param.rc.b_mb_tree && (i != h->param.i_width || j != h->param.i_height)  )
+            {
+                x264_log( h, X264_LOG_ERROR, "MB-tree doesn't support different resolution than 1st pass (%dx%d vs %dx%d)\n",
+                          h->param.i_width, h->param.i_height, i, j );
                 return -1;
             }
 
-            /* since B-adapt doesn't (yet) take into account B-pyramid,
-             * the converse is not a problem */
-            if( strstr( opts, "b_pyramid=1" ) && !h->param.b_bframe_pyramid )
-                x264_log( h, X264_LOG_WARNING, "1st pass used B-pyramid, 2nd doesn't\n" );
-
-            if( ( p = strstr( opts, "keyint=" ) ) && sscanf( p, "keyint=%d", &i )
-                && h->param.i_keyint_max != i )
-                x264_log( h, X264_LOG_WARNING, "different keyint than 1st pass (%d vs %d)\n",
-                          h->param.i_keyint_max, i );
+            CMP_OPT_FIRST_PASS( "wpredp", X264_MAX( 0, h->param.analyse.i_weighted_pred ) );
+            CMP_OPT_FIRST_PASS( "bframes", h->param.i_bframe );
+            CMP_OPT_FIRST_PASS( "b_pyramid", h->param.i_bframe_pyramid );
+            CMP_OPT_FIRST_PASS( "intra_refresh", h->param.b_intra_refresh );
+            CMP_OPT_FIRST_PASS( "keyint", h->param.i_keyint_max );
 
             if( strstr( opts, "qp=0" ) && h->param.rc.i_rc_method == X264_RC_ABR )
                 x264_log( h, X264_LOG_WARNING, "1st pass was lossless, bitrate prediction will be inaccurate\n" );
@@ -575,6 +653,7 @@ int x264_ratecontrol_new( x264_t *h )
             int e;
             char *next;
             float qp;
+            int ref;
 
             next= strchr(p, ';');
             if(next)
@@ -597,17 +676,56 @@ 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);
 
-            switch(pict_type)
+            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;
+
+            /* find weights */
+            rce->i_weight_denom = -1;
+            char *w = strchr( p, 'w' );
+            if( w )
+                if( sscanf( w, "w:%hd,%hd,%hd", &rce->i_weight_denom, &rce->weight[0], &rce->weight[1] ) != 3 )
+                    rce->i_weight_denom = -1;
+
+            if( pict_type != 'b' )
+                rce->kept_as_ref = 1;
+            switch( pict_type )
             {
-                case 'I': rce->kept_as_ref = 1;
-                case 'i': rce->pict_type = SLICE_TYPE_I; break;
-                case 'P': rce->pict_type = SLICE_TYPE_P; break;
-                case 'B': rce->kept_as_ref = 1;
-                case 'b': rce->pict_type = SLICE_TYPE_B; break;
+                case 'I':
+                    rce->frame_type = X264_TYPE_IDR;
+                    rce->pict_type  = SLICE_TYPE_I;
+                    break;
+                case 'i':
+                    rce->frame_type = X264_TYPE_I;
+                    rce->pict_type  = SLICE_TYPE_I;
+                    break;
+                case 'P':
+                    rce->frame_type = X264_TYPE_P;
+                    rce->pict_type  = SLICE_TYPE_P;
+                    break;
+                case 'B':
+                    rce->frame_type = X264_TYPE_BREF;
+                    rce->pict_type  = SLICE_TYPE_B;
+                    break;
+                case 'b':
+                    rce->frame_type = X264_TYPE_B;
+                    rce->pict_type  = SLICE_TYPE_B;
+                    break;
                 default:  e = -1; break;
             }
             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;
             }
@@ -661,7 +779,12 @@ int x264_ratecontrol_new( x264_t *h )
     }
 
     if( h->param.rc.b_mb_tree && (h->param.rc.b_stat_read || h->param.rc.b_stat_write) )
-        CHECKED_MALLOC( rc->qp_buffer, h->mb.i_mb_count * sizeof(uint16_t) );
+    {
+        CHECKED_MALLOC( rc->qp_buffer[0], h->mb.i_mb_count * sizeof(uint16_t) );
+        if( h->param.i_bframe_pyramid && h->param.rc.b_stat_read )
+            CHECKED_MALLOC( rc->qp_buffer[1], h->mb.i_mb_count * sizeof(uint16_t) );
+        rc->qpbuf_pos = -1;
+    }
 
     for( i=0; i<h->param.i_threads; i++ )
     {
@@ -669,7 +792,7 @@ int x264_ratecontrol_new( x264_t *h )
         if( i )
         {
             rc[i] = rc[0];
-            memcpy( &h->thread[i]->param, &h->param, sizeof(x264_param_t) );
+            h->thread[i]->param = h->param;
             h->thread[i]->mb.b_variable_qp = h->mb.b_variable_qp;
         }
     }
@@ -682,7 +805,7 @@ fail:
 static int parse_zone( x264_t *h, x264_zone_t *z, char *p )
 {
     int len = 0;
-    char *tok, UNUSED *saveptr;
+    char *tok, UNUSED *saveptr=NULL;
     z->param = NULL;
     z->f_bitrate_factor = 1;
     if( 3 <= sscanf(p, "%u,%u,q=%u%n", &z->i_start, &z->i_end, &z->i_qp, &len) )
@@ -728,7 +851,7 @@ static int parse_zones( x264_t *h )
     int i;
     if( h->param.rc.psz_zones && !h->param.rc.i_zones )
     {
-        char *psz_zones, *p, *tok, UNUSED *saveptr;
+        char *psz_zones, *p;
         CHECKED_MALLOC( psz_zones, strlen( h->param.rc.psz_zones )+1 );
         strcpy( psz_zones, h->param.rc.psz_zones );
         h->param.rc.i_zones = 1;
@@ -738,10 +861,11 @@ static int parse_zones( x264_t *h )
         p = psz_zones;
         for( i = 0; i < h->param.rc.i_zones; i++ )
         {
-            tok = strtok_r( p, "/", &saveptr );
-            if( !tok || parse_zone( h, &h->param.rc.zones[i], tok ) )
+            int i_tok = strcspn( p, "/" );
+            p[i_tok] = 0;
+            if( parse_zone( h, &h->param.rc.zones[i], p ) )
                 return -1;
-            p = NULL;
+            p += i_tok + 1;
         }
         x264_free( psz_zones );
     }
@@ -806,7 +930,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 );
@@ -817,11 +941,13 @@ void x264_ratecontrol_delete( x264_t *h )
 {
     x264_ratecontrol_t *rc = h->rc;
     int i;
+    int b_regular_file;
 
     if( rc->p_stat_file_out )
     {
+        b_regular_file = x264_is_regular_file( rc->p_stat_file_out );
         fclose( rc->p_stat_file_out );
-        if( h->i_frame >= rc->num_entries )
+        if( h->i_frame >= rc->num_entries && b_regular_file )
             if( rename( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ) != 0 )
             {
                 x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
@@ -831,8 +957,9 @@ void x264_ratecontrol_delete( x264_t *h )
     }
     if( rc->p_mbtree_stat_file_out )
     {
+        b_regular_file = x264_is_regular_file( rc->p_mbtree_stat_file_out );
         fclose( rc->p_mbtree_stat_file_out );
-        if( h->i_frame >= rc->num_entries )
+        if( h->i_frame >= rc->num_entries && b_regular_file )
             if( rename( rc->psz_mbtree_stat_file_tmpname, rc->psz_mbtree_stat_file_name ) != 0 )
             {
                 x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
@@ -846,7 +973,8 @@ void x264_ratecontrol_delete( x264_t *h )
     x264_free( rc->pred );
     x264_free( rc->pred_b_from_p );
     x264_free( rc->entry );
-    x264_free( rc->qp_buffer );
+    x264_free( rc->qp_buffer[0] );
+    x264_free( rc->qp_buffer[1] );
     if( rc->zones )
     {
         x264_free( rc->zones[0].param );
@@ -932,11 +1060,11 @@ void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
     }
     else if( rc->b_abr )
     {
-        q = qscale2qp( rate_estimate_qscale( h, overhead ) );
+        q = qscale2qp( rate_estimate_qscale( h ) );
     }
     else if( rc->b_2pass )
     {
-        rce->new_qscale = rate_estimate_qscale( h, overhead );
+        rce->new_qscale = rate_estimate_qscale( h );
         q = qscale2qp( rce->new_qscale );
     }
     else /* CQP */
@@ -978,27 +1106,36 @@ 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 pred_intra = predict_size( rc->row_pred[1], qp2qscale(qp), 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 )
 {
     int i;
     double bits = 0;
-    for( i = 0; i <= y; i++ )
+    for( i = h->i_threadslice_start; i <= y; i++ )
         bits += h->fdec->i_row_bits[i];
     return bits;
 }
@@ -1007,7 +1144,7 @@ static double predict_row_size_sum( x264_t *h, int y, int qp )
 {
     int i;
     double bits = row_bits_so_far(h, y);
-    for( i = y+1; i < h->sps->i_mb_height; i++ )
+    for( i = y+1; i < h->i_threadslice_end; i++ )
         bits += predict_row_size( h, i, qp );
     return bits;
 }
@@ -1029,80 +1166,79 @@ 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] )
+        update_predictor( rc->row_pred[1], qp2qscale(rc->qpm), h->fdec->i_row_satds[0][0][y], h->fdec->i_row_bits[y] );
+
+    /* tweak quality based on difference from predicted size */
+    if( y < h->i_threadslice_end-1 )
     {
-        /* 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 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 )
         {
-            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);
+            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 );
         }
-    }
-    else
-    {
-        update_predictor( rc->row_pred, qp2qscale(rc->qpm), h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] );
 
-        /* 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 )
+        float buffer_left_planned = rc->buffer_fill - rc->frame_size_planned;
+        float slice_size_planned = h->param.b_sliced_threads ? rc->slice_size_planned : rc->frame_size_planned;
+        float size_of_other_slices = rc->frame_size_planned - slice_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;
+        float max_frame_error = X264_MAX( 0.05, 1.0 / h->sps->i_mb_height );
+        int b1 = predict_row_size_sum( h, y, rc->qpm );
+
+        /* Assume that if this slice has become larger than expected,
+         * the other slices will have gotten equally larger. */
+        b1 += X264_MAX( size_of_other_slices * b1 / slice_size_planned, size_of_other_slices );
+
+        /* 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-size_of_other_slices) )
+            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)) )
         {
-            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 );
+            b1 += X264_MAX( size_of_other_slices * b1 / slice_size_planned, size_of_other_slices );
+        }
 
-            /* 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 );
+            b1 += X264_MAX( size_of_other_slices * b1 / slice_size_planned, size_of_other_slices );
+        }
 
-            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 * max_frame_error) )
+        {
+            rc->qpm ++;
+            b1 = predict_row_size_sum( h, y, rc->qpm );
+            b1 += X264_MAX( size_of_other_slices * b1 / slice_size_planned, size_of_other_slices );
         }
+
+        x264_ratecontrol_set_estimated_size(h, b1);
     }
+
     /* loses the fractional part of the frame-wise qp */
     rc->f_qpm = rc->qpm;
 }
@@ -1149,23 +1285,19 @@ int x264_ratecontrol_slice_type( x264_t *h, int frame_num )
             }
             return X264_TYPE_AUTO;
         }
-        switch( rc->entry[frame_num].pict_type )
-        {
-            case SLICE_TYPE_I:
-                return rc->entry[frame_num].kept_as_ref ? X264_TYPE_IDR : X264_TYPE_I;
-
-            case SLICE_TYPE_B:
-                return rc->entry[frame_num].kept_as_ref ? X264_TYPE_BREF : X264_TYPE_B;
-
-            case SLICE_TYPE_P:
-            default:
-                return X264_TYPE_P;
-        }
+        return rc->entry[frame_num].frame_type;
     }
     else
-    {
         return X264_TYPE_AUTO;
-    }
+}
+
+void x264_ratecontrol_set_weights( x264_t *h, x264_frame_t *frm )
+{
+    ratecontrol_entry_t *rce = &h->rc->entry[frm->i_frame];
+    if( h->param.analyse.i_weighted_pred <= 0 )
+        return;
+    if( rce->i_weight_denom >= 0 )
+        SET_WEIGHT( frm->weight[0][0], 1, rce->weight[0], rce->i_weight_denom, rce->weight[1] );
 }
 
 /* After encoding one frame, save stats and update ratecontrol state */
@@ -1198,7 +1330,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,
@@ -1208,7 +1340,28 @@ 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;
+
+        /* Only write information for reference reordering once. */
+        int use_old_stats = h->param.rc.b_stat_read && rc->rce->refs > 1;
+        for( i = 0; i < (use_old_stats ? rc->rce->refs : h->i_ref0); i++ )
+        {
+            int refcount = use_old_stats         ? rc->rce->refcount[i]
+                         : 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( h->sh.weight[0][0].weightfn )
+        {
+            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 )
+                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 )
@@ -1217,10 +1370,10 @@ int x264_ratecontrol_end( x264_t *h, int bits )
             int i;
             /* Values are stored as big-endian FIX8.8 */
             for( i = 0; i < h->mb.i_mb_count; i++ )
-                rc->qp_buffer[i] = endian_fix16( h->fenc->f_qp_offset[i]*256.0 );
+                rc->qp_buffer[0][i] = endian_fix16( h->fenc->f_qp_offset[i]*256.0 );
             if( fwrite( &i_type, 1, 1, rc->p_mbtree_stat_file_out ) < 1 )
                 goto fail;
-            if( fwrite( rc->qp_buffer, sizeof(uint16_t), h->mb.i_mb_count, rc->p_mbtree_stat_file_out ) < h->mb.i_mb_count )
+            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 )
                 goto fail;
         }
     }
@@ -1283,7 +1436,7 @@ static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor
 
     // avoid NaN's in the rc_eq
     if(!isfinite(q) || rce->tex_bits + rce->mv_bits == 0)
-        q = rcc->last_qscale;
+        q = rcc->last_qscale_for[rce->pict_type];
     else
     {
         rcc->last_rceq = q;
@@ -1407,32 +1560,38 @@ 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 += rcc->buffer_rate;
+    rct->buffer_fill_final = X264_MIN( rct->buffer_fill_final, rcc->buffer_size );
 }
 
 // provisionally update VBV according to the planned size of all frames currently in progress
 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;// - overhead;
-    if( h->param.i_threads > 1 )
+    rcc->buffer_fill = h->thread[0]->rc->buffer_fill_final;
+    if( h->i_thread_frames > 1 )
     {
         int j = h->rc - h->thread[0]->rc;
         int i;
-        for( i=1; i<h->param.i_threads; i++ )
+        for( i=1; i<h->i_thread_frames; i++ )
         {
-            x264_t *t = h->thread[ (j+i)%h->param.i_threads ];
+            x264_t *t = h->thread[ (j+i)%h->i_thread_frames ];
             double bits = t->rc->frame_size_planned;
             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 );
         }
     }
+    rcc->buffer_fill = X264_MIN( rcc->buffer_fill, rcc->buffer_size );
+    rcc->buffer_fill -= overhead;
 }
 
 // apply VBV constraints and clip qscale to between lmin and lmax
@@ -1460,7 +1619,7 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
             {
                 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 buffer_fill_cur = rcc->buffer_fill - cur_bits;
                 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;
@@ -1469,13 +1628,14 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
                 /* Loop over the planned future frames. */
                 for( j = 0; buffer_fill_cur >= 0 && buffer_fill_cur <= rcc->buffer_size; j++ )
                 {
+                    buffer_fill_cur += rcc->buffer_rate;
                     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;
+                    buffer_fill_cur -= cur_bits;
                 }
                 /* 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 );
@@ -1510,34 +1670,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 );
         }
@@ -1562,7 +1725,7 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
 }
 
 // update qscale for 1 frame based on actual bits used so far
-static float rate_estimate_qscale( x264_t *h, int overhead )
+static float rate_estimate_qscale( x264_t *h )
 {
     float q;
     x264_ratecontrol_t *rcc = h->rc;
@@ -1615,14 +1778,20 @@ static float rate_estimate_qscale( x264_t *h, int overhead )
         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 ) + overhead;
+        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
     {
-        double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate;
+        double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate * h->i_thread_frames;
 
         if( rcc->b_2pass )
         {
@@ -1632,13 +1801,13 @@ static float rate_estimate_qscale( x264_t *h, int overhead )
 
             if( rcc->b_vbv )
             {
-                if( h->param.i_threads > 1 )
+                if( h->i_thread_frames > 1 )
                 {
                     int j = h->rc - h->thread[0]->rc;
                     int i;
-                    for( i=1; i<h->param.i_threads; i++ )
+                    for( i=1; i<h->i_thread_frames; i++ )
                     {
-                        x264_t *t = h->thread[ (j+i)%h->param.i_threads ];
+                        x264_t *t = h->thread[ (j+i)%h->i_thread_frames ];
                         double bits = t->rc->frame_size_planned;
                         if( !t->b_thread_active )
                             continue;
@@ -1649,16 +1818,16 @@ static float rate_estimate_qscale( x264_t *h, int overhead )
             }
             else
             {
-                if( h->fenc->i_frame < h->param.i_threads )
+                if( h->fenc->i_frame < h->i_thread_frames )
                     predicted_bits += (int64_t)h->fenc->i_frame * rcc->bitrate / rcc->fps;
                 else
-                    predicted_bits += (int64_t)(h->param.i_threads - 1) * rcc->bitrate / rcc->fps;
+                    predicted_bits += (int64_t)(h->i_thread_frames - 1) * rcc->bitrate / rcc->fps;
             }
 
             diff = predicted_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 + 1 - h->param.i_threads) >= rcc->fps) &&
+            if( ((h->fenc->i_frame + 1 - h->i_thread_frames) >= rcc->fps) &&
                 (rcc->expected_bits_sum > 0))
             {
                 /* Adjust quant based on the difference between
@@ -1686,7 +1855,7 @@ static float rate_estimate_qscale( x264_t *h, int overhead )
                     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 );
         }
@@ -1704,7 +1873,7 @@ static float rate_estimate_qscale( x264_t *h, int overhead )
 
             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;
@@ -1725,7 +1894,7 @@ static float rate_estimate_qscale( x264_t *h, int overhead )
             }
             else
             {
-                int i_frame_done = h->fenc->i_frame + 1 - h->param.i_threads;
+                int i_frame_done = h->fenc->i_frame + 1 - h->i_thread_frames;
 
                 q = get_qscale( h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame );
 
@@ -1759,7 +1928,7 @@ static float rate_estimate_qscale( x264_t *h, int overhead )
 
                 q = x264_clip3f(q, lmin, lmax);
             }
-            else if( h->param.rc.i_rc_method == X264_RC_CRF )
+            else if( h->param.rc.i_rc_method == X264_RC_CRF && rcc->qcompress != 1 )
             {
                 q = qp2qscale( ABR_INIT_QP ) / fabs( h->param.rc.f_ip_factor );
             }
@@ -1773,17 +1942,73 @@ static float rate_estimate_qscale( x264_t *h, int overhead )
         rcc->last_qscale = q;
 
         if( !(rcc->b_2pass && !rcc->b_vbv) && h->fenc->i_frame == 0 )
-            rcc->last_qscale_for[SLICE_TYPE_P] = q;
+            rcc->last_qscale_for[SLICE_TYPE_P] = q * fabs( h->param.rc.f_ip_factor );
 
         if( rcc->b_2pass && rcc->b_vbv )
             rcc->frame_size_planned = qscale2bits(&rce, q);
         else
-            rcc->frame_size_planned = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd ) + overhead;
+            rcc->frame_size_planned = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
+
+        /* Always use up the whole VBV in this case. */
+        if( rcc->single_frame_vbv )
+            rcc->frame_size_planned = rcc->buffer_rate;
         x264_ratecontrol_set_estimated_size(h, rcc->frame_size_planned);
         return q;
     }
 }
 
+void x264_threads_distribute_ratecontrol( x264_t *h )
+{
+    int i, row, totalsize = 0;
+    if( h->rc->b_vbv )
+        for( row = 0; row < h->sps->i_mb_height; row++ )
+            totalsize += h->fdec->i_row_satd[row];
+    for( i = 0; i < h->param.i_threads; i++ )
+    {
+        x264_t *t = h->thread[i];
+        x264_ratecontrol_t *rc = h->rc;
+        memcpy( t->rc, rc, sizeof(x264_ratecontrol_t) );
+        /* Calculate the planned slice size. */
+        if( h->rc->b_vbv && rc->frame_size_planned )
+        {
+            int size = 0;
+            for( row = t->i_threadslice_start; row < t->i_threadslice_end; row++ )
+                size += h->fdec->i_row_satd[row];
+            t->rc->slice_size_planned = size * rc->frame_size_planned / totalsize;
+        }
+        else
+            t->rc->slice_size_planned = 0;
+    }
+}
+
+void x264_threads_merge_ratecontrol( x264_t *h )
+{
+    int i, j, k;
+    x264_ratecontrol_t *rc = h->rc;
+    x264_emms();
+
+    for( i = 1; i < h->param.i_threads; i++ )
+    {
+        x264_ratecontrol_t *t = h->thread[i]->rc;
+        rc->qpa_rc += t->qpa_rc;
+        rc->qpa_aq += t->qpa_aq;
+        for( j = 0; j < 5; j++ )
+            for( k = 0; k < 2; k++ )
+            {
+                rc->row_preds[j][k].coeff += t->row_preds[j][k].coeff;
+                rc->row_preds[j][k].offset += t->row_preds[j][k].offset;
+                rc->row_preds[j][k].count += t->row_preds[j][k].count;
+            }
+    }
+    for( j = 0; j < 5; j++ )
+        for( k = 0; k < 2; k++ )
+        {
+            rc->row_preds[j][k].coeff /= h->param.i_threads;
+            rc->row_preds[j][k].offset /= h->param.i_threads;
+            rc->row_preds[j][k].count /= h->param.i_threads;
+        }
+}
+
 void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
 {
     if( cur != prev )
@@ -1791,8 +2016,7 @@ void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
 #define COPY(var) memcpy(&cur->rc->var, &prev->rc->var, sizeof(cur->rc->var))
         /* these vars are updated in x264_ratecontrol_start()
          * so copy them from the context that most recently started (prev)
-         * to the context that's about to start (cur).
-         */
+         * to the context that's about to start (cur). */
         COPY(accum_p_qp);
         COPY(accum_p_norm);
         COPY(last_satd);
@@ -1803,6 +2027,15 @@ void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
         COPY(short_term_cplxcount);
         COPY(bframes);
         COPY(prev_zone);
+        COPY(qpbuf_pos);
+        /* these vars can be updated by x264_ratecontrol_init_reconfigurable */
+        COPY(buffer_rate);
+        COPY(buffer_size);
+        COPY(single_frame_vbv);
+        COPY(cbr_decay);
+        COPY(b_vbv_min_rate);
+        COPY(rate_factor_constant);
+        COPY(bitrate);
 #undef COPY
     }
     if( cur != next )
@@ -1810,8 +2043,7 @@ void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
 #define COPY(var) next->rc->var = cur->rc->var
         /* these vars are updated in x264_ratecontrol_end()
          * so copy them from the context that most recently ended (cur)
-         * to the context that's about to end (next)
-         */
+         * to the context that's about to end (next) */
         COPY(cplxr_sum);
         COPY(expected_bits_sum);
         COPY(wanted_bits_window);
@@ -2031,7 +2263,11 @@ static int init_pass2( x264_t *h )
 
     expected_bits = 1;
     for(i=0; i<rcc->num_entries; i++)
-        expected_bits += qscale2bits(&rcc->entry[i], get_qscale(h, &rcc->entry[i], 1.0, i));
+    {
+        double q = get_qscale(h, &rcc->entry[i], 1.0, i);
+        expected_bits += qscale2bits(&rcc->entry[i], q);
+        rcc->last_qscale_for[rcc->entry[i].pict_type] = q;
+    }
     step_mult = all_available_bits / expected_bits;
 
     rate_factor = 0;
@@ -2048,6 +2284,7 @@ static int init_pass2( x264_t *h )
         for(i=0; i<rcc->num_entries; i++)
         {
             qscale[i] = get_qscale(h, &rcc->entry[i], rate_factor, i);
+            rcc->last_qscale_for[rcc->entry[i].pict_type] = qscale[i];
         }
 
         /* fixed I/B qscale relative to P */