[svn] / trunk / xvidcore / examples / xvid_encraw.c Repository:
ViewVC logotype

Diff of /trunk/xvidcore/examples/xvid_encraw.c

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

revision 376, Sat Aug 17 20:03:36 2002 UTC revision 1909, Sun Nov 28 15:19:07 2010 UTC
# Line 1  Line 1 
1  /**************************************************************************  /*****************************************************************************
2   *   *
3   *      XVID MPEG-4 VIDEO CODEC - Example for encoding and decoding   *  XVID MPEG-4 VIDEO CODEC
4     *  - Console based test application  -
5     *
6     *  Copyright(C) 2002-2003 Christoph Lampert <gruel@web.de>
7     *               2002-2003 Edouard Gomez <ed.gomez@free.fr>
8     *               2003      Peter Ross <pross@xvid.org>
9     *               2003-2010 Michael Militzer <isibaar@xvid.org>
10   *   *
11   *      This program is free software; you can redistribute it and/or modify   *      This program is free software; you can redistribute it and/or modify
12   *      it under the terms of the GNU General Public License as published by   *      it under the terms of the GNU General Public License as published by
# Line 14  Line 20 
20   *   *
21   *      You should have received a copy of the GNU General Public License   *      You should have received a copy of the GNU General Public License
22   *      along with this program; if not, write to the Free Software   *      along with this program; if not, write to the Free Software
23   *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
24   *   *
25   *************************************************************************/   * $Id: xvid_encraw.c,v 1.45 2010-11-28 15:19:07 Isibaar Exp $
   
 /************************************************************************  
26   *   *
27   *  Speed test routine for XviD using the XviD-API   ****************************************************************************/
28   *  (C) Christoph Lampert, 2002/08/17  
29    /*****************************************************************************
30     *  Application notes :
31   *   *
32   *  A sequence of YUV pics in PGM or RAW file format is encoded and the   *  A sequence of raw YUV I420 pics or YUV I420 PGM file format is encoded
33   *  raw MPEG-4 stream is written to stdout.   *  The speed is measured and frames' PSNR are taken from core.
  *  The encoding speed of this is measured, too.  
34   *   *
35   *  The program is plain C and needs no libraries except for libxvidcore,   *  The program is plain C and needs no libraries except for libxvidcore,
36   *  and maths-lib, so with UN*X you simply compile by   *  and maths-lib.
  *  
  *   gcc xvid_encraw.c -lxvidcore -lm -o xvid_encraw  
  *  
  *  Run without or with illegal parameters, then PGM input input is read  
  *  from stdin.  
  *  
  *  Parameters are: xvid_stat XDIM YDIM QUALITY BITRATE/QUANTIZER FRAMERATE  
  *  
  *  if XDIM or YDIM are illegal (e.g. 0), they are ignored and input is  
  *  considered to be PGM. Otherwise (X and Y both greater than 0) raw YUV  
  *  is expected, as e.g. the standard MPEG test-files, like "foreman"  
  *  
  *  0 <= QUALITY <= 6  (default 5)  
  *  
  *  BITRATE is in kbps (default 900),  
  *      if BITRATE<32, then value is taken is fixed QUANTIZER  
  *  
  *  FRAMERATE is a float (with or without decimal dot), default is 25.00  
  *  
  *  input/output and m4v-output is saved, if corresponding flags are set  
  *  
  *  PGM input must in a very specific format, see read_pgmheader  
  *  it can be generated e.g. from MPEG2 by    mpeg2dec -o pgmpipe  
  *  
  ************************************************************************/  
   
 /************************************************************************  
37   *   *
38   *  For EXAMPLES how to use this, see the seperate file xvid_stat.examples   *  Use ./xvid_encraw -help for a list of options
39   *   *
40   ************************************************************************/   ************************************************************************/
41    
42  #include <stdio.h>  #include <stdio.h>
43    //#include <io.h>
44  #include <stdlib.h>  #include <stdlib.h>
45  #include <math.h>               // needed for log10  #include <string.h>
46  #include <sys/time.h>           // only needed for gettimeofday  #include <math.h>
47    #ifndef WIN32
48    #include <sys/time.h>
49    #else
50    #include <windows.h>
51    #include <vfw.h>
52    #include <time.h>
53    #define XVID_AVI_INPUT
54    #define XVID_AVI_OUTPUT
55    #endif
56    
57    #include "xvid.h"
58    #include "portab.h" /* for pthread */
59    
60    #ifdef XVID_MKV_OUTPUT
61    #include "matroska.cpp"
62    #endif
63    
64    #undef READ_PNM
65    
66    //#define USE_APP_LEVEL_THREADING /* Should xvid_encraw app use multi-threading? */
67    
68    /*****************************************************************************
69     *                            Quality presets
70     ****************************************************************************/
71    
72    // Equivalent to vfw's pmvfast_presets
73    static const int motion_presets[] = {
74            /* quality 0 */
75            0,
76    
77            /* quality 1 */
78            0,
79    
80            /* quality 2 */
81            0,
82    
83            /* quality 3 */
84            0,
85    
86            /* quality 4 */
87            0 | XVID_ME_HALFPELREFINE16 | 0,
88    
89  #include "../src/xvid.h"                /* comes with XviD */          /* quality 5 */
90            0 | XVID_ME_HALFPELREFINE16 | 0 | XVID_ME_ADVANCEDDIAMOND16,
91    
92            /* quality 6 */
93            XVID_ME_HALFPELREFINE16 | XVID_ME_EXTSEARCH16 | XVID_ME_HALFPELREFINE8 | 0 | XVID_ME_USESQUARES16
94    
95    };
96    #define ME_ELEMENTS (sizeof(motion_presets)/sizeof(motion_presets[0]))
97    
98    static const int vop_presets[] = {
99            /* quality 0 */
100            0,
101    
102            /* quality 1 */
103            0,
104    
105            /* quality 2 */
106            0,
107    
108            /* quality 3 */
109            0,
110    
111            /* quality 4 */
112            0,
113    
114            /* quality 5 */
115            XVID_VOP_INTER4V,
116    
117            /* quality 6 */
118            XVID_VOP_INTER4V,
119    
 int motion_presets[7] = {  
         0,                                                              // Q 0  
         PMV_EARLYSTOP16,                                                // Q 1  
         PMV_EARLYSTOP16,                                                // Q 2  
         PMV_EARLYSTOP16 | PMV_HALFPELREFINE16,                          // Q 3  
         PMV_EARLYSTOP16 | PMV_HALFPELREFINE16,                          // Q 4  
         PMV_EARLYSTOP16 | PMV_HALFPELREFINE16 | PMV_EARLYSTOP8          // Q 5  
                         | PMV_HALFPELREFINE8,  
         PMV_EARLYSTOP16 | PMV_HALFPELREFINE16 | PMV_EXTSEARCH16         // Q 6  
                         | PMV_USESQUARES16 | PMV_EARLYSTOP8 | PMV_HALFPELREFINE8  
120          };          };
121    #define VOP_ELEMENTS (sizeof(vop_presets)/sizeof(vop_presets[0]))
122    
123  int general_presets[7] = {  /*****************************************************************************
124          XVID_H263QUANT, /* or use XVID_MPEGQUANT */             // Q 0   *                     Command line global variables
125          XVID_MPEGQUANT,                                         // Q 1   ****************************************************************************/
         XVID_H263QUANT,                                // Q 2  
         XVID_H263QUANT | XVID_HALFPEL,                          // Q 3  
         XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V,           // Q 4  
         XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V,           // Q 5  
         XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V };         // Q 6  
126    
127    #define MAX_ZONES   64
128    #define MAX_ENC_INSTANCES 4
129    #define DEFAULT_QUANT 400
130    
131  /* my default values for encoding */  typedef struct
132    {
133            int frame;
134    
135  #define ABS_MAXFRAMENR 9999               // max number of frames          int type;
136            int mode;
137            int modifier;
138    
139  int ARG_BITRATE=900;          unsigned int greyscale;
140  int ARG_QUANTI=0;          unsigned int chroma_opt;
141            unsigned int bvop_threshold;
142            unsigned int cartoon_mode;
143    } zone_t;
144    
145  int ARG_QUALITY =6;  typedef struct
146  int ARG_MINQUANT=1;  {
147  int ARG_MAXQUANT=31;          int count;
148  float ARG_FRAMERATE=25.00;          int size;
149            int quants[32];
150    } frame_stats_t;
151    
152    typedef struct
153    {
154            pthread_t handle;       /* thread's handle */
155    
156  int ARG_MAXFRAMENR=ABS_MAXFRAMENR;          int start_num;          /* begin/end of sequence */
157            int stop_num;
158    
159  #ifdef BFRAMES          char *outfilename;      /* output filename */
160            char *statsfilename1;   /* pass1 statsfile */
161    
162  int ARG_MAXBFRAMES=1;          int input_num;
 int ARG_BQUANTRATIO=200;  
163    
164            int totalsize;          /* encoder stats */
165            double totalenctime;
166            float totalPSNR[3];
167            frame_stats_t framestats[7];
168    } enc_sequence_data_t;
169    
170    /* Maximum number of frames to encode */
171    #define ABS_MAXFRAMENR -1 /* no limit */
172    
173    #ifndef READ_PNM
174    #define IMAGE_SIZE(x,y) ((x)*(y)*3/2)
175    #else
176    #define IMAGE_SIZE(x,y) ((x)*(y)*3)
177  #endif  #endif
178    
179  #define MAX(A,B) ( ((A)>(B)) ? (A) : (B) )  #define MAX(A,B) ( ((A)>(B)) ? (A) : (B) )
180  #define SMALL_EPS 1e-10  #define SMALL_EPS (1e-10)
181    
182  /* these are global variables. Not very elegant, but easy, and this is an easy program */  #define SWAP(a) ( (((a)&0x000000ff)<<24) | (((a)&0x0000ff00)<<8) | \
183                      (((a)&0x00ff0000)>>8)  | (((a)&0xff000000)>>24) )
184    
185  int XDIM=0;  static zone_t ZONES[MAX_ZONES];
186  int YDIM=0;     // will be set when reading first image  static  int NUM_ZONES = 0;
 int i,filenr = 0;  
