[svn] / branches / dev-api-4 / xvidcore / src / plugins / plugin_2pass2.c Repository:
ViewVC logotype

Diff of /branches/dev-api-4/xvidcore/src/plugins/plugin_2pass2.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1040, Thu May 22 22:17:44 2003 UTC revision 1047, Thu May 29 10:36:41 2003 UTC
# Line 1  Line 1 
1  /******************************************************************************  /******************************************************************************
2   *   *
3   * XviD Bit Rate Controller Library   * XviD Bit Rate Controller Library
4   * - VBR 2 pass bitrate controler implementation -   * - VBR 2 pass bitrate controller implementation -
5   *   *
6   * Copyright (C)      2002 Foxer <email?>   * Copyright (C)      2002 Foxer <email?>
7   *                    2002 Dirk Knop <dknop@gwdg.de>   *                    2002 Dirk Knop <dknop@gwdg.de>
# Line 25  Line 25 
25   * along with this program; if not, write to the Free Software   * along with this program; if not, write to the Free Software
26   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27   *   *
28   * $Id: plugin_2pass2.c,v 1.1.2.9 2003-05-22 22:17:44 edgomez Exp $   * $Id: plugin_2pass2.c,v 1.1.2.14 2003-05-29 10:36:41 edgomez Exp $
29   *   *
30   *****************************************************************************/   *****************************************************************************/
31    
# Line 33  Line 33 
33  #include <math.h>  #include <math.h>
34  #include <limits.h>  #include <limits.h>
35    
 #define RAD2DEG 57.295779513082320876798154814105  
 #define DEG2RAD 0.017453292519943295769236907684886  
   
36  #include "../xvid.h"  #include "../xvid.h"
37  #include "../image/image.h"  #include "../image/image.h"
38    
39    /*****************************************************************************
40     * Some constants
41     ****************************************************************************/
42    
43    #define DEFAULT_KEYFRAME_BOOST 0
44    #define DEFAULT_PAYBACK_METHOD XVID_PAYBACK_PROP
45    #define DEFAULT_BITRATE_PAYBACK_DELAY 250
46    #define DEFAULT_CURVE_COMPRESSION_HIGH 0
47    #define DEFAULT_CURVE_COMPRESSION_LOW 0
48    #define DEFAULT_MAX_OVERFLOW_IMPROVEMENT 60
49    #define DEFAULT_MAX_OVERFLOW_DEGRADATION 60
50    
51    /* Alt curve settings */
52    #define DEFAULT_USE_ALT_CURVE 0
53    #define DEFAULT_ALT_CURVE_HIGH_DIST 500
54    #define DEFAULT_ALT_CURVE_LOW_DIST 90
55    #define DEFAULT_ALT_CURVE_USE_AUTO 1
56    #define DEFAULT_ALT_CURVE_AUTO_STR 30
57    #define DEFAULT_ALT_CURVE_TYPE XVID_CURVE_LINEAR
58    #define DEFAULT_ALT_CURVE_MIN_REL_QUAL 50
59    #define DEFAULT_ALT_CURVE_USE_AUTO_BONUS_BIAS 1
60    #define DEFAULT_ALT_CURVE_BONUS_BIAS 50
61    
62    /* Keyframe settings */
63    #define DEFAULT_KFTRESHOLD 10
64    #define DEFAULT_KFREDUCTION 20
65    #define DEFAULT_MIN_KEY_INTERVAL 1
66    
67    /*****************************************************************************
68     * Structures
69     ****************************************************************************/
70    
71    /* Statistics */
72  typedef struct {  typedef struct {
73      int type;               /* first pass type */      int type;               /* first pass type */
74      int quant;              /* first pass quant */      int quant;              /* first pass quant */
# Line 51  Line 81 
81      double weight;      double weight;
82  } stat_t;  } stat_t;
83    
84    /* Context struct */
   
   
 /* context struct */  
85  typedef struct  typedef struct
86  {  {
87      xvid_plugin_2pass2_t param;      xvid_plugin_2pass2_t param;
# Line 79  Line 106 
106      double curve_comp_scale;      double curve_comp_scale;
107      double movie_curve;      double movie_curve;
108    
         double alt_curve_low;  
         double alt_curve_high;  
         double alt_curve_low_diff;  
         double alt_curve_high_diff;  
     double alt_curve_curve_bias_bonus;  
         double alt_curve_mid_qual;  
         double alt_curve_qual_dev;  
   
109      /* dynamic */      /* dynamic */
110    
111      int * keyframe_locations;      int * keyframe_locations;
# Line 107  Line 126 
126  } rc_2pass2_t;  } rc_2pass2_t;
127    
128    
129    /*****************************************************************************
130     * Sub plugin functions prototypes
131     ****************************************************************************/
132    
133    static int rc_2pass2_create(xvid_plg_create_t * create, rc_2pass2_t ** handle);
134    static int rc_2pass2_before(rc_2pass2_t * rc, xvid_plg_data_t * data);
135    static int rc_2pass2_after(rc_2pass2_t * rc, xvid_plg_data_t * data);
136    static int rc_2pass2_destroy(rc_2pass2_t * rc, xvid_plg_destroy_t * destroy);
137    
138    /*****************************************************************************
139     * Plugin definition
140     ****************************************************************************/
141    
142  #define BUF_SZ 1024  int
143  #define MAX_COLS    5  xvid_plugin_2pass2(void * handle, int opt, void * param1, void * param2)
   
   
 /* open stats file, and count num frames */  
   
 static int det_stats_length(rc_2pass2_t * rc, char * filename)  
