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

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

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