187    
188  int save_m4v_flag = 1;          // output MPEG4-bytestream?  static  int ARG_NUM_APP_THREADS = 1;
189  int save_ref_flag = 0;          // save input image  static  int ARG_CPU_FLAGS = 0;
190    static  int ARG_STATS = 0;
191    static  int ARG_SSIM = -1;
192    static  int ARG_PSNRHVSM = 0;
193    static  char* ARG_SSIM_PATH = NULL;
194    static  int ARG_DUMP = 0;
195    static  int ARG_LUMIMASKING = 0;
196    static  int ARG_BITRATE = 0;
197    static  int ARG_TARGETSIZE = 0;
198    static  int ARG_SINGLE = 1;
199    static  char *ARG_PASS1 = 0;
200    static  char *ARG_PASS2 = 0;
201    //static int ARG_QUALITY = ME_ELEMENTS - 1;
202    static  int ARG_QUALITY = 6;
203    static  float ARG_FRAMERATE = 25.00f;
204    static  int ARG_DWRATE = 25;
205    static  int ARG_DWSCALE = 1;
206    static  int ARG_MAXFRAMENR = ABS_MAXFRAMENR;
207    static  int ARG_MAXKEYINTERVAL = 300;
208    static  int ARG_STARTFRAMENR = 0;
209    static  char *ARG_INPUTFILE = NULL;
210    static  int ARG_INPUTTYPE = 0;
211    static  int ARG_SAVEMPEGSTREAM = 0;
212    static  int ARG_SAVEINDIVIDUAL = 0;
213    static  char *ARG_OUTPUTFILE = NULL;
214    static  char *ARG_AVIOUTPUTFILE = NULL;
215    static  char *ARG_MKVOUTPUTFILE = NULL;
216    static  char *ARG_TIMECODEFILE = NULL;
217    static  int XDIM = 0;
218    static  int YDIM = 0;
219    static  int ARG_BQRATIO = 150;
220    static  int ARG_BQOFFSET = 100;
221    static  int ARG_MAXBFRAMES = 2;
222    static  int ARG_PACKED = 1;
223    static  int ARG_DEBUG = 0;
224    static  int ARG_VOPDEBUG = 0;
225    static  int ARG_TRELLIS = 1;
226    static  int ARG_QTYPE = 0;
227    static  int ARG_QMATRIX = 0;
228    static  int ARG_GMC = 0;
229    static  int ARG_INTERLACING = 0;
230    static  int ARG_QPEL = 0;
231    static  int ARG_TURBO = 0;
232    static  int ARG_VHQMODE = 1;
233    static  int ARG_BVHQ = 0;
234    static  int ARG_QMETRIC = 0;
235    static  int ARG_CLOSED_GOP = 1;
236    static  int ARG_CHROMAME = 1;
237    static  int ARG_PAR = 1;
238    static  int ARG_PARHEIGHT;
239    static  int ARG_PARWIDTH;
240    static  int ARG_QUANTS[6] = {2, 31, 2, 31, 2, 31};
241    static  int ARG_FRAMEDROP = 0;
242    static  double ARG_CQ = 0;
243    static  int ARG_FULL1PASS = 0;
244    static  int ARG_REACTION = 16;
245    static  int ARG_AVERAGING = 100;
246    static  int ARG_SMOOTHER = 100;
247    static  int ARG_KBOOST = 10;
248    static  int ARG_KREDUCTION = 20;
249    static  int ARG_KTHRESH = 1;
250    static  int ARG_CHIGH = 0;
251    static  int ARG_CLOW = 0;
252    static  int ARG_OVERSTRENGTH = 5;
253    static  int ARG_OVERIMPROVE = 5;
254    static  int ARG_OVERDEGRADE = 5;
255    static  int ARG_OVERHEAD = 0;
256    static  int ARG_VBVSIZE = 0;
257    static  int ARG_VBVMAXRATE = 0;
258    static  int ARG_VBVPEAKRATE = 0;
259    static  int ARG_THREADS = 0;
260    static  int ARG_VFR = 0;
261    static  int ARG_PROGRESS = 0;
262    static  int ARG_COLORSPACE = XVID_CSP_YV12;
263            /* the path where to save output */
264    static char filepath[256] = "./";
265    
266    static  unsigned char qmatrix_intra[64];
267    static  unsigned char qmatrix_inter[64];
268    
269    /****************************************************************************
270     *                     Nasty global vars ;-)
271     ***************************************************************************/
272    
273    static const int height_ratios[] = {1, 1, 11, 11, 11, 33};
274    static const int width_ratios[] = {1, 1, 12, 10, 16, 40};
275    
276    const char userdata_start_code[] = "\0\0\x01\xb2";
277    
278    
279    /*****************************************************************************
280     *               Local prototypes
281     ****************************************************************************/
282    
283    /* Prints program usage message */
284    static void usage();
285    
286    /* Statistical functions */
287    static double msecond();
288    int gcd(int a, int b);
289    int minquant(int quants[32]);
290    int maxquant(int quants[32]);
291    double avgquant(frame_stats_t frame);
292    
293    /* PGM related functions */
294    #ifndef READ_PNM
295    static int read_pgmheader(FILE * handle);
296    static int read_pgmdata(FILE * handle,
297                                                    unsigned char *image);
298    #else
299    static int read_pnmheader(FILE * handle);
300    static int read_pnmdata(FILE * handle,
301                                                    unsigned char *image);
302    #endif
303    static int read_yuvdata(FILE * handle,
304                                                    unsigned char *image);
305    
306  int pgmflag = 0;                // a flag, if input is in PGM format, overwritten in init-phase  /* Encoder related functions */
307  char filepath[256] = "./";      // the path where to save output  static void enc_gbl(int use_assembler);
308    static int  enc_init(void **enc_handle, char *stats_pass1, int start_num);
309    static int  enc_info();
310    static int  enc_stop(void *enc_handle);
311    static int  enc_main(void *enc_handle,
312                                             unsigned char *image,
313                                             unsigned char *bitstream,
314                                             int *key,
315                                             int *stats_type,
316                                             int *stats_quant,
317                                             int *stats_length,
318                                             int stats[3],
319                                             int framenum);
320    static void encode_sequence(enc_sequence_data_t *h);
321    
322    /* Zone Related Functions */
323    static void apply_zone_modifiers(xvid_enc_frame_t * frame, int framenum);
324    static void prepare_full1pass_zones();
325    static void prepare_cquant_zones();
326    void sort_zones(zone_t * zones, int zone_num, int * sel);
327    
328    
329    void removedivxp(char *buf, int size);
330    
331    /*****************************************************************************
332     *               Main function
333     ****************************************************************************/
334    
335    int
336    main(int argc,
337             char *argv[])
338    {
339            double totalenctime = 0.;
340            float totalPSNR[3] = {0., 0., 0.};
341    
342  void *enc_handle = NULL;                // internal structures (handles) for encoding          FILE *statsfile;
343            frame_stats_t framestats[7];
344    
345            int input_num = 0;
346            int totalsize = 0;
347            int use_assembler = 1;
348            int i;
349    
350  /*********************************************************************/          printf("xvid_encraw - raw mpeg4 bitstream encoder ");
351  /*                     "statistical" functions                       */          printf("written by Christoph Lampert\n\n");
 /*                                                                   */  
 /*  these are not needed for encoding or decoding, but for measuring */  
 /*  time and quality, there in nothing specific to XviD in these     */  
 /*                                                                   */  
 /*********************************************************************/  
352    
353  double msecond()          /* Is there a dumb Xvid coder ? */
354  /* return the current time in seconds(!)  */          if(ME_ELEMENTS != VOP_ELEMENTS) {
355  {                  fprintf(stderr, "Presets' arrays should have the same number of elements -- Please fill a bug to xvid-devel@xvid.org\n");
356          struct timeval  tv;                  return(-1);
357          gettimeofday(&tv, 0);          }
358          return tv.tv_sec + tv.tv_usec * 1.0e-6;  
359            /* Clear framestats */
360            memset(framestats, 0, sizeof(framestats));
361    
362    /*****************************************************************************
363     *                            Command line parsing
364     ****************************************************************************/
365    
366            for (i = 1; i < argc; i++) {
367    
368                    if (strcmp("-asm", argv[i]) == 0) {
369                            use_assembler = 1;
370                    } else if (strcmp("-noasm", argv[i]) == 0) {
371                            use_assembler = 0;
372                    } else if (strcmp("-w", argv[i]) == 0 && i < argc - 1) {
373                            i++;
374                            XDIM = atoi(argv[i]);
375                    } else if (strcmp("-h", argv[i]) == 0 && i < argc - 1) {
376                            i++;
377                            YDIM = atoi(argv[i]);
378                    } else if (strcmp("-csp",argv[i]) == 0 && i < argc - 1) {
379                            i++;
380                            if (strcmp(argv[i],"i420") == 0){
381                                    ARG_COLORSPACE = XVID_CSP_I420;
382                            } else if(strcmp(argv[i],"yv12") == 0){
383                                    ARG_COLORSPACE = XVID_CSP_YV12;
384                            } else {
385                                    printf("Invalid colorspace\n");
386                                    return 0;
387                            }
388                    } else if (strcmp("-bitrate", argv[i]) == 0) {
389                            if (i < argc - 1)
390                                    ARG_BITRATE = atoi(argv[i+1]);
391                            if (ARG_BITRATE) {
392                                    i++;
393                                    if (ARG_BITRATE <= 20000)
394                                            /* if given parameter is <= 20000, assume it means kbps */
395                                            ARG_BITRATE *= 1000;
396  }  }
397                            else
398                                    ARG_BITRATE = 700000;
399                    } else if (strcmp("-size", argv[i]) == 0 && i < argc - 1) {
400                            i++;
401                            ARG_TARGETSIZE = atoi(argv[i]);
402            } else if (strcmp("-cq", argv[i]) == 0 && i < argc - 1) {
403                            i++;
404                            ARG_CQ = atof(argv[i])*100;
405                    } else if (strcmp("-single", argv[i]) == 0) {
406                            ARG_SINGLE = 1;
407                            ARG_PASS1 = NULL;
408                            ARG_PASS2 = NULL;
409                    } else if (strcmp("-pass1", argv[i]) == 0) {
410                            ARG_SINGLE = 0;
411                            if ((i < argc - 1) && (*argv[i+1] != '-')) {
412                                    i++;
413                                    ARG_PASS1 = argv[i];
414                            } else {
415                                    ARG_PASS1 = "xvid.stats";
416                            }
417                    } else if (strcmp("-full1pass", argv[i]) == 0) {
418                            ARG_FULL1PASS = 1;
419                    } else if (strcmp("-pass2", argv[i]) == 0) {
420                            ARG_SINGLE = 0;
421                            if ((i < argc - 1) && (*argv[i+1] != '-')) {
422                                    i++;
423                                    ARG_PASS2 = argv[i];
424                            } else {
425                                    ARG_PASS2 = "xvid.stats";
426                            }
427                    } else if (strcmp("-max_bframes", argv[i]) == 0 && i < argc - 1) {
428                            i++;
429                            ARG_MAXBFRAMES = atoi(argv[i]);
430                    } else if (strcmp("-par", argv[i]) == 0 && i < argc - 1) {
431                            i++;
432                            if (sscanf(argv[i], "%d:%d", &(ARG_PARWIDTH), &(ARG_PARHEIGHT))!=2)
433                                    ARG_PAR = atoi(argv[i]);
434                            else {
435                                    int div;
436                                    ARG_PAR = 0;
437                                    div = gcd(ARG_PARWIDTH, ARG_PARHEIGHT);
438                                    ARG_PARWIDTH /= div;
439                                    ARG_PARHEIGHT /= div;
440                            }
441                    } else if (strcmp("-nopacked", argv[i]) == 0) {
442                            ARG_PACKED = 0;
443                    } else if (strcmp("-packed", argv[i]) == 0) {
444                            ARG_PACKED = 2;
445                    } else if (strcmp("-nochromame", argv[i]) == 0) {
446                            ARG_CHROMAME = 0;
447                    } else if (strcmp("-threads", argv[i]) == 0 && i < argc -1) {
448                            i++;
449                            ARG_THREADS = atoi(argv[i]);
450                    } else if (strcmp("-bquant_ratio", argv[i]) == 0 && i < argc - 1) {
451                            i++;
452                            ARG_BQRATIO = atoi(argv[i]);
453                    } else if (strcmp("-bquant_offset", argv[i]) == 0 && i < argc - 1) {
454                            i++;
455                            ARG_BQOFFSET = atoi(argv[i]);
456    
457                    } else if (strcmp("-zones", argv[i]) == 0 && i < argc -1) {
458                            char c;
459                            char *frameoptions, *rem;
460                            int startframe;
461                            char options[40];
462    
463                            i++;
464    
465                            do {
466                                    rem = strrchr(argv[i], '/');
467                                    if (rem==NULL)
468                                            rem=argv[i];
469                                    else {
470                                            *rem = '\0';
471                                            rem++;
472                                    }
473                                    if (sscanf(rem, "%d,%c,%s", &startframe, &c, options)<3) {
474                                            fprintf(stderr, "Zone error, bad parameters %s\n", rem);
475                                            continue;
476                                    }
477                                    if (NUM_ZONES >= MAX_ZONES) {
478                                            fprintf(stderr, "warning: too many zones; zone ignored\n");
479                                            continue;
480                                    }
481                                    memset(&ZONES[NUM_ZONES], 0, sizeof(zone_t));
482    
483  /*********************************************************************/                                  ZONES[NUM_ZONES].frame = startframe;
484  /*                    input and output functions                     */                                  ZONES[NUM_ZONES].modifier = atof(options)*100;
485  /*                                                                   */                                  if (toupper(c)=='Q')
486  /* the are small and simple routines to read and write PGM and YUV   */                                          ZONES[NUM_ZONES].mode = XVID_ZONE_QUANT;
487  /* image. It's just for convenience, again nothing specific to XviD  */                                  else if (toupper(c)=='W')
488  /*                                                                   */                                          ZONES[NUM_ZONES].mode = XVID_ZONE_WEIGHT;
489  /*********************************************************************/                                  else {
490                                            fprintf(stderr, "Bad zone type %c\n", c);
491                                            continue;
492                                    }
493    
494  int read_pgmheader(FILE* handle)                                  if ((frameoptions=strchr(options, ','))!=NULL) {
495  {                                          int readchar=0, count;
496          int bytes,xsize,ysize,depth;                                          frameoptions++;
497          char dummy[2];                                          while (readchar<strlen(frameoptions)) {
498                                                    if (sscanf(frameoptions+readchar, "%d%n", &(ZONES[NUM_ZONES].bvop_threshold), &count)==1) {
499                                                            readchar += count;
500                                                    }
501                                                    else {
502                                                            if (toupper(frameoptions[readchar])=='K')
503                                                                    ZONES[NUM_ZONES].type = XVID_TYPE_IVOP;
504                                                            else if (toupper(frameoptions[readchar])=='G')
505                                                                    ZONES[NUM_ZONES].greyscale = 1;
506                                                            else if (toupper(frameoptions[readchar])=='O')
507                                                                    ZONES[NUM_ZONES].chroma_opt = 1;
508                                                            else if (toupper(frameoptions[readchar])=='C')
509                                                                    ZONES[NUM_ZONES].cartoon_mode = 1;
510                                                            else {
511                                                                    fprintf(stderr, "Error in zone %s option %c\n", rem, frameoptions[readchar]);
512                                                                    break;
513                                                            }
514                                                            readchar++;
515                                                    }
516                                            }
517                                    }
518                                    NUM_ZONES++;
519                            } while (rem != argv[i]);
520    
         bytes = fread(dummy,1,2,handle);  
521    
522          if ( (bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '5' ))                  } else if ((strcmp("-zq", argv[i]) == 0 || strcmp("-zw", argv[i]) == 0) && i < argc - 2) {
523                  return 1;  
524          fscanf(handle,"%d %d %d",&xsize,&ysize,&depth);              if (NUM_ZONES >= MAX_ZONES) {
525          if ( (xsize > 1440) || (ysize > 2880 ) || (depth != 255) )                  fprintf(stderr,"warning: too many zones; zone ignored\n");
526          {                  continue;
                 return 2;  
527          }          }
528          if ( (XDIM==0) || (YDIM==0) )                          memset(&ZONES[NUM_ZONES], 0, sizeof(zone_t));
529          {       XDIM=xsize;                          if (strcmp("-zq", argv[i])== 0) {
530                  YDIM=ysize;                                  ZONES[NUM_ZONES].mode = XVID_ZONE_QUANT;
531                            }
532                            else {
533                                    ZONES[NUM_ZONES].mode = XVID_ZONE_WEIGHT;
534                            }
535                            ZONES[NUM_ZONES].modifier = atof(argv[i+2])*100;
536                            i++;
537                ZONES[NUM_ZONES].frame = atoi(argv[i]);
538                            i++;
539                            ZONES[NUM_ZONES].type = XVID_TYPE_AUTO;
540                            ZONES[NUM_ZONES].greyscale = 0;
541                            ZONES[NUM_ZONES].chroma_opt = 0;
542                            ZONES[NUM_ZONES].bvop_threshold = 0;
543                            ZONES[NUM_ZONES].cartoon_mode = 0;
544    
545                NUM_ZONES++;
546                    } else if (strcmp("-quality", argv[i]) == 0 && i < argc - 1) {
547                            i++;
548                            ARG_QUALITY = atoi(argv[i]);
549                    } else if (strcmp("-start", argv[i]) == 0 && i < argc - 1) {
550                            i++;
551                            ARG_STARTFRAMENR = atoi(argv[i]);
552                    } else if (strcmp("-vhqmode", argv[i]) == 0 && i < argc - 1) {
553                            i++;
554                            ARG_VHQMODE = atoi(argv[i]);
555                    } else if (strcmp("-metric", argv[i]) == 0 && i < argc - 1) {
556                            i++;
557                            ARG_QMETRIC = atoi(argv[i]);
558                    } else if (strcmp("-framerate", argv[i]) == 0 && i < argc - 1) {
559                            int exponent;
560                            i++;
561                            ARG_FRAMERATE = (float) atof(argv[i]);
562                            exponent = strcspn(argv[i], ".");
563                            if (exponent<strlen(argv[i]))
564                                    exponent=pow(10.0, (int)(strlen(argv[i])-1-exponent));
565                            else
566                                    exponent=1;
567                            ARG_DWRATE = atof(argv[i])*exponent;
568                            ARG_DWSCALE = exponent;
569                            exponent = gcd(ARG_DWRATE, ARG_DWSCALE);
570                            ARG_DWRATE /= exponent;
571                            ARG_DWSCALE /= exponent;
572                    } else if (strcmp("-max_key_interval", argv[i]) == 0 && i < argc - 1) {
573                            i++;
574                            ARG_MAXKEYINTERVAL = atoi(argv[i]);
575                    } else if (strcmp("-i", argv[i]) == 0 && i < argc - 1) {
576                            i++;
577                            ARG_INPUTFILE = argv[i];
578                    } else if (strcmp("-stats", argv[i]) == 0) {
579                            ARG_STATS = 1;
580                    } else if (strcmp("-ssim", argv[i]) == 0) {
581                            ARG_SSIM = 2;
582                            if ((i < argc - 1) && (*argv[i+1] != '-')) {
583                                    i++;
584                                    ARG_SSIM = atoi(argv[i]);
585                            }
586                    } else if (strcmp("-psnrhvsm", argv[i]) == 0) {
587                            ARG_PSNRHVSM = 1;
588                    } else if (strcmp("-ssim_file", argv[i]) == 0 && i < argc -1) {
589                            i++;
590                            ARG_SSIM_PATH = argv[i];
591                    } else if (strcmp("-timecode", argv[i]) == 0 && i < argc -1) {
592                            i++;
593                            ARG_TIMECODEFILE = argv[i];
594                    } else if (strcmp("-dump", argv[i]) == 0) {
595                            ARG_DUMP = 1;
596                    } else if (strcmp("-masking", argv[i]) == 0 && i < argc -1) {
597                            i++;
598                            ARG_LUMIMASKING = atoi(argv[i]);
599                    } else if (strcmp("-type", argv[i]) == 0 && i < argc - 1) {
600                            i++;
601                            ARG_INPUTTYPE = atoi(argv[i]);
602                    } else if (strcmp("-frames", argv[i]) == 0 && i < argc - 1) {
603                            i++;
604                            ARG_MAXFRAMENR = atoi(argv[i]);
605                    } else if (strcmp("-drop", argv[i]) == 0 && i < argc - 1) {
606                            i++;
607                            ARG_FRAMEDROP = atoi(argv[i]);
608                    } else if (strcmp("-imin", argv[i]) == 0 && i < argc - 1) {
609                            i++;
610                            ARG_QUANTS[0] = atoi(argv[i]);
611                    } else if (strcmp("-imax", argv[i]) == 0 && i < argc - 1) {
612                            i++;
613                            ARG_QUANTS[1] = atoi(argv[i]);
614                    } else if (strcmp("-pmin", argv[i]) == 0 && i < argc - 1) {
615                            i++;
616                            ARG_QUANTS[2] = atoi(argv[i]);
617                    } else if (strcmp("-pmax", argv[i]) == 0 && i < argc - 1) {
618                            i++;
619                            ARG_QUANTS[3] = atoi(argv[i]);
620                    } else if (strcmp("-bmin", argv[i]) == 0 && i < argc - 1) {
621                            i++;
622                            ARG_QUANTS[4] = atoi(argv[i]);
623                    } else if (strcmp("-bmax", argv[i]) == 0 && i < argc - 1) {
624                            i++;
625                            ARG_QUANTS[5] = atoi(argv[i]);
626                    } else if (strcmp("-qtype", argv[i]) == 0 && i < argc - 1) {
627                            i++;
628                            ARG_QTYPE = atoi(argv[i]);
629                    } else if (strcmp("-qmatrix", argv[i]) == 0 && i < argc - 1) {
630                            FILE *fp = fopen(argv[++i], "rb");
631                            if (fp == NULL) {
632                                    fprintf(stderr, "Error opening input file %s\n", argv[i]);
633                                    return (-1);
634                            }
635                            fseek(fp, 0, SEEK_END);
636                            if (ftell(fp) != 128) {
637                                    fprintf(stderr, "Unexpected size of input file %s\n", argv[i]);
638                                    return (-1);
639                            }
640    
641                            fseek(fp, 0, SEEK_SET);
642                            fread(qmatrix_intra, 1, 64, fp);
643                            fread(qmatrix_inter, 1, 64, fp);
644    
645                            ARG_QMATRIX = 1;
646                            ARG_QTYPE = 1;
647                    } else if (strcmp("-save", argv[i]) == 0) {
648                            ARG_SAVEMPEGSTREAM = 1;
649                            ARG_SAVEINDIVIDUAL = 1;
650                    } else if (strcmp("-debug", argv[i]) == 0 && i < argc -1) {
651                            i++;
652                if (!(sscanf(argv[i],"0x%x", &(ARG_DEBUG))))
653                                    sscanf(argv[i],"%d", &(ARG_DEBUG));
654                    } else if (strcmp("-o", argv[i]) == 0 && i < argc - 1) {
655                            ARG_SAVEMPEGSTREAM = 1;
656                            i++;
657                            ARG_OUTPUTFILE = argv[i];
658                    } else if (strcmp("-avi", argv[i]) == 0 && i < argc - 1) {
659    #ifdef XVID_AVI_OUTPUT
660                            ARG_SAVEMPEGSTREAM = 1;
661                            i++;
662                            ARG_AVIOUTPUTFILE = argv[i];
663    #else
664                            fprintf( stderr, "Not compiled with AVI output support.\n");
665                            return(-1);
666    #endif
667                    } else if (strcmp("-mkv", argv[i]) == 0 && i < argc - 1) {
668    #ifdef XVID_MKV_OUTPUT
669                            ARG_SAVEMPEGSTREAM = 1;
670                            i++;
671                            ARG_MKVOUTPUTFILE = argv[i];
672    #else
673                            fprintf(stderr, "Not compiled with MKV output support.\n");
674                            return(-1);
675    #endif
676                    } else if (strcmp("-vop_debug", argv[i]) == 0) {
677                            ARG_VOPDEBUG = 1;
678                    } else if (strcmp("-notrellis", argv[i]) == 0) {
679                            ARG_TRELLIS = 0;
680                    } else if (strcmp("-bvhq", argv[i]) == 0) {
681                            ARG_BVHQ = 1;
682                    } else if (strcmp("-qpel", argv[i]) == 0) {
683                            ARG_QPEL = 1;
684                    } else if (strcmp("-turbo", argv[i]) == 0) {
685                            ARG_TURBO = 1;
686                    } else if (strcmp("-gmc", argv[i]) == 0) {
687                            ARG_GMC = 1;
688                    } else if (strcmp("-interlaced", argv[i]) == 0) {
689                            if ((i < argc - 1) && (*argv[i+1] != '-')) {
690                                    i++;
691                                    ARG_INTERLACING = atoi(argv[i]);
692                            } else {
693                                    ARG_INTERLACING = 1;
694                            }
695                    } else if (strcmp("-noclosed_gop", argv[i]) == 0) {
696                            ARG_CLOSED_GOP = 0;
697                    } else if (strcmp("-closed_gop", argv[i]) == 0) {
698                            ARG_CLOSED_GOP = 2;
699                    } else if (strcmp("-vbvsize", argv[i]) == 0 && i < argc -1) {
700                            i++;
701                            ARG_VBVSIZE = atoi(argv[i]);
702                    } else if (strcmp("-vbvmax", argv[i]) == 0 && i < argc -1) {
703                            i++;
704                            ARG_VBVMAXRATE = atoi(argv[i]);
705                    } else if (strcmp("-vbvpeak", argv[i]) == 0 && i < argc -1) {
706                            i++;
707                            ARG_VBVPEAKRATE = atoi(argv[i]);
708                    } else if (strcmp("-reaction", argv[i]) == 0 && i < argc -1) {
709                            i++;
710                            ARG_REACTION = atoi(argv[i]);
711                    } else if (strcmp("-averaging", argv[i]) == 0 && i < argc -1) {
712                            i++;
713                            ARG_AVERAGING = atoi(argv[i]);
714                    } else if (strcmp("-smoother", argv[i]) == 0 && i < argc -1) {
715                            i++;
716                            ARG_SMOOTHER = atoi(argv[i]);
717                    } else if (strcmp("-kboost", argv[i]) == 0 && i < argc -1) {
718                            i++;
719                            ARG_KBOOST = atoi(argv[i]);
720                    } else if (strcmp("-kthresh", argv[i]) == 0 && i < argc -1) {
721                            i++;
722                            ARG_KTHRESH = atoi(argv[i]);
723                    } else if (strcmp("-chigh", argv[i]) == 0 && i < argc -1) {
724                            i++;
725                            ARG_CHIGH = atoi(argv[i]);
726                    } else if (strcmp("-clow", argv[i]) == 0 && i < argc -1) {
727                            i++;
728                            ARG_CLOW = atoi(argv[i]);
729                    } else if (strcmp("-ostrength", argv[i]) == 0 && i < argc -1) {
730                            i++;
731                            ARG_OVERSTRENGTH = atoi(argv[i]);
732                    } else if (strcmp("-oimprove", argv[i]) == 0 && i < argc -1) {
733                            i++;
734                            ARG_OVERIMPROVE = atoi(argv[i]);
735                    } else if (strcmp("-odegrade", argv[i]) == 0 && i < argc -1) {
736                            i++;
737                            ARG_OVERDEGRADE = atoi(argv[i]);
738                    } else if (strcmp("-overhead", argv[i]) == 0 && i < argc -1) {
739                            i++;
740                            ARG_OVERHEAD = atoi(argv[i]);
741                    } else if (strcmp("-kreduction", argv[i]) == 0 && i < argc -1) {
742                            i++;
743                            ARG_KREDUCTION = atoi(argv[i]);
744            } else if (strcmp("-progress", argv[i]) == 0) {
745                            if (i < argc - 1)
746                                    /* in kbps */
747                                    ARG_PROGRESS = atoi(argv[i+1]);
748                            if (ARG_PROGRESS > 0)
749                                    i++;
750                            else
751                                    ARG_PROGRESS = 10;
752                    } else if (strcmp("-help", argv[i])) {
753                            usage();
754                            return (0);
755                    } else {
756                            usage();
757                            exit(-1);
758          }          }
759    
         return 0;  
760  }  }
761    
762  int read_pgmdata(FILE* handle, unsigned char *image)  /*****************************************************************************
763  {   *                            Arguments checking
764          int i,status;   ****************************************************************************/
         char dummy;  
765    
766          unsigned char* buff1_ptr2 = image + XDIM*YDIM;          if (XDIM <= 0 || XDIM >= 4096 || YDIM <= 0 || YDIM >= 4096) {
767          unsigned char* buff1_ptr3 = image + XDIM*YDIM + XDIM/2*YDIM/2;                  fprintf(stderr,
768                                    "Trying to retrieve width and height from input header\n");
769                    if (!ARG_INPUTTYPE)
770                            ARG_INPUTTYPE = 1;              /* pgm */
771            }
772    
773          fread(image,XDIM*YDIM,1,stdin); // read Y component of picture          if (ARG_QUALITY < 0 ) {
774                    ARG_QUALITY = 0;
775            } else if (ARG_QUALITY >= ME_ELEMENTS) {
776                    ARG_QUALITY = ME_ELEMENTS - 1;
777            }
778    
779          for (i=0;i<YDIM/2;i++)          if (ARG_STARTFRAMENR < 0) {
780          {                  fprintf(stderr, "Bad starting frame number %d, cannot be negative\n", ARG_STARTFRAMENR);
781                  fread(buff1_ptr2,XDIM/2,1,stdin);        // read U                  return(-1);
                 buff1_ptr2 += XDIM/2;  
                 fread(buff1_ptr3,XDIM/2,1,stdin);        // read V  
                 buff1_ptr3 += XDIM/2;  
782          }          }
783          fread(&dummy,1,1,handle);       //  I don't know why, but this seems needed  
784          return 0;          if (ARG_PASS2) {
785                    if (ARG_PASS2 == ARG_PASS1) {
786                            fprintf(stderr, "Can't use the same statsfile for pass1 and pass2: %s\n", ARG_PASS2);
787                            return(-1);
788                    }
789                      statsfile = fopen(ARG_PASS2, "rb");
790                      if (statsfile == NULL) {
791                              fprintf(stderr, "Couldn't open statsfile '%s'!\n", ARG_PASS2);
792                              return (-1);
793                      }
794                      fclose(statsfile);
795  }  }
796    
797  int read_yuvdata(FILE* handle, unsigned char *image)  #ifdef XVID_AVI_OUTPUT
798  {       int i;          if (ARG_AVIOUTPUTFILE == NULL && ARG_PACKED <= 1)
799          char dummy;                  ARG_PACKED = 0;
800    #endif
801    
802          unsigned char* buff1_ptr2 = image + XDIM*YDIM;          if (ARG_BITRATE < 0) {
803          unsigned char* buff1_ptr3 = image + XDIM*YDIM + XDIM/2*YDIM/2;                  fprintf(stderr, "Bad bitrate %d, cannot be negative\n", ARG_BITRATE);
804                    return(-1);
805            }
806    
807            if (NUM_ZONES) {
808                    int i;
809                    sort_zones(ZONES, NUM_ZONES, &i);
810            }
811    
812            if (ARG_PAR > 5) {
813                    fprintf(stderr, "Bad PAR: %d. Must be [1..5] or width:height\n", ARG_PAR);
814                    return(-1);
815            }
816    
817            if (ARG_MAXFRAMENR == 0) {
818                    fprintf(stderr, "Wrong number of frames\n");
819                    return (-1);
820            }
821    
822            if (ARG_INPUTFILE != NULL) {
823    #if defined(XVID_AVI_INPUT)
824          if (strcmp(ARG_INPUTFILE+(strlen(ARG_INPUTFILE)-3), "avs")==0 ||
825              strcmp(ARG_INPUTFILE+(strlen(ARG_INPUTFILE)-3), "avi")==0 ||
826                      ARG_INPUTTYPE==2)
827          {
828                      PAVIFILE avi_in = NULL;
829                      PAVISTREAM avi_in_stream = NULL;
830                      PGETFRAME get_frame = NULL;
831                      BITMAPINFOHEADER myBitmapInfoHeader;
832                      AVISTREAMINFO avi_info;
833                      FILE *avi_fp = fopen(ARG_INPUTFILE, "rb");
834    
835                      AVIFileInit();
836    
837                      if (avi_fp == NULL) {
838                              fprintf(stderr, "Couldn't open file '%s'!\n", ARG_INPUTFILE);
839                              return (-1);
840                      }
841                      fclose(avi_fp);
842    
843                      if (AVIFileOpen(&avi_in, ARG_INPUTFILE, OF_READ, NULL) != AVIERR_OK) {
844                              fprintf(stderr, "Can't open avi/avs file %s\n", ARG_INPUTFILE);
845                              AVIFileExit();
846                              return(-1);
847                      }
848    
849                      if (AVIFileGetStream(avi_in, &avi_in_stream, streamtypeVIDEO, 0) != AVIERR_OK) {
850                              fprintf(stderr, "Can't open stream from file '%s'!\n", ARG_INPUTFILE);
851                              AVIFileRelease(avi_in);
852                              AVIFileExit();
853                              return (-1);
854                      }
855    
856                      AVIFileRelease(avi_in);
857    
858                      if(AVIStreamInfo(avi_in_stream, &avi_info, sizeof(AVISTREAMINFO)) != AVIERR_OK) {
859                              fprintf(stderr, "Can't get stream info from file '%s'!\n", ARG_INPUTFILE);
860                              AVIStreamRelease(avi_in_stream);
861                              AVIFileExit();
862                              return (-1);
863                      }
864    
865                  if (avi_info.fccHandler != MAKEFOURCC('Y', 'V', '1', '2')) {
866                              LONG size;
867                              fprintf(stderr, "Non YV12 input colorspace %c%c%c%c! Attempting conversion...\n",
868                                      avi_info.fccHandler%256, (avi_info.fccHandler>>8)%256, (avi_info.fccHandler>>16)%256,
869                                      (avi_info.fccHandler>>24)%256);
870                              size = sizeof(myBitmapInfoHeader);
871                              AVIStreamReadFormat(avi_in_stream, 0, &myBitmapInfoHeader, &size);
872                              if (size==0)
873                                      fprintf(stderr, "AVIStreamReadFormat read 0 bytes.\n");
874                              else {
875                                      fprintf(stderr, "AVIStreamReadFormat read %d bytes.\n", size);
876                                      fprintf(stderr, "width = %d, height = %d, planes = %d\n", myBitmapInfoHeader.biWidth,
877                                              myBitmapInfoHeader.biHeight, myBitmapInfoHeader.biPlanes);
878                                      fprintf(stderr, "Compression = %c%c%c%c, %d\n",
879                                              myBitmapInfoHeader.biCompression%256, (myBitmapInfoHeader.biCompression>>8)%256,
880                                              (myBitmapInfoHeader.biCompression>>16)%256, (myBitmapInfoHeader.biCompression>>24)%256,
881                                              myBitmapInfoHeader.biCompression);
882                                      fprintf(stderr, "Bits Per Pixel = %d\n", myBitmapInfoHeader.biBitCount);
883                                      myBitmapInfoHeader.biCompression = MAKEFOURCC('Y', 'V', '1', '2');
884                                      myBitmapInfoHeader.biBitCount = 12;
885                                      myBitmapInfoHeader.biSizeImage = (myBitmapInfoHeader.biWidth*myBitmapInfoHeader.biHeight)*3/2;
886                                      get_frame = AVIStreamGetFrameOpen(avi_in_stream, &myBitmapInfoHeader);
887                              }
888                              if (get_frame == NULL) {
889                                    AVIStreamRelease(avi_in_stream);
890                                    AVIFileExit();
891                                    return (-1);
892                              }
893                              else {
894                                    unsigned char *temp;
895                                    fprintf(stderr, "AVIStreamGetFrameOpen successful.\n");
896                                    temp = (unsigned char*)AVIStreamGetFrame(get_frame, 0);
897                                    if (temp != NULL) {
898                                            int i;
899                                            for (i = 0; i < ((DWORD*)temp)[0]; i++) {
900                                                    fprintf(stderr, "%2d ", temp[i]);
901                                            }
902                                            fprintf(stderr, "\n");
903                                    }
904                              }
905                              if (avi_info.fccHandler == MAKEFOURCC('D', 'I', 'B', ' ')) {
906                                      AVIStreamGetFrameClose(get_frame);
907                                      get_frame = NULL;
908                                      ARG_COLORSPACE = XVID_CSP_BGR | XVID_CSP_VFLIP;
909                              }
910                      }
911    
912          if (fread(image,XDIM,YDIM*3/2,stdin) != YDIM*3/2)            if (ARG_MAXFRAMENR<0)
913                  return 1;                          ARG_MAXFRAMENR = avi_info.dwLength-ARG_STARTFRAMENR;
914          else          else
915                  return 0;                          ARG_MAXFRAMENR = min(ARG_MAXFRAMENR, avi_info.dwLength-ARG_STARTFRAMENR);
916    
917                      XDIM = avi_info.rcFrame.right - avi_info.rcFrame.left;
918                      YDIM = avi_info.rcFrame.bottom - avi_info.rcFrame.top;
919                      if (ARG_FRAMERATE==0) {
920                            ARG_FRAMERATE = (float) avi_info.dwRate / (float) avi_info.dwScale;
921                            ARG_DWRATE = avi_info.dwRate;
922                            ARG_DWSCALE = avi_info.dwScale;
923  }  }
924    
925  int write_pgm(char *filename, unsigned char *image)                    ARG_INPUTTYPE = 2;
926    
927                      if (get_frame) AVIStreamGetFrameClose(get_frame);
928                      if (avi_in_stream) AVIStreamRelease(avi_in_stream);
929                      AVIFileExit();
930          }
931          else
932    #endif
933  {  {
934          FILE *filehandle;                          FILE *in_file = fopen(ARG_INPUTFILE, "rb");
935          filehandle=fopen(filename,"wb");                          int pos = 0;
936          if (filehandle)                          if (in_file == NULL) {
937          {                                  fprintf(stderr, "Error opening input file %s\n", ARG_INPUTFILE);
938                  fprintf(filehandle,"P5\n\n");           //                                  return (-1);
939                  fprintf(filehandle,"%d %d 255\n",XDIM,YDIM*3/2);                          }
940                  fwrite(image,XDIM,YDIM*3/2,filehandle);  #ifdef USE_APP_LEVEL_THREADING
941                  fclose(filehandle);                          fseek(in_file, 0, SEEK_END); /* Determine input size */
942                  return 0;                          pos = ftell(in_file);
943                            ARG_MAXFRAMENR = pos / IMAGE_SIZE(XDIM, YDIM); /* PGM, header size ?? */
944    #endif
945                            fclose(in_file);
946                    }
947            }
948    
949            if (ARG_FRAMERATE <= 0) {
950                    fprintf(stderr, "Wrong Framerate %f\n", ARG_FRAMERATE);
951                    return (-1);
952            }
953    
954            if (ARG_TARGETSIZE) {
955                    if (ARG_MAXFRAMENR <= 0) {
956                            fprintf(stderr, "Bad target size; number of input frames unknown\n");
957                            goto release_all;
958                    } else if (ARG_BITRATE) {
959                                    fprintf(stderr, "Parameter conflict: Do not specify both -bitrate and -size\n");
960                                    goto release_all;
961                    } else
962                            ARG_BITRATE = ((ARG_TARGETSIZE * 8) / (ARG_MAXFRAMENR / ARG_FRAMERATE)) * 1024;
963            }
964    
965                    /* Set constant quant to default if no bitrate given for single pass */
966            if (ARG_SINGLE && (!ARG_BITRATE) && (!ARG_CQ))
967                            ARG_CQ = DEFAULT_QUANT;
968    
969                    /* Init xvidcore */
970        enc_gbl(use_assembler);
971    
972    #ifdef USE_APP_LEVEL_THREADING
973            if (ARG_INPUTFILE == NULL || strcmp(ARG_INPUTFILE, "stdin") == 0 ||
974                ARG_NUM_APP_THREADS <= 1 || ARG_THREADS != 0 ||
975                ARG_TIMECODEFILE != NULL || ARG_AVIOUTPUTFILE != NULL ||
976                ARG_INPUTTYPE == 1 || ARG_MKVOUTPUTFILE != NULL)            /* TODO: PGM input */
977    #endif /* Spawn just one encoder instance */
978            {
979                    enc_sequence_data_t enc_data;
980                    memset(&enc_data, 0, sizeof(enc_sequence_data_t));
981    
982                    if (!ARG_THREADS) ARG_THREADS = ARG_NUM_APP_THREADS;
983                    ARG_NUM_APP_THREADS = 1;
984    
985                    enc_data.outfilename = ARG_OUTPUTFILE;
986                    enc_data.statsfilename1 = ARG_PASS1;
987                    enc_data.start_num = ARG_STARTFRAMENR;
988                    enc_data.stop_num = ARG_MAXFRAMENR;
989    
990                            /* Encode input */
991                    encode_sequence(&enc_data);
992    
993                            /* Copy back stats */
994                    input_num = enc_data.input_num;
995                    totalsize = enc_data.totalsize;
996                    totalenctime = enc_data.totalenctime;
997                    for (i=0; i < 3; i++) totalPSNR[i] = enc_data.totalPSNR[i];
998                    memcpy(framestats, enc_data.framestats, sizeof(framestats));
999            }
1000    #ifdef USE_APP_LEVEL_THREADING
1001            else { /* Split input into sequences and create multiple encoder instances */
1002                    int k;
1003                    void *status;
1004                    FILE *f_out = NULL, *f_stats = NULL;
1005    
1006                    enc_sequence_data_t enc_data[MAX_ENC_INSTANCES];
1007                    char outfile[MAX_ENC_INSTANCES][256];
1008                    char statsfilename[MAX_ENC_INSTANCES][256];
1009    
1010                    for (k = 0; k < MAX_ENC_INSTANCES; k++)
1011                            memset(&enc_data[k], 0, sizeof(enc_sequence_data_t));
1012    
1013                            /* Overwrite internal encoder threading */
1014                    if (ARG_NUM_APP_THREADS > MAX_ENC_INSTANCES) {
1015                            ARG_THREADS = (int) (ARG_NUM_APP_THREADS / MAX_ENC_INSTANCES);
1016                            ARG_NUM_APP_THREADS = MAX_ENC_INSTANCES;
1017          }          }
1018          else          else
1019                  return 1;                          ARG_THREADS = -1;
1020    
1021                    enc_data[0].outfilename = ARG_OUTPUTFILE;
1022                    enc_data[0].statsfilename1 = ARG_PASS1;
1023                    enc_data[0].start_num = ARG_STARTFRAMENR;
1024                    enc_data[0].stop_num = (ARG_MAXFRAMENR-ARG_STARTFRAMENR)/ARG_NUM_APP_THREADS;
1025    
1026                    for (k = 1; k < ARG_NUM_APP_THREADS; k++) {
1027                            sprintf(outfile[k], "%s.%03d", ARG_OUTPUTFILE, k);
1028                            enc_data[k].outfilename = outfile[k];
1029                            if (ARG_PASS1) {
1030                                    sprintf(statsfilename[k], "%s.%03d", ARG_PASS1, k);
1031                                    enc_data[k].statsfilename1 = statsfilename[k];
1032                            }
1033                            enc_data[k].start_num = (k*(ARG_MAXFRAMENR-ARG_STARTFRAMENR))/ARG_NUM_APP_THREADS;
1034                            enc_data[k].stop_num = ((k+1)*(ARG_MAXFRAMENR-ARG_STARTFRAMENR))/ARG_NUM_APP_THREADS;
1035                    }
1036    
1037                            /* Start multiple encoder threads in parallel */
1038                    for (k = 1; k < ARG_NUM_APP_THREADS; k++) {
1039                            pthread_create(&enc_data[k].handle, NULL, (void*)encode_sequence, (void*)&enc_data[k]);
1040                    }
1041    
1042                            /* Encode first sequence in this thread */
1043                    encode_sequence(&enc_data[0]);
1044    
1045                            /* Wait until encoder threads have finished */
1046                    for (k = 1; k < ARG_NUM_APP_THREADS; k++) {
1047                            pthread_join(enc_data[k].handle, &status);
1048                    }
1049    
1050                            /* Join encoder stats and encoder output files */
1051                    if (ARG_OUTPUTFILE)
1052                            f_out = fopen(enc_data[0].outfilename, "ab+");
1053                    if (ARG_PASS1)
1054                            f_stats = fopen(enc_data[0].statsfilename1, "ab+");
1055    
1056                    for (k = 0; k < ARG_NUM_APP_THREADS; k++) {
1057                                    /* Join stats */
1058                            input_num += enc_data[k].input_num;
1059                            totalsize += enc_data[k].totalsize;
1060                            totalenctime = MAX(totalenctime, enc_data[k].totalenctime);
1061    
1062                            for (i=0; i < 3; i++) totalPSNR[i] += enc_data[k].totalPSNR[i];
1063                            for (i=0; i < 8; i++) {
1064                                    int l;
1065                                    framestats[i].count += enc_data[k].framestats[i].count;
1066                                    framestats[i].size += enc_data[k].framestats[i].size;
1067                                    for (l=0; l < 32; l++)
1068                                            framestats[i].quants[l] += enc_data[k].framestats[i].quants[l];
1069                            }
1070                                    /* Join output files */
1071                            if ((k > 0) && (f_out != NULL)) {
1072                                    int ch;
1073                                    FILE *f = fopen(enc_data[k].outfilename, "rb");
1074                                    while((ch = fgetc(f)) != EOF) { fputc(ch, f_out); }
1075                                    fclose(f);
1076                                    remove(enc_data[k].outfilename);
1077                            }
1078                                    /* Join first pass stats files */
1079                            if ((k > 0) && (f_stats != NULL)) {
1080                                    char str[256];
1081                                    FILE *f = fopen(enc_data[k].statsfilename1, "r");
1082                                    while(fgets(str, sizeof(str), f) != NULL) {
1083                                            if (str[0] != '#' && strlen(str) > 3)
1084                                                    fputs(str, f_stats);
1085                                    }
1086                                    fclose(f);
1087                                    remove(enc_data[k].statsfilename1);
1088  }  }
1089                    }
1090                    if (f_out) fclose(f_out);
1091                    if (f_stats) fclose(f_stats);
1092            }
1093    #endif
1094    
1095  /*********************************************************************/  /*****************************************************************************
1096  /* Routines for encoding: init encoder, frame step, release encoder  */   *         Calculate totals and averages for output, print results
1097  /*********************************************************************/   ****************************************************************************/
1098    
1099     printf("\n");
1100            printf("Tot: enctime(ms) =%7.2f,               length(bytes) = %7d\n",
1101                       totalenctime, (int) totalsize);
1102    
1103            if (input_num > 0) {
1104                    totalsize /= input_num;
1105                    totalenctime /= input_num;
1106                    totalPSNR[0] /= input_num;
1107                    totalPSNR[1] /= input_num;
1108                    totalPSNR[2] /= input_num;
1109            } else {
1110                    totalsize = -1;
1111                    totalenctime = -1;
1112            }
1113    
1114            printf("Avg: enctime(ms) =%7.2f, fps =%7.2f, length(bytes) = %7d",
1115                       totalenctime, 1000 / totalenctime, (int) totalsize);
1116       if (ARG_STATS) {
1117           printf(", psnr y = %2.2f, psnr u = %2.2f, psnr v = %2.2f",
1118                      totalPSNR[0],totalPSNR[1],totalPSNR[2]);
1119            }
1120            printf("\n");
1121            if (framestats[XVID_TYPE_IVOP].count) {
1122                    printf("I frames: %6d frames, size = %7d/%7d, quants = %2d / %.2f / %2d\n", \
1123                            framestats[XVID_TYPE_IVOP].count, framestats[XVID_TYPE_IVOP].size/framestats[XVID_TYPE_IVOP].count, \
1124                            framestats[XVID_TYPE_IVOP].size, minquant(framestats[XVID_TYPE_IVOP].quants), \
1125                            avgquant(framestats[XVID_TYPE_IVOP]), maxquant(framestats[XVID_TYPE_IVOP].quants));
1126            }
1127            if (framestats[XVID_TYPE_PVOP].count) {
1128                    printf("P frames: %6d frames, size = %7d/%7d, quants = %2d / %.2f / %2d\n", \
1129                            framestats[XVID_TYPE_PVOP].count, framestats[XVID_TYPE_PVOP].size/framestats[XVID_TYPE_PVOP].count, \
1130                            framestats[XVID_TYPE_PVOP].size, minquant(framestats[XVID_TYPE_PVOP].quants), \
1131                            avgquant(framestats[XVID_TYPE_PVOP]), maxquant(framestats[XVID_TYPE_PVOP].quants));
1132            }
1133            if (framestats[XVID_TYPE_BVOP].count) {
1134                    printf("B frames: %6d frames, size = %7d/%7d, quants = %2d / %.2f / %2d\n", \
1135                            framestats[XVID_TYPE_BVOP].count, framestats[XVID_TYPE_BVOP].size/framestats[XVID_TYPE_BVOP].count, \
1136                            framestats[XVID_TYPE_BVOP].size, minquant(framestats[XVID_TYPE_BVOP].quants), \
1137                            avgquant(framestats[XVID_TYPE_BVOP]), maxquant(framestats[XVID_TYPE_BVOP].quants));
1138            }
1139            if (framestats[XVID_TYPE_SVOP].count) {
1140                    printf("S frames: %6d frames, size = %7d/%7d, quants = %2d / %.2f / %2d\n", \
1141                            framestats[XVID_TYPE_SVOP].count, framestats[XVID_TYPE_SVOP].size/framestats[XVID_TYPE_SVOP].count, \
1142                            framestats[XVID_TYPE_SVOP].size, minquant(framestats[XVID_TYPE_SVOP].quants), \
1143                            avgquant(framestats[XVID_TYPE_SVOP]), maxquant(framestats[XVID_TYPE_SVOP].quants));
1144            }
1145            if (framestats[5].count) {
1146                    printf("N frames: %6d frames, size = %7d/%7d\n", \
1147                            framestats[5].count, framestats[5].size/framestats[5].count, \
1148                            framestats[5].size);
1149            }
1150    
 #define FRAMERATE_INCR 1001  
