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

Legend:
Removed from v.561  
changed lines
  Added in v.2074

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