[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

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

Legend:
Removed from v.1676  
changed lines
  Added in v.1886

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