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

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

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

revision 376, Sat Aug 17 20:03:36 2002 UTC revision 1623, Tue Jul 5 20:39:52 2005 UTC
# Line 1  Line 1 
1  /**************************************************************************  /*****************************************************************************
2   *   *
3   *      XVID MPEG-4 VIDEO CODEC - Example for encoding and decoding   *  XVID MPEG-4 VIDEO CODEC
4     *  - Console based test application  -
5     *
6     *  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 14  Line 19 
19   *   *
20   *      You should have received a copy of the GNU General Public License   *      You should have received a copy of the GNU General Public License
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., 675 Mass Ave, Cambridge, MA 02139, USA.   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
23   *   *
24   *************************************************************************/   * $Id: xvid_encraw.c,v 1.18 2005-07-05 20:39:52 chl Exp $
   
 /************************************************************************  
25   *   *
26   *  Speed test routine for XviD using the XviD-API   ****************************************************************************/
27   *  (C) Christoph Lampert, 2002/08/17  
28    /*****************************************************************************
29     *  Application notes :
30   *   *
31   *  A sequence of YUV pics in PGM or RAW file format is encoded and the   *  A sequence of raw YUV I420 pics or YUV I420 PGM file format is encoded
32   *  raw MPEG-4 stream is written to stdout.   *  The speed is measured and frames' PSNR are taken from core.
  *  The encoding speed of this is measured, too.  
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, so with UN*X you simply compile by   *  and maths-lib.
  *  
  *   gcc xvid_encraw.c -lxvidcore -lm -o xvid_encraw  
  *  
  *  Run without or with illegal parameters, then PGM input input is read  
  *  from stdin.  
  *  
  *  Parameters are: xvid_stat XDIM YDIM QUALITY BITRATE/QUANTIZER FRAMERATE  
  *  
  *  if XDIM or YDIM are illegal (e.g. 0), they are ignored and input is  
  *  considered to be PGM. Otherwise (X and Y both greater than 0) raw YUV  
  *  is expected, as e.g. the standard MPEG test-files, like "foreman"  
  *  
  *  0 <= QUALITY <= 6  (default 5)  
36   *   *
37   *  BITRATE is in kbps (default 900),   *  Use ./xvid_encraw -help for a list of options
  *      if BITRATE<32, then value is taken is fixed QUANTIZER  
  *  
  *  FRAMERATE is a float (with or without decimal dot), default is 25.00  
  *  
  *  input/output and m4v-output is saved, if corresponding flags are set  
  *  
  *  PGM input must in a very specific format, see read_pgmheader  
  *  it can be generated e.g. from MPEG2 by    mpeg2dec -o pgmpipe  
  *  
  ************************************************************************/  
   
 /************************************************************************  
  *  
  *  For EXAMPLES how to use this, see the seperate file xvid_stat.examples  
38   *   *
39   ************************************************************************/   ************************************************************************/
40    
41  #include <stdio.h>  #include <stdio.h>
42  #include <stdlib.h>  #include <stdlib.h>
43  #include <math.h>               // needed for log10  #include <string.h>
44  #include <sys/time.h>           // only needed for gettimeofday  #include <math.h>
45    #ifndef WIN32
46    #include <sys/time.h>
47    #else
48    #include <time.h>
49    #endif
50    
51    #include "xvid.h"
52    
53  #include "../src/xvid.h"                /* comes with XviD */  #undef READ_PNM
54    
55    /*****************************************************************************
56     *                            Quality presets
57     ****************************************************************************/
58    
59    static const int motion_presets[] = {
60            /* quality 0 */
61            0,
62    
63            /* quality 1 */
64            XVID_ME_ADVANCEDDIAMOND16,
65    
66            /* quality 2 */
67            XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16,
68    
69            /* quality 3 */
70            XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16 |
71            XVID_ME_ADVANCEDDIAMOND8 | XVID_ME_HALFPELREFINE8,
72    
73            /* quality 4 */
74            XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16 |
75            XVID_ME_ADVANCEDDIAMOND8 | XVID_ME_HALFPELREFINE8 |
76            XVID_ME_CHROMA_PVOP | XVID_ME_CHROMA_BVOP,
77    
78            /* quality 5 */
79            XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16 |
80            XVID_ME_ADVANCEDDIAMOND8 | XVID_ME_HALFPELREFINE8 |
81            XVID_ME_CHROMA_PVOP | XVID_ME_CHROMA_BVOP,
82    
83            /* quality 6 */
84            XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16 | XVID_ME_EXTSEARCH16 |
85            XVID_ME_ADVANCEDDIAMOND8 | XVID_ME_HALFPELREFINE8 | XVID_ME_EXTSEARCH8 |
86            XVID_ME_CHROMA_PVOP | XVID_ME_CHROMA_BVOP,
87    
 int motion_presets[7] = {  
         0,                                                              // Q 0  
         PMV_EARLYSTOP16,                                                // Q 1  
         PMV_EARLYSTOP16,                                                // Q 2  
         PMV_EARLYSTOP16 | PMV_HALFPELREFINE16,                          // Q 3  
         PMV_EARLYSTOP16 | PMV_HALFPELREFINE16,                          // Q 4  
         PMV_EARLYSTOP16 | PMV_HALFPELREFINE16 | PMV_EARLYSTOP8          // Q 5  
                         | PMV_HALFPELREFINE8,  
         PMV_EARLYSTOP16 | PMV_HALFPELREFINE16 | PMV_EXTSEARCH16         // Q 6  
                         | PMV_USESQUARES16 | PMV_EARLYSTOP8 | PMV_HALFPELREFINE8  
88          };          };
89    #define ME_ELEMENTS (sizeof(motion_presets)/sizeof(motion_presets[0]))
90    
91  int general_presets[7] = {  static const int vop_presets[] = {
92          XVID_H263QUANT, /* or use XVID_MPEGQUANT */             // Q 0          /* quality 0 */
93          XVID_MPEGQUANT,                                         // Q 1          0,
         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  
94    
95            /* quality 1 */
96            0,
97    
98  /* my default values for encoding */          /* quality 2 */
99            XVID_VOP_HALFPEL,
100    
101  #define ABS_MAXFRAMENR 9999               // max number of frames          /* quality 3 */
102            XVID_VOP_HALFPEL | XVID_VOP_INTER4V,
103    
104  int ARG_BITRATE=900;          /* quality 4 */
105  int ARG_QUANTI=0;          XVID_VOP_HALFPEL | XVID_VOP_INTER4V,
106    
107  int ARG_QUALITY =6;          /* quality 5 */
108  int ARG_MINQUANT=1;          XVID_VOP_HALFPEL | XVID_VOP_INTER4V |
109  int ARG_MAXQUANT=31;          XVID_VOP_TRELLISQUANT,
 float ARG_FRAMERATE=25.00;  
110    
111  int ARG_MAXFRAMENR=ABS_MAXFRAMENR;          /* quality 6 */
112            XVID_VOP_HALFPEL | XVID_VOP_INTER4V |
113            XVID_VOP_TRELLISQUANT | XVID_VOP_HQACPRED,
114    
115  #ifdef BFRAMES  };
116    #define VOP_ELEMENTS (sizeof(vop_presets)/sizeof(vop_presets[0]))
117    
118  int ARG_MAXBFRAMES=1;  /*****************************************************************************
119  int ARG_BQUANTRATIO=200;   *                     Command line global variables
120     ****************************************************************************/
121    
122    #define MAX_ZONES   64
123    
124    static xvid_enc_zone_t ZONES[MAX_ZONES];
125    static int NUM_ZONES = 0;
126    
127    /* Maximum number of frames to encode */
128    #define ABS_MAXFRAMENR 9999
129    
130    static int ARG_STATS = 0;
131    static int ARG_DUMP = 0;
132    static int ARG_LUMIMASKING = 0;
133    static int ARG_BITRATE = 0;
134    static int ARG_SINGLE = 0;
135    static char *ARG_PASS1 = 0;
136    static char *ARG_PASS2 = 0;
137    static int ARG_QUALITY = ME_ELEMENTS - 1;
138    static float ARG_FRAMERATE = 25.00f;
139    static int ARG_MAXFRAMENR = ABS_MAXFRAMENR;
140    static int ARG_MAXKEYINTERVAL = 0;
141    static char *ARG_INPUTFILE = NULL;
142    static int ARG_INPUTTYPE = 0;
143    static int ARG_SAVEMPEGSTREAM = 0;
144    static int ARG_SAVEINDIVIDUAL = 0;
145    static char *ARG_OUTPUTFILE = NULL;
146    static int XDIM = 0;
147    static int YDIM = 0;
148    static int ARG_BQRATIO = 150;
149    static int ARG_BQOFFSET = 100;
150    static int ARG_MAXBFRAMES = 0;
151    static int ARG_PACKED = 0;
152    static int ARG_DEBUG = 0;
153    static int ARG_VOPDEBUG = 0;
154    static int ARG_GREYSCALE = 0;
155    static int ARG_GMC = 0;
156    static int ARG_INTERLACING = 0;
157    static int ARG_QPEL = 0;
158    static int ARG_CLOSED_GOP = 0;
159    
160    #ifndef READ_PNM
161    #define IMAGE_SIZE(x,y) ((x)*(y)*3/2)
162    #else
163    #define IMAGE_SIZE(x,y) ((x)*(y)*3)
164  #endif  #endif
165    
166  #define MAX(A,B) ( ((A)>(B)) ? (A) : (B) )  #define MAX(A,B) ( ((A)>(B)) ? (A) : (B) )
167  #define SMALL_EPS 1e-10  #define SMALL_EPS (1e-10)
168    
169  /* these are global variables. Not very elegant, but easy, and this is an easy program */  #define SWAP(a) ( (((a)&0x000000ff)<<24) | (((a)&0x0000ff00)<<8) | \
170                      (((a)&0x00ff0000)>>8)  | (((a)&0xff000000)>>24) )
171    
172  int XDIM=0;  /****************************************************************************
173  int YDIM=0;     // will be set when reading first image   *                     Nasty global vars ;-)
174  int i,filenr = 0;   ***************************************************************************/
175    
176  int save_m4v_flag = 1;          // output MPEG4-bytestream?  static int i;
 int save_ref_flag = 0;          // save input image  
177    
178  int pgmflag = 0;                // a flag, if input is in PGM format, overwritten in init-phase  /* the path where to save output */
179  char filepath[256] = "./";      // the path where to save output  static char filepath[256] = "./";
180    
181  void *enc_handle = NULL;                // internal structures (handles) for encoding  /* Internal structures (handles) for encoding and decoding */
182    static void *enc_handle = NULL;
183    
184    /*****************************************************************************
185     *               Local prototypes
186     ****************************************************************************/
187    
188  /*********************************************************************/  /* Prints program usage message */
189  /*                     "statistical" functions                       */  static void usage();
 /*                                                                   */  
 /*  these are not needed for encoding or decoding, but for measuring */  
 /*  time and quality, there in nothing specific to XviD in these     */  
 /*                                                                   */  
 /*********************************************************************/  
190    
191  double msecond()  /* Statistical functions */
192  /* return the current time in seconds(!)  */  static double msecond();
 {  
         struct timeval  tv;  
         gettimeofday(&tv, 0);  
         return tv.tv_sec + tv.tv_usec * 1.0e-6;  
 }  
193    
194  /*********************************************************************/  /* PGM related functions */
195  /*                    input and output functions                     */  #ifndef READ_PNM
196  /*                                                                   */  static int read_pgmheader(FILE * handle);
197  /* the are small and simple routines to read and write PGM and YUV   */  static int read_pgmdata(FILE * handle,
198  /* image. It's just for convenience, again nothing specific to XviD  */                                                  unsigned char *image);
199  /*                                                                   */  #else
200  /*********************************************************************/  static int read_pnmheader(FILE * handle);
201    static int read_pnmdata(FILE * handle,
202                                                    unsigned char *image);
203    #endif
204    static int read_yuvdata(FILE * handle,
205                                                    unsigned char *image);
206    
207  int read_pgmheader(FILE* handle)  /* Encoder related functions */
208    static int enc_init(int use_assembler);
209    static int enc_stop();
210    static int enc_main(unsigned char *image,
211                                            unsigned char *bitstream,
212                                            int *key,
213                                            int *stats_type,
214                                            int *stats_quant,
215                                            int *stats_length,
216                                            int stats[3]);
217    
218    /*****************************************************************************
219     *               Main function
220     ****************************************************************************/
221    
222    int
223    main(int argc,
224             char *argv[])
225  {  {
         int bytes,xsize,ysize,depth;  
         char dummy[2];  
226    
227          bytes = fread(dummy,1,2,handle);          unsigned char *mp4_buffer = NULL;
228            unsigned char *in_buffer = NULL;
229            unsigned char *out_buffer = NULL;
230    
231          if ( (bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '5' ))          double enctime;
232                  return 1;          double totalenctime = 0.;
233          fscanf(handle,"%d %d %d",&xsize,&ysize,&depth);          float totalPSNR[3] = {0., 0., 0.};
         if ( (xsize > 1440) || (ysize > 2880 ) || (depth != 255) )  
         {  
                 return 2;  
         }  
         if ( (XDIM==0) || (YDIM==0) )  
         {       XDIM=xsize;  
                 YDIM=ysize;  
         }  
234    
235          return 0;          int totalsize;
236  }          int result;
237            int m4v_size;
238            int key;
239            int stats_type;
240            int stats_quant;
241            int stats_length;
242            int use_assembler = 1;  // this default changed!
243    
244  int read_pgmdata(FILE* handle, unsigned char *image)          int input_num;
245  {          int output_num;
246          int i,status;  
247          char dummy;          char filename[256];
248    
249          unsigned char* buff1_ptr2 = image + XDIM*YDIM;          FILE *in_file = stdin;
250          unsigned char* buff1_ptr3 = image + XDIM*YDIM + XDIM/2*YDIM/2;          FILE *out_file = NULL;
251    
252          fread(image,XDIM*YDIM,1,stdin); // read Y component of picture          printf("xvid_encraw - raw mpeg4 bitstream encoder ");
253            printf("written by Christoph Lampert 2002-2003\n\n");
254    
255          for (i=0;i<YDIM/2;i++)          /* Is there a dumb XviD coder ? */
256          {          if(ME_ELEMENTS != VOP_ELEMENTS) {
257                  fread(buff1_ptr2,XDIM/2,1,stdin);        // read U                  fprintf(stderr, "Presets' arrays should have the same number of elements -- Please fill a bug to xvid-devel@xvid.org\n");
258                  buff1_ptr2 += XDIM/2;                  return(-1);
259                  fread(buff1_ptr3,XDIM/2,1,stdin);        // read V          }
260                  buff1_ptr3 += XDIM/2;  
261    /*****************************************************************************
262     *                            Command line parsing
263     ****************************************************************************/
264    
265            for (i = 1; i < argc; i++) {
266    
267                    if (strcmp("-asm", argv[i]) == 0) {
268                            use_assembler = 1;
269                    } else if (strcmp("-noasm", argv[i]) == 0) {
270                            use_assembler = 0;
271                    } else if (strcmp("-w", argv[i]) == 0 && i < argc - 1) {
272                            i++;
273                            XDIM = atoi(argv[i]);
274                    } else if (strcmp("-h", argv[i]) == 0 && i < argc - 1) {
275                            i++;
276                            YDIM = atoi(argv[i]);
277            } else if (strcmp("-bitrate", argv[i]) == 0 && i < argc - 1) {
278                            i++;
279                            ARG_BITRATE = atoi(argv[i]);
280                    } else if (strcmp("-single", argv[i]) == 0) {
281                            ARG_SINGLE = 1;
282                    } else if (strcmp("-pass1", argv[i]) == 0 && i < argc - 1) {
283                            i++;
284                            ARG_PASS1 = argv[i];
285                    } else if (strcmp("-pass2", argv[i]) == 0 && i < argc - 1) {
286                            i++;
287                            ARG_PASS2 = argv[i];
288                    } else if (strcmp("-max_bframes", argv[i]) == 0 && i < argc - 1) {
289                            i++;
290                            ARG_MAXBFRAMES = atoi(argv[i]);
291                    } else if (strcmp("-packed", argv[i]) == 0) {
292                            ARG_PACKED = 1;
293                    } else if (strcmp("-bquant_ratio", argv[i]) == 0 && i < argc - 1) {
294                            i++;
295                            ARG_BQRATIO = atoi(argv[i]);
296                    } else if (strcmp("-bquant_offset", argv[i]) == 0 && i < argc - 1) {
297                            i++;
298                            ARG_BQOFFSET = atoi(argv[i]);
299    
300            } else if ((strcmp("-zq", argv[i]) == 0 || strcmp("-zw", argv[i]) == 0) && i < argc - 2) {
301    
302                if (NUM_ZONES >= MAX_ZONES) {
303                    fprintf(stderr,"warning: too many zones; zone ignored\n");
304                    continue;
305                }
306                ZONES[NUM_ZONES].mode = strcmp("-zq", argv[i])==0 ? XVID_ZONE_QUANT : XVID_ZONE_WEIGHT;
307                            i++;
308                ZONES[NUM_ZONES].frame = atoi(argv[i]);
309                i++;
310                ZONES[NUM_ZONES].increment  = (int)(atof(argv[i]) * 100);
311                ZONES[NUM_ZONES].base  = 100;
312                NUM_ZONES++;
313    
314                    } else if (strcmp("-quality", argv[i]) == 0 && i < argc - 1) {
315                            i++;
316                            ARG_QUALITY = atoi(argv[i]);
317                    } else if (strcmp("-framerate", argv[i]) == 0 && i < argc - 1) {
318                            i++;
319                            ARG_FRAMERATE = (float) atof(argv[i]);
320                    } else if (strcmp("-max_key_interval", argv[i]) == 0 && i < argc - 1) {
321                            i++;
322                            ARG_MAXKEYINTERVAL = atoi(argv[i]);
323                    } else if (strcmp("-i", argv[i]) == 0 && i < argc - 1) {
324                            i++;
325                            ARG_INPUTFILE = argv[i];
326                    } else if (strcmp("-stats", argv[i]) == 0) {
327                            ARG_STATS = 1;
328                    } else if (strcmp("-dump", argv[i]) == 0) {
329                            ARG_DUMP = 1;
330                    } else if (strcmp("-lumimasking", argv[i]) == 0) {
331                            ARG_LUMIMASKING = 1;
332                    } else if (strcmp("-type", argv[i]) == 0 && i < argc - 1) {
333                            i++;
334                            ARG_INPUTTYPE = atoi(argv[i]);
335                    } else if (strcmp("-frames", argv[i]) == 0 && i < argc - 1) {
336                            i++;
337                            ARG_MAXFRAMENR = atoi(argv[i]);
338                    } else if (strcmp("-save", argv[i]) == 0) {
339                            ARG_SAVEMPEGSTREAM = 1;
340                            ARG_SAVEINDIVIDUAL = 1;
341                    } else if (strcmp("-debug", argv[i]) == 0) {
342                            i++;
343                if (sscanf(argv[i],"0x%x", &ARG_DEBUG) || sscanf(argv[i],"%d", &ARG_DEBUG)) ;
344                    } else if (strcmp("-o", argv[i]) == 0 && i < argc - 1) {
345                            ARG_SAVEMPEGSTREAM = 1;
346                            i++;
347                            ARG_OUTPUTFILE = argv[i];
348                    } else if (strcmp("-vop_debug", argv[i]) == 0) {
349                            ARG_VOPDEBUG = 1;
350                    }
351                    else if (strcmp("-grey", argv[i]) == 0) {
352                            ARG_GREYSCALE = 1;
353                    }
354                    else if (strcmp("-qpel", argv[i]) == 0) {
355                            ARG_QPEL = 1;
356                    } else if (strcmp("-gmc", argv[i]) == 0) {
357                            ARG_GMC = 1;
358                    } else if (strcmp("-interlaced", argv[i]) == 0) {
359                            ARG_INTERLACING = 1;
360                    } else if (strcmp("-closed_gop", argv[i]) == 0) {
361                            ARG_CLOSED_GOP = 1;
362                    } else if (strcmp("-help", argv[i])) {
363                            usage();
364                            return (0);
365                    } else {
366                            usage();
367                            exit(-1);
368                    }
369    
370            }
371    
372    /*****************************************************************************
373     *                            Arguments checking
374     ****************************************************************************/
375    
376            if (XDIM <= 0 || XDIM >= 4096 || YDIM <= 0 || YDIM >= 4096) {
377                    fprintf(stderr,
378                                    "Trying to retreive width and height from PGM header\n");
379                    ARG_INPUTTYPE = 1;              /* pgm */
380            }
381    
382            if (ARG_QUALITY < 0 ) {
383                    ARG_QUALITY = 0;
384            } else if (ARG_QUALITY >= ME_ELEMENTS) {
385                    ARG_QUALITY = ME_ELEMENTS - 1;
386            }
387    
388            if (ARG_FRAMERATE <= 0) {
389                    fprintf(stderr, "Wrong Framerate %s \n", argv[5]);
390                    return (-1);
391            }
392    
393            if (ARG_MAXFRAMENR <= 0) {
394                    fprintf(stderr, "Wrong number of frames\n");
395                    return (-1);
396            }
397    
398            if (ARG_INPUTFILE == NULL || strcmp(ARG_INPUTFILE, "stdin") == 0) {
399                    in_file = stdin;
400            } else {
401    
402                    in_file = fopen(ARG_INPUTFILE, "rb");
403                    if (in_file == NULL) {
404                            fprintf(stderr, "Error opening input file %s\n", ARG_INPUTFILE);
405                            return (-1);
406                    }
407            }
408    
409            if (ARG_INPUTTYPE) {
410    #ifndef READ_PNM
411                    if (read_pgmheader(in_file)) {
412    #else
413                    if (read_pnmheader(in_file)) {
414    #endif
415                            fprintf(stderr,
416                                            "Wrong input format, I want YUV encapsulated in PGM\n");
417                            return (-1);
418          }          }
         fread(&dummy,1,1,handle);       //  I don't know why, but this seems needed  
         return 0;  
419  }  }
420    
421  int read_yuvdata(FILE* handle, unsigned char *image)          /* now we know the sizes, so allocate memory */
422  {       int i;          in_buffer = (unsigned char *) malloc(IMAGE_SIZE(XDIM, YDIM));
423          char dummy;          if (!in_buffer)
424                    goto free_all_memory;
425    
426          unsigned char* buff1_ptr2 = image + XDIM*YDIM;          /* this should really be enough memory ! */
427          unsigned char* buff1_ptr3 = image + XDIM*YDIM + XDIM/2*YDIM/2;          mp4_buffer = (unsigned char *) malloc(IMAGE_SIZE(XDIM, YDIM) * 2);
428            if (!mp4_buffer)
429                    goto free_all_memory;
430    
431          if (fread(image,XDIM,YDIM*3/2,stdin) != YDIM*3/2)  /*****************************************************************************
432                  return 1;   *                            XviD PART  Start
433          else   ****************************************************************************/
434                  return 0;  
435    
436            result = enc_init(use_assembler);
437            if (result) {
438                    fprintf(stderr, "Encore INIT problem, return value %d\n", result);
439                    goto release_all;
440  }  }
441    
442  int write_pgm(char *filename, unsigned char *image)  /*****************************************************************************
443  {   *                            Main loop
444          FILE *filehandle;   ****************************************************************************/
445          filehandle=fopen(filename,"wb");  
446          if (filehandle)          if (ARG_SAVEMPEGSTREAM && ARG_OUTPUTFILE) {
447          {  
448                  fprintf(filehandle,"P5\n\n");           //                  if ((out_file = fopen(ARG_OUTPUTFILE, "w+b")) == NULL) {
449                  fprintf(filehandle,"%d %d 255\n",XDIM,YDIM*3/2);                          fprintf(stderr, "Error opening output file %s\n", ARG_OUTPUTFILE);
450                  fwrite(image,XDIM,YDIM*3/2,filehandle);                          goto release_all;
                 fclose(filehandle);  
                 return 0;  
451          }          }
452          else  
453                  return 1;          } else {
454                    out_file = NULL;
455  }  }
456    
457  /*********************************************************************/  /*****************************************************************************
458  /* Routines for encoding: init encoder, frame step, release encoder  */   *                       Encoding loop
459  /*********************************************************************/   ****************************************************************************/
460    
461  #define FRAMERATE_INCR 1001          totalsize = 0;
462    
463            result = 0;
464    
465  int enc_init(int use_assembler)          input_num = 0;                          /* input frame counter */
466  {       /* initialize encoder for first use, pass all needed parameters to the codec */          output_num = 0;                         /* output frame counter */
467          int xerr;  
468            do {
469    
470          XVID_INIT_PARAM xinit;                  char *type;
471          XVID_ENC_PARAM xparam;                  int sse[3];
472    
473          if(use_assembler)                  if (input_num >= ARG_MAXFRAMENR) {
474                            result = 1;
475                    }
476    
477  #ifdef ARCH_IA64                  if (!result) {
478                  xinit.cpu_flags = XVID_CPU_FORCE | XVID_CPU_IA64;                          if (ARG_INPUTTYPE) {
479                                    /* read PGM data (YUV-format) */
480    #ifndef READ_PNM
481                                    result = read_pgmdata(in_file, in_buffer);
482  #else  #else
483                  xinit.cpu_flags = 0;                                  result = read_pnmdata(in_file, in_buffer);
484  #endif  #endif
485                            } else {
486                                    /* read raw data (YUV-format) */
487                                    result = read_yuvdata(in_file, in_buffer);
488                            }
489                    }
490    
491          else  /*****************************************************************************
492                  xinit.cpu_flags = XVID_CPU_FORCE;   *                       Encode and decode this frame
493     ****************************************************************************/
494    
495          xvid_init(NULL, 0, &xinit, NULL);                  enctime = msecond();
496                    m4v_size =
497                            enc_main(!result ? in_buffer : 0, mp4_buffer, &key, &stats_type,
498                                             &stats_quant, &stats_length, sse);
499                    enctime = msecond() - enctime;
500    
501          xparam.width = XDIM;                  /* Write the Frame statistics */
502          xparam.height = YDIM;  
503          if ((ARG_FRAMERATE - (int)ARG_FRAMERATE) < SMALL_EPS)                  printf("%5d: key=%i, time= %6.0f, len= %7d", !result ? input_num : -1,
504          {                             key, (float) enctime, (int) m4v_size);
505                  xparam.fincr = 1;  
506                  xparam.fbase = (int)ARG_FRAMERATE;                  if (stats_type > 0) {   /* !XVID_TYPE_NOTHING */
507          }  
508          else                          switch (stats_type) {
509          {                          case XVID_TYPE_IVOP:
510                  xparam.fincr = FRAMERATE_INCR;                                  type = "I";
511                  xparam.fbase = (int)(FRAMERATE_INCR * ARG_FRAMERATE);                                  break;
512                            case XVID_TYPE_PVOP:
513                                    type = "P";
514                                    break;
515                            case XVID_TYPE_BVOP:
516                                    type = "B";
517                                    break;
518                            case XVID_TYPE_SVOP:
519                                    type = "S";
520                                    break;
521                            default:
522                                    type = "U";
523                                    break;
524          }          }
         xparam.rc_reaction_delay_factor = 16;  
         xparam.rc_averaging_period = 100;  
         xparam.rc_buffer = 10;  
         xparam.rc_bitrate = ARG_BITRATE*1000;  
         xparam.min_quantizer = 1;  
         xparam.max_quantizer = 31;  
         xparam.max_key_interval = (int)ARG_FRAMERATE*10;  
525    
526  #ifdef BFRAMES                          printf(" | type=%s, quant= %2d, len= %7d", type, stats_quant,
527          xparam.global = XVID_GLOBAL_DX50BVOP;                                     stats_length);
         xparam.max_bframes = ARG_MAXBFRAMES;  
         xparam.bquant_ratio = ARG_BQUANTRATIO;  
         xparam.frame_drop_ratio=0;  
 #endif  
528    
529          /* I use a small value here, since will not encode whole movies,  #define SSE2PSNR(sse, width, height) ((!(sse))?0.0f : 48.131f - 10*(float)log10((float)(sse)/((float)((width)*(height)))))
                 but short clips */  
530    
531          xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xparam, NULL);                          if (ARG_STATS) {
532          enc_handle=xparam.handle;                                  printf(", psnr y = %2.2f, psnr u = %2.2f, psnr v = %2.2f",
533                                               SSE2PSNR(sse[0], XDIM, YDIM), SSE2PSNR(sse[1], XDIM / 2,
534                                                                                                                              YDIM / 2),
535                                               SSE2PSNR(sse[2], XDIM / 2, YDIM / 2));
536    
537          return xerr;                                  totalPSNR[0] += SSE2PSNR(sse[0], XDIM, YDIM);
538                                    totalPSNR[1] += SSE2PSNR(sse[1], XDIM/2, YDIM/2);
539                                    totalPSNR[2] += SSE2PSNR(sse[2], XDIM/2, YDIM/2);
540  }  }
541    
 int  enc_stop()  
 {       int xerr;  
   
         xerr = xvid_encore(enc_handle, XVID_ENC_DESTROY, NULL, NULL);  
         return xerr;  
542  }  }
543    #undef SSE2PSNR
544    
545                    printf("\n");
546    
547  int  enc_main(unsigned char* image, unsigned char* bitstream, int *streamlength, int* frametype)                  if (m4v_size < 0) {
548  {       int xerr;                          break;
549                    }
550    
551          XVID_ENC_FRAME xframe;                  /* Update encoding time stats */
552          XVID_ENC_STATS xstats;                  totalenctime += enctime;
553                    totalsize += m4v_size;
554    
555          xframe.bitstream = bitstream;  /*****************************************************************************
556          xframe.length = -1;     // this is written by the routine   *                       Save stream to file
557     ****************************************************************************/
558    
559          xframe.image = image;                  if (m4v_size > 0 && ARG_SAVEMPEGSTREAM) {
         xframe.colorspace = XVID_CSP_YV12;      // defined in <xvid.h>  
560    
561          xframe.intra = -1; // let the codec decide between I-frame (1) and P-frame (0)                          /* Save single files */
562                            if (ARG_SAVEINDIVIDUAL) {
563                                    FILE *out;
564                                    sprintf(filename, "%sframe%05d.m4v", filepath, output_num);
565                                    out = fopen(filename, "w+b");
566                                    fwrite(mp4_buffer, m4v_size, 1, out);
567                                    fclose(out);
568                                    output_num++;
569                            }
570    
571          xframe.quant = ARG_QUANTI;      // is quant != 0, use a fixed quant (and ignore bitrate)                          /* Save ES stream */
572                            if (ARG_OUTPUTFILE && out_file)
573                                    fwrite(mp4_buffer, 1, m4v_size, out_file);
574                    }
575    
576          xframe.motion = motion_presets[ARG_QUALITY];                  input_num++;
         xframe.general = general_presets[ARG_QUALITY];  
         xframe.quant_intra_matrix = xframe.quant_inter_matrix = NULL;  
577    
578  #ifdef BFRAMES                  /* Read the header if it's pgm stream */
579          xframe.bquant = 0;                  if (!result && ARG_INPUTTYPE)
580    #ifndef READ_PNM
581                            result = read_pgmheader(in_file);
582    #else
583                            result = read_pnmheader(in_file);
584  #endif  #endif
585            } while (1);
586    
         xerr = xvid_encore(enc_handle, XVID_ENC_ENCODE, &xframe, &xstats);  