144  {  {
145      FILE * f;      switch(opt) {
146      int n, ignore;      case XVID_PLG_INFO :
     char type;  
   
     rc->num_frames = 0;  
     rc->num_keyframes = 0;  
   
     if ((f = fopen(filename, "rt")) == NULL)  
147          return 0;          return 0;
148    
149      while((n = fscanf(f, "%c %d %d %d %d %d %d\n",      case XVID_PLG_CREATE :
150          &type, &ignore, &ignore, &ignore, &ignore, &ignore, &ignore)) != EOF) {          return rc_2pass2_create((xvid_plg_create_t*)param1, param2);
         if (type == 'i') {  
             rc->num_frames++;  
             rc->num_keyframes++;  
         }else if (type == 'p' || type == 'b' || type == 's') {  
             rc->num_frames++;  
         }  
     }  
151    
152      fclose(f);      case XVID_PLG_DESTROY :
153            return rc_2pass2_destroy((rc_2pass2_t*)handle, (xvid_plg_destroy_t*)param1);
154    
155      return 1;      case XVID_PLG_BEFORE :
156            return rc_2pass2_before((rc_2pass2_t*)handle, (xvid_plg_data_t*)param1);
157    
158        case XVID_PLG_AFTER :
159            return rc_2pass2_after((rc_2pass2_t*)handle, (xvid_plg_data_t*)param1);
160  }  }
161    
162        return XVID_ERR_FAIL;
163    }
164    
165    /*****************************************************************************
166     * Sub plugin functions definitions
167     ****************************************************************************/
168    
169    /* First a few local helping function prototypes */
170    static  int det_stats_length(rc_2pass2_t * rc, char * filename);
171    static  int load_stats(rc_2pass2_t *rc, char * filename);
172    static void zone_process(rc_2pass2_t *rc, const xvid_plg_create_t * create);
173    static void internal_scale(rc_2pass2_t *rc);
174    static void pre_process0(rc_2pass2_t * rc);
175    static void pre_process1(rc_2pass2_t * rc);
176    
177  /* open stats file(s) and read into rc->stats array */  /*----------------------------------------------------------------------------
178     *--------------------------------------------------------------------------*/
179    
180  static int load_stats(rc_2pass2_t *rc, char * filename)  static int
181    rc_2pass2_create(xvid_plg_create_t * create, rc_2pass2_t **handle)
182  {  {
183      FILE * f;      xvid_plugin_2pass2_t * param = (xvid_plugin_2pass2_t *)create->param;
184      int i, not_scaled;      rc_2pass2_t * rc;
185        int i;
186    
187        rc = malloc(sizeof(rc_2pass2_t));
188        if (rc == NULL)
189            return XVID_ERR_MEMORY;
190    
191      if ((f = fopen(filename, "rt"))==NULL)      rc->param = *param;
         return 0;  
192    
193      i = 0;  #define _INIT(a, b) if((a) <= 0) (a) = (b)
194          not_scaled = 0;      /* Let's set our defaults if needed */
195      while(i < rc->num_frames) {          _INIT(rc->param.keyframe_boost, DEFAULT_KEYFRAME_BOOST);
196          stat_t * s = &rc->stats[i];          _INIT(rc->param.payback_method, DEFAULT_PAYBACK_METHOD);
197          int n;          _INIT(rc->param.bitrate_payback_delay, DEFAULT_BITRATE_PAYBACK_DELAY);
198          char type;      _INIT(rc->param.curve_compression_high, DEFAULT_CURVE_COMPRESSION_HIGH);
199        _INIT(rc->param.curve_compression_low, DEFAULT_CURVE_COMPRESSION_LOW);
200        _INIT(rc->param.max_overflow_improvement, DEFAULT_MAX_OVERFLOW_IMPROVEMENT);
201        _INIT(rc->param.max_overflow_degradation,  DEFAULT_MAX_OVERFLOW_DEGRADATION);
202    
203        /* Keyframe settings */
204            _INIT(rc->param.kftreshold, DEFAULT_KFTRESHOLD);
205        _INIT(rc->param.kfreduction, DEFAULT_KFREDUCTION);
206        _INIT(rc->param.min_key_interval, DEFAULT_MIN_KEY_INTERVAL);
207    #undef _INIT
208    
209                  s->scaled_length = 0;          /* Count frames in the stats file */
210          n = fscanf(f, "%c %d %d %d %d %d %d\n", &type, &s->quant, &s->blks[0], &s->blks[1], &s->blks[2], &s->length, &s->scaled_length);      if (!det_stats_length(rc, param->filename)) {
211          if (n == EOF) break;          DPRINTF(XVID_DEBUG_RC,"fopen %s failed\n", param->filename);
212                  if (n < 7) {          free(rc);
213                          not_scaled = 1;          return XVID_ERR_FAIL;
214                  }                  }
215    
216          if (type == 'i') {      /* Allocate the stats' memory */
217              s->type = XVID_TYPE_IVOP;          if ((rc->stats = malloc(rc->num_frames * sizeof(stat_t))) == NULL) {
218          }else if (type == 'p' || type == 's') {          free(rc);
219              s->type = XVID_TYPE_PVOP;          return XVID_ERR_MEMORY;
         }else if (type == 'b') {  
             s->type = XVID_TYPE_BVOP;  
         }else{  /* unknown type */  
             DPRINTF(XVID_DEBUG_RC, "unknown stats frame type; assuming pvop\n");  
             s->type = XVID_TYPE_PVOP;  
220          }          }
221    
222          i++;      /*
223             * Allocate keyframes location's memory
224             * PS: see comment in pre_process0 for the +1 location requirement
225             */
226        if ((rc->keyframe_locations = malloc((rc->num_keyframes + 1) * sizeof(int))) == NULL) {
227            free(rc->stats);
228            free(rc);
229            return XVID_ERR_MEMORY;
230      }      }
231    
232      rc->num_frames = i;      if (!load_stats(rc, param->filename)) {
233            DPRINTF(XVID_DEBUG_RC,"fopen %s failed\n", param->filename);
234            free(rc->keyframe_locations);
235            free(rc->stats);
236            free(rc);
237            return XVID_ERR_FAIL;
238        }
239    
240          fclose(f);      /* pre-process our stats */
241    
242      return 1;          if (rc->num_frames  < create->fbase/create->fincr) {
243                    rc->target = rc->param.bitrate / 8;     /* one second */
244            } else {
245                    rc->target =
246                            ((uint64_t)rc->param.bitrate * (uint64_t)rc->num_frames * (uint64_t)create->fincr) / \
247                            ((uint64_t)create->fbase * 8);
248  }  }
249    
250        DPRINTF(XVID_DEBUG_RC, "Number of frames: %d\n", rc->num_frames);
251            DPRINTF(XVID_DEBUG_RC, "Frame rate: %d/%d\n", create->fbase, create->fincr);
252            DPRINTF(XVID_DEBUG_RC, "Target bitrate: %ld\n", rc->param.bitrate);
253            DPRINTF(XVID_DEBUG_RC, "Target filesize: %lld\n", rc->target);
254    
255            /* Compensate the mean frame overhead caused by the container */
256            rc->target -= rc->num_frames*rc->param.container_frame_overhead;
257            DPRINTF(XVID_DEBUG_RC, "Container Frame overhead: %d\n", rc->param.container_frame_overhead);
258            DPRINTF(XVID_DEBUG_RC, "Target filesize (after container compensation): %lld\n", rc->target);
259    
260  #if 0          pre_process0(rc);
261  static void print_stats(rc_2pass2_t * rc)  
262  {          if (rc->param.bitrate) {
263      int i;          zone_process(rc, create);
264      DPRINTF(XVID_DEBUG_RC, "type quant length scaled_length\n");                  internal_scale(rc);
265        }else{
266            /* external scaler: ignore zone */
267          for (i = 0; i < rc->num_frames; i++) {          for (i = 0; i < rc->num_frames; i++) {
268          stat_t * s = &rc->stats[i];              rc->stats[i].zone_mode = XVID_ZONE_WEIGHT;
269          DPRINTF(XVID_DEBUG_RC, "%d %d %d %d\n", s->type, s->quant, s->length, s->scaled_length);              rc->stats[i].weight = 1.0;
270      }      }
271            rc->avg_weight = 1.0;
272            rc->tot_quant = 0;
273  }  }
274  #endif          pre_process1(rc);
   
 /* pre-process the statistics data  
     - for each type, count, tot_length, min_length, max_length  
     - set keyframes_locations  
 */  
   
 static void  
 pre_process0(rc_2pass2_t * rc)  
 {  
     int i,j;  
275    
276      for (i=0; i<3; i++) {      for (i=0; i<32;i++) {
277          rc->count[i]=0;          rc->pquant_error[i] = 0;
278          rc->tot_length[i] = 0;          rc->bquant_error[i] = 0;
279          rc->last_quant[i] = 0;          rc->quant_count[i] = 0;
                 rc->min_length[i] = INT_MAX;  
280      }      }
281    
282          rc->max_length = INT_MIN;      rc->fq_error = 0;
283    
284      for (i=j=0; i<rc->num_frames; i++) {      *handle = rc;
285          stat_t * s = &rc->stats[i];          return(0);
286    }
287    
288          rc->count[s->type-1]++;  /*----------------------------------------------------------------------------
289          rc->tot_length[s->type-1] += s->length;   *--------------------------------------------------------------------------*/
290    
291          if (s->length < rc->min_length[s->type-1]) {  static int
292              rc->min_length[s->type-1] = s->length;  rc_2pass2_destroy(rc_2pass2_t * rc, xvid_plg_destroy_t * destroy)
293    {
294        free(rc->keyframe_locations);
295        free(rc->stats);
296            free(rc);
297            return(0);
298          }          }
299    
300          if (s->length > rc->max_length) {  /*----------------------------------------------------------------------------
301              rc->max_length = s->length;   *--------------------------------------------------------------------------*/
         }  
302    
303          if (s->type == XVID_TYPE_IVOP) {  static int
304              rc->keyframe_locations[j] = i;  rc_2pass2_before(rc_2pass2_t * rc, xvid_plg_data_t * data)
305              j++;  {
306          }      stat_t * s = &rc->stats[data->frame_num];
307      }      int overflow;
308        int desired;
309        double dbytes;
310        double curve_temp;
311        int capped_to_max_framesize = 0;
312    
313          /*          /*
314           * The "per sequence" overflow system considers a natural sequence to be           * This function is quite long but easy to understand. In order to simplify
315           * formed by all frames between two iframes, so if we want to make sure           * the code path (a bit), we treat 3 cases that can return immediatly.
          * the system does not go nuts during last sequence, we force the last  
          * frame to appear in the keyframe locations array.  
316           */           */
     rc->keyframe_locations[j] = i;  
   
         DPRINTF(XVID_DEBUG_RC, "Min 1st pass IFrame length: %d\n", rc->min_length[0]);  
         DPRINTF(XVID_DEBUG_RC, "Min 1st pass PFrame length: %d\n", rc->min_length[1]);  
         DPRINTF(XVID_DEBUG_RC, "Min 1st pass BFrame length: %d\n", rc->min_length[2]);  
 }  
317    
318            /* First case: Another plugin has already set a quantizer */
319        if (data->quant > 0)
320                    return(0);
321    
322  /* calculate zone weight "center" */          /* Second case: We are in a Quant zone */
323            if (s->zone_mode == XVID_ZONE_QUANT) {
324    
325  static void                  rc->fq_error += s->weight;
326  zone_process(rc_2pass2_t *rc, const xvid_plg_create_t * create)                  data->quant = (int)rc->fq_error;
327  {                  rc->fq_error -= data->quant;
     int i,j;  
     int n = 0;  
328    
329      rc->avg_weight = 0.0;                  s->desired_length = s->length;
     rc->tot_quant = 0;  
330    
331                    return(0);
332    
     if (create->num_zones == 0) {  
         for (j = 0; j < rc->num_frames; j++) {  
             rc->stats[j].zone_mode = XVID_ZONE_WEIGHT;  
             rc->stats[j].weight = 1.0;  
         }  
         rc->avg_weight += rc->num_frames * 1.0;  
         n += rc->num_frames;  
333      }      }
334    
335            /* Third case: insufficent stats data */
336            if (data->frame_num >= rc->num_frames)
337                    return 0;
338    
339      for(i=0; i < create->num_zones; i++) {          /*
340             * The last case is the one every normal minded developer should fear to
341             * maintain in a project :-)
342             */
343    
344          int next = (i+1<create->num_zones) ? create->zones[i+1].frame : rc->num_frames;          /* XXX: why by 8 */
345            overflow = rc->overflow / 8;
346    
347          if (i==0 && create->zones[i].frame > 0) {          /*
348              for (j = 0; j < create->zones[i].frame && j < rc->num_frames; j++) {           * The rc->overflow field represents the overflow in current scene (between two
349                  rc->stats[j].zone_mode = XVID_ZONE_WEIGHT;           * IFrames) so we must not forget to reset it if we are entering a new scene
350                  rc->stats[j].weight = 1.0;           */
351              }          if (s->type == XVID_TYPE_IVOP)
352              rc->avg_weight += create->zones[i].frame * 1.0;                  overflow = 0;
             n += create->zones[i].frame;  
         }  
353    
354          if (create->zones[i].mode == XVID_ZONE_WEIGHT) {          desired = s->scaled_length;
             for (j = create->zones[i].frame; j < next && j < rc->num_frames; j++ ) {  
                 rc->stats[j].zone_mode = XVID_ZONE_WEIGHT;  
                 rc->stats[j].weight = (double)create->zones[i].increment / (double)create->zones[i].base;  
             }  
             next -= create->zones[i].frame;  
             rc->avg_weight += (double)(next * create->zones[i].increment) / (double)create->zones[i].base;  
             n += next;  
         }else{  // XVID_ZONE_QUANT  
             for (j = create->zones[i].frame; j < next && j < rc->num_frames; j++ ) {  
                 rc->stats[j].zone_mode = XVID_ZONE_QUANT;  
                 rc->stats[j].weight = (double)create->zones[i].increment / (double)create->zones[i].base;  
                 rc->tot_quant += rc->stats[j].length;  
             }  
         }  
     }  
     rc->avg_weight = n>0 ? rc->avg_weight/n : 1.0;  
355    
356      DPRINTF(XVID_DEBUG_RC, "center_weight: %f (for %i frames);   fixed_bytes: %i\n", rc->avg_weight, n, rc->tot_quant);          dbytes = desired;
357  }          if (s->type == XVID_TYPE_IVOP)
358                    dbytes += desired * rc->param.keyframe_boost / 100;
359            dbytes /= rc->movie_curve;
360    
361            /*
362             * We are now entering in the hard part of the algo, it was first designed
363             * to work with i/pframes only streams, so the way it computes things is
364             * adapted to pframes only. However we can use it if we just take care to
365             * scale the bframes sizes to pframes sizes using the ratio avg_p/avg_p and
366             * then before really using values depending on frame sizes, scaling the
367             * value again with the inverse ratio
368             */
369            if (s->type == XVID_TYPE_BVOP)
370                    dbytes *= rc->avg_length[XVID_TYPE_PVOP-1] / rc->avg_length[XVID_TYPE_BVOP-1];
371    
372  /* scale the curve */          /*
373             * Apply user's choosen Payback method. Payback helps bitrate to follow the
374             * scaled curve "paying back" past errors in curve previsions.
375             */
376            if (rc->param.payback_method == XVID_PAYBACK_BIAS) {
377                    desired =(int)(rc->curve_comp_error / rc->param.bitrate_payback_delay);
378            } else {
379                    desired = (int)(rc->curve_comp_error * dbytes /
380                                                    rc->avg_length[XVID_TYPE_PVOP-1] / rc->param.bitrate_payback_delay);
381    
382  static void                  if (labs(desired) > fabs(rc->curve_comp_error)) {
383  internal_scale(rc_2pass2_t *rc)                          desired = (int)rc->curve_comp_error;
384  {                  }
385          int64_t target  = rc->target - rc->tot_quant;          }
         int64_t pass1_length = rc->tot_length[0] + rc->tot_length[1] + rc->tot_length[2] - rc->tot_quant;  
         int min_size[3];  
         double scaler;  
         int i;  
386    
387            rc->curve_comp_error -= desired;
388    
389          /*          /*
390           * Perform an initial scale pass.           * Alt curve treatment is not that hard to understand though the formulas
391           * if a frame size is scaled underneath our hardcoded minimums, then we           * seem to be huge. Alt treatment is basically a way to soft/harden the
392           * force the frame size to the minimum, and deduct the original & scaled           * curve flux applying sine/linear/cosine ratios
          * frame length from the original and target total lengths  
393           */           */
394    
395          min_size[0] = ((rc->stats[0].blks[0]*22) + 240) / 8;          /* XXX: warning */
396          min_size[1] = (rc->stats[0].blks[0] + 88) / 8;          curve_temp = 0;
         min_size[2] = 8;  
397    
398          scaler = (double)target / (double)pass1_length;          if ((rc->param.curve_compression_high + rc->param.curve_compression_low) &&     s->type != XVID_TYPE_IVOP) {
399    
400          if (target <= 0 || pass1_length <= 0 || target >= pass1_length) {                  curve_temp = rc->curve_comp_scale;
401                  DPRINTF(XVID_DEBUG_RC, "undersize warning\n");                  if (dbytes > rc->avg_length[XVID_TYPE_PVOP-1]) {
402          scaler = 1.0;                          curve_temp *= ((double)dbytes + (rc->avg_length[XVID_TYPE_PVOP-1] - dbytes) * rc->param.curve_compression_high / 100.0);
403                    } else {
404                            curve_temp *= ((double)dbytes + (rc->avg_length[XVID_TYPE_PVOP-1] - dbytes) * rc->param.curve_compression_low / 100.0);
405          }          }
406    
407      DPRINTF(XVID_DEBUG_RC,                  /*
408                          "Before any correction: target=%i, tot_length=%i, scaler=%f\n",                   * End of code path for curve_temp, as told earlier, we are now
409                          (int)target, (int)pass1_length, scaler);                   * obliged to scale the value to a bframe one using the inverse
410                     * ratio applied earlier
411          for (i=0; i<rc->num_frames; i++) {                   */
412                  stat_t * s = &rc->stats[i];                  if (s->type == XVID_TYPE_BVOP)
413                  int len;                          curve_temp *= rc->avg_length[XVID_TYPE_BVOP-1] / rc->avg_length[XVID_TYPE_PVOP-1];
414    
415          if (s->zone_mode == XVID_ZONE_QUANT) {                  desired += (int)curve_temp;
416              s->scaled_length = s->length;                  rc->curve_comp_error += curve_temp - (int)curve_temp;
         }else {  
                     len = (int)((double)s->length * scaler * s->weight / rc->avg_weight);  
                     if (len < min_size[s->type-1]) {            /* force frame size */  
                             s->scaled_length = min_size[s->type-1];  
                             target -= s->scaled_length;  
                             pass1_length -= s->length;  
417                      }else{                      }else{
418                              s->scaled_length = 0;                  /*
419                      }                   * End of code path for dbytes, as told earlier, we are now
420          }                   * obliged to scale the value to a bframe one using the inverse
421          }                   * ratio applied earlier
422                     */
423                    if (s->type == XVID_TYPE_BVOP)
424                            dbytes *= rc->avg_length[XVID_TYPE_BVOP-1] / rc->avg_length[XVID_TYPE_PVOP-1];
425    
426      scaler = (double)target / (double)pass1_length;                  desired += (int)dbytes;
427      if (target <= 0 || pass1_length <= 0 || target >= pass1_length) {                  rc->curve_comp_error += dbytes - (int)dbytes;
                 DPRINTF(XVID_DEBUG_RC,"undersize warning\n");  
                 scaler = 1.0;  
428          }          }
429    
         DPRINTF(XVID_DEBUG_RC,  
                         "After correction: target=%i, tot_length=%i, scaler=%f\n",  
                         (int)target, (int)pass1_length, scaler);  
   
         for (i=0; i<rc->num_frames; i++) {  
                 stat_t * s = &rc->stats[i];  
430    
431                  if (s->scaled_length==0) {      /* ignore frame with forced frame sizes */          /*
432                          s->scaled_length = (int)((double)s->length * scaler * s->weight / rc->avg_weight);           * We can't do bigger frames than first pass, this would be stupid as first
433             * pass is quant=2 and that reaching quant=1 is not worth it. We would lose
434             * many bytes and we would not not gain much quality.
435             */
436            if (desired > s->length) {
437                    rc->curve_comp_error += desired - s->length;
438                    desired = s->length;
439            } else {
440                    if (desired < rc->min_length[s->type-1]) {
441                            if (s->type == XVID_TYPE_IVOP){
442                                    rc->curve_comp_error -= rc->min_length[XVID_TYPE_IVOP-1] - desired;
443                  }                  }
444                            desired = rc->min_length[s->type-1];
445          }          }
446  }  }
447    
448            s->desired_length = desired;
449    
450    
451            /* if this keyframe is too close to the next, reduce it's byte allotment
452               XXX: why do we do this after setting the desired length  */
453    
454  static void          if (s->type == XVID_TYPE_IVOP) {
455  pre_process1(rc_2pass2_t * rc)                  int KFdistance = rc->keyframe_locations[rc->KF_idx] - rc->keyframe_locations[rc->KF_idx - 1];
 {  
     int i;  
     double total1, total2;  
     uint64_t ivop_boost_total;  
   
     ivop_boost_total = 0;  
     rc->curve_comp_error = 0;  
456    
457      for (i=0; i<3; i++) {                  if (KFdistance < rc->param.kftreshold) {
         rc->tot_scaled_length[i] = 0;  
     }  
458    
459      for (i=0; i<rc->num_frames; i++) {                          KFdistance -= rc->param.min_key_interval;
         stat_t * s = &rc->stats[i];  
460    
461          rc->tot_scaled_length[s->type-1] += s->scaled_length;                          if (KFdistance >= 0) {
462                                    int KF_min_size;
463    
464          if (s->type == XVID_TYPE_IVOP) {                                  KF_min_size = desired * (100 - rc->param.kfreduction) / 100;
465              ivop_boost_total += s->scaled_length * rc->param.keyframe_boost / 100;                                  if (KF_min_size < 1)
466          }                                          KF_min_size = 1;
     }  
467    
468      rc->movie_curve = ((double)(rc->tot_scaled_length[XVID_TYPE_PVOP-1] + rc->tot_scaled_length[XVID_TYPE_BVOP-1] + ivop_boost_total) /                                  desired = KF_min_size + (desired - KF_min_size) * KFdistance /
469                                          (rc->tot_scaled_length[XVID_TYPE_PVOP-1] + rc->tot_scaled_length[XVID_TYPE_BVOP-1]));                                          (rc->param.kftreshold - rc->param.min_key_interval);
470    
471      for(i=0; i<3; i++) {                                  if (desired < 1)
472          if (rc->count[i] == 0 || rc->movie_curve == 0) {                                          desired = 1;
473              rc->avg_length[i] = 1;                          }
         }else{  
             rc->avg_length[i] = rc->tot_scaled_length[i] / rc->count[i] / rc->movie_curve;  
474          }          }
475      }      }
476    
477      /* alt curve stuff here */          overflow = (int)((double)overflow * desired / rc->avg_length[XVID_TYPE_PVOP-1]);
478    
479      if (rc->param.use_alt_curve) {          /* Reign in overflow with huge frames */
480          const double avg_pvop = rc->avg_length[XVID_TYPE_PVOP-1];          if (labs(overflow) > labs(rc->overflow))
481          const uint64_t tot_pvop = rc->tot_length[XVID_TYPE_PVOP-1];                  overflow = rc->overflow;
         const uint64_t tot_bvop = rc->tot_length[XVID_TYPE_BVOP-1];  
         const uint64_t tot_scaled_pvop = rc->tot_scaled_length[XVID_TYPE_PVOP-1];  
         const uint64_t tot_scaled_bvop = rc->tot_scaled_length[XVID_TYPE_BVOP-1];  
   
                 rc->alt_curve_low = avg_pvop - avg_pvop * (double)rc->param.alt_curve_low_dist / 100.0;  
                 rc->alt_curve_low_diff = avg_pvop - rc->alt_curve_low;  
                 rc->alt_curve_high = avg_pvop + avg_pvop * (double)rc->param.alt_curve_high_dist / 100.0;  
                 rc->alt_curve_high_diff = rc->alt_curve_high - avg_pvop;  
   
         if (rc->param.alt_curve_use_auto) {  
             if (tot_bvop + tot_pvop > tot_scaled_bvop + tot_scaled_pvop) {  
                                 rc->param.alt_curve_min_rel_qual = (int)(100.0 - (100.0 - 100.0 /  
                                         ((double)(tot_pvop + tot_bvop) / (double)(tot_scaled_pvop + tot_scaled_bvop))) * (double)rc->param.alt_curve_auto_str / 100.0);  
482    
483                                  if (rc->param.alt_curve_min_rel_qual < 20)          /* Make sure overflow doesn't run away */
484                                          rc->param.alt_curve_min_rel_qual = 20;          if (overflow > desired * rc->param.max_overflow_improvement / 100) {
485                    desired += (overflow <= desired) ? desired * rc->param.max_overflow_improvement / 100 :
486                            overflow * rc->param.max_overflow_improvement / 100;
487            } else if (overflow < desired * rc->param.max_overflow_degradation / -100){
488                    desired += desired * rc->param.max_overflow_degradation / -100;
489              }else{              }else{
490                                  rc->param.alt_curve_min_rel_qual = 100;                  desired += overflow;
             }  
491          }          }
                 rc->alt_curve_mid_qual = (1.0 + (double)rc->param.alt_curve_min_rel_qual / 100.0) / 2.0;  
                 rc->alt_curve_qual_dev = 1.0 - rc->alt_curve_mid_qual;  
492    
493          if (rc->param.alt_curve_low_dist > 100) {          /* Make sure we are not higher than desired frame size */
494                          switch(rc->param.alt_curve_type) {          if (desired > rc->max_length) {
495              case XVID_CURVE_SINE: // Sine Curve (high aggressiveness)                  capped_to_max_framesize = 1;
496                                  rc->alt_curve_qual_dev *= 2.0 / (1.0 + sin(DEG2RAD * (avg_pvop * 90.0 / rc->alt_curve_low_diff)));                  desired = rc->max_length;
497                                  rc->alt_curve_mid_qual = 1.0 - rc->alt_curve_qual_dev * sin(DEG2RAD * (avg_pvop * 90.0 / rc->alt_curve_low_diff));                  DPRINTF(XVID_DEBUG_RC,"[%i] Capped to maximum frame size\n",
498                                  break;                                  data->frame_num);
                         case XVID_CURVE_LINEAR: // Linear (medium aggressiveness)  
                                 rc->alt_curve_qual_dev *= 2.0 / (1.0 + avg_pvop / rc->alt_curve_low_diff);  
                                 rc->alt_curve_mid_qual = 1.0 - rc->alt_curve_qual_dev * avg_pvop / rc->alt_curve_low_diff;  
                                 break;  
                         case XVID_CURVE_COSINE: // Cosine Curve (low aggressiveness)  
                                 rc->alt_curve_qual_dev *= 2.0 / (1.0 + (1.0 - cos(DEG2RAD * (avg_pvop * 90.0 / rc->alt_curve_low_diff))));  
                                 rc->alt_curve_mid_qual = 1.0 - rc->alt_curve_qual_dev * (1.0 - cos(DEG2RAD * (avg_pvop * 90.0 / rc->alt_curve_low_diff)));  
                         }  
                 }  
499      }      }
     /* --- */  
   
500    
501      total1=total2=0;          /* Make sure to not scale below the minimum framesize */
502      for (i=0; i<rc->num_frames; i++) {          if (desired < rc->min_length[s->type-1]) {
503          stat_t * s = &rc->stats[i];                  desired = rc->min_length[s->type-1];
504                    DPRINTF(XVID_DEBUG_RC,"[%i] Capped to minimum frame size\n",
505                                    data->frame_num);
506            }
507    
508          if (s->type != XVID_TYPE_IVOP) {          /*
509              double dbytes,dbytes2;           * Don't laugh at this very 'simple' quant<->filesize relationship, it
510             * proves to be acurate enough for our algorithm
511             */
512            data->quant = s->quant*s->length/desired;
513    
514              dbytes = s->scaled_length / rc->movie_curve;          /* Let's clip the computed quantizer, if needed */
515              dbytes2 = 0; /* XXX: warning */          if (data->quant < 1) {
516              total1 += dbytes;                  data->quant = 1;
517              if (s->type == XVID_TYPE_BVOP)          } else if (data->quant > 31) {
518                  dbytes *= rc->avg_length[XVID_TYPE_PVOP-1] / rc->avg_length[XVID_TYPE_BVOP-1];                  data->quant = 31;
519            } else if (s->type != XVID_TYPE_IVOP) {
520    
521              if (rc->param.use_alt_curve) {                  /*
522                  if (dbytes > rc->avg_length[XVID_TYPE_PVOP-1]) {                   * The frame quantizer has not been clipped, this appear to be a good
523                     * computed quantizer, however past frames give us some info about how
524                     * this quantizer performs against the algo prevision. Let's use this
525                     * prevision to increase the quantizer when we observe a too big
526                     * accumulated error
527                     */
528                    if (s->type == XVID_TYPE_BVOP) {
529                            rc->bquant_error[data->quant] += ((double)(s->quant * s->length) / desired) - data->quant;
530    
531                      if (dbytes >= rc->alt_curve_high) {                          if (rc->bquant_error[data->quant] >= 1.0) {
532                                                  dbytes2 = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev);                                  rc->bquant_error[data->quant] -= 1.0;
533                      }else{                                  data->quant++;
                                                 switch(rc->param.alt_curve_type) {  
                         case XVID_CURVE_SINE :  
                                                     dbytes2 = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * sin(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_high_diff)));  
                                                         break;  
                         case XVID_CURVE_LINEAR :  
                                                     dbytes2 = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) / rc->alt_curve_high_diff);  
                                                         break;  
                                                 case XVID_CURVE_COSINE :  
                                                     dbytes2 = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (1.0 - cos(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_high_diff))));  
                                                 }  
534                                          }                                          }
535                  }else{                  }else{
536                      if (dbytes <= rc->alt_curve_low) {                          rc->pquant_error[data->quant] += ((double)(s->quant * s->length) / desired) - data->quant;
                                                 dbytes2 = dbytes;  
                     }else{  
                                                 switch(rc->param.alt_curve_type) {  
                                                 case XVID_CURVE_SINE :  
                                                     dbytes2 = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * sin(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_low_diff)));  
                                                         break;  
                                                 case XVID_CURVE_LINEAR :  
                                                     dbytes2 = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) / rc->alt_curve_low_diff);  
                                                         break;  
                                                 case XVID_CURVE_COSINE :  
                                                     dbytes2 = dbytes * (rc->alt_curve_mid_qual + rc->alt_curve_qual_dev * (1.0 - cos(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_low_diff))));  
                                                 }  
                                         }  
