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

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

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