1151    
1152    /*****************************************************************************
1153     *                            Xvid PART  Stop
1154     ****************************************************************************/
1155    
1156  int enc_init(int use_assembler)    release_all:
 {       /* initialize encoder for first use, pass all needed parameters to the codec */  
         int xerr;  
1157    
1158          XVID_INIT_PARAM xinit;          return (0);
1159          XVID_ENC_PARAM xparam;  }
1160    
1161    /*****************************************************************************
1162     *               Encode a sequence
1163     ****************************************************************************/
1164    
1165    void encode_sequence(enc_sequence_data_t *h) {
1166    
1167            /* Internal structures (handles) for encoding */
1168            void *enc_handle = NULL;
1169    
1170            int start_num = h->start_num;
1171            int stop_num = h->stop_num;
1172            char *outfilename = h->outfilename;
1173            float *totalPSNR = h->totalPSNR;
1174    
1175            int input_num;
1176            int totalsize;
1177            double totalenctime = 0.;
1178    
1179          if(use_assembler)          unsigned char *mp4_buffer = NULL;
1180            unsigned char *in_buffer = NULL;
1181            unsigned char *out_buffer = NULL;
1182    
1183            double enctime;
1184    
1185            int result;
1186            int output_num;
1187            int nvop_counter;
1188            int m4v_size;
1189            int key;
1190            int stats_type;
1191            int stats_quant;
1192            int stats_length;
1193            int fakenvop = 0;
1194    
1195            FILE *in_file = stdin;
1196            FILE *out_file = NULL;
1197            FILE *time_file = NULL;
1198    
1199            char filename[256];
1200    
1201  #ifdef ARCH_IA64  #ifdef XVID_MKV_OUTPUT
1202                  xinit.cpu_flags = XVID_CPU_FORCE | XVID_CPU_IA64;          PMKVFILE myMKVFile = NULL;
1203            PMKVSTREAM myMKVStream = NULL;
1204            MKVSTREAMINFO myMKVStreamInfo;
1205    #endif
1206    #if defined(XVID_AVI_INPUT)
1207            PAVIFILE avi_in = NULL;
1208            PAVISTREAM avi_in_stream = NULL;
1209            PGETFRAME get_frame = NULL;
1210            BITMAPINFOHEADER myBitmapInfoHeader;
1211  #else  #else
1212                  xinit.cpu_flags = 0;  #define get_frame NULL
1213    #endif
1214    #if defined(XVID_AVI_OUTPUT)
1215            int avierr;
1216            PAVIFILE myAVIFile = NULL;
1217            PAVISTREAM myAVIStream = NULL;
1218            AVISTREAMINFO myAVIStreamInfo;
1219    #endif
1220    #if defined(XVID_AVI_INPUT) || defined(XVID_AVI_OUTPUT)
1221            if (ARG_NUM_APP_THREADS > 1)
1222                    CoInitializeEx(0, COINIT_MULTITHREADED);
1223            AVIFileInit();
1224  #endif  #endif
1225    
1226            if (ARG_INPUTFILE == NULL || strcmp(ARG_INPUTFILE, "stdin") == 0) {
1227                    in_file = stdin;
1228            } else {
1229    #ifdef XVID_AVI_INPUT
1230          if (strcmp(ARG_INPUTFILE+(strlen(ARG_INPUTFILE)-3), "avs")==0 ||
1231              strcmp(ARG_INPUTFILE+(strlen(ARG_INPUTFILE)-3), "avi")==0 ||
1232                      ARG_INPUTTYPE==2)
1233          {
1234                      AVISTREAMINFO avi_info;
1235                      FILE *avi_fp = fopen(ARG_INPUTFILE, "rb");
1236    
1237                      if (avi_fp == NULL) {
1238                              fprintf(stderr, "Couldn't open file '%s'!\n", ARG_INPUTFILE);
1239                              return;
1240                      }
1241                      fclose(avi_fp);
1242    
1243                      if (AVIFileOpen(&avi_in, ARG_INPUTFILE, OF_READ, NULL) != AVIERR_OK) {
1244                              fprintf(stderr, "Can't open avi/avs file %s\n", ARG_INPUTFILE);
1245                              AVIFileExit();
1246                              return;
1247                      }
1248    
1249                      if (AVIFileGetStream(avi_in, &avi_in_stream, streamtypeVIDEO, 0) != AVIERR_OK) {
1250                              fprintf(stderr, "Can't open stream from file '%s'!\n", ARG_INPUTFILE);
1251                              AVIFileRelease(avi_in);
1252                              AVIFileExit();
1253                              return;
1254                      }
1255    
1256                      AVIFileRelease(avi_in);
1257    
1258                      if(AVIStreamInfo(avi_in_stream, &avi_info, sizeof(AVISTREAMINFO)) != AVIERR_OK) {
1259                              fprintf(stderr, "Can't get stream info from file '%s'!\n", ARG_INPUTFILE);
1260                              AVIStreamRelease(avi_in_stream);
1261                              AVIFileExit();
1262                              return;
1263                      }
1264    
1265                  if (avi_info.fccHandler != MAKEFOURCC('Y', 'V', '1', '2')) {
1266                              LONG size;
1267                              fprintf(stderr, "Non YV12 input colorspace %c%c%c%c! Attempting conversion...\n",
1268                                      avi_info.fccHandler%256, (avi_info.fccHandler>>8)%256, (avi_info.fccHandler>>16)%256,
1269                                      (avi_info.fccHandler>>24)%256);
1270                              size = sizeof(myBitmapInfoHeader);
1271                              AVIStreamReadFormat(avi_in_stream, 0, &myBitmapInfoHeader, &size);
1272                              if (size==0)
1273                                      fprintf(stderr, "AVIStreamReadFormat read 0 bytes.\n");
1274                              else {
1275                                      fprintf(stderr, "AVIStreamReadFormat read %d bytes.\n", size);
1276                                      fprintf(stderr, "width = %d, height = %d, planes = %d\n", myBitmapInfoHeader.biWidth,
1277                                              myBitmapInfoHeader.biHeight, myBitmapInfoHeader.biPlanes);
1278                                      fprintf(stderr, "Compression = %c%c%c%c, %d\n",
1279                                              myBitmapInfoHeader.biCompression%256, (myBitmapInfoHeader.biCompression>>8)%256,
1280                                              (myBitmapInfoHeader.biCompression>>16)%256, (myBitmapInfoHeader.biCompression>>24)%256,
1281                                              myBitmapInfoHeader.biCompression);
1282                                      fprintf(stderr, "Bits Per Pixel = %d\n", myBitmapInfoHeader.biBitCount);
1283                                      myBitmapInfoHeader.biCompression = MAKEFOURCC('Y', 'V', '1', '2');
1284                                      myBitmapInfoHeader.biBitCount = 12;
1285                                      myBitmapInfoHeader.biSizeImage = (myBitmapInfoHeader.biWidth*myBitmapInfoHeader.biHeight)*3/2;
1286                                      get_frame = AVIStreamGetFrameOpen(avi_in_stream, &myBitmapInfoHeader);
1287                              }
1288                              if (get_frame == NULL) {
1289                                    AVIStreamRelease(avi_in_stream);
1290                                    AVIFileExit();
1291                                    return;
1292                              }
1293                              else {
1294                                    unsigned char *temp;
1295                                    fprintf(stderr, "AVIStreamGetFrameOpen successful.\n");
1296                                    temp = (unsigned char*)AVIStreamGetFrame(get_frame, 0);
1297                                    if (temp != NULL) {
1298                                            int i;
1299                                            for (i = 0; i < ((DWORD*)temp)[0]; i++) {
1300                                                    fprintf(stderr, "%2d ", temp[i]);
1301                                            }
1302                                            fprintf(stderr, "\n");
1303                                    }
1304                              }
1305                              if (avi_info.fccHandler == MAKEFOURCC('D', 'I', 'B', ' ')) {
1306                                      AVIStreamGetFrameClose(get_frame);
1307                                      get_frame = NULL;
1308                                      ARG_COLORSPACE = XVID_CSP_BGR | XVID_CSP_VFLIP;
1309                              }
1310                      }
1311        }
1312          else          else
1313                  xinit.cpu_flags = XVID_CPU_FORCE;  #endif
1314                    {
1315                            in_file = fopen(ARG_INPUTFILE, "rb");
1316                            if (in_file == NULL) {
1317                                    fprintf(stderr, "Error opening input file %s\n", ARG_INPUTFILE);
1318                                    return;
1319                            }
1320                    }
1321            }
1322    
1323            // This should be after the avi input opening stuff
1324            if (ARG_TIMECODEFILE != NULL) {
1325                    time_file = fopen(ARG_TIMECODEFILE, "r");
1326                    if (time_file==NULL) {
1327                            fprintf(stderr, "Couldn't open timecode file '%s'!\n", ARG_TIMECODEFILE);
1328                            return;
1329                    }
1330                    else {
1331                            fscanf(time_file, "# timecode format v2\n");
1332                    }
1333            }
1334    
1335            if (ARG_INPUTTYPE==1) {
1336    #ifndef READ_PNM
1337                    if (read_pgmheader(in_file)) {
1338    #else
1339                    if (read_pnmheader(in_file)) {
1340    #endif
1341                            fprintf(stderr,
1342                                            "Wrong input format, I want YUV encapsulated in PGM\n");
1343                            return;
1344                    }
1345            }
1346    
1347            /* Jump to the starting frame */
1348            if (ARG_INPUTTYPE == 0) /* TODO: Other input formats ??? */
1349                    fseek(in_file, start_num*IMAGE_SIZE(XDIM, YDIM), SEEK_SET);
1350    
1351    
1352                    /* now we know the sizes, so allocate memory */
1353            if (get_frame == NULL)
1354            {
1355                    in_buffer = (unsigned char *) malloc(4*XDIM*YDIM);
1356                    if (!in_buffer)
1357                            goto free_all_memory;
1358            }
1359    
1360            /* this should really be enough memory ! */
1361            mp4_buffer = (unsigned char *) malloc(IMAGE_SIZE(XDIM, YDIM) * 2);
1362            if (!mp4_buffer)
1363                    goto free_all_memory;
1364    
1365    /*****************************************************************************
1366     *                            Xvid PART  Start
1367     ****************************************************************************/
1368    
1369    
1370            result = enc_init(&enc_handle, h->statsfilename1, h->start_num);
1371            if (result) {
1372                    fprintf(stderr, "Encore INIT problem, return value %d\n", result);
1373                    goto release_all;
1374            }
1375    
1376          xvid_init(NULL, 0, &xinit, NULL);  /*****************************************************************************
1377     *                            Main loop
1378     ****************************************************************************/
1379    
1380            if (ARG_SAVEMPEGSTREAM) {
1381    
1382                    if (outfilename) {
1383                            if ((out_file = fopen(outfilename, "w+b")) == NULL) {
1384                                    fprintf(stderr, "Error opening output file %s\n", outfilename);
1385                                    goto release_all;
1386                            }
1387                    }
1388    
1389          xparam.width = XDIM;  #ifdef XVID_AVI_OUTPUT
1390          xparam.height = YDIM;                  if (ARG_AVIOUTPUTFILE != NULL ) {
         if ((ARG_FRAMERATE - (int)ARG_FRAMERATE) < SMALL_EPS)  
1391          {          {
1392                  xparam.fincr = 1;                                  /* Open the .avi output then close it */
1393                  xparam.fbase = (int)ARG_FRAMERATE;                                  /* Resets the file size to 0, which AVIFile doesn't seem to do */
1394                                    FILE *scrub;
1395                                    if ((scrub = fopen(ARG_AVIOUTPUTFILE, "w+b")) == NULL) {
1396                                            fprintf(stderr, "Error opening output file %s\n", ARG_AVIOUTPUTFILE);
1397                                            goto release_all;
1398          }          }
1399          else          else
1400                                            fclose(scrub);
1401                            }
1402                            memset(&myAVIStreamInfo, 0, sizeof(AVISTREAMINFO));
1403                            myAVIStreamInfo.fccType = streamtypeVIDEO;
1404                            myAVIStreamInfo.fccHandler = MAKEFOURCC('x', 'v', 'i', 'd');
1405                            myAVIStreamInfo.dwScale = ARG_DWSCALE;
1406                            myAVIStreamInfo.dwRate = ARG_DWRATE;
1407                            myAVIStreamInfo.dwLength = ARG_MAXFRAMENR;
1408                            myAVIStreamInfo.dwQuality = 10000;
1409                            SetRect(&myAVIStreamInfo.rcFrame, 0, 0, YDIM, XDIM);
1410    
1411                            if (avierr=AVIFileOpen(&myAVIFile, ARG_AVIOUTPUTFILE, OF_CREATE|OF_WRITE, NULL)) {
1412                                    fprintf(stderr, "AVIFileOpen failed opening output file %s, error code %d\n", ARG_AVIOUTPUTFILE, avierr);
1413                                    goto release_all;
1414                            }
1415    
1416                            if (avierr=AVIFileCreateStream(myAVIFile, &myAVIStream, &myAVIStreamInfo)) {
1417                                    fprintf(stderr, "AVIFileCreateStream failed, error code %d\n", avierr);
1418                                    goto release_all;
1419                            }
1420    
1421                            memset(&myBitmapInfoHeader, 0, sizeof(BITMAPINFOHEADER));
1422                            myBitmapInfoHeader.biHeight = YDIM;
1423                            myBitmapInfoHeader.biWidth = XDIM;
1424                            myBitmapInfoHeader.biPlanes = 1;
1425                            myBitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER);
1426                            myBitmapInfoHeader.biCompression = MAKEFOURCC('X', 'V', 'I', 'D');
1427                            myBitmapInfoHeader.biBitCount = 12;
1428                            myBitmapInfoHeader.biSizeImage = 6*XDIM*YDIM;
1429                            if (avierr=AVIStreamSetFormat(myAVIStream, 0, &myBitmapInfoHeader, sizeof(BITMAPINFOHEADER))) {
1430                                    fprintf(stderr, "AVIStreamSetFormat failed, error code %d\n", avierr);
1431                                    goto release_all;
1432                            }
1433                    }
1434    #endif
1435    #ifdef XVID_MKV_OUTPUT
1436                    if (ARG_MKVOUTPUTFILE != NULL) {
1437          {          {
1438                  xparam.fincr = FRAMERATE_INCR;                                  /* Open the .mkv output then close it */
1439                  xparam.fbase = (int)(FRAMERATE_INCR * ARG_FRAMERATE);                                  /* Just to make sure we can write to it */
1440                                    FILE *scrub;
1441                                    if ((scrub = fopen(ARG_MKVOUTPUTFILE, "w+b")) == NULL) {
1442                                            fprintf(stderr, "Error opening output file %s\n", ARG_MKVOUTPUTFILE);
1443                                            goto release_all;
1444                                    }
1445                                    else
1446                                            fclose(scrub);
1447          }          }
         xparam.rc_reaction_delay_factor = 16;  
         xparam.rc_averaging_period = 100;  
         xparam.rc_buffer = 10;  
         xparam.rc_bitrate = ARG_BITRATE*1000;  
         xparam.min_quantizer = 1;  
         xparam.max_quantizer = 31;  
         xparam.max_key_interval = (int)ARG_FRAMERATE*10;  
1448    
1449  #ifdef BFRAMES                          MKVFileOpen(&myMKVFile, ARG_MKVOUTPUTFILE, OF_CREATE|OF_WRITE, NULL);
1450          xparam.global = XVID_GLOBAL_DX50BVOP;                          if (ARG_PAR) {
1451          xparam.max_bframes = ARG_MAXBFRAMES;                                  myMKVStreamInfo.display_height = YDIM*height_ratios[ARG_PAR];
1452          xparam.bquant_ratio = ARG_BQUANTRATIO;                                  myMKVStreamInfo.display_width = XDIM*width_ratios[ARG_PAR];
1453          xparam.frame_drop_ratio=0;                          }
1454                            else {
1455                                    myMKVStreamInfo.display_height = YDIM*ARG_PARHEIGHT;
1456                                    myMKVStreamInfo.display_width = XDIM*ARG_PARWIDTH;
1457                            }
1458                            myMKVStreamInfo.height = YDIM;
1459                            myMKVStreamInfo.width = XDIM;
1460                            myMKVStreamInfo.framerate = ARG_DWRATE;
1461                            myMKVStreamInfo.framescale = ARG_DWSCALE;
1462                            myMKVStreamInfo.length = ARG_MAXFRAMENR;
1463                            MKVFileCreateStream(myMKVFile, &myMKVStream, &myMKVStreamInfo);
1464                    }
1465  #endif  #endif
1466            } else {
1467                    out_file = NULL;
1468            }
1469    
1470    
1471    /*****************************************************************************
1472     *                       Encoding loop
1473     ****************************************************************************/
1474    
1475            totalsize = 0;
1476    
1477            result = 0;
1478    
1479            input_num = 0;                      /* input frame counter */
1480            output_num = start_num;             /* output frame counter */
1481    
1482            nvop_counter = 0;
1483    
1484          /* I use a small value here, since will not encode whole movies,          do {
                 but short clips */  
1485    
1486          xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xparam, NULL);                  char *type;
1487          enc_handle=xparam.handle;                  int sse[3];
1488    
1489          return xerr;                  if ((input_num+start_num) >= stop_num && stop_num > 0) {
1490                            result = 1;
1491  }  }
1492    
1493  int  enc_stop()                  if (!result) {
1494  {       int xerr;  #ifdef XVID_AVI_INPUT
1495                            if (ARG_INPUTTYPE==2) {
1496                                    /* read avs/avi data (YUV-format) */
1497                                    if (get_frame != NULL) {
1498                                            in_buffer = (unsigned char*)AVIStreamGetFrame(get_frame, input_num+start_num);
1499                                            if (in_buffer == NULL)
1500                                                    result = 1;
1501                                            else
1502                                                    in_buffer += ((DWORD*)in_buffer)[0];
1503                                    } else {
1504                                            if(AVIStreamRead(avi_in_stream, input_num+start_num, 1, in_buffer, 4*XDIM*YDIM, NULL, NULL ) != AVIERR_OK)
1505                                                    result = 1;
1506                                    }
1507                            } else
1508    #endif
1509                            if (ARG_INPUTTYPE==1) {
1510                                    /* read PGM data (YUV-format) */
1511    #ifndef READ_PNM
1512                                    result = read_pgmdata(in_file, in_buffer);
1513    #else
1514                                    result = read_pnmdata(in_file, in_buffer);
1515    #endif
1516                            } else {
1517                                    /* read raw data (YUV-format) */
1518                                    result = read_yuvdata(in_file, in_buffer);
1519                            }
1520                    }
1521    
1522          xerr = xvid_encore(enc_handle, XVID_ENC_DESTROY, NULL, NULL);  /*****************************************************************************
1523          return xerr;   *                       Encode and decode this frame
1524     ****************************************************************************/
1525    
1526                    if ((input_num+start_num) >= (unsigned int)(stop_num-1) && ARG_MAXBFRAMES) {
1527                            stats_type = XVID_TYPE_PVOP;
1528  }  }
1529                    else
1530                            stats_type = XVID_TYPE_AUTO;
1531    
1532  int  enc_main(unsigned char* image, unsigned char* bitstream, int *streamlength, int* frametype)                  enctime = msecond();
1533  {       int xerr;                  m4v_size =
1534                            enc_main(enc_handle, !result ? in_buffer : 0, mp4_buffer, &key, &stats_type,
1535                                             &stats_quant, &stats_length, sse, input_num);
1536                    enctime = msecond() - enctime;
1537    
1538                    /* Write the Frame statistics */
1539    
1540                    if (stats_type > 0) {   /* !XVID_TYPE_NOTHING */
1541                            switch (stats_type) {
1542                                    case XVID_TYPE_IVOP:
1543                                            type = "I";
1544                                            break;
1545                                    case XVID_TYPE_PVOP:
1546                                            type = "P";
1547                                            break;
1548                                    case XVID_TYPE_BVOP:
1549                                            type = "B";
1550                                            if (ARG_PACKED)
1551                                                    fakenvop = 1;
1552                                            break;
1553                                    case XVID_TYPE_SVOP:
1554                                            type = "S";
1555                                            break;
1556                                    default:
1557                                            type = "U";
1558                                            break;
1559                            }
1560    
1561          XVID_ENC_FRAME xframe;                          if (stats_length > 8) {
1562          XVID_ENC_STATS xstats;                                  h->framestats[stats_type].count++;
1563                                    h->framestats[stats_type].quants[stats_quant]++;
1564                                    h->framestats[stats_type].size += stats_length;
1565                            }
1566                            else {
1567                                    h->framestats[5].count++;
1568                                    h->framestats[5].quants[stats_quant]++;
1569                                    h->framestats[5].size += stats_length;
1570                            }
1571    
1572          xframe.bitstream = bitstream;  #define SSE2PSNR(sse, width, height) ((!(sse))?0.0f : 48.131f - 10*(float)log10((float)(sse)/((float)((width)*(height)))))
         xframe.length = -1;     // this is written by the routine  
1573    
1574          xframe.image = image;                          if (ARG_PROGRESS == 0) {
1575          xframe.colorspace = XVID_CSP_YV12;      // defined in <xvid.h>                                  printf("%5d: key=%i, time= %6.0f, len= %7d", !result ? (input_num+start_num) : -1,
1576                                            key, (float) enctime, (int) m4v_size);
1577                                    printf(" | type=%s, quant= %2d, len= %7d", type, stats_quant,
1578                                       stats_length);
1579    
         xframe.intra = -1; // let the codec decide between I-frame (1) and P-frame (0)  
1580    
1581          xframe.quant = ARG_QUANTI;      // is quant != 0, use a fixed quant (and ignore bitrate)                                  if (ARG_STATS) {
1582                                            printf(", psnr y = %2.2f, psnr u = %2.2f, psnr v = %2.2f",
1583                                                    SSE2PSNR(sse[0], XDIM, YDIM), SSE2PSNR(sse[1], XDIM / 2, YDIM / 2),
1584                                                    SSE2PSNR(sse[2], XDIM / 2, YDIM / 2));
1585                                    }
1586                                    printf("\n");
1587                            } else {
1588                                    if ((input_num) % ARG_PROGRESS == 1) {
1589                                            if (stop_num > 0) {
1590                                                    fprintf(stderr, "\r%7d frames(%3d%%) encoded, %6.2f fps, Average Bitrate = %5.0fkbps", \
1591                                                            (ARG_NUM_APP_THREADS*input_num), (input_num)*100/(stop_num-start_num), (ARG_NUM_APP_THREADS*input_num)*1000/(totalenctime), \
1592                                                            ((((totalsize)/1000)*ARG_FRAMERATE)*8)/(input_num));
1593                                            } else {
1594                                                    fprintf(stderr, "\r%7d frames encoded, %6.2f fps, Average Bitrate = %5.0fkbps", \
1595                                                            (ARG_NUM_APP_THREADS*input_num), (ARG_NUM_APP_THREADS*input_num)*1000/(totalenctime), \
1596                                                            ((((totalsize)/1000)*ARG_FRAMERATE)*8)/(input_num));
1597                                            }
1598                                    }
1599                            }
1600    
1601          xframe.motion = motion_presets[ARG_QUALITY];                          if (ARG_STATS) {
1602          xframe.general = general_presets[ARG_QUALITY];                                  totalPSNR[0] += SSE2PSNR(sse[0], XDIM, YDIM);
1603          xframe.quant_intra_matrix = xframe.quant_inter_matrix = NULL;                                  totalPSNR[1] += SSE2PSNR(sse[1], XDIM/2, YDIM/2);
1604                                    totalPSNR[2] += SSE2PSNR(sse[2], XDIM/2, YDIM/2);
1605                            }
1606    #undef SSE2PSNR
1607                    }
1608    
1609  #ifdef BFRAMES                  if (m4v_size < 0)
1610          xframe.bquant = 0;                          break;
 #endif  