587    
 /*              enc_result->is_key_frame = xframe.intra;  
                 enc_result->quantizer = xframe.quant;  
                 enc_result->total_bits = xframe.length * 8;  
                 enc_result->motion_bits = xstats.hlength * 8;  
                 enc_result->texture_bits = enc_result->total_bits - enc_result->motion_bits;  
 */  
588    
589  /*  This is statictical data, e.g. for 2-pass.  /*****************************************************************************
590      If you are not interested in any of this, you can use   *         Calculate totals and averages for output, print results
591          NULL instead of &xstats   ****************************************************************************/
592  */  
593          *frametype = xframe.intra;          printf("Tot: enctime(ms) =%7.2f,               length(bytes) = %7d\n",
594          *streamlength = xframe.length;                     totalenctime, (int) totalsize);
595    
596          return xerr;          if (input_num > 0) {
597                    totalsize /= input_num;
598                    totalenctime /= input_num;
599                    totalPSNR[0] /= input_num;
600                    totalPSNR[1] /= input_num;
601                    totalPSNR[2] /= input_num;
602            } else {
603                    totalsize = -1;
604                    totalenctime = -1;
605  }  }
606    
607  /*********************************************************************/          printf("Avg: enctime(ms) =%7.2f, fps =%7.2f, length(bytes) = %7d",
608  /*                          Main program                             */                     totalenctime, 1000 / totalenctime, (int) totalsize);
609  /*********************************************************************/     if (ARG_STATS) {
610           printf(", psnr y = %2.2f, psnr u = %2.2f, psnr v = %2.2f",
611                      totalPSNR[0],totalPSNR[1],totalPSNR[2]);
612            }
613            printf("\n");
614    
 int main(int argc, char *argv[])  
 {  
   unsigned char *divx_buffer = NULL;  
   unsigned char *in_buffer = NULL;  
615    
616    double enctime;  /*****************************************************************************
617    double totalenctime=0.;   *                            XviD PART  Stop
618     ****************************************************************************/
619    
620    long totalsize=0;    release_all:
   int status;  
621    
622    int m4v_size;          if (enc_handle) {
623    int frame_type[ABS_MAXFRAMENR];                  result = enc_stop();
624    int Iframes=0, Pframes=0, Bframes=0;                  if (result)
625    int use_assembler=1;                          fprintf(stderr, "Encore RELEASE problem return value %d\n",
626                                            result);
627            }
628    
629    char filename[256];          if (in_file)
630                    fclose(in_file);
631            if (out_file)
632                    fclose(out_file);
633    
634    FILE *filehandle;    free_all_memory:
635            free(out_buffer);
636            free(mp4_buffer);
637            free(in_buffer);
638    
639            return (0);
640    
641    }
642    
643    
644    /*****************************************************************************
645     *                        "statistical" functions
646     *
647     *  these are not needed for encoding or decoding, but for measuring
648     *  time and quality, there in nothing specific to XviD in these
649     *
650     *****************************************************************************/
651    
652  /* read YUV in pgm format from stdin */  /* Return time elapsed time in miliseconds since the program started */
653    if (!pgmflag)  static double
654    msecond()
655    {    {
656          pgmflag = 1;  #ifndef WIN32
657            struct timeval tv;
658    
659            gettimeofday(&tv, 0);
660            return (tv.tv_sec * 1.0e3 + tv.tv_usec * 1.0e-3);
661    #else
662            clock_t clk;
663    
664  //      if (argc==2 && !strcmp(argv[1],"-noasm"))          clk = clock();
665  //        use_assembler = 0;          return (clk * 1000 / CLOCKS_PER_SEC);
666    #endif
667    }
668    
669          if (argc>=3)  /*****************************************************************************
670          {       XDIM = atoi(argv[1]);   *                             Usage message
671                  YDIM = atoi(argv[2]);   *****************************************************************************/
672                  if ( (XDIM <= 0) || (XDIM >= 2048) || (YDIM <=0) || (YDIM >= 2048) )  
673                  {       fprintf(stderr,"Wrong frames size %d %d, trying PGM \n",XDIM, YDIM);  static void
674    usage()
675    {
676            fprintf(stderr, "Usage : xvid_stat [OPTIONS]\n\n");
677            fprintf(stderr, "Input options:\n");
678            fprintf(stderr, " -i      string : input filename (default=stdin)\n");
679            fprintf(stderr, " -type   integer: input data type (yuv=0, pgm=1)\n");
680            fprintf(stderr, " -w      integer: frame width ([1.2048])\n");
681            fprintf(stderr, " -h      integer: frame height ([1.2048])\n");
682            fprintf(stderr, " -frames integer: number of frames to encode\n");
683            fprintf(stderr, "\n");
684            fprintf(stderr, "Output options:\n");
685            fprintf(stderr, " -dump    : save decoder output\n");
686            fprintf(stderr, " -save    : save an Elementary Stream file per frame\n");
687            fprintf(stderr, " -o string: save an Elementary Stream for the complete sequence\n");
688            fprintf(stderr, "\n");
689            fprintf(stderr, "BFrames options:\n");
690            fprintf(stderr, " -max_bframes   integer: max bframes (default=0)\n");
691            fprintf(stderr, " -bquant_ratio  integer: bframe quantizer ratio (default=150)\n");
692            fprintf(stderr, " -bquant_offset integer: bframe quantizer offset (default=100)\n");
693            fprintf(stderr, "\n");
694            fprintf(stderr, "Rate control options:\n");
695            fprintf(stderr, " -framerate float               : target framerate (>0 | default=25.0)\n");
696            fprintf(stderr, " -bitrate   integer             : target bitrate\n");
697        fprintf(stderr,     " -single                        : single pass mode\n");
698            fprintf(stderr, " -pass1     filename            : twopass mode (first pass)\n");
699            fprintf(stderr, " -pass2     filename            : twopass mode (2nd pass)\n");
700            fprintf(stderr, " -zq starting_frame float       : bitrate zone; quant\n");
701            fprintf(stderr, " -zw starting_frame float       : bitrate zone; weight\n");
702        fprintf(stderr, " -max_key_interval integer      : maximum keyframe interval\n");
703        fprintf(stderr, "\n");
704            fprintf(stderr, "Other options\n");
705            fprintf(stderr, " -asm            : use assembly optmized code\n");
706            fprintf(stderr, " -noasm            : do not use assembly optmized code\n");
707            fprintf(stderr, " -quality integer: quality ([0..%d])\n", ME_ELEMENTS - 1);
708            fprintf(stderr, " -qpel           : use quarter pixel ME\n");
709            fprintf(stderr, " -gmc            : use global motion compensation\n");
710            fprintf(stderr, " -interlaced     : use interlaced encoding (this is NOT a deinterlacer!)\n");
711            fprintf(stderr, " -packed         : packed mode\n");
712            fprintf(stderr, " -closed_gop     : closed GOP mode\n");
713            fprintf(stderr, " -grey           : grey scale coding (chroma is discarded)\n");
714            fprintf(stderr, " -lumimasking    : use lumimasking algorithm\n");
715            fprintf(stderr, " -stats          : print stats about encoded frames\n");
716            fprintf(stderr, " -debug          : activates xvidcore internal debugging output\n");
717            fprintf(stderr, " -vop_debug      : print some info directly into encoded frames\n");
718            fprintf(stderr, " -help           : prints this help message\n");
719            fprintf(stderr, "\n");
720            fprintf(stderr, "NB: You can define %d zones repeating the -z[qw] option as many times as needed.\n", MAX_ZONES);
721            fprintf(stderr, "\n");
722                  }                  }
723                  else  
724    /*****************************************************************************
725     *                       Input and output functions
726     *
727     *      the are small and simple routines to read and write PGM and YUV
728     *      image. It's just for convenience, again nothing specific to XviD
729     *
730     *****************************************************************************/
731    
732    #ifndef READ_PNM
733    static int
734    read_pgmheader(FILE * handle)
735                  {                  {
736                          YDIM = YDIM*3/2; /* for YUV */          int bytes, xsize, ysize, depth;
737                          pgmflag = 0;          char dummy[2];
738    
739            bytes = fread(dummy, 1, 2, handle);
740    
741            if ((bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '5'))
742                    return (1);
743    
744            fscanf(handle, "%d %d %d", &xsize, &ysize, &depth);
745            if ((xsize > 4096) || (ysize > 4096*3/2) || (depth != 255)) {
746                    fprintf(stderr, "%d %d %d\n", xsize, ysize, depth);
747                    return (2);
748                  }                  }
749            if ((XDIM == 0) || (YDIM == 0)) {
750                    XDIM = xsize;
751                    YDIM = ysize * 2 / 3;
752          }          }
753    
754            return (0);
755    }    }
756    
757    if (pgmflag)  static int
758    {     if (read_pgmheader(stdin))  read_pgmdata(FILE * handle,
759                             unsigned char *image)
760              {              {
761                fprintf(stderr,"Wrong input format, I want YUV encapsulated in PGM\n");          int i;
762                return 1;          char dummy;
763              }  
764            unsigned char *y = image;
765            unsigned char *u = image + XDIM * YDIM;
766            unsigned char *v = image + XDIM * YDIM + XDIM / 2 * YDIM / 2;
767    
768            /* read Y component of picture */
769            fread(y, 1, XDIM * YDIM, handle);
770    
771            for (i = 0; i < YDIM / 2; i++) {
772                    /* read U */
773                    fread(u, 1, XDIM / 2, handle);
774    
775                    /* read V */
776                    fread(v, 1, XDIM / 2, handle);
777    
778                    /* Update pointers */
779                    u += XDIM / 2;
780                    v += XDIM / 2;
781    }    }
782    if (argc>=4)  
783    {     ARG_QUALITY = atoi(argv[3]);          /*  I don't know why, but this seems needed */
784          if ( (ARG_QUALITY < 0) || (ARG_QUALITY > 6) )          fread(&dummy, 1, 1, handle);
785                  { fprintf(stderr,"Wrong Quality\n"); return -1; }  
786          else          return (0);
                   fprintf(stderr,"Quality %d\n",ARG_QUALITY);  
787    }    }
788    if (argc>=5)  #else
789    {     ARG_BITRATE = atoi(argv[4]);  static int
790          if ( (ARG_BITRATE <= 0) )  read_pnmheader(FILE * handle)
791                  { fprintf(stderr,"Wrong Bitrate\n"); return -1; }  {
792          if ( (ARG_BITRATE < 32) )          int bytes, xsize, ysize, depth;
793                  { ARG_QUANTI = ARG_BITRATE;          char dummy[2];
794                    ARG_BITRATE=0;  
795                    fprintf(stderr,"Quantizer %d\n",ARG_QUANTI);          bytes = fread(dummy, 1, 2, handle);
796    
797            if ((bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '6'))
798                    return (1);
799    
800            fscanf(handle, "%d %d %d", &xsize, &ysize, &depth);
801            if ((xsize > 1440) || (ysize > 2880) || (depth != 255)) {
802                    fprintf(stderr, "%d %d %d\n", xsize, ysize, depth);
803                    return (2);
804                  }                  }
805          else  
806                    fprintf(stderr,"Bitrate %d kbps\n",ARG_BITRATE);          XDIM = xsize;
807            YDIM = ysize;
808    
809            return (0);
810    }    }
811    if (argc>=6)  
812    {     ARG_FRAMERATE = (float)atof(argv[5]);  static int
813          if ( (ARG_FRAMERATE <= 0) )  read_pnmdata(FILE * handle,
814                  { fprintf(stderr,"Wrong Fraterate %s \n",argv[5]); return -1; }                           unsigned char *image)
815          fprintf(stderr,"Framerate %6.3f fps\n",ARG_FRAMERATE);  {
816    }          int i;
817            char dummy;
818    if (argc>=7)  
819    {     ARG_MAXFRAMENR = atoi(argv[6]);          /* read Y component of picture */
820          if ( (ARG_MAXFRAMENR <= 0) )          fread(image, 1, XDIM * YDIM * 3, handle);
821           { fprintf(stderr,"Wrong number of frames\n"); return -1; }  
822          fprintf(stderr,"max. Framenr. %d\n",ARG_MAXFRAMENR);          /*  I don't know why, but this seems needed */
823    }          fread(&dummy, 1, 1, handle);
824    
825  #ifdef BFRAMES          return (0);
   if (argc>=8)  
   {     ARG_MAXBFRAMES = atoi(argv[7]);  
         if ( (ARG_MAXBFRAMES < -1) || ( ARG_MAXBFRAMES > ARG_FRAMERATE) )  
          { fprintf(stderr,"Wrong maximumnumber of bframes\n"); return -1; }  
         fprintf(stderr,"max. B-frames %d\n",ARG_MAXBFRAMES);  
   }  
   
   if (argc>=9)  
   {     ARG_MAXFRAMENR = atoi(argv[8]);  
         if ( (ARG_BQUANTRATIO <= 0) )  
          { fprintf(stderr,"Wrong B-frames Quantizer ratio \n"); return -1; }  
         fprintf(stderr,"B-frames quant-ratio %d\n",ARG_BQUANTRATIO);  
826    }    }
827  #endif  #endif
828    
829  /* now we know the sizes, so allocate memory */  static int
830    read_yuvdata(FILE * handle,
831    in_buffer = (unsigned char *) malloc(XDIM*YDIM);                           unsigned char *image)
832    if (!in_buffer)  {
     goto free_all_memory;  
833    
834    divx_buffer = (unsigned char *) malloc(XDIM*YDIM*2);          if (fread(image, 1, IMAGE_SIZE(XDIM, YDIM), handle) !=
835    if (!divx_buffer)                  (unsigned int) IMAGE_SIZE(XDIM, YDIM))
836      goto free_all_memory;                  return (1);
837            else
838                    return (0);
839    }
840    
841    YDIM = YDIM*2/3; // PGM is YUV 4:2:0 format, so real image height is *2/3 of PGM picture  /*****************************************************************************
842     *     Routines for encoding: init encoder, frame step, release encoder
843     ****************************************************************************/
844    
845  /*********************************************************************/  /* sample plugin */
 /*                         XviD PART  Start                          */  
 /*********************************************************************/  