537    
538                            if (rc->pquant_error[data->quant] >= 1.0) {
539                                    rc->pquant_error[data->quant] -= 1.0;
540                                    data->quant++;
541                  }                  }
   
   
             }else{  
                 if (dbytes > rc->avg_length[XVID_TYPE_PVOP-1]) {  
                     dbytes2=((double)dbytes + (rc->avg_length[XVID_TYPE_PVOP-1] - dbytes) * rc->param.curve_compression_high / 100.0);  
                 }else{  
                                 dbytes2 = ((double)dbytes + (rc->avg_length[XVID_TYPE_PVOP-1] - dbytes) * rc->param.curve_compression_low / 100.0);  
542                  }                  }
543              }              }
544    
545              if (s->type == XVID_TYPE_BVOP) {          /*
546                              dbytes2 *= rc->avg_length[XVID_TYPE_BVOP-1] / rc->avg_length[XVID_TYPE_PVOP-1];           * Now we have a computed quant that is in the right quante range, with a
547                              if (dbytes2 < rc->min_length[XVID_TYPE_BVOP-1])           * possible +1 correction due to cumulated error. We can now safely clip
548                                      dbytes2 = rc->min_length[XVID_TYPE_BVOP-1];           * the quantizer again with user's quant ranges. "Safely" means the Rate
549              }else{           * Control could learn more about this quantizer, this knowledge is useful
550                              if (dbytes2 < rc->min_length[XVID_TYPE_PVOP-1])           * for future frames even if it this quantizer won't be really used atm,
551                                      dbytes2 = rc->min_length[XVID_TYPE_PVOP-1];           * that's why we don't perform this clipping earlier.
552              }           */
553              total2 += dbytes2;          if (data->quant < data->min_quant[s->type-1]) {
554          }                  data->quant = data->min_quant[s->type-1];
555            } else if (data->quant > data->max_quant[s->type-1]) {
556                    data->quant = data->max_quant[s->type-1];
557      }      }
558    
559      rc->curve_comp_scale = total1 / total2;          /*
560             * To avoid big quality jumps from frame to frame, we apply a "security"
561             * rule that makes |last_quant - new_quant| <= 2. This rule only applies
562             * to predicted frames (P and B)
563             */
564            if (s->type != XVID_TYPE_IVOP && rc->last_quant[s->type-1] && capped_to_max_framesize == 0) {
565    
566      if (!rc->param.use_alt_curve) {                  if (data->quant > rc->last_quant[s->type-1] + 2) {
567          DPRINTF(XVID_DEBUG_RC, "middle frame size for asymmetric curve compression: %i\n",                          data->quant = rc->last_quant[s->type-1] + 2;
568              (int)(rc->avg_length[XVID_TYPE_PVOP-1] * rc->curve_comp_scale));                          DPRINTF(XVID_DEBUG_RC,
569                                            "[%i] p/b-frame quantizer prevented from rising too steeply\n",
570                                            data->frame_num);
571                    }
572                    if (data->quant < rc->last_quant[s->type-1] - 2) {
573                            data->quant = rc->last_quant[s->type-1] - 2;
574                            DPRINTF(XVID_DEBUG_RC,
575                                            "[%i] p/b-frame quantizer prevented from falling too steeply\n",
576                                            data->frame_num);
577                    }
578      }      }
579    
580      if (rc->param.use_alt_curve) {          /*
581          int bonus_bias = rc->param.alt_curve_bonus_bias;           * We don't want to pollute the RC history results when our computed quant
582          int oldquant = 1;           * has been computed from a capped frame size
583             */
584            if (capped_to_max_framesize == 0)
585                    rc->last_quant[s->type-1] = data->quant;
586    
587            return 0;
588    }
589    
590              if (rc->param.alt_curve_use_auto_bonus_bias)  /*----------------------------------------------------------------------------
591                      bonus_bias = rc->param.alt_curve_min_rel_qual;   *--------------------------------------------------------------------------*/
592    
593              rc->alt_curve_curve_bias_bonus = (total1 - total2) * (double)bonus_bias / 100.0 / (double)(rc->num_frames /* - credits_frames */ - rc->num_keyframes);  static int
594              rc->curve_comp_scale = ((total1 - total2) * (1.0 - (double)bonus_bias / 100.0) + total2) / total2;  rc_2pass2_after(rc_2pass2_t * rc, xvid_plg_data_t * data)
595    {
596            const char frame_type[4] = { 'i', 'p', 'b', 's'};
597            stat_t * s = &rc->stats[data->frame_num];
598    
599            /* Insufficent stats data */
600        if (data->frame_num >= rc->num_frames)
601            return 0;
602    
603          /* special info for alt curve:  bias bonus and quantizer thresholds */      rc->quant_count[data->quant]++;
604    
605                  DPRINTF(XVID_DEBUG_RC, "avg scaled framesize:%i\n", (int)rc->avg_length[XVID_TYPE_PVOP-1]);      if (data->type == XVID_TYPE_IVOP) {
606                  DPRINTF(XVID_DEBUG_RC, "bias bonus:%i bytes\n", (int)rc->alt_curve_curve_bias_bonus);          int kfdiff = (rc->keyframe_locations[rc->KF_idx] -      rc->keyframe_locations[rc->KF_idx - 1]);
607    
608                  for (i=1; i <= (int)(rc->alt_curve_high*2)+1; i++) {          rc->overflow += rc->KFoverflow;
609              double curve_temp, dbytes;          rc->KFoverflow = s->desired_length - data->length;
             int newquant;  
610    
611              dbytes = i;          if (kfdiff > 1) {  // non-consecutive keyframes
612                          if (dbytes > rc->avg_length[XVID_TYPE_PVOP-1]) {              rc->KFoverflow_partial = rc->KFoverflow / (kfdiff - 1);
613                  if (dbytes >= rc->alt_curve_high) {          }else{ // consecutive keyframes
614                                          curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev);                          rc->overflow += rc->KFoverflow;
615                  }else{                          rc->KFoverflow = 0;
616                                          switch(rc->param.alt_curve_type)                          rc->KFoverflow_partial = 0;
                                         {  
                                         case XVID_CURVE_SINE :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * sin(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_high_diff)));  
                                                 break;  
                                         case XVID_CURVE_LINEAR :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) / rc->alt_curve_high_diff);  
                                                 break;  
                                         case XVID_CURVE_COSINE :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (1.0 - cos(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_high_diff))));  
                                         }  