1611    
1612          xerr = xvid_encore(enc_handle, XVID_ENC_ENCODE, &xframe, &xstats);                  /* Update encoding time stats */
1613                    totalenctime += enctime;
1614                    totalsize += m4v_size;
1615    
1616    /*****************************************************************************
1617     *                       Save stream to file
1618     ****************************************************************************/
1619    
1620                    if (m4v_size > 0 && ARG_SAVEMPEGSTREAM) {
1621                            char timecode[50];
1622    
1623                            if (time_file != NULL) {
1624                                    if (fscanf(time_file, "%s\n", timecode) != 1) {
1625                                            fprintf(stderr, "Error reading timecode file, frame %d\n", output_num);
1626                                            goto release_all;
1627                                    }
1628                            }
1629                            else
1630                                    sprintf(timecode, "%f", ((double)ARG_DWSCALE/ARG_DWRATE)*1000*output_num);
1631    
1632  /*              enc_result->is_key_frame = xframe.intra;                          /* Save single files */
1633                  enc_result->quantizer = xframe.quant;                          if (ARG_SAVEINDIVIDUAL) {
1634                  enc_result->total_bits = xframe.length * 8;                                  FILE *out;
1635                  enc_result->motion_bits = xstats.hlength * 8;                                  sprintf(filename, "%sframe%05d.m4v", filepath, output_num);
1636                  enc_result->texture_bits = enc_result->total_bits - enc_result->motion_bits;                                  out = fopen(filename, "w+b");
1637  */                                  fwrite(mp4_buffer, m4v_size, 1, out);
1638                                    fclose(out);
1639                            }
1640    #ifdef XVID_AVI_OUTPUT
1641                            if (ARG_AVIOUTPUTFILE && myAVIStream) {
1642                                    int output_frame;
1643    
1644                                    if (time_file == NULL)
1645                                            output_frame = output_num;
1646                                    else {
1647                                            output_frame = (int)(atof(timecode)/1000/((double)ARG_DWSCALE/ARG_DWRATE)+.5);
1648                                    }
1649                                    if (AVIStreamWrite(myAVIStream, output_frame, 1, mp4_buffer, m4v_size, key ? AVIIF_KEYFRAME : 0, NULL, NULL)) {
1650                                            fprintf(stderr, "AVIStreamWrite failed writing frame %d\n", output_num);
1651                                            goto release_all;
1652                                    }
1653                            }
1654    #endif
1655    
1656  /*  This is statictical data, e.g. for 2-pass.                                  if (key && ARG_PACKED)
1657      If you are not interested in any of this, you can use                                          removedivxp((char*)mp4_buffer, m4v_size);
         NULL instead of &xstats  
 */  
         *frametype = xframe.intra;  
         *streamlength = xframe.length;  
1658    
1659          return xerr;                                  /* Save ES stream */
1660                                    if (outfilename && out_file && !(fakenvop && m4v_size <= 8)) {
1661                                                    fwrite(mp4_buffer, 1, m4v_size, out_file);
1662                                    }
1663    #ifdef XVID_MKV_OUTPUT
1664                                    if (ARG_MKVOUTPUTFILE && myMKVStream) {
1665                                            MKVStreamWrite(myMKVStream, atof(timecode), 1, (ARG_PACKED && fakenvop && (m4v_size <= 8)) ? NULL : mp4_buffer, m4v_size, key ? AVIIF_KEYFRAME : 0, NULL, NULL);
1666  }  }
1667    #endif
1668    
1669  /*********************************************************************/                          output_num++;
1670  /*                          Main program                             */                          if (stats_type != XVID_TYPE_BVOP)
1671  /*********************************************************************/                                  fakenvop=0;
1672                    }
1673    
1674  int main(int argc, char *argv[])                  if (!result)
1675  {                          (input_num)++;
1676    unsigned char *divx_buffer = NULL;  
1677    unsigned char *in_buffer = NULL;                  /* Read the header if it's pgm stream */
1678                    if (!result && (ARG_INPUTTYPE==1))
1679    #ifndef READ_PNM
1680                            result = read_pgmheader(in_file);
1681    #else
1682                            result = read_pnmheader(in_file);
1683    #endif
1684            } while (1);
1685    
   double enctime;  
   double totalenctime=0.;  