846    
847    status = enc_init(use_assembler);  int
848          if (status)  rawenc_debug(void *handle,
849                             int opt,
850                             void *param1,
851                             void *param2)
852          {          {
853                  fprintf(stderr,"Encore INIT problem, return value %d\n", status);          switch (opt) {
854                  goto release_all;          case XVID_PLG_INFO:
855                    {
856                            xvid_plg_info_t *info = (xvid_plg_info_t *) param1;
857    
858                            info->flags = XVID_REQDQUANTS;
859                            return 0;
860          }          }
861    
862  /*********************************************************************/          case XVID_PLG_CREATE:
863  /*                               Main loop                           */          case XVID_PLG_DESTROY:
864  /*********************************************************************/          case XVID_PLG_BEFORE:
865                    return 0;
866    
867    do          case XVID_PLG_AFTER:
868      {      {
869          if (pgmflag)                          xvid_plg_data_t *data = (xvid_plg_data_t *) param1;
870                status = read_pgmdata(stdin, in_buffer);  // read PGM data (YUV-format)                          int i, j;
         else  
               status = read_yuvdata(stdin, in_buffer);  // read raw data (YUV-format)  
871    
872      if (status)                          printf("---[ frame: %5i   quant: %2i   length: %6i ]---\n",
873          {                                     data->frame_num, data->quant, data->length);
874            // Couldn't read image, most likely end-of-file                          for (j = 0; j < data->mb_height; j++) {
875            continue;                                  for (i = 0; i < data->mb_width; i++)
876                                            printf("%2i ", data->dquant[j * data->dquant_stride + i]);
877                                    printf("\n");
878                            }
879    
880                            return 0;
881                    }
882          }          }
883    
884            return XVID_ERR_FAIL;
885    }
886    
887    
888    #define FRAMERATE_INCR 1001
889    
890      if (save_ref_flag)  
891    /* Initialize encoder for first use, pass all needed parameters to the codec */
892    static int
893    enc_init(int use_assembler)
894          {          {
895                  sprintf(filename, "%s%05d.pgm", filepath, filenr);          int xerr;
896                  write_pgm(filename,in_buffer);          //xvid_plugin_cbr_t cbr;
897        xvid_plugin_single_t single;
898            xvid_plugin_2pass1_t rc2pass1;
899            xvid_plugin_2pass2_t rc2pass2;
900            //xvid_plugin_fixed_t rcfixed;
901            xvid_enc_plugin_t plugins[7];
902            xvid_gbl_init_t xvid_gbl_init;
903            xvid_enc_create_t xvid_enc_create;
904    
905            /*------------------------------------------------------------------------
906             * XviD core initialization
907             *----------------------------------------------------------------------*/
908    
909            /* Set version -- version checking will done by xvidcore */
910            memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init));
911            xvid_gbl_init.version = XVID_VERSION;
912        xvid_gbl_init.debug = ARG_DEBUG;
913    
914    
915            /* Do we have to enable ASM optimizations ? */
916            if (use_assembler) {
917    
918    #ifdef ARCH_IS_IA64
919                    xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ASM;
920    #else
921                    xvid_gbl_init.cpu_flags = 0;
922    #endif
923            } else {
924                    xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
925          }          }
926    
927            /* Initialize XviD core -- Should be done once per __process__ */
928            xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
929    
930  /*********************************************************************/          /*------------------------------------------------------------------------
931  /*               analyse this frame before encoding                  */           * XviD encoder initialization
932  /*********************************************************************/           *----------------------------------------------------------------------*/
933    
934            /* Version again */
935            memset(&xvid_enc_create, 0, sizeof(xvid_enc_create));
936            xvid_enc_create.version = XVID_VERSION;
937    
938            /* Width and Height of input frames */
939            xvid_enc_create.width = XDIM;
940            xvid_enc_create.height = YDIM;
941            xvid_enc_create.profile = XVID_PROFILE_AS_L4;
942    
943            /* init plugins  */
944        xvid_enc_create.zones = ZONES;
945        xvid_enc_create.num_zones = NUM_ZONES;
946    
947            xvid_enc_create.plugins = plugins;
948            xvid_enc_create.num_plugins = 0;
949    
950            if (ARG_SINGLE) {
951                    memset(&single, 0, sizeof(xvid_plugin_single_t));
952                    single.version = XVID_VERSION;
953                    single.bitrate = ARG_BITRATE;
954    
955                    plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
956                    plugins[xvid_enc_create.num_plugins].param = &single;
957                    xvid_enc_create.num_plugins++;
958            }
959    
960            if (ARG_PASS2) {
961                    memset(&rc2pass2, 0, sizeof(xvid_plugin_2pass2_t));
962                    rc2pass2.version = XVID_VERSION;
963                    rc2pass2.filename = ARG_PASS2;
964                    rc2pass2.bitrate = ARG_BITRATE;
965    
966    /*              An example of activating VBV could look like this
967                    rc2pass2.vbv_size     =  3145728;
968                    rc2pass2.vbv_initial  =  2359296;
969                    rc2pass2.vbv_maxrate  =  4000000;
970                    rc2pass2.vbv_peakrate = 10000000;
971    */
972    
973  //      nothing is done here at the moment, but you could e.g. create                  plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
974  //      histograms or measure entropy or apply preprocessing filters...                  plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
975                    xvid_enc_create.num_plugins++;
976            }
977    
978  /*********************************************************************/          if (ARG_PASS1) {
979  /*               encode and decode this frame                        */                  memset(&rc2pass1, 0, sizeof(xvid_plugin_2pass1_t));
980  /*********************************************************************/                  rc2pass1.version = XVID_VERSION;
981                    rc2pass1.filename = ARG_PASS1;
982    
983          enctime = -msecond();                  plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass1;
984          status = enc_main(in_buffer, divx_buffer, &m4v_size, &frame_type[filenr]);                  plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
985          enctime += msecond();                  xvid_enc_create.num_plugins++;
986            }
987    
988          totalenctime += enctime;          if (ARG_LUMIMASKING) {
989          totalsize += m4v_size;                  plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
990                    plugins[xvid_enc_create.num_plugins].param = NULL;
991                    xvid_enc_create.num_plugins++;
992            }
993    
994          fprintf(stderr,"Frame %5d: intra %d, enctime =%6.1f ms length=%7d bytes\n",          if (ARG_DUMP) {
995                   filenr, frame_type[filenr], enctime*1000, m4v_size);                  plugins[xvid_enc_create.num_plugins].func = xvid_plugin_dump;
996                    plugins[xvid_enc_create.num_plugins].param = NULL;
997                    xvid_enc_create.num_plugins++;
998            }
999    
1000          if (save_m4v_flag)  #if 0
1001          {          if (ARG_DEBUG) {
1002                  fwrite(divx_buffer, m4v_size, 1, stdout);                  plugins[xvid_enc_create.num_plugins].func = rawenc_debug;
1003                    plugins[xvid_enc_create.num_plugins].param = NULL;
1004                    xvid_enc_create.num_plugins++;
1005          }          }
1006    #endif
1007    
1008          if (pgmflag)          /* No fancy thread tests */
1009                  status = read_pgmheader(stdin);          xvid_enc_create.num_threads = 0;
                                 // because if this was the last PGM, stop now  
