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

Legend:
Removed from v.1014  
changed lines
  Added in v.1063

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