617                                  }                                  }
618            rc->KF_idx++;
619                          }else{                          }else{
620                  if (dbytes <= rc->alt_curve_low) {          // distribute part of the keyframe overflow
621                                          curve_temp = dbytes;          rc->overflow += s->desired_length - data->length + rc->KFoverflow_partial;
622                  }else{          rc->KFoverflow -= rc->KFoverflow_partial;
                                         switch(rc->param.alt_curve_type)  
                                         {  
                                         case XVID_CURVE_SINE :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * sin(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_low_diff)));  
                                                 break;  
                                         case XVID_CURVE_LINEAR :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) / rc->alt_curve_low_diff);  
                                                 break;  
                                         case XVID_CURVE_COSINE :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual + rc->alt_curve_qual_dev * (1.0 - cos(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_low_diff))));  
                                         }  
                                 }  
                         }  
   
                         if (rc->movie_curve > 1.0)  
                                 dbytes *= rc->movie_curve;  
   
                         newquant = (int)(dbytes * 2.0 / (curve_temp * rc->curve_comp_scale + rc->alt_curve_curve_bias_bonus));  
                         if (newquant > 1) {  
                                 if (newquant != oldquant) {  
                     int percent = (int)((i - rc->avg_length[XVID_TYPE_PVOP-1]) * 100.0 / rc->avg_length[XVID_TYPE_PVOP-1]);  
                                         oldquant = newquant;  
                                         DPRINTF(XVID_DEBUG_RC, "quant:%i threshold at %i : %i percent\n", newquant, i, percent);  
                                 }  
                         }  