1686    
1687    long totalsize=0;    release_all:
   int status;  
1688    
1689    int m4v_size;    h->input_num = input_num;
1690    int frame_type[ABS_MAXFRAMENR];    h->totalenctime = totalenctime;
1691    int Iframes=0, Pframes=0, Bframes=0;    h->totalsize = totalsize;
1692    int use_assembler=1;  
1693    #ifdef XVID_AVI_INPUT
1694            if (get_frame) AVIStreamGetFrameClose(get_frame);
1695            if (avi_in_stream) AVIStreamRelease(avi_in_stream);
1696    #endif
1697    
1698    char filename[256];          if (enc_handle) {
1699                    result = enc_stop(enc_handle);
1700                    if (result)
1701                            fprintf(stderr, "Encore RELEASE problem return value %d\n",
1702                                            result);
1703            }
1704    
1705            if (in_file)
1706                    fclose(in_file);
1707            if (out_file)
1708                    fclose(out_file);
1709            if (time_file)
1710                    fclose(time_file);
1711    
1712    #ifdef XVID_AVI_OUTPUT
1713            if (myAVIStream) AVIStreamRelease(myAVIStream);
1714            if (myAVIFile) AVIFileRelease(myAVIFile);
1715    #endif
1716    #ifdef XVID_MKV_OUTPUT
1717            if (myMKVStream) MKVStreamRelease(myMKVStream);
1718            if (myMKVFile) MKVFileRelease(myMKVFile);
1719    #endif
1720    #if defined(XVID_AVI_INPUT) || defined(XVID_AVI_OUTPUT)
1721            AVIFileExit();
1722    #endif
1723    
1724    FILE *filehandle;    free_all_memory:
1725            free(out_buffer);
1726            free(mp4_buffer);
1727            free(in_buffer);
1728    }
1729    
1730  /* read YUV in pgm format from stdin */  /*****************************************************************************
1731    if (!pgmflag)   *                        "statistical" functions
1732     *
1733     *  these are not needed for encoding or decoding, but for measuring
1734     *  time and quality, there in nothing specific to Xvid in these
1735     *
1736     *****************************************************************************/
1737    
1738    /* Return time elapsed time in miliseconds since the program started */
1739    static double
1740    msecond()
1741    {    {
1742          pgmflag = 1;  #ifndef WIN32
1743            struct timeval tv;
1744    
1745  //      if (argc==2 && !strcmp(argv[1],"-noasm"))          gettimeofday(&tv, 0);
1746  //        use_assembler = 0;          return (tv.tv_sec * 1.0e3 + tv.tv_usec * 1.0e-3);
1747    #else
1748            clock_t clk;
1749    
1750          if (argc>=3)          clk = clock();
1751          {       XDIM = atoi(argv[1]);          return (clk * 1000.0 / CLOCKS_PER_SEC);
1752                  YDIM = atoi(argv[2]);  #endif
                 if ( (XDIM <= 0) || (XDIM >= 2048) || (YDIM <=0) || (YDIM >= 2048) )  
                 {       fprintf(stderr,"Wrong frames size %d %d, trying PGM \n",XDIM, YDIM);  
1753                  }                  }
1754                  else  
1755    int
1756    gcd(int a, int b)
1757                  {                  {
1758                          YDIM = YDIM*3/2; /* for YUV */          int r ;
1759                          pgmflag = 0;  
1760            if (b > a) {
1761                    r = a;
1762                    a = b;
1763                    b = r;
1764                  }                  }
1765    
1766            while ((r = a % b)) {
1767                    a = b;
1768                    b = r;
1769          }          }
1770            return b;
1771    }    }
1772    
1773    if (pgmflag)  int minquant(int quants[32])
   {     if (read_pgmheader(stdin))  
1774              {              {
1775                fprintf(stderr,"Wrong input format, I want YUV encapsulated in PGM\n");          int i = 1;
1776                return 1;          while (quants[i] == 0) {
1777                    i++;
1778              }              }
1779            return i;
1780    }    }
1781    if (argc>=4)  
1782    {     ARG_QUALITY = atoi(argv[3]);  int maxquant(int quants[32])
1783          if ( (ARG_QUALITY < 0) || (ARG_QUALITY > 6) )  {
1784                  { fprintf(stderr,"Wrong Quality\n"); return -1; }          int i = 31;
1785          else          while (quants[i] == 0) {
1786                    fprintf(stderr,"Quality %d\n",ARG_QUALITY);                  i--;
1787    }    }
1788    if (argc>=5)          return i;
   {     ARG_BITRATE = atoi(argv[4]);  
         if ( (ARG_BITRATE <= 0) )  
                 { fprintf(stderr,"Wrong Bitrate\n"); return -1; }  
         if ( (ARG_BITRATE < 32) )  
                 { ARG_QUANTI = ARG_BITRATE;  
                   ARG_BITRATE=0;  
                   fprintf(stderr,"Quantizer %d\n",ARG_QUANTI);  
1789                  }                  }
1790          else  
1791                    fprintf(stderr,"Bitrate %d kbps\n",ARG_BITRATE);  double avgquant(frame_stats_t frame)
1792    {
1793            double avg=0;
1794            int i;
1795            for (i=1; i < 32; i++) {
1796                    avg += frame.quants[i]*i;
1797    }    }
1798    if (argc>=6)          avg /= frame.count;
1799    {     ARG_FRAMERATE = (float)atof(argv[5]);          return avg;
         if ( (ARG_FRAMERATE <= 0) )  
                 { fprintf(stderr,"Wrong Fraterate %s \n",argv[5]); return -1; }  
         fprintf(stderr,"Framerate %6.3f fps\n",ARG_FRAMERATE);  
1800    }    }
1801    
1802    if (argc>=7)  /*****************************************************************************
1803    {     ARG_MAXFRAMENR = atoi(argv[6]);   *                             Usage message
1804          if ( (ARG_MAXFRAMENR <= 0) )   *****************************************************************************/
1805           { fprintf(stderr,"Wrong number of frames\n"); return -1; }  
1806          fprintf(stderr,"max. Framenr. %d\n",ARG_MAXFRAMENR);  static void
1807    usage()
1808    {
1809            fprintf(stderr, "xvid_encraw built at %s on %s\n", __TIME__, __DATE__);
1810            fprintf(stderr, "Usage : xvid_encraw [OPTIONS]\n\n");
1811            fprintf(stderr, "Input options:\n");
1812            fprintf(stderr, " -i      string : input filename (stdin)\n");
1813    #ifdef XVID_AVI_INPUT
1814            fprintf(stderr, " -type   integer: input data type (yuv=0, pgm=1, avi/avs=2)\n");
1815    #else
1816            fprintf(stderr, " -type   integer: input data type (yuv=0, pgm=1)\n");
1817    #endif
1818            fprintf(stderr, " -w      integer: frame width ([1.2048])\n");
1819            fprintf(stderr, " -h      integer: frame height ([1.2048])\n");
1820            fprintf(stderr, " -csp    string : colorspace of raw input file i420, yv12 (default)\n");
1821            fprintf(stderr, " -frames integer: number of frames to encode\n");
1822            fprintf(stderr, "\n");
1823            fprintf(stderr, "Output options:\n");
1824            fprintf(stderr, " -dump      : save decoder output\n");
1825            fprintf(stderr, " -save      : save an Elementary Stream file per frame\n");
1826            fprintf(stderr, " -o string  : save an Elementary Stream for the complete sequence\n");
1827    #ifdef XVID_AVI_OUTPUT
1828            fprintf(stderr, " -avi string: save an AVI file for the complete sequence\n");
1829    #endif
1830            fprintf(stderr, " -mkv string: save a MKV file for the complete sequence\n");
1831            fprintf(stderr, "\n");
1832            fprintf(stderr, "BFrames options:\n");
1833            fprintf(stderr, " -max_bframes   integer: max bframes (2)\n");
1834            fprintf(stderr, " -bquant_ratio  integer: bframe quantizer ratio (150)\n");
1835            fprintf(stderr, " -bquant_offset integer: bframe quantizer offset (100)\n");
1836            fprintf(stderr, "\n");
1837            fprintf(stderr, "Rate control options:\n");
1838            fprintf(stderr, " -framerate float               : target framerate (25.0)\n");
1839            fprintf(stderr, " -bitrate   [integer]           : target bitrate in kbps (700)\n");
1840            fprintf(stderr, " -size      integer                     : target size in kilobytes\n");
1841        fprintf(stderr,     " -single                        : single pass mode (default)\n");
1842            fprintf(stderr, " -cq        float               : single pass constant quantizer\n");
1843            fprintf(stderr, " -pass1     [filename]          : twopass mode (first pass)\n");
1844            fprintf(stderr, " -full1pass                     : perform full first pass\n");
1845            fprintf(stderr, " -pass2     [filename]          : twopass mode (2nd pass)\n");
1846            fprintf(stderr, " -zq starting_frame float       : bitrate zone; quant\n");
1847            fprintf(stderr, " -zw starting_frame float       : bitrate zone; weight\n");
1848        fprintf(stderr, " -max_key_interval integer      : maximum keyframe interval (300)\n");
1849        fprintf(stderr, "\n");
1850            fprintf(stderr, "Single Pass options:\n");
1851            fprintf(stderr, "-reaction   integer             : reaction delay factor (16)\n");
1852            fprintf(stderr, "-averaging  integer             : averaging period (100)\n");
1853            fprintf(stderr, "-smoother   integer             : smoothing buffer (100)\n");
1854            fprintf(stderr, "\n");
1855            fprintf(stderr, "Second Pass options:\n");
1856            fprintf(stderr, "-kboost     integer             : I frame boost (10)\n");
1857            fprintf(stderr, "-kthresh    integer             : I frame reduction threshold (1)\n");
1858            fprintf(stderr, "-kreduction integer             : I frame reduction amount (20)\n");
1859            fprintf(stderr, "-ostrength  integer             : overflow control strength (5)\n");
1860            fprintf(stderr, "-oimprove   integer             : max overflow improvement (5)\n");
1861            fprintf(stderr, "-odegrade   integer             : max overflow degradation (5)\n");
1862            fprintf(stderr, "-chigh      integer             : high bitrate scenes degradation (0)\n");
1863            fprintf(stderr, "-clow       integer             : low bitrate scenes improvement (0)\n");
1864            fprintf(stderr, "-overhead   integer             : container frame overhead (0)\n");
1865            fprintf(stderr, "-vbvsize    integer             : use vbv buffer size\n");
1866            fprintf(stderr, "-vbvmax     integer             : vbv max bitrate\n");
1867            fprintf(stderr, "-vbvpeak    integer             : vbv peak bitrate over 1 second\n");
1868            fprintf(stderr, "\n");
1869            fprintf(stderr, "Other options\n");
1870            fprintf(stderr, " -noasm                         : do not use assembly optmized code\n");
1871            fprintf(stderr, " -turbo                         : use turbo presets for higher encoding speed\n");
1872            fprintf(stderr, " -quality integer               : quality ([0..%d]) (6)\n", ME_ELEMENTS - 1);
1873            fprintf(stderr, " -vhqmode integer               : level of R-D optimizations ([0..4]) (1)\n");
1874            fprintf(stderr, " -bvhq                          : use R-D optimizations for B-frames\n");
1875            fprintf(stderr, " -metric integer                : distortion metric for R-D opt (PSNR:0, PSNRHVSM: 1)\n");
1876            fprintf(stderr, " -qpel                          : use quarter pixel ME\n");
1877            fprintf(stderr, " -gmc                           : use global motion compensation\n");
1878            fprintf(stderr, " -qtype   integer               : quantization type (H263:0, MPEG4:1) (0)\n");
1879            fprintf(stderr, " -qmatrix filename              : use custom MPEG4 quantization matrix\n");
1880            fprintf(stderr, " -interlaced [integer]          : interlaced encoding (BFF:1, TFF:2) (1)\n");
1881            fprintf(stderr, " -nopacked                      : Disable packed mode\n");
1882            fprintf(stderr, " -noclosed_gop                  : Disable closed GOP mode\n");
1883            fprintf(stderr, " -masking [integer]             : HVS masking mode (None:0, Lumi:1, Variance:2) (0)\n");
1884            fprintf(stderr, " -stats                         : print stats about encoded frames\n");
1885            fprintf(stderr, " -ssim [integer]                : prints ssim for every frame (accurate: 0 fast: 4) (2)\n");
1886            fprintf(stderr, " -ssim_file filename            : outputs the ssim stats into a file\n");
1887            fprintf(stderr, " -psnrhvsm                      : prints PSNRHVSM metric for every frame\n");
1888            fprintf(stderr, " -debug                         : activates xvidcore internal debugging output\n");
1889            fprintf(stderr, " -vop_debug                     : print some info directly into encoded frames\n");
1890            fprintf(stderr, " -nochromame                    : Disable chroma motion estimation\n");
1891            fprintf(stderr, " -notrellis                     : Disable trellis quantization\n");
1892            fprintf(stderr, " -imin    integer               : Minimum I Quantizer (1..31) (2)\n");
1893            fprintf(stderr, " -imax    integer               : Maximum I quantizer (1..31) (31)\n");
1894            fprintf(stderr, " -bmin    integer               : Minimum B Quantizer (1..31) (2)\n");
1895            fprintf(stderr, " -bmax    integer               : Maximum B quantizer (1..31) (31)\n");
1896            fprintf(stderr, " -pmin    integer               : Minimum P Quantizer (1..31) (2)\n");
1897            fprintf(stderr, " -pmax    integer               : Maximum P quantizer (1..31) (31)\n");
1898            fprintf(stderr, " -drop    integer               : Frame Drop Ratio (0..100) (0)\n");
1899            fprintf(stderr, " -start   integer               : Starting frame number\n");
1900            fprintf(stderr, " -threads integer               : Number of threads\n");
1901            fprintf(stderr, " -progress [integer]            : Show progress updates every n frames (10)\n");
1902            fprintf(stderr, " -par     integer[:integer]     : Set Pixel Aspect Ratio.\n");
1903            fprintf(stderr, "                                  1 = 1:1\n");
1904            fprintf(stderr, "                                  2 = 12:11 (4:3 PAL)\n");
1905            fprintf(stderr, "                                  3 = 10:11 (4:3 NTSC)\n");
1906            fprintf(stderr, "                                  4 = 16:11 (16:9 PAL)\n");
1907            fprintf(stderr, "                                  5 = 40:33 (16:9 NTSC)\n");
1908            fprintf(stderr, "                              other = custom (width:height)\n");
1909            fprintf(stderr, " -help                          : prints this help message\n");
1910            fprintf(stderr, "\n");
1911            fprintf(stderr, "NB: You can define %d zones repeating the -z[qw] option as needed.\n", MAX_ZONES);
1912    }    }
1913    
1914  #ifdef BFRAMES  /*****************************************************************************
1915    if (argc>=8)   *                       Input and output functions
1916    {     ARG_MAXBFRAMES = atoi(argv[7]);   *
1917          if ( (ARG_MAXBFRAMES < -1) || ( ARG_MAXBFRAMES > ARG_FRAMERATE) )   *      the are small and simple routines to read and write PGM and YUV
1918           { fprintf(stderr,"Wrong maximumnumber of bframes\n"); return -1; }   *      image. It's just for convenience, again nothing specific to Xvid
1919          fprintf(stderr,"max. B-frames %d\n",ARG_MAXBFRAMES);   *
1920     *****************************************************************************/
1921    
1922    #ifndef READ_PNM
1923    static int
1924    read_pgmheader(FILE * handle)
1925    {
1926            int bytes, xsize, ysize, depth;
1927            char dummy[2];
1928    
1929            bytes = fread(dummy, 1, 2, handle);
1930    
1931            if ((bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '5'))
1932                    return (1);
1933    
1934            fscanf(handle, "%d %d %d", &xsize, &ysize, &depth);
1935            if ((xsize > 4096) || (ysize > 4096*3/2) || (depth != 255)) {
1936                    fprintf(stderr, "%d %d %d\n", xsize, ysize, depth);
1937                    return (2);
1938            }
1939            if ((XDIM == 0) || (YDIM == 0)) {
1940                    XDIM = xsize;
1941                    YDIM = ysize * 2 / 3;
1942    }    }
1943    
1944    if (argc>=9)          return (0);
   {     ARG_MAXFRAMENR = atoi(argv[8]);  
         if ( (ARG_BQUANTRATIO <= 0) )  
          { fprintf(stderr,"Wrong B-frames Quantizer ratio \n"); return -1; }  
         fprintf(stderr,"B-frames quant-ratio %d\n",ARG_BQUANTRATIO);  
1945    }    }
 #endif  
