[svn] / branches / release-1_3-branch / xvidcore / examples / xvid_encraw.c Repository:
ViewVC logotype

Diff of /branches/release-1_3-branch/xvidcore/examples/xvid_encraw.c

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

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

Legend:
Removed from v.1683  
changed lines
  Added in v.2061

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