623                  }                  }
624    
625      }          DPRINTF(XVID_DEBUG_RC, "[%i] type:%c quant:%i stats1:%i scaled:%i actual:%i overflow:%i\n",
626                            data->frame_num,
627                            frame_type[data->type-1],
628                            data->quant,
629                            s->length,
630                            s->scaled_length,
631                            data->length,
632                            rc->overflow);
633    
634      rc->overflow = 0;      return(0);
     rc->KFoverflow = 0;  
     rc->KFoverflow_partial = 0;  
     rc->KF_idx = 1;  
635  }  }
636    
637    /*****************************************************************************
638     * Helper functions definition
639     ****************************************************************************/
640    
641    #define BUF_SZ   1024
642    #define MAX_COLS 5
643    
644    /* open stats file, and count num frames */
645  static int rc_2pass2_create(xvid_plg_create_t * create, rc_2pass2_t ** handle)  static int
646    det_stats_length(rc_2pass2_t * rc, char * filename)
647  {  {
648      xvid_plugin_2pass2_t * param = (xvid_plugin_2pass2_t *)create->param;      FILE * f;
649      rc_2pass2_t * rc;      int n, ignore;
650      int i;      char type;
   
     rc = malloc(sizeof(rc_2pass2_t));  
     if (rc == NULL)  
         return XVID_ERR_MEMORY;  
651    
652      rc->param = *param;      rc->num_frames = 0;
653        rc->num_keyframes = 0;
654    
655      if (rc->param.keyframe_boost <= 0) rc->param.keyframe_boost = 0;      if ((f = fopen(filename, "rt")) == NULL)
656      if (rc->param.payback_method <= 0) rc->param.payback_method = XVID_PAYBACK_PROP;          return 0;
     if (rc->param.bitrate_payback_delay <= 0) rc->param.bitrate_payback_delay = 250;  
     if (rc->param.curve_compression_high <= 0) rc->param.curve_compression_high = 0;  
     if (rc->param.curve_compression_low <= 0) rc->param.curve_compression_low = 0;  
     if (rc->param.max_overflow_improvement <= 0) rc->param.max_overflow_improvement = 60;  
     if (rc->param.max_overflow_degradation <= 0) rc->param.max_overflow_degradation = 60;  
   
     if (rc->param.use_alt_curve <= 0) rc->param.use_alt_curve = 0;  
     if (rc->param.alt_curve_high_dist <= 0) rc->param.alt_curve_high_dist = 500;  
     if (rc->param.alt_curve_low_dist <= 0) rc->param.alt_curve_low_dist = 90;  
     if (rc->param.alt_curve_use_auto <= 0) rc->param.alt_curve_use_auto = 1;  
     if (rc->param.alt_curve_auto_str <= 0) rc->param.alt_curve_auto_str = 30;  
     if (rc->param.alt_curve_type <= 0) rc->param.alt_curve_type = XVID_CURVE_LINEAR;  
     if (rc->param.alt_curve_min_rel_qual <= 0) rc->param.alt_curve_min_rel_qual = 50;  
     if (rc->param.alt_curve_use_auto_bonus_bias <= 0) rc->param.alt_curve_use_auto_bonus_bias = 1;  
     if (rc->param.alt_curve_bonus_bias <= 0) rc->param.alt_curve_bonus_bias = 50;  
   
     if (rc->param.kftreshold <= 0) rc->param.kftreshold = 10;  
     if (rc->param.kfreduction <= 0) rc->param.kfreduction = 20;  
     if (rc->param.min_key_interval <= 0) rc->param.min_key_interval = 300;  
657    
658      if (!det_stats_length(rc, param->filename)){      while((n = fscanf(f, "%c %d %d %d %d %d %d\n",
659          DPRINTF(XVID_DEBUG_RC,"fopen %s failed\n", param->filename);          &type, &ignore, &ignore, &ignore, &ignore, &ignore, &ignore)) != EOF) {
660          free(rc);          if (type == 'i') {
661          return XVID_ERR_FAIL;              rc->num_frames++;
662                rc->num_keyframes++;
663            }else if (type == 'p' || type == 'b' || type == 's') {
664                rc->num_frames++;
665      }      }
   
     if ((rc->stats = malloc(rc->num_frames * sizeof(stat_t))) == NULL) {  
         free(rc);  
         return XVID_ERR_MEMORY;  
666      }      }
667    
668      /*      fclose(f);
          * We need an extra location because we do as if the last frame were an  
          * IFrame. This is needed because our code consider that frames between  
          * 2 IFrames form a natural sequence. So we store last frame as a  
          * keyframe location.  
          */  
     if ((rc->keyframe_locations = malloc((rc->num_keyframes + 1) * sizeof(int))) == NULL) {  
         free(rc->stats);  
         free(rc);  
         return XVID_ERR_MEMORY;  
     }  
669    
670      if (!load_stats(rc, param->filename)) {      return 1;
         DPRINTF(XVID_DEBUG_RC,"fopen %s failed\n", param->filename);  
         free(rc->keyframe_locations);  
         free(rc->stats);  
         free(rc);  
         return XVID_ERR_FAIL;  
671      }      }
672    
673      /* pre-process our stats */  /* open stats file(s) and read into rc->stats array */
   
         if (rc->num_frames  < create->fbase/create->fincr) {  
                 rc->target = rc->param.bitrate / 8;     /* one second */  
         }else{  
                 rc->target =  
                         ((uint64_t)rc->param.bitrate * (uint64_t)rc->num_frames * (uint64_t)create->fincr) / \  
                         ((uint64_t)create->fbase * 8);  
         }  
674    
675      DPRINTF(XVID_DEBUG_RC, "Number of frames: %d\n", rc->num_frames);  static int
676          DPRINTF(XVID_DEBUG_RC, "Frame rate: %d/%d\n", create->fbase, create->fincr);  load_stats(rc_2pass2_t *rc, char * filename)
677          DPRINTF(XVID_DEBUG_RC, "Target bitrate: %ld\n", rc->param.bitrate);  {
678          DPRINTF(XVID_DEBUG_RC, "Target filesize: %lld\n", rc->target);      FILE * f;
679        int i, not_scaled;
680    
 #if 0  
         rc->target -= rc->num_frames*24;        /* avi file header */  
 #endif  
681    
682        if ((f = fopen(filename, "rt"))==NULL)
683            return 0;
684    
685          pre_process0(rc);      i = 0;
686            not_scaled = 0;
687        while(i < rc->num_frames) {
688            stat_t * s = &rc->stats[i];
689            int n;
690            char type;
691    
692          if (rc->param.bitrate) {                  s->scaled_length = 0;
693          zone_process(rc, create);          n = fscanf(f, "%c %d %d %d %d %d %d\n", &type, &s->quant, &s->blks[0], &s->blks[1], &s->blks[2], &s->length, &s->scaled_length);
694                  internal_scale(rc);          if (n == EOF) break;
695      }else{                  if (n < 7) {
696          /* external scaler: ignore zone */                          not_scaled = 1;
         for (i=0;i<rc->num_frames;i++) {  
             rc->stats[i].zone_mode = XVID_ZONE_WEIGHT;  
             rc->stats[i].weight = 1.0;  
697          }          }
698          rc->avg_weight = 1.0;  
699          rc->tot_quant = 0;          if (type == 'i') {
700                s->type = XVID_TYPE_IVOP;
701            }else if (type == 'p' || type == 's') {
702                s->type = XVID_TYPE_PVOP;
703            }else if (type == 'b') {
704                s->type = XVID_TYPE_BVOP;
705            }else{  /* unknown type */
706                DPRINTF(XVID_DEBUG_RC, "unknown stats frame type; assuming pvop\n");
707                s->type = XVID_TYPE_PVOP;
708      }      }
         pre_process1(rc);  
709    
710      for (i=0; i<32;i++) {          i++;
         rc->pquant_error[i] = 0;  
         rc->bquant_error[i] = 0;  
         rc->quant_count[i] = 0;  
711      }      }
712    
713      rc->fq_error = 0;      rc->num_frames = i;
714    
715      *handle = rc;          fclose(f);
         return(0);  
 }  
716    
717        return 1;
718    }
719    
720  static int rc_2pass2_destroy(rc_2pass2_t * rc, xvid_plg_destroy_t * destroy)  #if 0
721    static void print_stats(rc_2pass2_t * rc)
722  {  {
723      free(rc->keyframe_locations);      int i;
724      free(rc->stats);      DPRINTF(XVID_DEBUG_RC, "type quant length scaled_length\n");
725          free(rc);          for (i = 0; i < rc->num_frames; i++) {
726          return(0);          stat_t * s = &rc->stats[i];
727            DPRINTF(XVID_DEBUG_RC, "%d %d %d %d\n", s->type, s->quant, s->length, s->scaled_length);
728  }  }
729    }
730    #endif
731    
732    /* pre-process the statistics data
733        - for each type, count, tot_length, min_length, max_length
734        - set keyframes_locations
735    */
736    
737    static void
738  static int rc_2pass2_before(rc_2pass2_t * rc, xvid_plg_data_t * data)  pre_process0(rc_2pass2_t * rc)
739  {  {
740      stat_t * s = &rc->stats[data->frame_num];      int i,j;
     int overflow;  
     int desired;  
     double dbytes;  
     double curve_temp;  
     int capped_to_max_framesize = 0;  
   
         /*  
          * This function is quite long but easy to understand. In order to simplify  
          * the code path (a bit), we treat 3 cases that can return immediatly.  
          */  
741    
742          /* First case: Another plugin has already set a quantizer */      for (i=0; i<3; i++) {
743      if (data->quant > 0)          rc->count[i]=0;
744                  return(0);          rc->tot_length[i] = 0;
745            rc->last_quant[i] = 0;
746                    rc->min_length[i] = INT_MAX;
747        }
748    
749          /* Second case: We are in a Quant zone */          rc->max_length = INT_MIN;
         if (s->zone_mode == XVID_ZONE_QUANT) {  
750    
751                  rc->fq_error += s->weight;      for (i=j=0; i<rc->num_frames; i++) {
752                  data->quant = (int)rc->fq_error;          stat_t * s = &rc->stats[i];
                 rc->fq_error -= data->quant;  
753    
754                  s->desired_length = s->length;          rc->count[s->type-1]++;
755            rc->tot_length[s->type-1] += s->length;
756    
757                  return(0);          if (s->length < rc->min_length[s->type-1]) {
758                rc->min_length[s->type-1] = s->length;
759            }
760    
761            if (s->length > rc->max_length) {
762                rc->max_length = s->length;
763          }          }
764    
765          /* Third case: insufficent stats data */          if (s->type == XVID_TYPE_IVOP) {
766          if (data->frame_num >= rc->num_frames)              rc->keyframe_locations[j] = i;
767                  return 0;              j++;
768            }
769        }
770    
771          /*          /*
772           * The last case is the one every normal minded developer should fear to           * Nota Bene:
773           * maintain in a project :-)           * The "per sequence" overflow system considers a natural sequence to be
774             * formed by all frames between two iframes, so if we want to make sure
775             * the system does not go nuts during last sequence, we force the last
776             * frame to appear in the keyframe locations array.
777           */           */
778        rc->keyframe_locations[j] = i;
779    
780          /* XXX: why by 8 */          DPRINTF(XVID_DEBUG_RC, "Min 1st pass IFrame length: %d\n", rc->min_length[0]);
781          overflow = rc->overflow / 8;          DPRINTF(XVID_DEBUG_RC, "Min 1st pass PFrame length: %d\n", rc->min_length[1]);
782            DPRINTF(XVID_DEBUG_RC, "Min 1st pass BFrame length: %d\n", rc->min_length[2]);
         /*  
          * The rc->overflow field represents the overflow in current scene (between two  
          * IFrames) so we must not forget to reset it if we are enetring a new scene  
          */  
         if (s->type == XVID_TYPE_IVOP) {  
                 overflow = 0;  
783          }          }
784    
785          desired = s->scaled_length;  /* calculate zone weight "center" */
786    
787          dbytes = desired;  static void
788          if (s->type == XVID_TYPE_IVOP) {  zone_process(rc_2pass2_t *rc, const xvid_plg_create_t * create)
789                  dbytes += desired * rc->param.keyframe_boost / 100;  {
790          }      int i,j;
791          dbytes /= rc->movie_curve;      int n = 0;
792    
793          /*      rc->avg_weight = 0.0;
794           * We are now entering in the hard part of the algo, it was first designed      rc->tot_quant = 0;
          * to work with i/pframes only streams, so the way it computes things is  
          * adapted to pframes only. However we can use it if we just take care to  
          * scale the bframes sizes to pframes sizes using the ratio avg_p/avg_p and  
          * then before really using values depending on frame sizes, scaling the  
          * value again with the inverse ratio  
          */  
         if (s->type == XVID_TYPE_BVOP) {  
                 dbytes *= rc->avg_length[XVID_TYPE_PVOP-1] / rc->avg_length[XVID_TYPE_BVOP-1];  
         }  
795    
         /*  
          * Apply user's choosen Payback method. Payback helps bitrate to follow the  
          * scaled curve "paying back" past errors in curve previsions.  
          */  
         if (rc->param.payback_method == XVID_PAYBACK_BIAS) {  
                 desired =(int)(rc->curve_comp_error / rc->param.bitrate_payback_delay);  
         }else{  
                 desired = (int)(rc->curve_comp_error * dbytes /  
                                                 rc->avg_length[XVID_TYPE_PVOP-1] / rc->param.bitrate_payback_delay);  
796    
797                  if (labs(desired) > fabs(rc->curve_comp_error)) {      if (create->num_zones == 0) {
798                          desired = (int)rc->curve_comp_error;          for (j = 0; j < rc->num_frames; j++) {
799                rc->stats[j].zone_mode = XVID_ZONE_WEIGHT;
800                rc->stats[j].weight = 1.0;
801                  }                  }
802            rc->avg_weight += rc->num_frames * 1.0;
803            n += rc->num_frames;
804          }          }
805    
         rc->curve_comp_error -= desired;  
806    
807          /*      for(i=0; i < create->num_zones; i++) {
          * Alt curve treatment is not that hard to understand though the formulas  
          * seem to be huge. Alt treatment is basically a way to soft/harden the  
          * curve flux applying sine/linear/cosine ratios  
          */  
808    
809          /* XXX: warning */          int next = (i+1<create->num_zones) ? create->zones[i+1].frame : rc->num_frames;
         curve_temp = 0;  
810    
811          if (rc->param.use_alt_curve) {          if (i==0 && create->zones[i].frame > 0) {
812                  if (s->type != XVID_TYPE_IVOP)  {              for (j = 0; j < create->zones[i].frame && j < rc->num_frames; j++) {
813                          if (dbytes > rc->avg_length[XVID_TYPE_PVOP-1]) {                  rc->stats[j].zone_mode = XVID_ZONE_WEIGHT;
814                                  if (dbytes >= rc->alt_curve_high) {                  rc->stats[j].weight = 1.0;
                                         curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev);  
                                 } else {  
                                         switch(rc->param.alt_curve_type) {  
                                         case XVID_CURVE_SINE :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * sin(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_high_diff)));  
                                                 break;  
                                         case XVID_CURVE_LINEAR :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) / rc->alt_curve_high_diff);  
                                                 break;  
                                         case XVID_CURVE_COSINE :  
                                                 curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (1.0 - cos(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_high_diff))));  
815                                          }                                          }
816                rc->avg_weight += create->zones[i].frame * 1.0;
817                n += create->zones[i].frame;
818                                  }                                  }
819                          } else {  
820                                  if (dbytes <= rc->alt_curve_low){          if (create->zones[i].mode == XVID_ZONE_WEIGHT) {
821                                          curve_temp = dbytes;              for (j = create->zones[i].frame; j < next && j < rc->num_frames; j++ ) {
822                                  } else {                  rc->stats[j].zone_mode = XVID_ZONE_WEIGHT;
823                                          switch(rc->param.alt_curve_type) {                  rc->stats[j].weight = (double)create->zones[i].increment / (double)create->zones[i].base;
824                                          case XVID_CURVE_SINE :              }
825                                                  curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * sin(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_low_diff)));              next -= create->zones[i].frame;
826                                                  break;              rc->avg_weight += (double)(next * create->zones[i].increment) / (double)create->zones[i].base;
827                                          case XVID_CURVE_LINEAR :              n += next;
828                                                  curve_temp = dbytes * (rc->alt_curve_mid_qual - rc->alt_curve_qual_dev * (dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) / rc->alt_curve_low_diff);          }else{  // XVID_ZONE_QUANT
829                                                  break;              for (j = create->zones[i].frame; j < next && j < rc->num_frames; j++ ) {
830                                          case XVID_CURVE_COSINE :                  rc->stats[j].zone_mode = XVID_ZONE_QUANT;
831                                                  curve_temp = dbytes * (rc->alt_curve_mid_qual + rc->alt_curve_qual_dev * (1.0 - cos(DEG2RAD * ((dbytes - rc->avg_length[XVID_TYPE_PVOP-1]) * 90.0 / rc->alt_curve_low_diff))));                  rc->stats[j].weight = (double)create->zones[i].increment / (double)create->zones[i].base;
832                    rc->tot_quant += rc->stats[j].length;
833                                          }                                          }
834                                  }                                  }
835                          }                          }
836        rc->avg_weight = n>0 ? rc->avg_weight/n : 1.0;
837    
838                          /*      DPRINTF(XVID_DEBUG_RC, "center_weight: %f (for %i frames);   fixed_bytes: %i\n", rc->avg_weight, n, rc->tot_quant);
839                           * End of code path for curve_temp, as told earlier, we are now  }
                          * obliged to scale the value to a bframe one using the inverse  
                          * ratio applied earlier  
                          */  
                         if (s->type == XVID_TYPE_BVOP)  
                                 curve_temp *= rc->avg_length[XVID_TYPE_BVOP-1] / rc->avg_length[XVID_TYPE_PVOP-1];  