1946    
1947  /* now we know the sizes, so allocate memory */  static int
1948    read_pgmdata(FILE * handle,
1949                             unsigned char *image)
1950    {
1951            int i;
1952            char dummy;
1953    
1954    in_buffer = (unsigned char *) malloc(XDIM*YDIM);          unsigned char *y = image;
1955    if (!in_buffer)          unsigned char *u = image + XDIM * YDIM;
1956      goto free_all_memory;          unsigned char *v = image + XDIM * YDIM + XDIM / 2 * YDIM / 2;
1957    
1958    divx_buffer = (unsigned char *) malloc(XDIM*YDIM*2);          /* read Y component of picture */
1959    if (!divx_buffer)          fread(y, 1, XDIM * YDIM, handle);
     goto free_all_memory;  
1960    
1961    YDIM = YDIM*2/3; // PGM is YUV 4:2:0 format, so real image height is *2/3 of PGM picture          for (i = 0; i < YDIM / 2; i++) {
1962                    /* read U */
1963                    fread(u, 1, XDIM / 2, handle);
1964    
1965                    /* read V */
1966                    fread(v, 1, XDIM / 2, handle);
1967    
1968                    /* Update pointers */
1969                    u += XDIM / 2;
1970                    v += XDIM / 2;
1971            }
1972    
1973  /*********************************************************************/          /*  I don't know why, but this seems needed */
1974  /*                         XviD PART  Start                          */          fread(&dummy, 1, 1, handle);
 /*********************************************************************/  