1010    
1011          filenr++;          /* Frame rate - Do some quick float fps = fincr/fbase hack */
1012            if ((ARG_FRAMERATE - (int) ARG_FRAMERATE) < SMALL_EPS) {
1013                    xvid_enc_create.fincr = 1;
1014                    xvid_enc_create.fbase = (int) ARG_FRAMERATE;
1015            } else {
1016                    xvid_enc_create.fincr = FRAMERATE_INCR;
1017                    xvid_enc_create.fbase = (int) (FRAMERATE_INCR * ARG_FRAMERATE);
1018            }
1019    
1020     } while ( (!status) && (filenr<ARG_MAXFRAMENR) );          /* Maximum key frame interval */
1021        if (ARG_MAXKEYINTERVAL > 0) {
1022            xvid_enc_create.max_key_interval = ARG_MAXKEYINTERVAL;
1023        }else {
1024                xvid_enc_create.max_key_interval = (int) ARG_FRAMERATE *10;
1025        }
1026    
1027            /* Bframes settings */
1028            xvid_enc_create.max_bframes = ARG_MAXBFRAMES;
1029            xvid_enc_create.bquant_ratio = ARG_BQRATIO;
1030            xvid_enc_create.bquant_offset = ARG_BQOFFSET;
1031    
1032            /* Dropping ratio frame -- we don't need that */
1033            xvid_enc_create.frame_drop_ratio = 0;
1034    
1035  /*********************************************************************/          /* Global encoder options */
1036  /*     calculate totals and averages for output, print results       */          xvid_enc_create.global = 0;
 /*********************************************************************/  