840    
                         curve_temp = curve_temp * rc->curve_comp_scale + rc->alt_curve_curve_bias_bonus;  
841    
842                          desired += ((int)curve_temp);  /* scale the curve */
                         rc->curve_comp_error += curve_temp - (int)curve_temp;  
                 } else {  
                         /*  
                          * End of code path for dbytes, as told earlier, we are now  
                          * obliged to scale the value to a bframe one using the inverse  
                          * ratio applied earlier  
                          */  
                         if (s->type == XVID_TYPE_BVOP)  
                                 dbytes *= rc->avg_length[XVID_TYPE_BVOP-1] / rc->avg_length[XVID_TYPE_PVOP-1];  
843    
844                          desired += ((int)dbytes);  static void
845                          rc->curve_comp_error += dbytes - (int)dbytes;  internal_scale(rc_2pass2_t *rc)
846                  }  {
847            int64_t target  = rc->target - rc->tot_quant;
848            int64_t pass1_length = rc->tot_length[0] + rc->tot_length[1] + rc->tot_length[2] - rc->tot_quant;
849            double scaler;
850            int i, num_MBs;
851            int min_size[3];
852    
853          } else if ((rc->param.curve_compression_high + rc->param.curve_compression_low) &&      s->type != XVID_TYPE_IVOP) {          /* Let's compute a linear scaler in order to perform curve scaling */
854            scaler = (double)target / (double)pass1_length;
855    
856                  curve_temp = rc->curve_comp_scale;          if (target <= 0 || pass1_length <= 0 || target >= pass1_length) {
857                  if (dbytes > rc->avg_length[XVID_TYPE_PVOP-1]) {                  DPRINTF(XVID_DEBUG_RC, "WARNING: Undersize detected\n");
858                          curve_temp *= ((double)dbytes + (rc->avg_length[XVID_TYPE_PVOP-1] - dbytes) * rc->param.curve_compression_high / 100.0);          scaler = 1.0;
                 } else {  
                         curve_temp *= ((double)dbytes + (rc->avg_length[XVID_TYPE_PVOP-1] - dbytes) * rc->param.curve_compression_low / 100.0);  
859                  }                  }
860    
861        DPRINTF(XVID_DEBUG_RC,
862                            "Before correction: target=%i, tot_length=%i, scaler=%f\n",
863                            (int)target, (int)pass1_length, scaler);
864    
865                  /*                  /*
866                   * End of code path for curve_temp, as told earlier, we are now           * Compute min frame lengths (for each frame type) according to the number
867                   * obliged to scale the value to a bframe one using the inverse           * of MBs. We sum all blocks count from frame 0 (should be an IFrame, so
868                   * ratio applied earlier           * blocks[0] should be enough) to know how many MBs there are.
869                   */           */
870                  if (s->type == XVID_TYPE_BVOP)          num_MBs = rc->stats[0].blks[0] + rc->stats[0].blks[1] + rc->stats[0].blks[2];
871                          curve_temp *= rc->avg_length[XVID_TYPE_BVOP-1] / rc->avg_length[XVID_TYPE_PVOP-1];          min_size[0] = ((num_MBs*22) + 240) / 8;
872            min_size[1] = ((num_MBs)    + 88)  / 8;
873            min_size[2] = 8;
874    
                 desired += (int)curve_temp;  
                 rc->curve_comp_error += curve_temp - (int)curve_temp;  
         } else {  
875                  /*                  /*
876                   * End of code path for dbytes, as told earlier, we are now           * Perform an initial scale pass.
877                   * obliged to scale the value to a bframe one using the inverse           * If a frame size is scaled underneath our hardcoded minimums, then we
878                   * ratio applied earlier           * force the frame size to the minimum, and deduct the original & scaled
879             * frame length from the original and target total lengths
880                   */                   */
881                  if (s->type == XVID_TYPE_BVOP){          for (i=0; i<rc->num_frames; i++) {
882                          dbytes *= rc->avg_length[XVID_TYPE_BVOP-1] / rc->avg_length[XVID_TYPE_PVOP-1];                  stat_t * s = &rc->stats[i];
883                  }                  int len;
884    
885                  desired += (int)dbytes;          if (s->zone_mode == XVID_ZONE_QUANT) {
886                  rc->curve_comp_error += dbytes - (int)dbytes;              s->scaled_length = s->length;
887                            continue;
888          }          }
889    
890                    /* Compute teh scaled length */
891                    len = (int)((double)s->length * scaler * s->weight / rc->avg_weight);
892    
893          /*                  /* Compare with the computed minimum */
894           * We can't do bigger frames than first pass, this would be stupid as first                  if (len < min_size[s->type-1]) {
895           * pass is quant=2 and that reaching quant=1 is not worth it. We would lose                          /* force frame size to our computed minimum */
896           * many bytes and we would not not gain much quality.                          s->scaled_length = min_size[s->type-1];
897           */                          target -= s->scaled_length;
898          if (desired > s->length) {                          pass1_length -= s->length;
                 rc->curve_comp_error += desired - s->length;  
                 desired = s->length;  
899          }else{          }else{
900                  if (desired < rc->min_length[s->type-1]) {                          /* Do nothing for now, we'll scale this later */
901                          if (s->type == XVID_TYPE_IVOP){                          s->scaled_length = 0;
                                 rc->curve_comp_error -= rc->min_length[XVID_TYPE_IVOP-1] - desired;  
                         }  
                         desired = rc->min_length[s->type-1];  
902                  }                  }
903          }          }
904    
905          s->desired_length = desired;          /* Correct the scaler for all non forced frames */
906            scaler = (double)target / (double)pass1_length;
   
         /* if this keyframe is too close to the next, reduce it's byte allotment  
            XXX: why do we do this after setting the desired length  */  
   
         if (s->type == XVID_TYPE_IVOP) {  
                 int KFdistance = rc->keyframe_locations[rc->KF_idx] - rc->keyframe_locations[rc->KF_idx - 1];  
   
                 if (KFdistance < rc->param.kftreshold) {  
   
                         KFdistance = KFdistance - rc->param.min_key_interval;  
   
                         if (KFdistance >= 0) {  
                                 int KF_min_size;  
   
                                 KF_min_size = desired * (100 - rc->param.kfreduction) / 100;  
                                 if (KF_min_size < 1)  
                                         KF_min_size = 1;  
   
                                 desired = KF_min_size + (desired - KF_min_size) * KFdistance /  
                                         (rc->param.kftreshold - rc->param.min_key_interval);  
907    
908                                  if (desired < 1)          /* Detect undersizing */
909                                          desired = 1;      if (target <= 0 || pass1_length <= 0 || target >= pass1_length) {
910                          }                  DPRINTF(XVID_DEBUG_RC, "WARNING: Undersize detected\n");
911                  }                  scaler = 1.0;
912          }          }
913    
914          overflow = (int)((double)overflow * desired / rc->avg_length[XVID_TYPE_PVOP-1]);          DPRINTF(XVID_DEBUG_RC,
915                            "After correction: target=%i, tot_length=%i, scaler=%f\n",
916          /* Reign in overflow with huge frames */                          (int)target, (int)pass1_length, scaler);
         if (labs(overflow) > labs(rc->overflow)) {  
                 overflow = rc->overflow;  
         }  