1975    
1976    status = enc_init(use_assembler);          return (0);
1977          if (status)  }
1978    #else
1979    static int
1980    read_pnmheader(FILE * handle)
1981          {          {
1982                  fprintf(stderr,"Encore INIT problem, return value %d\n", status);          int bytes, xsize, ysize, depth;
1983                  goto release_all;          char dummy[2];
1984    
1985            bytes = fread(dummy, 1, 2, handle);
1986    
1987            if ((bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '6'))
1988                    return (1);
1989    
1990            fscanf(handle, "%d %d %d", &xsize, &ysize, &depth);
1991            if ((xsize > 1440) || (ysize > 2880) || (depth != 255)) {
1992                    fprintf(stderr, "%d %d %d\n", xsize, ysize, depth);
1993                    return (2);
1994          }          }
1995    
1996  /*********************************************************************/          XDIM = xsize;
1997  /*                               Main loop                           */          YDIM = ysize;
 /*********************************************************************/  
1998    
1999    do          return (0);
2000    }
2001    
2002    static int
2003    read_pnmdata(FILE * handle,
2004                             unsigned char *image)
2005      {      {
2006          if (pgmflag)          int i;
2007                status = read_pgmdata(stdin, in_buffer);  // read PGM data (YUV-format)          char dummy;
2008    
2009            /* read Y component of picture */
2010            fread(image, 1, XDIM * YDIM * 3, handle);
2011    
2012            /*  I don't know why, but this seems needed */
2013            fread(&dummy, 1, 1, handle);
2014    
2015            return (0);
2016    }
2017    #endif
2018    
2019    static int
2020    read_yuvdata(FILE * handle,
2021                             unsigned char *image)
2022    {
2023    
2024            if (fread(image, 1, IMAGE_SIZE(XDIM, YDIM), handle) !=
2025                    (unsigned int) IMAGE_SIZE(XDIM, YDIM))
2026                    return (1);
2027          else          else
2028                status = read_yuvdata(stdin, in_buffer);  // read raw data (YUV-format)                  return (0);
2029    }
2030    
2031    /*****************************************************************************
2032     *     Routines for encoding: init encoder, frame step, release encoder
2033     ****************************************************************************/
2034    
2035      if (status)  /* sample plugin */
2036    
2037    int
2038    rawenc_debug(void *handle,
2039                             int opt,
2040                             void *param1,
2041                             void *param2)
2042          {          {
2043            // Couldn't read image, most likely end-of-file          switch (opt) {
2044            continue;          case XVID_PLG_INFO:
2045                    {
2046                            xvid_plg_info_t *info = (xvid_plg_info_t *) param1;
2047    
2048                            info->flags = XVID_REQDQUANTS;
2049                            return 0;
2050          }          }
2051    
2052            case XVID_PLG_CREATE:
2053            case XVID_PLG_DESTROY:
2054            case XVID_PLG_BEFORE:
2055                    return 0;
2056    
2057      if (save_ref_flag)          case XVID_PLG_AFTER:
2058          {          {
2059                  sprintf(filename, "%s%05d.pgm", filepath, filenr);                          xvid_plg_data_t *data = (xvid_plg_data_t *) param1;
2060                  write_pgm(filename,in_buffer);                          int i, j;
2061    
2062                            printf("---[ frame: %5i   quant: %2i   length: %6i ]---\n",
2063                                       data->frame_num, data->quant, data->length);
2064                            for (j = 0; j < data->mb_height; j++) {
2065                                    for (i = 0; i < data->mb_width; i++)
2066                                            printf("%2i ", data->dquant[j * data->dquant_stride + i]);
2067                                    printf("\n");
2068                            }
2069    
2070                            return 0;
2071                    }
2072          }          }
2073    
2074            return XVID_ERR_FAIL;
2075    }
2076    
 /*********************************************************************/  
 /*               analyse this frame before encoding                  */  
 /*********************************************************************/  
2077    
2078  //      nothing is done here at the moment, but you could e.g. create  #define FRAMERATE_INCR 1001
 //      histograms or measure entropy or apply preprocessing filters...  
2079    
2080  /*********************************************************************/  /* Gobal encoder init, once per process */
2081  /*               encode and decode this frame                        */  void
2082  /*********************************************************************/  enc_gbl(int use_assembler)
2083    {
2084            xvid_gbl_init_t xvid_gbl_init;
2085    
2086          enctime = -msecond();          /*------------------------------------------------------------------------
2087          status = enc_main(in_buffer, divx_buffer, &m4v_size, &frame_type[filenr]);           * Xvid core initialization
2088          enctime += msecond();           *----------------------------------------------------------------------*/
2089    
2090            /* Set version -- version checking will done by xvidcore */
2091            memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init));
2092            xvid_gbl_init.version = XVID_VERSION;
2093        xvid_gbl_init.debug = ARG_DEBUG;
2094    
         totalenctime += enctime;  
         totalsize += m4v_size;  