1037    
1038          totalsize    /= filenr;          if (ARG_PACKED)
1039          totalenctime /= filenr;                  xvid_enc_create.global |= XVID_GLOBAL_PACKED;
1040    
1041          for (i=0;i<filenr;i++)          if (ARG_CLOSED_GOP)
1042          {                  xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
1043                  switch (frame_type[i])  
1044            if (ARG_STATS)
1045                    xvid_enc_create.global |= XVID_GLOBAL_EXTRASTATS_ENABLE;
1046    
1047            /* I use a small value here, since will not encode whole movies, but short clips */
1048            xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
1049    
1050            /* Retrieve the encoder instance from the structure */
1051            enc_handle = xvid_enc_create.handle;
1052    
1053            return (xerr);
1054    }
1055    
1056    static int
1057    enc_stop()
1058                  {                  {
1059                  case 0:          int xerr;
1060                          Pframes++;  
1061                          break;          /* Destroy the encoder instance */
1062                  case 1:          xerr = xvid_encore(enc_handle, XVID_ENC_DESTROY, NULL, NULL);
1063                          Iframes++;  
1064                          break;          return (xerr);
                 case 2:  
                 default:  
                         Bframes++;  
                         break;  
1065                  }                  }
1066    
1067    static int
1068    enc_main(unsigned char *image,
1069                     unsigned char *bitstream,
1070                     int *key,
1071                     int *stats_type,
1072                     int *stats_quant,
1073                     int *stats_length,
1074                     int sse[3])
1075    {
1076            int ret;
1077    
1078            xvid_enc_frame_t xvid_enc_frame;
1079            xvid_enc_stats_t xvid_enc_stats;
1080    
1081            /* Version for the frame and the stats */
1082            memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
1083            xvid_enc_frame.version = XVID_VERSION;
1084    
1085            memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
1086            xvid_enc_stats.version = XVID_VERSION;
1087    
1088            /* Bind output buffer */
1089            xvid_enc_frame.bitstream = bitstream;
1090            xvid_enc_frame.length = -1;
1091    
1092            /* Initialize input image fields */
1093            if (image) {
1094                    xvid_enc_frame.input.plane[0] = image;
1095    #ifndef READ_PNM
1096                    xvid_enc_frame.input.csp = XVID_CSP_I420;
1097                    xvid_enc_frame.input.stride[0] = XDIM;
1098    #else
1099                    xvid_enc_frame.input.csp = XVID_CSP_BGR;
1100                    xvid_enc_frame.input.stride[0] = XDIM*3;
1101    #endif
1102            } else {
1103                    xvid_enc_frame.input.csp = XVID_CSP_NULL;
1104          }          }
1105    
1106          fprintf(stderr,"Avg: enctime %5.2f ms, %5.2f fps, filesize =%d\n",          /* Set up core's general features */
1107                  1000*totalenctime, 1./totalenctime, totalsize);          xvid_enc_frame.vol_flags = 0;
1108            if (ARG_STATS)
1109                    xvid_enc_frame.vol_flags |= XVID_VOL_EXTRASTATS;
1110            if (ARG_QPEL)
1111                    xvid_enc_frame.vol_flags |= XVID_VOL_QUARTERPEL;
1112            if (ARG_GMC)
1113                    xvid_enc_frame.vol_flags |= XVID_VOL_GMC;
1114            if (ARG_INTERLACING)
1115                    xvid_enc_frame.vol_flags |= XVID_VOL_INTERLACING;
1116    
1117  /*********************************************************************/          /* Set up core's general features */
1118  /*                         XviD PART  Stop                           */          xvid_enc_frame.vop_flags = vop_presets[ARG_QUALITY];
 /*********************************************************************/  