917    
918          /* Make sure overflow doesn't run away */          /* Do another pass with the new scaler */
919          if (overflow > desired * rc->param.max_overflow_improvement / 100) {          for (i=0; i<rc->num_frames; i++) {
920                  desired += (overflow <= desired) ? desired * rc->param.max_overflow_improvement / 100 :                  stat_t * s = &rc->stats[i];
                         overflow * rc->param.max_overflow_improvement / 100;  
         } else if (overflow < desired * rc->param.max_overflow_degradation / -100){  
                 desired += desired * rc->param.max_overflow_degradation / -100;  
         } else {  
                 desired += overflow;  
         }  
921    
922          /* Make sure we are not higher than desired frame size */                  /* Ignore frame with forced frame sizes */
923          if (desired > rc->max_length) {                  if (s->scaled_length == 0)
924                  capped_to_max_framesize = 1;                          s->scaled_length = (int)((double)s->length * scaler * s->weight / rc->avg_weight);
                 desired = rc->max_length;  
                 DPRINTF(XVID_DEBUG_RC,"[%i] Capped to maximum frame size\n",  
                                 data->frame_num);  
925          }          }
926    
         /* Make sure to not scale below the minimum framesize */  
         if (desired < rc->min_length[s->type-1]) {  
                 desired = rc->min_length[s->type-1];  
                 DPRINTF(XVID_DEBUG_RC,"[%i] Capped to minimum frame size\n",  
                                 data->frame_num);  
927          }          }
928    
929          /*  static void
930           * Don't laugh at this very 'simple' quant<->filesize relationship, it  pre_process1(rc_2pass2_t * rc)
931           * proves to be acurate enough for our algorithm  {
932           */      int i;
933          data->quant= (s->quant * s->length) / desired;      double total1, total2;
934        uint64_t ivop_boost_total;
         /* Let's clip the computed quantizer, if needed */  
         if (data->quant < 1) {  
                 data->quant = 1;  
         } else if (data->quant > 31) {  
                 data->quant = 31;  
         } else if (s->type != XVID_TYPE_IVOP) {  
   
                 /*  
                  * The frame quantizer has not been clipped, this appear to be a good  
                  * computed quantizer, however past frames give us some info about how  
                  * this quantizer performs against the algo prevision. Let's use this  
                  * prevision to increase the quantizer when we observe a too big  
                  * accumulated error  
                  */  
                 if (s->type== XVID_TYPE_BVOP) {  
                         rc->bquant_error[data->quant] += ((double)(s->quant * s->length) / desired) - data->quant;  
935    
936                          if (rc->bquant_error[data->quant] >= 1.0) {      ivop_boost_total = 0;
937                                  rc->bquant_error[data->quant] -= 1.0;      rc->curve_comp_error = 0;
                                 data->quant++;  
                         }  
                 } else {  
                         rc->pquant_error[data->quant] += ((double)(s->quant * s->length) / desired) - data->quant;  
938    
939                          if (rc->pquant_error[data->quant] >= 1.0) {      for (i=0; i<3; i++) {
940                                  rc->pquant_error[data->quant] -= 1.0;          rc->tot_scaled_length[i] = 0;
                                 ++data->quant;  
                         }  
                 }  
941          }          }
942    
943          /*      for (i=0; i<rc->num_frames; i++) {
944           * Now we have a computed quant that is in the right quante range, with a          stat_t * s = &rc->stats[i];
          * possible +1 correction due to cumulated error. We can now safely clip  
          * the quantizer again with user's quant ranges. "Safely" means the Rate  
          * Control could learn more about this quantizer, this knowledge is useful  
          * for future frames even if it this quantizer won't be really used atm,  
          * that's why we don't perform this clipping earlier.  
          */  
         if (data->quant < data->min_quant[s->type-1]) {  
                 data->quant = data->min_quant[s->type-1];  
         } else if (data->quant > data->max_quant[s->type-1]) {  
                 data->quant = data->max_quant[s->type-1];  
         }  