2095    
2096          fprintf(stderr,"Frame %5d: intra %d, enctime =%6.1f ms length=%7d bytes\n",          /* Do we have to enable ASM optimizations ? */
2097                   filenr, frame_type[filenr], enctime*1000, m4v_size);          if (use_assembler) {
2098    
2099          if (save_m4v_flag)  #ifdef ARCH_IS_IA64
2100                    xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ASM;
2101    #else
2102                    xvid_gbl_init.cpu_flags = 0;
2103    #endif
2104            } else {
2105                    xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
2106            }
2107    
2108            /* Initialize Xvid core -- Should be done once per __process__ */
2109            xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
2110        ARG_CPU_FLAGS = xvid_gbl_init.cpu_flags;
2111            enc_info();
2112    }
2113    
2114    /* Initialize encoder for first use, pass all needed parameters to the codec */
2115    static int
2116    enc_init(void **enc_handle, char *stats_pass1, int start_num)
2117          {          {
2118                  fwrite(divx_buffer, m4v_size, 1, stdout);          int xerr;
2119            //xvid_plugin_cbr_t cbr;
2120        xvid_plugin_single_t single;
2121            xvid_plugin_2pass1_t rc2pass1;
2122            xvid_plugin_2pass2_t rc2pass2;
2123            xvid_plugin_ssim_t ssim;
2124        xvid_plugin_lumimasking_t masking;
2125            //xvid_plugin_fixed_t rcfixed;
2126            xvid_enc_plugin_t plugins[8];
2127            xvid_enc_create_t xvid_enc_create;
2128            int i;
2129    
2130            /*------------------------------------------------------------------------
2131             * Xvid encoder initialization
2132             *----------------------------------------------------------------------*/
2133    
2134            /* Version again */
2135            memset(&xvid_enc_create, 0, sizeof(xvid_enc_create));
2136            xvid_enc_create.version = XVID_VERSION;
2137    
2138            /* Width and Height of input frames */
2139            xvid_enc_create.width = XDIM;
2140            xvid_enc_create.height = YDIM;
2141            xvid_enc_create.profile = 0xf5; /* Unrestricted */
2142    
2143            /* init plugins  */
2144    //    xvid_enc_create.zones = ZONES;
2145    //    xvid_enc_create.num_zones = NUM_ZONES;
2146    
2147            xvid_enc_create.plugins = plugins;
2148            xvid_enc_create.num_plugins = 0;
2149    
2150            if (ARG_SINGLE) {
2151                    memset(&single, 0, sizeof(xvid_plugin_single_t));
2152                    single.version = XVID_VERSION;
2153                    single.bitrate = ARG_BITRATE;
2154                    single.reaction_delay_factor = ARG_REACTION;
2155                    single.averaging_period = ARG_AVERAGING;
2156                    single.buffer = ARG_SMOOTHER;
2157    
2158    
2159                    plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
2160                    plugins[xvid_enc_create.num_plugins].param = &single;
2161                    xvid_enc_create.num_plugins++;
2162                    if (!ARG_BITRATE)
2163                            prepare_cquant_zones();
2164            }
2165    
2166            if (ARG_PASS2) {
2167                    memset(&rc2pass2, 0, sizeof(xvid_plugin_2pass2_t));
2168                    rc2pass2.version = XVID_VERSION;
2169                    rc2pass2.filename = ARG_PASS2;
2170                    rc2pass2.bitrate = ARG_BITRATE;
2171    
2172                    rc2pass2.keyframe_boost = ARG_KBOOST;
2173                    rc2pass2.curve_compression_high = ARG_CHIGH;
2174                    rc2pass2.curve_compression_low = ARG_CLOW;
2175                    rc2pass2.overflow_control_strength = ARG_OVERSTRENGTH;
2176                    rc2pass2.max_overflow_improvement = ARG_OVERIMPROVE;
2177                    rc2pass2.max_overflow_degradation = ARG_OVERDEGRADE;
2178                    rc2pass2.kfreduction = ARG_KREDUCTION;
2179                    rc2pass2.kfthreshold = ARG_KTHRESH;
2180                    rc2pass2.container_frame_overhead = ARG_OVERHEAD;
2181    
2182    //              An example of activating VBV could look like this
2183                    rc2pass2.vbv_size     =  ARG_VBVSIZE;
2184                    rc2pass2.vbv_initial  =  (ARG_VBVSIZE*3)/4;
2185                    rc2pass2.vbv_maxrate  =  ARG_VBVMAXRATE;
2186                    rc2pass2.vbv_peakrate =  ARG_VBVPEAKRATE;
2187    
2188    
2189                    plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
2190                    plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
2191                    xvid_enc_create.num_plugins++;
2192            }
2193    
2194            if (stats_pass1) {
2195                    memset(&rc2pass1, 0, sizeof(xvid_plugin_2pass1_t));
2196                    rc2pass1.version = XVID_VERSION;
2197                    rc2pass1.filename = stats_pass1;
2198                    if (ARG_FULL1PASS)
2199                            prepare_full1pass_zones();
2200                    plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass1;
2201                    plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
2202                    xvid_enc_create.num_plugins++;
2203            }
2204    
2205            /* Zones stuff */
2206            xvid_enc_create.zones = (xvid_enc_zone_t*)malloc(sizeof(xvid_enc_zone_t) * NUM_ZONES);
2207            xvid_enc_create.num_zones = NUM_ZONES;
2208            for (i=0; i < xvid_enc_create.num_zones; i++) {
2209                    xvid_enc_create.zones[i].frame = ZONES[i].frame;
2210                    xvid_enc_create.zones[i].base = 100;
2211                    xvid_enc_create.zones[i].mode = ZONES[i].mode;
2212                    xvid_enc_create.zones[i].increment = ZONES[i].modifier;
2213            }
2214    
2215    
2216            if (ARG_LUMIMASKING) {
2217                    memset(&masking, 0, sizeof(xvid_plugin_lumimasking_t));
2218                    masking.method = (ARG_LUMIMASKING==2);
2219                    plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
2220                    plugins[xvid_enc_create.num_plugins].param = &masking;
2221                    xvid_enc_create.num_plugins++;
2222            }
2223    
2224            if (ARG_DUMP) {
2225                    plugins[xvid_enc_create.num_plugins].func = xvid_plugin_dump;
2226                    plugins[xvid_enc_create.num_plugins].param = NULL;
2227                    xvid_enc_create.num_plugins++;
2228            }
2229    
2230            if (ARG_SSIM>=0 || ARG_SSIM_PATH != NULL) {
2231            memset(&ssim, 0, sizeof(xvid_plugin_ssim_t));
2232    
2233            plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
2234    
2235                    if( ARG_SSIM >=0){
2236                            ssim.b_printstat = 1;
2237                            ssim.acc = ARG_SSIM;
2238                    } else {
2239                            ssim.b_printstat = 0;
2240                            ssim.acc = 2;
2241                    }
2242    
2243                    if(ARG_SSIM_PATH != NULL){
2244                            ssim.stat_path = ARG_SSIM_PATH;
2245                    }
2246    
2247            ssim.cpu_flags = ARG_CPU_FLAGS;
2248                    ssim.b_visualize = 0;
2249                    plugins[xvid_enc_create.num_plugins].param = &ssim;
2250                    xvid_enc_create.num_plugins++;
2251            }
2252    
2253            if (ARG_PSNRHVSM>0) {
2254            plugins[xvid_enc_create.num_plugins].func = xvid_plugin_psnrhvsm;
2255                    plugins[xvid_enc_create.num_plugins].param = NULL;
2256                    xvid_enc_create.num_plugins++;
2257            }
2258    
2259    #if 0
2260            if (ARG_DEBUG) {
2261                    plugins[xvid_enc_create.num_plugins].func = rawenc_debug;
2262                    plugins[xvid_enc_create.num_plugins].param = NULL;
2263                    xvid_enc_create.num_plugins++;
2264          }          }
2265    #endif
2266    
2267          if (pgmflag)          xvid_enc_create.num_threads = ARG_THREADS;
                 status = read_pgmheader(stdin);  
                                 // because if this was the last PGM, stop now  
2268    
2269          filenr++;          /* Frame rate  */
2270            xvid_enc_create.fincr = ARG_DWSCALE;
2271            xvid_enc_create.fbase = ARG_DWRATE;
2272    
2273            /* Maximum key frame interval */
2274        if (ARG_MAXKEYINTERVAL > 0) {
2275            xvid_enc_create.max_key_interval = ARG_MAXKEYINTERVAL;
2276        }else {
2277                xvid_enc_create.max_key_interval = (int) ARG_FRAMERATE *10;
2278        }
2279    
2280            xvid_enc_create.min_quant[0]=ARG_QUANTS[0];
2281            xvid_enc_create.min_quant[1]=ARG_QUANTS[2];
2282            xvid_enc_create.min_quant[2]=ARG_QUANTS[4];
2283            xvid_enc_create.max_quant[0]=ARG_QUANTS[1];
2284            xvid_enc_create.max_quant[1]=ARG_QUANTS[3];
2285            xvid_enc_create.max_quant[2]=ARG_QUANTS[5];
2286    
2287            /* Bframes settings */
2288            xvid_enc_create.max_bframes = ARG_MAXBFRAMES;
2289            xvid_enc_create.bquant_ratio = ARG_BQRATIO;
2290            xvid_enc_create.bquant_offset = ARG_BQOFFSET;
2291    
2292            /* Frame drop ratio */
2293            xvid_enc_create.frame_drop_ratio = ARG_FRAMEDROP;
2294    
2295            /* Start frame number */
2296            xvid_enc_create.start_frame_num = start_num;
2297    
2298            /* Global encoder options */
2299            xvid_enc_create.global = 0;
2300    
2301            if (ARG_PACKED)
2302                    xvid_enc_create.global |= XVID_GLOBAL_PACKED;
2303    
2304            if (ARG_CLOSED_GOP)
2305                    xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
2306    
2307            if (ARG_STATS)
2308                    xvid_enc_create.global |= XVID_GLOBAL_EXTRASTATS_ENABLE;
2309    
2310            /* I use a small value here, since will not encode whole movies, but short clips */
2311            xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
2312    
2313            /* Retrieve the encoder instance from the structure */
2314            *enc_handle = xvid_enc_create.handle;
2315    
2316            free(xvid_enc_create.zones);
2317    
2318            return (xerr);
2319    }
2320    
2321    static int
2322    enc_info()
2323    {
2324            xvid_gbl_info_t xvid_gbl_info;
2325            int ret;
2326    
2327            memset(&xvid_gbl_info, 0, sizeof(xvid_gbl_info));
2328            xvid_gbl_info.version = XVID_VERSION;
2329            ret = xvid_global(NULL, XVID_GBL_INFO, &xvid_gbl_info, NULL);
2330            if (xvid_gbl_info.build != NULL) {
2331                    fprintf(stderr, "xvidcore build version: %s\n", xvid_gbl_info.build);
2332            }
2333            fprintf(stderr, "Bitstream version: %d.%d.%d\n", XVID_VERSION_MAJOR(xvid_gbl_info.actual_version), XVID_VERSION_MINOR(xvid_gbl_info.actual_version), XVID_VERSION_PATCH(xvid_gbl_info.actual_version));
2334            fprintf(stderr, "Detected CPU flags: ");
2335            if (xvid_gbl_info.cpu_flags & XVID_CPU_ASM)
2336                    fprintf(stderr, "ASM ");
2337            if (xvid_gbl_info.cpu_flags & XVID_CPU_MMX)
2338                    fprintf(stderr, "MMX ");
2339            if (xvid_gbl_info.cpu_flags & XVID_CPU_MMXEXT)
2340                    fprintf(stderr, "MMXEXT ");
2341            if (xvid_gbl_info.cpu_flags & XVID_CPU_SSE)
2342                    fprintf(stderr, "SSE ");
2343            if (xvid_gbl_info.cpu_flags & XVID_CPU_SSE2)
2344                    fprintf(stderr, "SSE2 ");
2345            if (xvid_gbl_info.cpu_flags & XVID_CPU_SSE3)
2346                    fprintf(stderr, "SSE3 ");
2347            if (xvid_gbl_info.cpu_flags & XVID_CPU_SSE41)
2348                    fprintf(stderr, "SSE41 ");
2349        if (xvid_gbl_info.cpu_flags & XVID_CPU_3DNOW)
2350                    fprintf(stderr, "3DNOW ");
2351            if (xvid_gbl_info.cpu_flags & XVID_CPU_3DNOWEXT)
2352                    fprintf(stderr, "3DNOWEXT ");
2353            if (xvid_gbl_info.cpu_flags & XVID_CPU_TSC)
2354                    fprintf(stderr, "TSC ");
2355            fprintf(stderr, "\n");
2356            fprintf(stderr, "Detected %d cpus,", xvid_gbl_info.num_threads);
2357            ARG_NUM_APP_THREADS = xvid_gbl_info.num_threads;
2358            fprintf(stderr, " using %d threads.\n", (!ARG_THREADS) ? ARG_NUM_APP_THREADS : ARG_THREADS);
2359            return ret;
2360    }
2361    
2362     } while ( (!status) && (filenr<ARG_MAXFRAMENR) );  static int
2363    enc_stop(void *enc_handle)
2364    {
2365            int xerr;
2366    
2367            /* Destroy the encoder instance */
2368            xerr = xvid_encore(enc_handle, XVID_ENC_DESTROY, NULL, NULL);
2369    
2370            return (xerr);
2371    }
2372    
2373  /*********************************************************************/  static int
2374  /*     calculate totals and averages for output, print results       */  enc_main(void *enc_handle,
2375  /*********************************************************************/                   unsigned char *image,
2376                     unsigned char *bitstream,
2377                     int *key,
2378                     int *stats_type,
2379                     int *stats_quant,
2380                     int *stats_length,
2381                     int sse[3],
2382                     int framenum)
2383    {
2384            int ret;
2385    
2386            xvid_enc_frame_t xvid_enc_frame;
2387            xvid_enc_stats_t xvid_enc_stats;
2388    
2389            /* Version for the frame and the stats */
2390            memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
2391            xvid_enc_frame.version = XVID_VERSION;
2392    
2393            memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
2394            xvid_enc_stats.version = XVID_VERSION;
2395    
2396            /* Bind output buffer */
2397            xvid_enc_frame.bitstream = bitstream;
2398            xvid_enc_frame.length = -1;
2399    
2400            /* Initialize input image fields */
2401            if (image) {
2402                    xvid_enc_frame.input.plane[0] = image;
2403    #ifndef READ_PNM
2404                    xvid_enc_frame.input.csp = ARG_COLORSPACE;
2405                    xvid_enc_frame.input.stride[0] = XDIM;
2406    #else
2407                    xvid_enc_frame.input.csp = XVID_CSP_BGR;
2408                    xvid_enc_frame.input.stride[0] = XDIM*3;
2409    #endif
2410            } else {
2411                    xvid_enc_frame.input.csp = XVID_CSP_NULL;
2412            }
2413    
2414          totalsize    /= filenr;          /* Set up core's general features */
2415          totalenctime /= filenr;          xvid_enc_frame.vol_flags = 0;
2416            if (ARG_STATS)
2417                    xvid_enc_frame.vol_flags |= XVID_VOL_EXTRASTATS;
2418            if (ARG_QTYPE) {
2419                    xvid_enc_frame.vol_flags |= XVID_VOL_MPEGQUANT;
2420                    if (ARG_QMATRIX) {
2421                            xvid_enc_frame.quant_intra_matrix = qmatrix_intra;
2422                            xvid_enc_frame.quant_inter_matrix = qmatrix_inter;
2423                    }
2424                    else {
2425                            /* We don't use special matrices */
2426                            xvid_enc_frame.quant_intra_matrix = NULL;
2427                            xvid_enc_frame.quant_inter_matrix = NULL;
2428                    }
2429            }
2430    
2431          for (i=0;i<filenr;i++)          if (ARG_PAR)
2432          {                  xvid_enc_frame.par = ARG_PAR;
2433                  switch (frame_type[i])          else {
2434                    xvid_enc_frame.par = XVID_PAR_EXT;
2435                    xvid_enc_frame.par_width = ARG_PARWIDTH;
2436                    xvid_enc_frame.par_height = ARG_PARHEIGHT;
2437            }
2438    
2439    
2440            if (ARG_QPEL) {
2441                    xvid_enc_frame.vol_flags |= XVID_VOL_QUARTERPEL;
2442                    xvid_enc_frame.motion |= XVID_ME_QUARTERPELREFINE16 | XVID_ME_QUARTERPELREFINE8;
2443            }
2444            if (ARG_GMC) {
2445                    xvid_enc_frame.vol_flags |= XVID_VOL_GMC;
2446                    xvid_enc_frame.motion |= XVID_ME_GME_REFINE;
2447            }
2448    
2449            /* Set up core's general features */
2450            xvid_enc_frame.vop_flags = vop_presets[ARG_QUALITY];
2451    
2452            if (ARG_INTERLACING) {
2453                    xvid_enc_frame.vol_flags |= XVID_VOL_INTERLACING;
2454                    if (ARG_INTERLACING == 2)
2455                            xvid_enc_frame.vop_flags |= XVID_VOP_TOPFIELDFIRST;
2456            }
2457    
2458            xvid_enc_frame.vop_flags |= XVID_VOP_HALFPEL;
2459            xvid_enc_frame.vop_flags |= XVID_VOP_HQACPRED;
2460    
2461        if (ARG_VOPDEBUG) {
2462            xvid_enc_frame.vop_flags |= XVID_VOP_DEBUG;
2463        }
2464    
2465        if (ARG_TRELLIS) {
2466            xvid_enc_frame.vop_flags |= XVID_VOP_TRELLISQUANT;
2467        }
2468    
2469            /* Frame type -- taken from function call parameter */
2470            /* Sometimes we might want to force the last frame to be a P Frame */
2471            xvid_enc_frame.type = *stats_type;
2472    
2473            /* Force the right quantizer -- It is internally managed by RC plugins */
2474            xvid_enc_frame.quant = 0;
2475    
2476            if (ARG_CHROMAME)
2477                    xvid_enc_frame.motion |= XVID_ME_CHROMA_PVOP + XVID_ME_CHROMA_BVOP;
2478    
2479            /* Set up motion estimation flags */
2480            xvid_enc_frame.motion |= motion_presets[ARG_QUALITY];
2481    
2482            if (ARG_TURBO)
2483                    xvid_enc_frame.motion |= XVID_ME_FASTREFINE16 | XVID_ME_FASTREFINE8 |
2484                                                                     XVID_ME_SKIP_DELTASEARCH | XVID_ME_FAST_MODEINTERPOLATE |
2485                                                                     XVID_ME_BFRAME_EARLYSTOP;
2486    
2487            if (ARG_BVHQ)
2488                    xvid_enc_frame.vop_flags |= XVID_VOP_RD_BVOP;
2489    
2490            if (ARG_QMETRIC == 1)
2491                    xvid_enc_frame.vop_flags |= XVID_VOP_RD_PSNRHVSM;
2492    
2493            switch (ARG_VHQMODE) /* this is the same code as for vfw */
2494                  {                  {
2495                  case 0:          case 1: /* VHQ_MODE_DECISION */
2496                          Pframes++;                  xvid_enc_frame.vop_flags |= XVID_VOP_MODEDECISION_RD;
2497                          break;                          break;
2498                  case 1:  
2499                          Iframes++;          case 2: /* VHQ_LIMITED_SEARCH */
2500                    xvid_enc_frame.vop_flags |= XVID_VOP_MODEDECISION_RD;
2501                    xvid_enc_frame.motion |= XVID_ME_HALFPELREFINE16_RD;
2502                    xvid_enc_frame.motion |= XVID_ME_QUARTERPELREFINE16_RD;
2503                    break;
2504    
2505            case 3: /* VHQ_MEDIUM_SEARCH */
2506                    xvid_enc_frame.vop_flags |= XVID_VOP_MODEDECISION_RD;
2507                    xvid_enc_frame.motion |= XVID_ME_HALFPELREFINE16_RD;
2508                    xvid_enc_frame.motion |= XVID_ME_HALFPELREFINE8_RD;
2509                    xvid_enc_frame.motion |= XVID_ME_QUARTERPELREFINE16_RD;
2510                    xvid_enc_frame.motion |= XVID_ME_QUARTERPELREFINE8_RD;
2511                    xvid_enc_frame.motion |= XVID_ME_CHECKPREDICTION_RD;
2512                          break;                          break;
2513                  case 2:  
2514            case 4: /* VHQ_WIDE_SEARCH */
2515                    xvid_enc_frame.vop_flags |= XVID_VOP_MODEDECISION_RD;
2516                    xvid_enc_frame.motion |= XVID_ME_HALFPELREFINE16_RD;
2517                    xvid_enc_frame.motion |= XVID_ME_HALFPELREFINE8_RD;
2518                    xvid_enc_frame.motion |= XVID_ME_QUARTERPELREFINE16_RD;
2519                    xvid_enc_frame.motion |= XVID_ME_QUARTERPELREFINE8_RD;
2520                    xvid_enc_frame.motion |= XVID_ME_CHECKPREDICTION_RD;
2521                    xvid_enc_frame.motion |= XVID_ME_EXTSEARCH_RD;
2522                    break;
2523    
2524                  default:                  default:
                         Bframes++;  
2525                          break;                          break;
2526                  }                  }
2527    
2528            /* Not sure what this does */
2529            // force keyframe spacing in 2-pass 1st pass
2530            if (ARG_QUALITY == 0)
2531                    xvid_enc_frame.type = XVID_TYPE_IVOP;
2532    
2533            /* frame-based stuff */
2534            apply_zone_modifiers(&xvid_enc_frame, framenum);
2535    
2536    
2537            /* Encode the frame */
2538            ret = xvid_encore(enc_handle, XVID_ENC_ENCODE, &xvid_enc_frame,
2539                                              &xvid_enc_stats);
2540    
2541            *key = (xvid_enc_frame.out_flags & XVID_KEYFRAME);
2542            *stats_type = xvid_enc_stats.type;
2543            *stats_quant = xvid_enc_stats.quant;
2544            *stats_length = xvid_enc_stats.length;
2545            sse[0] = xvid_enc_stats.sse_y;
2546            sse[1] = xvid_enc_stats.sse_u;
2547            sse[2] = xvid_enc_stats.sse_v;
2548    
2549            return (ret);
2550          }          }
2551    
2552          fprintf(stderr,"Avg: enctime %5.2f ms, %5.2f fps, filesize =%d\n",  void
2553                  1000*totalenctime, 1./totalenctime, totalsize);  sort_zones(zone_t * zones, int zone_num, int * sel)
2554    {
2555            int i, j;
2556            zone_t tmp;
2557            for (i = 0; i < zone_num; i++) {
2558                    int cur = i;
2559                    int min_f = zones[i].frame;
2560                    for (j = i + 1; j < zone_num; j++) {
2561                            if (zones[j].frame < min_f) {
2562                                    min_f = zones[j].frame;
2563                                    cur = j;
2564                            }
2565                    }
2566                    if (cur != i) {
2567                            tmp = zones[i];
2568                            zones[i] = zones[cur];
2569                            zones[cur] = tmp;
2570                            if (i == *sel) *sel = cur;
2571                            else if (cur == *sel) *sel = i;
2572                    }
2573            }
2574    }
2575    
2576  /*********************************************************************/  /* constant-quant zones for fixed quant encoding */
2577  /*                         XviD PART  Stop                           */  static void
2578  /*********************************************************************/  prepare_cquant_zones() {
2579    
2580  release_all:          int i = 0;
2581            if (NUM_ZONES == 0 || ZONES[0].frame != 0) {
2582                    /* first zone does not start at frame 0 or doesn't exist */
2583    
2584                    if (NUM_ZONES >= MAX_ZONES) NUM_ZONES--; /* we sacrifice last zone */
2585    
2586                    ZONES[NUM_ZONES].frame = 0;
2587                    ZONES[NUM_ZONES].mode = XVID_ZONE_QUANT;
2588                    ZONES[NUM_ZONES].modifier = ARG_CQ;
2589                    ZONES[NUM_ZONES].type = XVID_TYPE_AUTO;
2590                    ZONES[NUM_ZONES].greyscale = 0;
2591                    ZONES[NUM_ZONES].chroma_opt = 0;
2592                    ZONES[NUM_ZONES].bvop_threshold = 0;
2593                    ZONES[NUM_ZONES].cartoon_mode = 0;
2594                    NUM_ZONES++;
2595    
2596                    sort_zones(ZONES, NUM_ZONES, &i);
2597            }
2598    
2599            /* step 2: let's change all weight zones into quant zones */
2600    
2601            for(i = 0; i < NUM_ZONES; i++)
2602                    if (ZONES[i].mode == XVID_ZONE_WEIGHT) {
2603                            ZONES[i].mode = XVID_ZONE_QUANT;
2604                            ZONES[i].modifier = (100*ARG_CQ) / ZONES[i].modifier;
2605                    }
2606    }
2607    
2608          if (enc_handle)  /* full first pass zones */
2609    static void
2610    prepare_full1pass_zones() {
2611    
2612            int i = 0;
2613            if (NUM_ZONES == 0 || ZONES[0].frame != 0) {
2614                    /* first zone does not start at frame 0 or doesn't exist */
2615    
2616                    if (NUM_ZONES >= MAX_ZONES) NUM_ZONES--; /* we sacrifice last zone */
2617    
2618                    ZONES[NUM_ZONES].frame = 0;
2619                    ZONES[NUM_ZONES].mode = XVID_ZONE_QUANT;
2620                    ZONES[NUM_ZONES].modifier = 200;
2621                    ZONES[NUM_ZONES].type = XVID_TYPE_AUTO;
2622                    ZONES[NUM_ZONES].greyscale = 0;
2623                    ZONES[NUM_ZONES].chroma_opt = 0;
2624                    ZONES[NUM_ZONES].bvop_threshold = 0;
2625                    ZONES[NUM_ZONES].cartoon_mode = 0;
2626                    NUM_ZONES++;
2627    
2628                    sort_zones(ZONES, NUM_ZONES, &i);
2629            }
2630    
2631            /* step 2: let's change all weight zones into quant zones */
2632    
2633            for(i = 0; i < NUM_ZONES; i++)
2634                    if (ZONES[i].mode == XVID_ZONE_WEIGHT) {
2635                            ZONES[i].mode = XVID_ZONE_QUANT;
2636                            ZONES[i].modifier = 200;
2637                    }
2638    }
2639    
2640    static void apply_zone_modifiers(xvid_enc_frame_t * frame, int framenum)
2641          {          {
2642                  status = enc_stop();          int i;
2643                  if (status)  
2644                          fprintf(stderr,"Encore RELEASE problem return value %d\n", status);          for (i=0; i<NUM_ZONES && ZONES[i].frame <= framenum; i++) ;
2645    
2646            if (--i < 0) return; /* there are no zones, or we're before the first zone */
2647    
2648            if (framenum == ZONES[i].frame)
2649                    frame->type = ZONES[i].type;
2650    
2651            if (ZONES[i].greyscale) {
2652                    frame->vop_flags |= XVID_VOP_GREYSCALE;
2653          }          }
2654    
2655  free_all_memory:          if (ZONES[i].chroma_opt) {
2656          free(divx_buffer);                  frame->vop_flags |= XVID_VOP_CHROMAOPT;
2657          free(in_buffer);          }
2658    
2659    return 0;          if (ZONES[i].cartoon_mode) {
2660                    frame->vop_flags |= XVID_VOP_CARTOON;
2661                    frame->motion |= XVID_ME_DETECT_STATIC_MOTION;
2662            }
2663    
2664            if (ARG_MAXBFRAMES) {
2665                    frame->bframe_threshold = ZONES[i].bvop_threshold;
2666            }
2667    }
2668    
2669    void removedivxp(char *buf, int bufsize) {
2670            int i;
2671            char* userdata;
2672    
2673            for (i=0; i <= (bufsize-sizeof(userdata_start_code)); i++) {
2674                    if (memcmp((void*)userdata_start_code, (void*)(buf+i), strlen(userdata_start_code))==0) {
2675                            if ((userdata = strstr(buf+i+4, "DivX"))!=NULL) {
2676                                    userdata[strlen(userdata)-1] = '\0';
2677                                    return;
2678                            }
2679                    }
2680            }
2681  }  }

Legend:
Removed from v.376  
changed lines
  Added in v.1909

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