1119    
1120  release_all:      if (ARG_VOPDEBUG) {
1121            xvid_enc_frame.vop_flags |= XVID_VOP_DEBUG;
1122        }
1123    
1124          if (enc_handle)      if (ARG_GREYSCALE) {
1125          {          xvid_enc_frame.vop_flags |= XVID_VOP_GREYSCALE;
                 status = enc_stop();  
                 if (status)  
                         fprintf(stderr,"Encore RELEASE problem return value %d\n", status);  
1126          }          }
1127    
1128  free_all_memory:          /* Frame type -- let core decide for us */
1129          free(divx_buffer);          xvid_enc_frame.type = XVID_TYPE_AUTO;
         free(in_buffer);  
1130    
1131    return 0;          /* Force the right quantizer -- It is internally managed by RC plugins */
1132            xvid_enc_frame.quant = 0;
1133    
1134            /* Set up motion estimation flags */
1135            xvid_enc_frame.motion = motion_presets[ARG_QUALITY];
1136    
1137            if (ARG_GMC)
1138                    xvid_enc_frame.motion |= XVID_ME_GME_REFINE;
1139    
1140            if (ARG_QPEL)
1141                    xvid_enc_frame.motion |= XVID_ME_QUARTERPELREFINE16;
1142            if (ARG_QPEL && (xvid_enc_frame.vop_flags & XVID_VOP_INTER4V))
1143                    xvid_enc_frame.motion |= XVID_ME_QUARTERPELREFINE8;
1144    
1145            /* We don't use special matrices */
1146            xvid_enc_frame.quant_intra_matrix = NULL;
1147            xvid_enc_frame.quant_inter_matrix = NULL;
1148    
1149            /* Encode the frame */
1150            ret = xvid_encore(enc_handle, XVID_ENC_ENCODE, &xvid_enc_frame,
1151                                              &xvid_enc_stats);
1152    
1153            *key = (xvid_enc_frame.out_flags & XVID_KEYFRAME);
1154            *stats_type = xvid_enc_stats.type;
1155            *stats_quant = xvid_enc_stats.quant;
1156            *stats_length = xvid_enc_stats.length;
1157            sse[0] = xvid_enc_stats.sse_y;
1158            sse[1] = xvid_enc_stats.sse_u;
1159            sse[2] = xvid_enc_stats.sse_v;
1160    
1161            return (ret);
1162  }  }

Legend:
Removed from v.376  
changed lines
  Added in v.1623

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