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

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

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

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

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

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