945    
946          /*          rc->tot_scaled_length[s->type-1] += s->scaled_length;
          * To avoid big quality jumps from frame to frame, we apply a "security"  
          * rule that makes |last_quant - new_quant| <= 2. This rule only applies  
          * to predicted frames (P and B)  
          */  
         if (s->type != XVID_TYPE_IVOP && rc->last_quant[s->type-1] && capped_to_max_framesize == 0) {  
947    
948                  if (data->quant > rc->last_quant[s->type-1] + 2) {          if (s->type == XVID_TYPE_IVOP) {
949                          data->quant = rc->last_quant[s->type-1] + 2;              ivop_boost_total += s->scaled_length * rc->param.keyframe_boost / 100;
                         DPRINTF(XVID_DEBUG_RC,  
                                         "[%i] p/b-frame quantizer prevented from rising too steeply\n",  
                                         data->frame_num);  
                 }  
                 if (data->quant < rc->last_quant[s->type-1] - 2) {  
                         data->quant = rc->last_quant[s->type-1] - 2;  
                         DPRINTF(XVID_DEBUG_RC,  
                                         "[%i] p/b-frame quantizer prevented from falling too steeply\n",  
                                         data->frame_num);  
950                  }                  }
951          }          }
952    
953          /*      rc->movie_curve = ((double)(rc->tot_scaled_length[XVID_TYPE_PVOP-1] + rc->tot_scaled_length[XVID_TYPE_BVOP-1] + ivop_boost_total) /
954           * We don't want to pollute the RC history results when our computed quant                                          (rc->tot_scaled_length[XVID_TYPE_PVOP-1] + rc->tot_scaled_length[XVID_TYPE_BVOP-1]));
          * has been computed from a capped frame size  
          */  
         if (capped_to_max_framesize == 0) {  
                 rc->last_quant[s->type-1] = data->quant;  
         }  
955    
956          return 0;      for(i=0; i<3; i++) {
957            if (rc->count[i] == 0 || rc->movie_curve == 0) {
958                rc->avg_length[i] = 1;
959            }else{
960                rc->avg_length[i] = rc->tot_scaled_length[i] / rc->count[i] / rc->movie_curve;
961            }
962  }  }
963    
964        /* --- */
965    
966        total1=total2=0;
967    
968  static int rc_2pass2_after(rc_2pass2_t * rc, xvid_plg_data_t * data)      for (i=0; i<rc->num_frames; i++) {
969  {          stat_t * s = &rc->stats[i];
     stat_t * s = &rc->stats[data->frame_num];  
   
         /* Insufficent stats data */  
     if (data->frame_num >= rc->num_frames)  
         return 0;  
   
     rc->quant_count[data->quant]++;  
970    
971      if (data->type == XVID_TYPE_IVOP) {          if (s->type != XVID_TYPE_IVOP) {
972          int kfdiff = (rc->keyframe_locations[rc->KF_idx] -      rc->keyframe_locations[rc->KF_idx - 1]);              double dbytes,dbytes2;
973    
974          rc->overflow += rc->KFoverflow;              dbytes = s->scaled_length / rc->movie_curve;
975          rc->KFoverflow = s->desired_length - data->length;              dbytes2 = 0; /* XXX: warning */
976                total1 += dbytes;
977                if (s->type == XVID_TYPE_BVOP)
978                    dbytes *= rc->avg_length[XVID_TYPE_PVOP-1] / rc->avg_length[XVID_TYPE_BVOP-1];
979    
980          if (kfdiff > 1) {  // non-consecutive keyframes                          if (dbytes > rc->avg_length[XVID_TYPE_PVOP-1]) {
981              rc->KFoverflow_partial = rc->KFoverflow / (kfdiff - 1);                                  dbytes2=((double)dbytes + (rc->avg_length[XVID_TYPE_PVOP-1] - dbytes) * rc->param.curve_compression_high / 100.0);
         }else{ // consecutive keyframes  
                         rc->overflow += rc->KFoverflow;  
                         rc->KFoverflow = 0;  
                         rc->KFoverflow_partial = 0;  
         }  
         rc->KF_idx++;  
982      }else{      }else{
983          // distribute part of the keyframe overflow                                  dbytes2 = ((double)dbytes + (rc->avg_length[XVID_TYPE_PVOP-1] - dbytes) * rc->param.curve_compression_low / 100.0);
         rc->overflow += s->desired_length - data->length + rc->KFoverflow_partial;  
         rc->KFoverflow -= rc->KFoverflow_partial;  
984      }      }
985    
986      DPRINTF(XVID_DEBUG_RC, "[%i] quant:%i stats1:%i scaled:%i actual:%i overflow:%i\n",              if (s->type == XVID_TYPE_BVOP) {
987          data->frame_num,                              dbytes2 *= rc->avg_length[XVID_TYPE_BVOP-1] / rc->avg_length[XVID_TYPE_PVOP-1];
988          data->quant,                              if (dbytes2 < rc->min_length[XVID_TYPE_BVOP-1])
989          s->length,                                      dbytes2 = rc->min_length[XVID_TYPE_BVOP-1];
990          s->scaled_length,              }else{
991          data->length,                              if (dbytes2 < rc->min_length[XVID_TYPE_PVOP-1])
992          rc->overflow);                                      dbytes2 = rc->min_length[XVID_TYPE_PVOP-1];
993                }
994      return(0);              total2 += dbytes2;
995            }
996  }  }
997    
998        rc->curve_comp_scale = total1 / total2;
999    
1000            DPRINTF(XVID_DEBUG_RC, "middle frame size for asymmetric curve compression: %i\n",
1001                (int)(rc->avg_length[XVID_TYPE_PVOP-1] * rc->curve_comp_scale));
1002    
1003  int xvid_plugin_2pass2(void * handle, int opt, void * param1, void * param2)      rc->overflow = 0;
1004  {      rc->KFoverflow = 0;
1005      switch(opt)      rc->KFoverflow_partial = 0;
1006      {      rc->KF_idx = 1;
     case XVID_PLG_INFO :  
         return 0;  
   
     case XVID_PLG_CREATE :  
         return rc_2pass2_create((xvid_plg_create_t*)param1, param2);  
   
     case XVID_PLG_DESTROY :  
         return rc_2pass2_destroy((rc_2pass2_t*)handle, (xvid_plg_destroy_t*)param1);  
   
     case XVID_PLG_BEFORE :  
         return rc_2pass2_before((rc_2pass2_t*)handle, (xvid_plg_data_t*)param1);  
   
     case XVID_PLG_AFTER :  
         return rc_2pass2_after((rc_2pass2_t*)handle, (xvid_plg_data_t*)param1);  
     }  
   
     return XVID_ERR_FAIL;  
1007  }  }

Legend:
Removed from v.1040  
changed lines
  Added in v.1047

No admin address has been configured
ViewVC Help
Powered by ViewVC 1.0.4