[svn] / trunk / xvidcore / examples / xvid_encraw.c Repository:
ViewVC logotype

Diff of /trunk/xvidcore/examples/xvid_encraw.c

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

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

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

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