]> git.sesse.net Git - x264/blob - encoder/ratecontrol.c
extend zones to support (some) encoding parameters in addition to ratecontrol.
[x264] / encoder / ratecontrol.c
1 /***************************************************-*- coding: iso-8859-1 -*-
2  * ratecontrol.c: h264 encoder library (Rate Control)
3  *****************************************************************************
4  * Copyright (C) 2005 x264 project
5  * $Id: ratecontrol.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
6  *
7  * Authors: Loren Merritt <lorenm@u.washington.edu>
8  *          Michael Niedermayer <michaelni@gmx.at>
9  *          Måns Rullgård <mru@mru.ath.cx>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 #define _ISOC99_SOURCE
27 #undef NDEBUG // always check asserts, the speed effect is far too small to disable them
28 #include <stdio.h>
29 #include <string.h>
30 #include <math.h>
31 #include <limits.h>
32 #include <assert.h>
33
34 #include "common/common.h"
35 #include "common/cpu.h"
36 #include "ratecontrol.h"
37
38 #if defined(SYS_OPENBSD)
39 #define isfinite finite
40 #endif
41 #if defined(_MSC_VER)
42 #define isfinite _finite
43 #endif
44 #if defined(_MSC_VER) || defined(SYS_SunOS) || defined(SYS_MACOSX)
45 #define sqrtf sqrt
46 #endif
47 #ifdef WIN32 // POSIX says that rename() removes the destination, but win32 doesn't.
48 #define rename(src,dst) (unlink(dst), rename(src,dst))
49 #endif
50
51 typedef struct
52 {
53     int pict_type;
54     int kept_as_ref;
55     float qscale;
56     int mv_bits;
57     int i_tex_bits;
58     int p_tex_bits;
59     int misc_bits;
60     uint64_t expected_bits;
61     float new_qscale;
62     int new_qp;
63     int i_count;
64     int p_count;
65     int s_count;
66     float blurred_complexity;
67     char direct_mode;
68 } ratecontrol_entry_t;
69
70 typedef struct
71 {
72     double coeff;
73     double count;
74     double decay;
75 } predictor_t;
76
77 struct x264_ratecontrol_t
78 {
79     /* constants */
80     int b_abr;
81     int b_2pass;
82     int b_vbv;
83     int b_vbv_min_rate;
84     double fps;
85     double bitrate;
86     double rate_tolerance;
87     int nmb;                    /* number of macroblocks in a frame */
88     int qp_constant[5];
89
90     /* current frame */
91     ratecontrol_entry_t *rce;
92     int qp;                     /* qp for current frame */
93     int qpm;                    /* qp for current macroblock */
94     float qpa;                  /* average of macroblocks' qp */
95     int qp_force;
96
97     /* VBV stuff */
98     double buffer_size;
99     double buffer_fill_final;   /* real buffer as of the last finished frame */
100     double buffer_fill;         /* planned buffer, if all in-progress frames hit their bit budget */
101     double buffer_rate;         /* # of bits added to buffer_fill after each frame */
102     predictor_t *pred;          /* predict frame size from satd */
103
104     /* ABR stuff */
105     int    last_satd;
106     double last_rceq;
107     double cplxr_sum;           /* sum of bits*qscale/rceq */
108     double expected_bits_sum;   /* sum of qscale2bits after rceq, ratefactor, and overflow */
109     double wanted_bits_window;  /* target bitrate * window */
110     double cbr_decay;
111     double short_term_cplxsum;
112     double short_term_cplxcount;
113     double rate_factor_constant;
114     double ip_offset;
115     double pb_offset;
116
117     /* 2pass stuff */
118     FILE *p_stat_file_out;
119     char *psz_stat_file_tmpname;
120
121     int num_entries;            /* number of ratecontrol_entry_ts */
122     ratecontrol_entry_t *entry; /* FIXME: copy needed data and free this once init is done */
123     double last_qscale;
124     double last_qscale_for[5];  /* last qscale for a specific pict type, used for max_diff & ipb factor stuff  */
125     int last_non_b_pict_type;
126     double accum_p_qp;          /* for determining I-frame quant */
127     double accum_p_norm;
128     double last_accum_p_norm;
129     double lmin[5];             /* min qscale by frame type */
130     double lmax[5];
131     double lstep;               /* max change (multiply) in qscale per frame */
132     double i_cplx_sum[5];       /* estimated total texture bits in intra MBs at qscale=1 */
133     double p_cplx_sum[5];
134     double mv_bits_sum[5];
135     int frame_count[5];         /* number of frames of each type */
136
137     /* MBRC stuff */
138     double frame_size_planned;
139     predictor_t *row_pred;
140     predictor_t row_preds[5];
141     predictor_t *pred_b_from_p; /* predict B-frame size from P-frame satd */
142     int bframes;                /* # consecutive B-frames before this P-frame */
143     int bframe_bits;            /* total cost of those frames */
144
145     int i_zones;
146     x264_zone_t *zones;
147     x264_zone_t *prev_zone;
148 };
149
150
151 static int parse_zones( x264_t *h );
152 static int init_pass2(x264_t *);
153 static float rate_estimate_qscale( x264_t *h );
154 static void update_vbv( x264_t *h, int bits );
155 static void update_vbv_plan( x264_t *h );
156 static double predict_size( predictor_t *p, double q, double var );
157 static void update_predictor( predictor_t *p, double q, double var, double bits );
158 int  x264_rc_analyse_slice( x264_t *h );
159
160 /* Terminology:
161  * qp = h.264's quantizer
162  * qscale = linearized quantizer = Lagrange multiplier
163  */
164 static inline double qp2qscale(double qp)
165 {
166     return 0.85 * pow(2.0, ( qp - 12.0 ) / 6.0);
167 }
168 static inline double qscale2qp(double qscale)
169 {
170     return 12.0 + 6.0 * log(qscale/0.85) / log(2.0);
171 }
172
173 /* Texture bitrate is not quite inversely proportional to qscale,
174  * probably due the the changing number of SKIP blocks.
175  * MV bits level off at about qp<=12, because the lambda used
176  * for motion estimation is constant there. */
177 static inline double qscale2bits(ratecontrol_entry_t *rce, double qscale)
178 {
179     if(qscale<0.1)
180         qscale = 0.1;
181     return (rce->i_tex_bits + rce->p_tex_bits + .1) * pow( rce->qscale / qscale, 1.1 )
182            + rce->mv_bits * pow( X264_MAX(rce->qscale, 1) / X264_MAX(qscale, 1), 0.5 )
183            + rce->misc_bits;
184 }
185
186
187 int x264_ratecontrol_new( x264_t *h )
188 {
189     x264_ratecontrol_t *rc;
190     int i;
191
192     x264_cpu_restore( h->param.cpu );
193
194     rc = h->rc = x264_malloc( h->param.i_threads * sizeof(x264_ratecontrol_t) );
195     memset( rc, 0, h->param.i_threads * sizeof(x264_ratecontrol_t) );
196
197     rc->b_abr = h->param.rc.i_rc_method != X264_RC_CQP && !h->param.rc.b_stat_read;
198     rc->b_2pass = h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.b_stat_read;
199     
200     /* FIXME: use integers */
201     if(h->param.i_fps_num > 0 && h->param.i_fps_den > 0)
202         rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den;
203     else
204         rc->fps = 25.0;
205
206     rc->bitrate = h->param.rc.i_bitrate * 1000;
207     rc->rate_tolerance = h->param.rc.f_rate_tolerance;
208     rc->nmb = h->mb.i_mb_count;
209     rc->last_non_b_pict_type = -1;
210     rc->cbr_decay = 1.0;
211
212     if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.b_stat_read )
213     {
214         x264_log(h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n");
215         return -1;
216     }
217     if( h->param.rc.i_vbv_buffer_size )
218     {
219         if( h->param.rc.i_rc_method == X264_RC_CQP )
220             x264_log(h, X264_LOG_WARNING, "VBV is incompatible with constant QP, ignored.\n");
221         else if( h->param.rc.i_vbv_max_bitrate == 0 )
222         {
223             x264_log( h, X264_LOG_DEBUG, "VBV maxrate unspecified, assuming CBR\n" );
224             h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
225         }
226     }
227     if( h->param.rc.i_vbv_max_bitrate < h->param.rc.i_bitrate &&
228         h->param.rc.i_vbv_max_bitrate > 0)
229         x264_log(h, X264_LOG_WARNING, "max bitrate less than average bitrate, ignored.\n");
230     else if( h->param.rc.i_vbv_max_bitrate > 0 &&
231              h->param.rc.i_vbv_buffer_size > 0 )
232     {
233         if( h->param.rc.i_vbv_buffer_size < 3 * h->param.rc.i_vbv_max_bitrate / rc->fps )
234         {
235             h->param.rc.i_vbv_buffer_size = 3 * h->param.rc.i_vbv_max_bitrate / rc->fps;
236             x264_log( h, X264_LOG_WARNING, "VBV buffer size too small, using %d kbit\n",
237                       h->param.rc.i_vbv_buffer_size );
238         }
239         rc->buffer_rate = h->param.rc.i_vbv_max_bitrate * 1000 / rc->fps;
240         rc->buffer_size = h->param.rc.i_vbv_buffer_size * 1000;
241         rc->buffer_fill_final = rc->buffer_size * h->param.rc.f_vbv_buffer_init;
242         rc->cbr_decay = 1.0 - rc->buffer_rate / rc->buffer_size
243                       * 0.5 * X264_MAX(0, 1.5 - rc->buffer_rate * rc->fps / rc->bitrate);
244         rc->b_vbv = 1;
245         rc->b_vbv_min_rate = !rc->b_2pass
246                           && h->param.rc.i_rc_method == X264_RC_ABR
247                           && h->param.rc.i_vbv_max_bitrate <= h->param.rc.i_bitrate;
248     }
249     else if( h->param.rc.i_vbv_max_bitrate )
250     {
251         x264_log(h, X264_LOG_WARNING, "VBV maxrate specified, but no bufsize.\n");
252         h->param.rc.i_vbv_max_bitrate = 0;
253     }
254     if(rc->rate_tolerance < 0.01) {
255         x264_log(h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n");
256         rc->rate_tolerance = 0.01;
257     }
258
259     h->mb.b_variable_qp = rc->b_vbv && !rc->b_2pass;
260
261     if( rc->b_abr )
262     {
263         /* FIXME ABR_INIT_QP is actually used only in CRF */
264 #define ABR_INIT_QP ( h->param.rc.i_rc_method == X264_RC_CRF ? h->param.rc.f_rf_constant : 24 )
265         rc->accum_p_norm = .01;
266         rc->accum_p_qp = ABR_INIT_QP * rc->accum_p_norm;
267         /* estimated ratio that produces a reasonable QP for the first I-frame */
268         rc->cplxr_sum = .01 * pow( 7.0e5, h->param.rc.f_qcompress ) * pow( h->mb.i_mb_count, 0.5 );
269         rc->wanted_bits_window = 1.0 * rc->bitrate / rc->fps;
270         rc->last_non_b_pict_type = SLICE_TYPE_I;
271     }
272
273     if( h->param.rc.i_rc_method == X264_RC_CRF )
274     {
275         /* arbitrary rescaling to make CRF somewhat similar to QP */
276         double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
277         rc->rate_factor_constant = pow( base_cplx, 1 - h->param.rc.f_qcompress )
278                                  / qp2qscale( h->param.rc.f_rf_constant );
279     }
280
281     rc->ip_offset = 6.0 * log(h->param.rc.f_ip_factor) / log(2.0);
282     rc->pb_offset = 6.0 * log(h->param.rc.f_pb_factor) / log(2.0);
283     rc->qp_constant[SLICE_TYPE_P] = h->param.rc.i_qp_constant;
284     rc->qp_constant[SLICE_TYPE_I] = x264_clip3( h->param.rc.i_qp_constant - rc->ip_offset + 0.5, 0, 51 );
285     rc->qp_constant[SLICE_TYPE_B] = x264_clip3( h->param.rc.i_qp_constant + rc->pb_offset + 0.5, 0, 51 );
286
287     rc->lstep = pow( 2, h->param.rc.i_qp_step / 6.0 );
288     rc->last_qscale = qp2qscale(26);
289     rc->pred = x264_malloc( 5*sizeof(predictor_t) );
290     rc->pred_b_from_p = x264_malloc( sizeof(predictor_t) );
291     for( i = 0; i < 5; i++ )
292     {
293         rc->last_qscale_for[i] = qp2qscale( ABR_INIT_QP );
294         rc->lmin[i] = qp2qscale( h->param.rc.i_qp_min );
295         rc->lmax[i] = qp2qscale( h->param.rc.i_qp_max );
296         rc->pred[i].coeff= 2.0;
297         rc->pred[i].count= 1.0;
298         rc->pred[i].decay= 0.5;
299         rc->row_preds[i].coeff= .25;
300         rc->row_preds[i].count= 1.0;
301         rc->row_preds[i].decay= 0.5;
302     }
303     *rc->pred_b_from_p = rc->pred[0];
304
305     if( parse_zones( h ) < 0 )
306     {
307         x264_log( h, X264_LOG_ERROR, "failed to parse zones\n" );
308         return -1;
309     }
310
311     /* Load stat file and init 2pass algo */
312     if( h->param.rc.b_stat_read )
313     {
314         char *p, *stats_in, *stats_buf;
315
316         /* read 1st pass stats */
317         assert( h->param.rc.psz_stat_in );
318         stats_buf = stats_in = x264_slurp_file( h->param.rc.psz_stat_in );
319         if( !stats_buf )
320         {
321             x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
322             return -1;
323         }
324
325         /* check whether 1st pass options were compatible with current options */
326         if( !strncmp( stats_buf, "#options:", 9 ) )
327         {
328             int i;
329             char *opts = stats_buf;
330             stats_in = strchr( stats_buf, '\n' );
331             if( !stats_in )
332                 return -1;
333             *stats_in = '\0';
334             stats_in++;
335
336             if( ( p = strstr( opts, "bframes=" ) ) && sscanf( p, "bframes=%d", &i )
337                 && h->param.i_bframe != i )
338             {
339                 x264_log( h, X264_LOG_ERROR, "different number of B-frames than 1st pass (%d vs %d)\n",
340                           h->param.i_bframe, i );
341                 return -1;
342             }
343
344             /* since B-adapt doesn't (yet) take into account B-pyramid,
345              * the converse is not a problem */
346             if( strstr( opts, "b_pyramid=1" ) && !h->param.b_bframe_pyramid )
347                 x264_log( h, X264_LOG_WARNING, "1st pass used B-pyramid, 2nd doesn't\n" );
348
349             if( ( p = strstr( opts, "keyint=" ) ) && sscanf( p, "keyint=%d", &i )
350                 && h->param.i_keyint_max != i )
351                 x264_log( h, X264_LOG_WARNING, "different keyint than 1st pass (%d vs %d)\n",
352                           h->param.i_keyint_max, i );
353
354             if( strstr( opts, "qp=0" ) && h->param.rc.i_rc_method == X264_RC_ABR )
355                 x264_log( h, X264_LOG_WARNING, "1st pass was lossless, bitrate prediction will be inaccurate\n" );
356         }
357
358         /* find number of pics */
359         p = stats_in;
360         for(i=-1; p; i++)
361             p = strchr(p+1, ';');
362         if(i==0)
363         {
364             x264_log(h, X264_LOG_ERROR, "empty stats file\n");
365             return -1;
366         }
367         rc->num_entries = i;
368
369         if( h->param.i_frame_total < rc->num_entries && h->param.i_frame_total > 0 )
370         {
371             x264_log( h, X264_LOG_WARNING, "2nd pass has fewer frames than 1st pass (%d vs %d)\n",
372                       h->param.i_frame_total, rc->num_entries );
373         }
374         if( h->param.i_frame_total > rc->num_entries + h->param.i_bframe )
375         {
376             x264_log( h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d vs %d)\n",
377                       h->param.i_frame_total, rc->num_entries );
378             return -1;
379         }
380
381         /* FIXME: ugly padding because VfW drops delayed B-frames */
382         rc->num_entries += h->param.i_bframe;
383
384         rc->entry = (ratecontrol_entry_t*) x264_malloc(rc->num_entries * sizeof(ratecontrol_entry_t));
385         memset(rc->entry, 0, rc->num_entries * sizeof(ratecontrol_entry_t));
386
387         /* init all to skipped p frames */
388         for(i=0; i<rc->num_entries; i++){
389             ratecontrol_entry_t *rce = &rc->entry[i];
390             rce->pict_type = SLICE_TYPE_P;
391             rce->qscale = rce->new_qscale = qp2qscale(20);
392             rce->misc_bits = rc->nmb + 10;
393             rce->new_qp = 0;
394         }
395
396         /* read stats */
397         p = stats_in;
398         for(i=0; i < rc->num_entries - h->param.i_bframe; i++){
399             ratecontrol_entry_t *rce;
400             int frame_number;
401             char pict_type;
402             int e;
403             char *next;
404             float qp;
405
406             next= strchr(p, ';');
407             if(next){
408                 (*next)=0; //sscanf is unbelievably slow on looong strings
409                 next++;
410             }
411             e = sscanf(p, " in:%d ", &frame_number);
412
413             if(frame_number < 0 || frame_number >= rc->num_entries)
414             {
415                 x264_log(h, X264_LOG_ERROR, "bad frame number (%d) at stats line %d\n", frame_number, i);
416                 return -1;
417             }
418             rce = &rc->entry[frame_number];
419             rce->direct_mode = 0;
420
421             e += sscanf(p, " in:%*d out:%*d type:%c q:%f itex:%d ptex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c",
422                    &pict_type, &qp, &rce->i_tex_bits, &rce->p_tex_bits,
423                    &rce->mv_bits, &rce->misc_bits, &rce->i_count, &rce->p_count,
424                    &rce->s_count, &rce->direct_mode);
425
426             switch(pict_type){
427                 case 'I': rce->kept_as_ref = 1;
428                 case 'i': rce->pict_type = SLICE_TYPE_I; break;
429                 case 'P': rce->pict_type = SLICE_TYPE_P; break;
430                 case 'B': rce->kept_as_ref = 1;
431                 case 'b': rce->pict_type = SLICE_TYPE_B; break;
432                 default:  e = -1; break;
433             }
434             if(e < 10){
435                 x264_log(h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);
436                 return -1;
437             }
438             rce->qscale = qp2qscale(qp);
439             p = next;
440         }
441
442         x264_free(stats_buf);
443
444         if(h->param.rc.i_rc_method == X264_RC_ABR)
445         {
446             if(init_pass2(h) < 0) return -1;
447         } /* else we're using constant quant, so no need to run the bitrate allocation */
448     }
449
450     /* Open output file */
451     /* If input and output files are the same, output to a temp file
452      * and move it to the real name only when it's complete */
453     if( h->param.rc.b_stat_write )
454     {
455         char *p;
456
457         rc->psz_stat_file_tmpname = x264_malloc( strlen(h->param.rc.psz_stat_out) + 6 );
458         strcpy( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out );
459         strcat( rc->psz_stat_file_tmpname, ".temp" );
460
461         rc->p_stat_file_out = fopen( rc->psz_stat_file_tmpname, "wb" );
462         if( rc->p_stat_file_out == NULL )
463         {
464             x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
465             return -1;
466         }
467
468         p = x264_param2string( &h->param, 1 );
469         fprintf( rc->p_stat_file_out, "#options: %s\n", p );
470         x264_free( p );
471     }
472
473     for( i=1; i<h->param.i_threads; i++ )
474     {
475         h->thread[i]->rc = rc+i;
476         rc[i] = rc[0];
477     }
478
479     return 0;
480 }
481
482 static int parse_zone( x264_t *h, x264_zone_t *z, char *p )
483 {
484     int len = 0;
485     char *tok, *saveptr;
486     z->param = NULL;
487     z->f_bitrate_factor = 1;
488     if( 3 <= sscanf(p, "%u,%u,q=%u%n", &z->i_start, &z->i_end, &z->i_qp, &len) )
489         z->b_force_qp = 1;
490     else if( 3 <= sscanf(p, "%u,%u,b=%f%n", &z->i_start, &z->i_end, &z->f_bitrate_factor, &len) )
491         z->b_force_qp = 0;
492     else if( 2 <= sscanf(p, "%u,%u%n", &z->i_start, &z->i_end, &len) )
493         z->b_force_qp = 0;
494     else
495     {
496         x264_log( h, X264_LOG_ERROR, "invalid zone: \"%s\"\n", p );
497         return -1;
498     }
499     p += len;
500     if( !*p )
501         return 0;
502     z->param = malloc( sizeof(x264_param_t) );
503     memcpy( z->param, &h->param, sizeof(x264_param_t) );
504     while( (tok = strtok_r( p, ",", &saveptr )) )
505     {
506         char *val = strchr( tok, '=' );
507         if( val )
508         {
509             *val = '\0';
510             val++;
511         }
512         if( x264_param_parse( z->param, tok, val ) )
513         {
514             x264_log( h, X264_LOG_ERROR, "invalid zone param: %s = %s\n", tok, val );
515             return -1;
516         }
517         p = NULL;
518     }
519     return 0;
520 }
521
522 static int parse_zones( x264_t *h )
523 {
524     x264_ratecontrol_t *rc = h->rc;
525     int i;
526     if( h->param.rc.psz_zones && !h->param.rc.i_zones )
527     {
528         char *p, *tok, *saveptr;
529         char *psz_zones = x264_malloc( strlen(h->param.rc.psz_zones)+1 );
530         strcpy( psz_zones, h->param.rc.psz_zones );
531         h->param.rc.i_zones = 1;
532         for( p = psz_zones; *p; p++ )
533             h->param.rc.i_zones += (*p == '/');
534         h->param.rc.zones = x264_malloc( h->param.rc.i_zones * sizeof(x264_zone_t) );
535         p = psz_zones;
536         for( i = 0; i < h->param.rc.i_zones; i++ )
537         {
538             tok = strtok_r( p, "/", &saveptr );
539             if( !tok || parse_zone( h, &h->param.rc.zones[i], tok ) )
540                 return -1;
541             p = NULL;
542         }
543         x264_free( psz_zones );
544     }
545
546     if( h->param.rc.i_zones > 0 )
547     {
548         for( i = 0; i < h->param.rc.i_zones; i++ )
549         {
550             x264_zone_t z = h->param.rc.zones[i];
551             if( z.i_start < 0 || z.i_start > z.i_end )
552             {
553                 x264_log( h, X264_LOG_ERROR, "invalid zone: start=%d end=%d\n",
554                           z.i_start, z.i_end );
555                 return -1;
556             }
557             else if( !z.b_force_qp && z.f_bitrate_factor <= 0 )
558             {
559                 x264_log( h, X264_LOG_ERROR, "invalid zone: bitrate_factor=%f\n",
560                           z.f_bitrate_factor );
561                 return -1;
562             }
563         }
564
565         rc->i_zones = h->param.rc.i_zones + 1;
566         rc->zones = x264_malloc( rc->i_zones * sizeof(x264_zone_t) );
567         memcpy( rc->zones+1, h->param.rc.zones, (rc->i_zones-1) * sizeof(x264_zone_t) );
568
569         // default zone to fall back to if none of the others match
570         rc->zones[0].i_start = 0;
571         rc->zones[0].i_end = INT_MAX;
572         rc->zones[0].b_force_qp = 0;
573         rc->zones[0].f_bitrate_factor = 1;
574         rc->zones[0].param = x264_malloc( sizeof(x264_param_t) );
575         memcpy( rc->zones[0].param, &h->param, sizeof(x264_param_t) );
576         for( i = 1; i < rc->i_zones; i++ )
577         {
578             if( !rc->zones[i].param )
579                 rc->zones[i].param = rc->zones[0].param;
580         }
581     }
582
583     return 0;
584 }
585
586 x264_zone_t *get_zone( x264_t *h, int frame_num )
587 {
588     int i;
589     for( i = h->rc->i_zones-1; i >= 0; i-- )
590     {
591         x264_zone_t *z = &h->rc->zones[i];
592         if( frame_num >= z->i_start && frame_num <= z->i_end )
593             return z;
594     }
595     return NULL;
596 }
597
598 void x264_ratecontrol_summary( x264_t *h )
599 {
600     x264_ratecontrol_t *rc = h->rc;
601     if( rc->b_abr && h->param.rc.i_rc_method == X264_RC_ABR && rc->cbr_decay > .9999 )
602     {
603         double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
604         x264_log( h, X264_LOG_INFO, "final ratefactor: %.2f\n", 
605                   qscale2qp( pow( base_cplx, 1 - h->param.rc.f_qcompress )
606                              * rc->cplxr_sum / rc->wanted_bits_window ) );
607     }
608 }
609
610 void x264_ratecontrol_delete( x264_t *h )
611 {
612     x264_ratecontrol_t *rc = h->rc;
613     int i;
614
615     if( rc->p_stat_file_out )
616     {
617         fclose( rc->p_stat_file_out );
618         if( h->i_frame >= rc->num_entries - h->param.i_bframe )
619             if( rename( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ) != 0 )
620             {
621                 x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
622                           rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out );
623             }
624         x264_free( rc->psz_stat_file_tmpname );
625     }
626     x264_free( rc->pred );
627     x264_free( rc->pred_b_from_p );
628     x264_free( rc->entry );
629     if( rc->zones )
630     {
631         x264_free( rc->zones[0].param );
632         if( h->param.rc.psz_zones )
633             for( i=1; i<rc->i_zones; i++ )
634                 if( rc->zones[i].param != rc->zones[0].param )
635                     x264_free( rc->zones[i].param );
636         x264_free( rc->zones );
637     }
638     x264_free( rc );
639 }
640
641 static void accum_p_qp_update( x264_t *h, float qp )
642 {
643     x264_ratecontrol_t *rc = h->rc;
644     rc->accum_p_qp   *= .95;
645     rc->accum_p_norm *= .95;
646     rc->accum_p_norm += 1;
647     if( h->sh.i_type == SLICE_TYPE_I )
648         rc->accum_p_qp += qp + rc->ip_offset;
649     else
650         rc->accum_p_qp += qp;
651 }
652
653 /* Before encoding a frame, choose a QP for it */
654 void x264_ratecontrol_start( x264_t *h, int i_force_qp )
655 {
656     x264_ratecontrol_t *rc = h->rc;
657     ratecontrol_entry_t *rce = NULL;
658     x264_zone_t *zone = get_zone( h, h->fenc->i_frame );
659     float q;
660
661     x264_cpu_restore( h->param.cpu );
662
663     if( zone && (!rc->prev_zone || zone->param != rc->prev_zone->param) )
664         x264_encoder_reconfig( h, zone->param );
665     rc->prev_zone = zone;
666
667     rc->qp_force = i_force_qp;
668
669     if( h->param.rc.b_stat_read )
670     {
671         int frame = h->fenc->i_frame;
672         assert( frame >= 0 && frame < rc->num_entries );
673         rce = h->rc->rce = &h->rc->entry[frame];
674
675         if( h->sh.i_type == SLICE_TYPE_B
676             && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
677         {
678             h->sh.b_direct_spatial_mv_pred = ( rce->direct_mode == 's' );
679             h->mb.b_direct_auto_read = ( rce->direct_mode == 's' || rce->direct_mode == 't' );
680         }
681     }
682
683     if( rc->b_vbv )
684     {
685         memset( h->fdec->i_row_bits, 0, h->sps->i_mb_height * sizeof(int) );
686         rc->row_pred = &rc->row_preds[h->sh.i_type];
687         update_vbv_plan( h );
688     }
689
690     if( h->sh.i_type != SLICE_TYPE_B )
691     {
692         rc->bframes = 0;
693         while( h->frames.current[rc->bframes] && IS_X264_TYPE_B(h->frames.current[rc->bframes]->i_type) )
694             rc->bframes++;
695     }
696
697     rc->qpa = 0;
698
699     if( i_force_qp )
700     {
701         q = i_force_qp - 1;
702     }
703     else if( rc->b_abr )
704     {
705         q = qscale2qp( rate_estimate_qscale( h ) );
706     }
707     else if( rc->b_2pass )
708     {
709         rce->new_qscale = rate_estimate_qscale( h );
710         q = qscale2qp( rce->new_qscale );
711     }
712     else /* CQP */
713     {
714         if( h->sh.i_type == SLICE_TYPE_B && h->fdec->b_kept_as_ref )
715             q = ( rc->qp_constant[ SLICE_TYPE_B ] + rc->qp_constant[ SLICE_TYPE_P ] ) / 2;
716         else
717             q = rc->qp_constant[ h->sh.i_type ];
718
719         if( zone )
720         {
721             if( zone->b_force_qp )
722                 q += zone->i_qp - rc->qp_constant[SLICE_TYPE_P];
723             else
724                 q -= 6*log(zone->f_bitrate_factor)/log(2);
725         }
726     }
727
728     h->fdec->f_qp_avg =
729     rc->qpm =
730     rc->qp = x264_clip3( (int)(q + 0.5), 0, 51 );
731     if( rce )
732         rce->new_qp = rc->qp;
733
734     /* accum_p_qp needs to be here so that future frames can benefit from the
735      * data before this frame is done. but this only works because threading
736      * guarantees to not re-encode any frames. so the non-threaded case does
737      * accum_p_qp later. */
738     if( h->param.i_threads > 1 )
739         accum_p_qp_update( h, rc->qp );
740
741     if( h->sh.i_type != SLICE_TYPE_B )
742         rc->last_non_b_pict_type = h->sh.i_type;
743 }
744
745 double predict_row_size( x264_t *h, int y, int qp )
746 {
747     /* average between two predictors:
748      * absolute SATD, and scaled bit cost of the colocated row in the previous frame */
749     x264_ratecontrol_t *rc = h->rc;
750     double pred_s = predict_size( rc->row_pred, qp2qscale(qp), h->fdec->i_row_satd[y] );
751     double pred_t = 0;
752     if( h->sh.i_type != SLICE_TYPE_I 
753         && h->fref0[0]->i_type == h->fdec->i_type
754         && h->fref0[0]->i_row_satd[y] > 0 )
755     {
756         pred_t = h->fref0[0]->i_row_bits[y] * h->fdec->i_row_satd[y] / h->fref0[0]->i_row_satd[y]
757                  * qp2qscale(h->fref0[0]->i_row_qp[y]) / qp2qscale(qp);
758     }
759     if( pred_t == 0 )
760         pred_t = pred_s;
761
762     return (pred_s + pred_t) / 2;
763 }
764
765 double predict_row_size_sum( x264_t *h, int y, int qp )
766 {
767     int i;
768     double bits = 0;
769     for( i = 0; i <= y; i++ )
770         bits += h->fdec->i_row_bits[i];
771     for( i = y+1; i < h->sps->i_mb_height; i++ )
772         bits += predict_row_size( h, i, qp );
773     return bits;
774 }
775
776 void x264_ratecontrol_mb( x264_t *h, int bits )
777 {
778     x264_ratecontrol_t *rc = h->rc;
779     const int y = h->mb.i_mb_y;
780
781     x264_cpu_restore( h->param.cpu );
782
783     h->fdec->i_row_bits[y] += bits;
784     rc->qpa += rc->qpm;
785
786     if( h->mb.i_mb_x != h->sps->i_mb_width - 1 || !h->mb.b_variable_qp )
787         return;
788
789     h->fdec->i_row_qp[y] = rc->qpm;
790
791     if( h->sh.i_type == SLICE_TYPE_B )
792     {
793         /* B-frames shouldn't use lower QP than their reference frames */
794         if( y < h->sps->i_mb_height-1 )
795         {
796             rc->qpm = X264_MAX( rc->qp,
797                       X264_MIN( h->fref0[0]->i_row_qp[y+1],
798                                 h->fref1[0]->i_row_qp[y+1] ));
799         }
800     }
801     else
802     {
803         update_predictor( rc->row_pred, qp2qscale(rc->qpm), h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] );
804
805         /* tweak quality based on difference from predicted size */
806         if( y < h->sps->i_mb_height-1 && h->stat.i_slice_count[h->sh.i_type] > 0 )
807         {
808             int prev_row_qp = h->fdec->i_row_qp[y];
809             int b0 = predict_row_size_sum( h, y, rc->qpm );
810             int b1 = b0;
811             int i_qp_max = X264_MIN( prev_row_qp + h->param.rc.i_qp_step, h->param.rc.i_qp_max );
812             int i_qp_min = X264_MAX( prev_row_qp - h->param.rc.i_qp_step, h->param.rc.i_qp_min );
813             float buffer_left_planned = rc->buffer_fill - rc->frame_size_planned;
814
815             if( !rc->b_vbv_min_rate )
816                 i_qp_min = X264_MAX( i_qp_min, h->sh.i_qp );
817
818             while( rc->qpm < i_qp_max
819                    && (b1 > rc->frame_size_planned * 1.15
820                     || (rc->buffer_fill - b1 < buffer_left_planned * 0.5)))
821             {
822                 rc->qpm ++;
823                 b1 = predict_row_size_sum( h, y, rc->qpm );
824             }
825
826             while( rc->qpm > i_qp_min
827                    && buffer_left_planned > rc->buffer_size * 0.4
828                    && ((b1 < rc->frame_size_planned * 0.8 && rc->qpm <= prev_row_qp)
829                      || b1 < (rc->buffer_fill - rc->buffer_size + rc->buffer_rate) * 1.1) )
830             {
831                 rc->qpm --;
832                 b1 = predict_row_size_sum( h, y, rc->qpm );
833             }
834         }
835     }
836 }
837
838 int x264_ratecontrol_qp( x264_t *h )
839 {
840     return h->rc->qpm;
841 }
842
843 /* In 2pass, force the same frame types as in the 1st pass */
844 int x264_ratecontrol_slice_type( x264_t *h, int frame_num )
845 {
846     x264_ratecontrol_t *rc = h->rc;
847     if( h->param.rc.b_stat_read )
848     {
849         if( frame_num >= rc->num_entries )
850         {
851             /* We could try to initialize everything required for ABR and
852              * adaptive B-frames, but that would be complicated.
853              * So just calculate the average QP used so far. */
854
855             h->param.rc.i_qp_constant = (h->stat.i_slice_count[SLICE_TYPE_P] == 0) ? 24
856                                       : 1 + h->stat.i_slice_qp[SLICE_TYPE_P] / h->stat.i_slice_count[SLICE_TYPE_P];
857             rc->qp_constant[SLICE_TYPE_P] = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
858             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 );
859             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 );
860
861             x264_log(h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d)\n", rc->num_entries);
862             x264_log(h, X264_LOG_ERROR, "continuing anyway, at constant QP=%d\n", h->param.rc.i_qp_constant);
863             if( h->param.b_bframe_adaptive )
864                 x264_log(h, X264_LOG_ERROR, "disabling adaptive B-frames\n");
865
866             rc->b_abr = 0;
867             rc->b_2pass = 0;
868             h->param.rc.i_rc_method = X264_RC_CQP;
869             h->param.rc.b_stat_read = 0;
870             h->param.b_bframe_adaptive = 0;
871             if( h->param.i_bframe > 1 )
872                 h->param.i_bframe = 1;
873             return X264_TYPE_P;
874         }
875         switch( rc->entry[frame_num].pict_type )
876         {
877             case SLICE_TYPE_I:
878                 return rc->entry[frame_num].kept_as_ref ? X264_TYPE_IDR : X264_TYPE_I;
879
880             case SLICE_TYPE_B:
881                 return rc->entry[frame_num].kept_as_ref ? X264_TYPE_BREF : X264_TYPE_B;
882
883             case SLICE_TYPE_P:
884             default:
885                 return X264_TYPE_P;
886         }
887     }
888     else
889     {
890         return X264_TYPE_AUTO;
891     }
892 }
893
894 /* After encoding one frame, save stats and update ratecontrol state */
895 void x264_ratecontrol_end( x264_t *h, int bits )
896 {
897     x264_ratecontrol_t *rc = h->rc;
898     const int *mbs = h->stat.frame.i_mb_count;
899     int i;
900
901     x264_cpu_restore( h->param.cpu );
902
903     h->stat.frame.i_mb_count_skip = mbs[P_SKIP] + mbs[B_SKIP];
904     h->stat.frame.i_mb_count_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
905     h->stat.frame.i_mb_count_p = mbs[P_L0] + mbs[P_8x8];
906     for( i = B_DIRECT; i < B_8x8; i++ )
907         h->stat.frame.i_mb_count_p += mbs[i];
908
909     if( h->mb.b_variable_qp )
910         rc->qpa /= h->mb.i_mb_count;
911     else
912         rc->qpa = rc->qp;
913     h->fdec->f_qp_avg = rc->qpa;
914
915     if( h->param.rc.b_stat_write )
916     {
917         char c_type = h->sh.i_type==SLICE_TYPE_I ? (h->fenc->i_poc==0 ? 'I' : 'i')
918                     : h->sh.i_type==SLICE_TYPE_P ? 'P'
919                     : h->fenc->b_kept_as_ref ? 'B' : 'b';
920         int dir_frame = h->stat.frame.i_direct_score[1] - h->stat.frame.i_direct_score[0];
921         int dir_avg = h->stat.i_direct_score[1] - h->stat.i_direct_score[0];
922         char c_direct = h->mb.b_direct_auto_write ?
923                         ( dir_frame>0 ? 's' : dir_frame<0 ? 't' : 
924                           dir_avg>0 ? 's' : dir_avg<0 ? 't' : '-' )
925                         : '-';
926         fprintf( rc->p_stat_file_out,
927                  "in:%d out:%d type:%c q:%.2f itex:%d ptex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c;\n",
928                  h->fenc->i_frame, h->i_frame,
929                  c_type, rc->qpa,
930                  h->stat.frame.i_itex_bits, h->stat.frame.i_ptex_bits,
931                  h->stat.frame.i_hdr_bits, h->stat.frame.i_misc_bits,
932                  h->stat.frame.i_mb_count_i,
933                  h->stat.frame.i_mb_count_p,
934                  h->stat.frame.i_mb_count_skip,
935                  c_direct);
936     }
937
938     if( rc->b_abr )
939     {
940         if( h->sh.i_type != SLICE_TYPE_B )
941             rc->cplxr_sum += bits * qp2qscale(rc->qpa) / rc->last_rceq;
942         else
943         {
944             /* Depends on the fact that B-frame's QP is an offset from the following P-frame's.
945              * Not perfectly accurate with B-refs, but good enough. */
946             rc->cplxr_sum += bits * qp2qscale(rc->qpa) / (rc->last_rceq * fabs(h->param.rc.f_pb_factor));
947         }
948         rc->cplxr_sum *= rc->cbr_decay;
949         rc->wanted_bits_window += rc->bitrate / rc->fps;
950         rc->wanted_bits_window *= rc->cbr_decay;
951
952         if( h->param.i_threads == 1 )
953             accum_p_qp_update( h, rc->qpa );
954     }
955
956     if( rc->b_2pass )
957     {
958         rc->expected_bits_sum += qscale2bits( rc->rce, qp2qscale(rc->rce->new_qp) );
959     }
960
961     if( h->mb.b_variable_qp )
962     {
963         if( h->sh.i_type == SLICE_TYPE_B )
964         {
965             rc->bframe_bits += bits;
966             if( !h->frames.current[0] || !IS_X264_TYPE_B(h->frames.current[0]->i_type) )
967             {
968                 update_predictor( rc->pred_b_from_p, qp2qscale(rc->qpa),
969                                   h->fref1[h->i_ref1-1]->i_satd, rc->bframe_bits / rc->bframes );
970                 rc->bframe_bits = 0;
971             }
972         }
973     }
974
975     update_vbv( h, bits );
976 }
977
978 /****************************************************************************
979  * 2 pass functions
980  ***************************************************************************/
981
982 double x264_eval( char *s, double *const_value, const char **const_name,
983                   double (**func1)(void *, double), const char **func1_name,
984                   double (**func2)(void *, double, double), char **func2_name,
985                   void *opaque );
986
987 /**
988  * modify the bitrate curve from pass1 for one frame
989  */
990 static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor, int frame_num)
991 {
992     x264_ratecontrol_t *rcc= h->rc;
993     const int pict_type = rce->pict_type;
994     double q;
995     x264_zone_t *zone = get_zone( h, frame_num );
996
997     double const_values[]={
998         rce->i_tex_bits * rce->qscale,
999         rce->p_tex_bits * rce->qscale,
1000         (rce->i_tex_bits + rce->p_tex_bits) * rce->qscale,
1001         rce->mv_bits * rce->qscale,
1002         (double)rce->i_count / rcc->nmb,
1003         (double)rce->p_count / rcc->nmb,
1004         (double)rce->s_count / rcc->nmb,
1005         rce->pict_type == SLICE_TYPE_I,
1006         rce->pict_type == SLICE_TYPE_P,
1007         rce->pict_type == SLICE_TYPE_B,
1008         h->param.rc.f_qcompress,
1009         rcc->i_cplx_sum[SLICE_TYPE_I] / rcc->frame_count[SLICE_TYPE_I],
1010         rcc->i_cplx_sum[SLICE_TYPE_P] / rcc->frame_count[SLICE_TYPE_P],
1011         rcc->p_cplx_sum[SLICE_TYPE_P] / rcc->frame_count[SLICE_TYPE_P],
1012         rcc->p_cplx_sum[SLICE_TYPE_B] / rcc->frame_count[SLICE_TYPE_B],
1013         (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / rcc->frame_count[pict_type],
1014         rce->blurred_complexity,
1015         0
1016     };
1017     static const char *const_names[]={
1018         "iTex",
1019         "pTex",
1020         "tex",
1021         "mv",
1022         "iCount",
1023         "pCount",
1024         "sCount",
1025         "isI",
1026         "isP",
1027         "isB",
1028         "qComp",
1029         "avgIITex",
1030         "avgPITex",
1031         "avgPPTex",
1032         "avgBPTex",
1033         "avgTex",
1034         "blurCplx",
1035         NULL
1036     };
1037     static double (*func1[])(void *, double)={
1038 //      (void *)bits2qscale,
1039         (void *)qscale2bits,
1040         NULL
1041     };
1042     static const char *func1_names[]={
1043 //      "bits2qp",
1044         "qp2bits",
1045         NULL
1046     };
1047
1048     q = x264_eval((char*)h->param.rc.psz_rc_eq, const_values, const_names, func1, func1_names, NULL, NULL, rce);
1049
1050     // avoid NaN's in the rc_eq
1051     if(!isfinite(q) || rce->i_tex_bits + rce->p_tex_bits + rce->mv_bits == 0)
1052         q = rcc->last_qscale;
1053     else {
1054         rcc->last_rceq = q;
1055         q /= rate_factor;
1056         rcc->last_qscale = q;
1057     }
1058
1059     if( zone )
1060     {
1061         if( zone->b_force_qp )
1062             q = qp2qscale(zone->i_qp);
1063         else
1064             q /= zone->f_bitrate_factor;
1065     }
1066
1067     return q;
1068 }
1069
1070 static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
1071 {
1072     x264_ratecontrol_t *rcc = h->rc;
1073     const int pict_type = rce->pict_type;
1074
1075     // force I/B quants as a function of P quants
1076     const double last_p_q    = rcc->last_qscale_for[SLICE_TYPE_P];
1077     const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
1078     if( pict_type == SLICE_TYPE_I )
1079     {
1080         double iq = q;
1081         double pq = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
1082         double ip_factor = fabs( h->param.rc.f_ip_factor );
1083         /* don't apply ip_factor if the following frame is also I */
1084         if( rcc->accum_p_norm <= 0 )
1085             q = iq;
1086         else if( h->param.rc.f_ip_factor < 0 )
1087             q = iq / ip_factor;
1088         else if( rcc->accum_p_norm >= 1 )
1089             q = pq / ip_factor;
1090         else
1091             q = rcc->accum_p_norm * pq / ip_factor + (1 - rcc->accum_p_norm) * iq;
1092     }
1093     else if( pict_type == SLICE_TYPE_B )
1094     {
1095         if( h->param.rc.f_pb_factor > 0 )
1096             q = last_non_b_q;
1097         if( !rce->kept_as_ref )
1098             q *= fabs( h->param.rc.f_pb_factor );
1099     }
1100     else if( pict_type == SLICE_TYPE_P
1101              && rcc->last_non_b_pict_type == SLICE_TYPE_P
1102              && rce->i_tex_bits + rce->p_tex_bits == 0 )
1103     {
1104         q = last_p_q;
1105     }
1106
1107     /* last qscale / qdiff stuff */
1108     if(rcc->last_non_b_pict_type==pict_type
1109        && (pict_type!=SLICE_TYPE_I || rcc->last_accum_p_norm < 1))
1110     {
1111         double last_q = rcc->last_qscale_for[pict_type];
1112         double max_qscale = last_q * rcc->lstep;
1113         double min_qscale = last_q / rcc->lstep;
1114
1115         if     (q > max_qscale) q = max_qscale;
1116         else if(q < min_qscale) q = min_qscale;
1117     }
1118
1119     rcc->last_qscale_for[pict_type] = q;
1120     if(pict_type!=SLICE_TYPE_B)
1121         rcc->last_non_b_pict_type = pict_type;
1122     if(pict_type==SLICE_TYPE_I)
1123     {
1124         rcc->last_accum_p_norm = rcc->accum_p_norm;
1125         rcc->accum_p_norm = 0;
1126         rcc->accum_p_qp = 0;
1127     }
1128     if(pict_type==SLICE_TYPE_P)
1129     {
1130         float mask = 1 - pow( (float)rce->i_count / rcc->nmb, 2 );
1131         rcc->accum_p_qp   = mask * (qscale2qp(q) + rcc->accum_p_qp);
1132         rcc->accum_p_norm = mask * (1 + rcc->accum_p_norm);
1133     }
1134     return q;
1135 }
1136
1137 static double predict_size( predictor_t *p, double q, double var )
1138 {
1139      return p->coeff*var / (q*p->count);
1140 }
1141
1142 static void update_predictor( predictor_t *p, double q, double var, double bits )
1143 {
1144     if( var < 10 )
1145         return;
1146     p->count *= p->decay;
1147     p->coeff *= p->decay;
1148     p->count ++;
1149     p->coeff += bits*q / var;
1150 }
1151
1152 // update VBV after encoding a frame
1153 static void update_vbv( x264_t *h, int bits )
1154 {
1155     x264_ratecontrol_t *rcc = h->rc;
1156     x264_ratecontrol_t *rct = h->thread[0]->rc;
1157
1158     if( rcc->last_satd >= h->mb.i_mb_count )
1159         update_predictor( &rct->pred[h->sh.i_type], qp2qscale(rcc->qpa), rcc->last_satd, bits );
1160
1161     if( !rcc->b_vbv )
1162         return;
1163
1164     rct->buffer_fill_final += rct->buffer_rate - bits;
1165     if( rct->buffer_fill_final < 0 && !rct->b_2pass )
1166         x264_log( h, X264_LOG_WARNING, "VBV underflow (%.0f bits)\n", rct->buffer_fill_final );
1167     rct->buffer_fill_final = x264_clip3( rct->buffer_fill_final, 0, rct->buffer_size );
1168 }
1169
1170 // provisionally update VBV according to the planned size of all frames currently in progress
1171 static void update_vbv_plan( x264_t *h )
1172 {
1173     x264_ratecontrol_t *rcc = h->rc;
1174     rcc->buffer_fill = h->thread[0]->rc->buffer_fill_final;
1175     if( h->param.i_threads > 1 )
1176     {
1177         int j = h->rc - h->thread[0]->rc;
1178         int i;
1179         for( i=1; i<h->param.i_threads; i++ )
1180         {
1181             x264_t *t = h->thread[ (j+i)%h->param.i_threads ];
1182             double bits = t->rc->frame_size_planned;
1183             if( !t->b_thread_active )
1184                 continue;
1185             rcc->buffer_fill += rcc->buffer_rate - bits;
1186             rcc->buffer_fill = x264_clip3( rcc->buffer_fill, 0, rcc->buffer_size );
1187         }
1188     }
1189 }
1190
1191 // apply VBV constraints and clip qscale to between lmin and lmax
1192 static double clip_qscale( x264_t *h, int pict_type, double q )
1193 {
1194     x264_ratecontrol_t *rcc = h->rc;
1195     double lmin = rcc->lmin[pict_type];
1196     double lmax = rcc->lmax[pict_type];
1197     double q0 = q;
1198
1199     /* B-frames are not directly subject to VBV,
1200      * since they are controlled by the P-frames' QPs.
1201      * FIXME: in 2pass we could modify previous frames' QP too,
1202      *        instead of waiting for the buffer to fill */
1203     if( rcc->b_vbv &&
1204         ( pict_type == SLICE_TYPE_P ||
1205           ( pict_type == SLICE_TYPE_I && rcc->last_non_b_pict_type == SLICE_TYPE_I ) ) )
1206     {
1207         if( rcc->buffer_fill/rcc->buffer_size < 0.5 )
1208             q /= x264_clip3f( 2.0*rcc->buffer_fill/rcc->buffer_size, 0.5, 1.0 );
1209     }
1210
1211     if( rcc->b_vbv && rcc->last_satd > 0 )
1212     {
1213         /* Now a hard threshold to make sure the frame fits in VBV.
1214          * This one is mostly for I-frames. */
1215         double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
1216         double qf = 1.0;
1217         if( bits > rcc->buffer_fill/2 )
1218             qf = x264_clip3f( rcc->buffer_fill/(2*bits), 0.2, 1.0 );
1219         q /= qf;
1220         bits *= qf;
1221         if( bits < rcc->buffer_rate/2 )
1222             q *= bits*2/rcc->buffer_rate;
1223         q = X264_MAX( q0, q );
1224
1225         /* Check B-frame complexity, and use up any bits that would
1226          * overflow before the next P-frame. */
1227         if( h->sh.i_type == SLICE_TYPE_P )
1228         {
1229             int nb = rcc->bframes;
1230             double pbbits = bits;
1231             double bbits = predict_size( rcc->pred_b_from_p, q * h->param.rc.f_pb_factor, rcc->last_satd );
1232             double space;
1233
1234             if( bbits > rcc->buffer_rate )
1235                 nb = 0;
1236             pbbits += nb * bbits;
1237
1238             space = rcc->buffer_fill + (1+nb)*rcc->buffer_rate - rcc->buffer_size;
1239             if( pbbits < space )
1240             {
1241                 q *= X264_MAX( pbbits / space,
1242                                bits / (0.5 * rcc->buffer_size) );
1243             }
1244             q = X264_MAX( q0-5, q );
1245         }
1246
1247         if( !rcc->b_vbv_min_rate )
1248             q = X264_MAX( q0, q );
1249     }
1250
1251     if(lmin==lmax)
1252         return lmin;
1253     else if(rcc->b_2pass)
1254     {
1255         double min2 = log(lmin);
1256         double max2 = log(lmax);
1257         q = (log(q) - min2)/(max2-min2) - 0.5;
1258         q = 1.0/(1.0 + exp(-4*q));
1259         q = q*(max2-min2) + min2;
1260         return exp(q);
1261     }
1262     else
1263         return x264_clip3f(q, lmin, lmax);
1264 }
1265
1266 // update qscale for 1 frame based on actual bits used so far
1267 static float rate_estimate_qscale( x264_t *h )
1268 {
1269     float q;
1270     x264_ratecontrol_t *rcc = h->rc;
1271     ratecontrol_entry_t rce;
1272     int pict_type = h->sh.i_type;
1273     double lmin = rcc->lmin[pict_type];
1274     double lmax = rcc->lmax[pict_type];
1275     int64_t total_bits = 8*(h->stat.i_slice_size[SLICE_TYPE_I]
1276                           + h->stat.i_slice_size[SLICE_TYPE_P]
1277                           + h->stat.i_slice_size[SLICE_TYPE_B]);
1278
1279     if( rcc->b_2pass )
1280     {
1281         rce = *rcc->rce;
1282         if(pict_type != rce.pict_type)
1283         {
1284             x264_log(h, X264_LOG_ERROR, "slice=%c but 2pass stats say %c\n",
1285                      slice_type_to_char[pict_type], slice_type_to_char[rce.pict_type]);
1286         }
1287     }
1288
1289     if( pict_type == SLICE_TYPE_B )
1290     {
1291         /* B-frames don't have independent ratecontrol, but rather get the
1292          * average QP of the two adjacent P-frames + an offset */
1293
1294         int i0 = IS_X264_TYPE_I(h->fref0[0]->i_type);
1295         int i1 = IS_X264_TYPE_I(h->fref1[0]->i_type);
1296         int dt0 = abs(h->fenc->i_poc - h->fref0[0]->i_poc);
1297         int dt1 = abs(h->fenc->i_poc - h->fref1[0]->i_poc);
1298         float q0 = h->fref0[0]->f_qp_avg;
1299         float q1 = h->fref1[0]->f_qp_avg;
1300
1301         if( h->fref0[0]->i_type == X264_TYPE_BREF )
1302             q0 -= rcc->pb_offset/2;
1303         if( h->fref1[0]->i_type == X264_TYPE_BREF )
1304             q1 -= rcc->pb_offset/2;
1305
1306         if(i0 && i1)
1307             q = (q0 + q1) / 2 + rcc->ip_offset;
1308         else if(i0)
1309             q = q1;
1310         else if(i1)
1311             q = q0;
1312         else
1313             q = (q0*dt1 + q1*dt0) / (dt0 + dt1);
1314
1315         if(h->fenc->b_kept_as_ref)
1316             q += rcc->pb_offset/2;
1317         else
1318             q += rcc->pb_offset;
1319
1320         rcc->frame_size_planned = predict_size( rcc->pred_b_from_p, q, h->fref1[h->i_ref1-1]->i_satd );
1321         rcc->last_satd = 0;
1322         return qp2qscale(q);
1323     }
1324     else
1325     {
1326         double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate;
1327         if( rcc->b_2pass )
1328         {
1329             //FIXME adjust abr_buffer based on distance to the end of the video
1330             int64_t diff = total_bits - (int64_t)rce.expected_bits;
1331             q = rce.new_qscale;
1332             q /= x264_clip3f((double)(abr_buffer - diff) / abr_buffer, .5, 2);
1333             if( h->fenc->i_frame > 30 )
1334             {
1335                 /* Adjust quant based on the difference between
1336                  * achieved and expected bitrate so far */
1337                 double time = (double)h->fenc->i_frame / rcc->num_entries;
1338                 double w = x264_clip3f( time*100, 0.0, 1.0 );
1339                 q *= pow( (double)total_bits / rcc->expected_bits_sum, w );
1340             }
1341             q = x264_clip3f( q, lmin, lmax );
1342         }
1343         else /* 1pass ABR */
1344         {
1345             /* Calculate the quantizer which would have produced the desired
1346              * average bitrate if it had been applied to all frames so far.
1347              * Then modulate that quant based on the current frame's complexity
1348              * relative to the average complexity so far (using the 2pass RCEQ).
1349              * Then bias the quant up or down if total size so far was far from
1350              * the target.
1351              * Result: Depending on the value of rate_tolerance, there is a
1352              * tradeoff between quality and bitrate precision. But at large
1353              * tolerances, the bit distribution approaches that of 2pass. */
1354
1355             double wanted_bits, overflow=1, lmin, lmax;
1356
1357             rcc->last_satd = x264_rc_analyse_slice( h );
1358             rcc->short_term_cplxsum *= 0.5;
1359             rcc->short_term_cplxcount *= 0.5;
1360             rcc->short_term_cplxsum += rcc->last_satd;
1361             rcc->short_term_cplxcount ++;
1362
1363             rce.p_tex_bits = rcc->last_satd;
1364             rce.blurred_complexity = rcc->short_term_cplxsum / rcc->short_term_cplxcount;
1365             rce.i_tex_bits = 0;
1366             rce.mv_bits = 0;
1367             rce.p_count = rcc->nmb;
1368             rce.i_count = 0;
1369             rce.s_count = 0;
1370             rce.qscale = 1;
1371             rce.pict_type = pict_type;
1372
1373             if( h->param.rc.i_rc_method == X264_RC_CRF )
1374             {
1375                 q = get_qscale( h, &rce, rcc->rate_factor_constant, h->fenc->i_frame );
1376             }
1377             else
1378             {
1379                 int i_frame_done = h->fenc->i_frame + 1 - h->param.i_threads;
1380
1381                 q = get_qscale( h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame );
1382
1383                 // FIXME is it simpler to keep track of wanted_bits in ratecontrol_end?
1384                 wanted_bits = i_frame_done * rcc->bitrate / rcc->fps;
1385                 if( wanted_bits > 0 )
1386                 {
1387                     abr_buffer *= X264_MAX( 1, sqrt(i_frame_done/25) );
1388                     overflow = x264_clip3f( 1.0 + (total_bits - wanted_bits) / abr_buffer, .5, 2 );
1389                     q *= overflow;
1390                 }
1391             }
1392
1393             if( pict_type == SLICE_TYPE_I && h->param.i_keyint_max > 1
1394                 /* should test _next_ pict type, but that isn't decided yet */
1395                 && rcc->last_non_b_pict_type != SLICE_TYPE_I )
1396             {
1397                 q = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
1398                 q /= fabs( h->param.rc.f_ip_factor );
1399             }
1400             else if( h->i_frame > 0 )
1401             {
1402                 /* Asymmetric clipping, because symmetric would prevent
1403                  * overflow control in areas of rapidly oscillating complexity */
1404                 lmin = rcc->last_qscale_for[pict_type] / rcc->lstep;
1405                 lmax = rcc->last_qscale_for[pict_type] * rcc->lstep;
1406                 if( overflow > 1.1 && h->i_frame > 3 )
1407                     lmax *= rcc->lstep;
1408                 else if( overflow < 0.9 )
1409                     lmin /= rcc->lstep;
1410
1411                 q = x264_clip3f(q, lmin, lmax);
1412             }
1413             else if( h->param.rc.i_rc_method == X264_RC_CRF )
1414             {
1415                 q = qp2qscale( ABR_INIT_QP ) / fabs( h->param.rc.f_ip_factor );
1416             }
1417
1418             //FIXME use get_diff_limited_q() ?
1419             q = clip_qscale( h, pict_type, q );
1420         }
1421
1422         rcc->last_qscale_for[pict_type] =
1423         rcc->last_qscale = q;
1424
1425         if( !rcc->b_2pass && h->fenc->i_frame == 0 )
1426             rcc->last_qscale_for[SLICE_TYPE_P] = q;
1427
1428         rcc->frame_size_planned = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
1429         return q;
1430     }
1431 }
1432
1433 void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
1434 {
1435     if( cur != prev )
1436     {
1437 #define COPY(var) memcpy(&cur->rc->var, &prev->rc->var, sizeof(cur->rc->var))
1438         /* these vars are updated in x264_ratecontrol_start()
1439          * so copy them from the context that most recently started (prev)
1440          * to the context that's about to start (cur).
1441          */
1442         COPY(accum_p_qp);
1443         COPY(accum_p_norm);
1444         COPY(last_satd);
1445         COPY(last_rceq);
1446         COPY(last_qscale_for);
1447         COPY(last_non_b_pict_type);
1448         COPY(short_term_cplxsum);
1449         COPY(short_term_cplxcount);
1450         COPY(bframes);
1451         COPY(prev_zone);
1452 #undef COPY
1453     }
1454     if( cur != next )
1455     {
1456 #define COPY(var) next->rc->var = cur->rc->var
1457         /* these vars are updated in x264_ratecontrol_end()
1458          * so copy them from the context that most recently ended (cur)
1459          * to the context that's about to end (next)
1460          */
1461         COPY(cplxr_sum);
1462         COPY(expected_bits_sum);
1463         COPY(wanted_bits_window);
1464         COPY(bframe_bits);
1465 #undef COPY
1466     }
1467     //FIXME row_preds[] (not strictly necessary, but would improve prediction)
1468     /* the rest of the variables are either constant or thread-local */
1469 }
1470
1471 static int init_pass2( x264_t *h )
1472 {
1473     x264_ratecontrol_t *rcc = h->rc;
1474     uint64_t all_const_bits = 0;
1475     uint64_t all_available_bits = (uint64_t)(h->param.rc.i_bitrate * 1000 * (double)rcc->num_entries / rcc->fps);
1476     double rate_factor, step, step_mult;
1477     double qblur = h->param.rc.f_qblur;
1478     double cplxblur = h->param.rc.f_complexity_blur;
1479     const int filter_size = (int)(qblur*4) | 1;
1480     double expected_bits;
1481     double *qscale, *blurred_qscale;
1482     int i;
1483
1484     /* find total/average complexity & const_bits */
1485     for(i=0; i<rcc->num_entries; i++){
1486         ratecontrol_entry_t *rce = &rcc->entry[i];
1487         all_const_bits += rce->misc_bits;
1488         rcc->i_cplx_sum[rce->pict_type] += rce->i_tex_bits * rce->qscale;
1489         rcc->p_cplx_sum[rce->pict_type] += rce->p_tex_bits * rce->qscale;
1490         rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits * rce->qscale;
1491         rcc->frame_count[rce->pict_type] ++;
1492     }
1493
1494     if( all_available_bits < all_const_bits)
1495     {
1496         x264_log(h, X264_LOG_ERROR, "requested bitrate is too low. estimated minimum is %d kbps\n",
1497                  (int)(all_const_bits * rcc->fps / (rcc->num_entries * 1000)));
1498         return -1;
1499     }
1500
1501     /* Blur complexities, to reduce local fluctuation of QP.
1502      * We don't blur the QPs directly, because then one very simple frame
1503      * could drag down the QP of a nearby complex frame and give it more
1504      * bits than intended. */
1505     for(i=0; i<rcc->num_entries; i++){
1506         ratecontrol_entry_t *rce = &rcc->entry[i];
1507         double weight_sum = 0;
1508         double cplx_sum = 0;
1509         double weight = 1.0;
1510         int j;
1511         /* weighted average of cplx of future frames */
1512         for(j=1; j<cplxblur*2 && j<rcc->num_entries-i; j++){
1513             ratecontrol_entry_t *rcj = &rcc->entry[i+j];
1514             weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 );
1515             if(weight < .0001)
1516                 break;
1517             weight_sum += weight;
1518             cplx_sum += weight * (qscale2bits(rcj, 1) - rcj->misc_bits);
1519         }
1520         /* weighted average of cplx of past frames */
1521         weight = 1.0;
1522         for(j=0; j<=cplxblur*2 && j<=i; j++){
1523             ratecontrol_entry_t *rcj = &rcc->entry[i-j];
1524             weight_sum += weight;
1525             cplx_sum += weight * (qscale2bits(rcj, 1) - rcj->misc_bits);
1526             weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 );
1527             if(weight < .0001)
1528                 break;
1529         }
1530         rce->blurred_complexity = cplx_sum / weight_sum;
1531     }
1532
1533     qscale = x264_malloc(sizeof(double)*rcc->num_entries);
1534     if(filter_size > 1)
1535         blurred_qscale = x264_malloc(sizeof(double)*rcc->num_entries);
1536     else
1537         blurred_qscale = qscale;
1538
1539     /* Search for a factor which, when multiplied by the RCEQ values from
1540      * each frame, adds up to the desired total size.
1541      * There is no exact closed-form solution because of VBV constraints and
1542      * because qscale2bits is not invertible, but we can start with the simple
1543      * approximation of scaling the 1st pass by the ratio of bitrates.
1544      * The search range is probably overkill, but speed doesn't matter here. */
1545
1546     expected_bits = 1;
1547     for(i=0; i<rcc->num_entries; i++)
1548         expected_bits += qscale2bits(&rcc->entry[i], get_qscale(h, &rcc->entry[i], 1.0, i));
1549     step_mult = all_available_bits / expected_bits;
1550
1551     rate_factor = 0;
1552     for(step = 1E4 * step_mult; step > 1E-7 * step_mult; step *= 0.5){
1553         expected_bits = 0;
1554         rate_factor += step;
1555
1556         rcc->last_non_b_pict_type = -1;
1557         rcc->last_accum_p_norm = 1;
1558         rcc->accum_p_norm = 0;
1559         rcc->buffer_fill = rcc->buffer_size * h->param.rc.f_vbv_buffer_init;
1560
1561         /* find qscale */
1562         for(i=0; i<rcc->num_entries; i++){
1563             qscale[i] = get_qscale(h, &rcc->entry[i], rate_factor, i);
1564         }
1565
1566         /* fixed I/B qscale relative to P */
1567         for(i=rcc->num_entries-1; i>=0; i--){
1568             qscale[i] = get_diff_limited_q(h, &rcc->entry[i], qscale[i]);
1569             assert(qscale[i] >= 0);
1570         }
1571
1572         /* smooth curve */
1573         if(filter_size > 1){
1574             assert(filter_size%2==1);
1575             for(i=0; i<rcc->num_entries; i++){
1576                 ratecontrol_entry_t *rce = &rcc->entry[i];
1577                 int j;
1578                 double q=0.0, sum=0.0;
1579
1580                 for(j=0; j<filter_size; j++){
1581                     int index = i+j-filter_size/2;
1582                     double d = index-i;
1583                     double coeff = qblur==0 ? 1.0 : exp(-d*d/(qblur*qblur));
1584                     if(index < 0 || index >= rcc->num_entries) continue;
1585                     if(rce->pict_type != rcc->entry[index].pict_type) continue;
1586                     q += qscale[index] * coeff;
1587                     sum += coeff;
1588                 }
1589                 blurred_qscale[i] = q/sum;
1590             }
1591         }
1592
1593         /* find expected bits */
1594         for(i=0; i<rcc->num_entries; i++){
1595             ratecontrol_entry_t *rce = &rcc->entry[i];
1596             double bits;
1597             rce->new_qscale = clip_qscale(h, rce->pict_type, blurred_qscale[i]);
1598             assert(rce->new_qscale >= 0);
1599             bits = qscale2bits(rce, rce->new_qscale);
1600
1601             rce->expected_bits = expected_bits;
1602             expected_bits += bits;
1603             update_vbv(h, bits);
1604             rcc->buffer_fill = rcc->buffer_fill_final;
1605         }
1606
1607 //printf("expected:%llu available:%llu factor:%lf avgQ:%lf\n", (uint64_t)expected_bits, all_available_bits, rate_factor);
1608         if(expected_bits > all_available_bits) rate_factor -= step;
1609     }
1610
1611     x264_free(qscale);
1612     if(filter_size > 1)
1613         x264_free(blurred_qscale);
1614
1615     if(fabs(expected_bits/all_available_bits - 1.0) > 0.01)
1616     {
1617         double avgq = 0;
1618         for(i=0; i<rcc->num_entries; i++)
1619             avgq += rcc->entry[i].new_qscale;
1620         avgq = qscale2qp(avgq / rcc->num_entries);
1621
1622         x264_log(h, X264_LOG_WARNING, "Error: 2pass curve failed to converge\n");
1623         x264_log(h, X264_LOG_WARNING, "target: %.2f kbit/s, expected: %.2f kbit/s, avg QP: %.4f\n",
1624                  (float)h->param.rc.i_bitrate,
1625                  expected_bits * rcc->fps / (rcc->num_entries * 1000.),
1626                  avgq);
1627         if(expected_bits < all_available_bits && avgq < h->param.rc.i_qp_min + 2)
1628         {
1629             if(h->param.rc.i_qp_min > 0)
1630                 x264_log(h, X264_LOG_WARNING, "try reducing target bitrate or reducing qp_min (currently %d)\n", h->param.rc.i_qp_min);
1631             else
1632                 x264_log(h, X264_LOG_WARNING, "try reducing target bitrate\n");
1633         }
1634         else if(expected_bits > all_available_bits && avgq > h->param.rc.i_qp_max - 2)
1635         {
1636             if(h->param.rc.i_qp_max < 51)
1637                 x264_log(h, X264_LOG_WARNING, "try increasing target bitrate or increasing qp_max (currently %d)\n", h->param.rc.i_qp_max);
1638             else
1639                 x264_log(h, X264_LOG_WARNING, "try increasing target bitrate\n");
1640         }
1641         else
1642             x264_log(h, X264_LOG_WARNING, "internal error\n");
1643     }
1644
1645     return 0;
1646 }
1647
1648