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

Legend:
Removed from v.942  
changed lines
  Added in v.1043

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