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

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

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