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

Legend:
Removed from v.851  
changed lines
  Added in v.1894

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