[svn] / branches / dev-api-4 / xvidcore / examples / xvid_encraw.c Repository:
ViewVC logotype

Diff of /branches/dev-api-4/xvidcore/examples/xvid_encraw.c

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

trunk/xvidcore/examples/xvid_encraw.c revision 376, Sat Aug 17 20:03:36 2002 UTC branches/dev-api-4/xvidcore/examples/xvid_encraw.c revision 913, Sun Mar 9 16:45:24 2003 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
7   *   *
8   *      This program is free software; you can redistribute it and/or modify   *      This program is free software; you can redistribute it and/or modify
9   *      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 17 
17   *   *
18   *      You should have received a copy of the GNU General Public License   *      You should have received a copy of the GNU General Public License
19   *      along with this program; if not, write to the Free Software   *      along with this program; if not, write to the Free Software
20   *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21   *   *
22   *************************************************************************/   * $Id: xvid_encraw.c,v 1.11.2.2 2003-03-09 16:45:24 edgomez Exp $
   
 /************************************************************************  
23   *   *
24   *  Speed test routine for XviD using the XviD-API   ****************************************************************************/
25   *  (C) Christoph Lampert, 2002/08/17  
26    /*****************************************************************************
27     *  Application notes :
28   *   *
29   *  A sequence of YUV pics in PGM or RAW file format is encoded and the   *  A sequence of YUV pics in PGM file format is encoded and decoded
30   *  raw MPEG-4 stream is written to stdout.   *  The speed is measured and PSNR of decoded picture is calculated.
  *  The encoding speed of this is measured, too.  
31   *   *
32   *  The program is plain C and needs no libraries except for libxvidcore,   *  The program is plain C and needs no libraries except for libxvidcore,
33   *  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)  
  *  
  *  BITRATE is in kbps (default 900),  
  *      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  
34   *   *
35   ************************************************************************/   ************************************************************************/
36    
37  #include <stdio.h>  #include <stdio.h>
38  #include <stdlib.h>  #include <stdlib.h>
39  #include <math.h>               // needed for log10  #include <string.h>
40  #include <sys/time.h>           // only needed for gettimeofday  #include <math.h>
41    #ifndef WIN32
42    #include <sys/time.h>
43    #else
44    #include <time.h>
45    #endif
46    
47  #include "../src/xvid.h"                /* comes with XviD */  #include "xvid.h"
48    
49  int motion_presets[7] = {  /*****************************************************************************
50          0,                                                              // Q 0   *                            Quality presets
51          PMV_EARLYSTOP16,                                                // Q 1   ****************************************************************************/
52          PMV_EARLYSTOP16,                                                // Q 2  
53          PMV_EARLYSTOP16 | PMV_HALFPELREFINE16,                          // Q 3  static xvid_motion_t const motion_presets[] = {
54          PMV_EARLYSTOP16 | PMV_HALFPELREFINE16,                          // Q 4          0,
55          PMV_EARLYSTOP16 | PMV_HALFPELREFINE16 | PMV_EARLYSTOP8          // Q 5          PMV_HALFPELREFINE16,
56                          | PMV_HALFPELREFINE8,          PMV_HALFPELREFINE16,
57          PMV_EARLYSTOP16 | PMV_HALFPELREFINE16 | PMV_EXTSEARCH16         // Q 6          PMV_HALFPELREFINE16 | PMV_HALFPELREFINE8,
58                          | PMV_USESQUARES16 | PMV_EARLYSTOP8 | PMV_HALFPELREFINE8          PMV_HALFPELREFINE16 | PMV_HALFPELREFINE8 | PMV_EXTSEARCH16 | PMV_USESQUARES16,
59            PMV_HALFPELREFINE16 | PMV_HALFPELREFINE8 | PMV_EXTSEARCH16 | PMV_USESQUARES16 | PMV_CHROMA16 | PMV_CHROMA8,
60          };          };
61    
62  int general_presets[7] = {  static xvid_vol_t const vol_presets[] = {
63          XVID_H263QUANT, /* or use XVID_MPEGQUANT */             // Q 0          XVID_MPEGQUANT,
64          XVID_MPEGQUANT,                                         // Q 1          0,
65          XVID_H263QUANT,                                // Q 2          0,
66          XVID_H263QUANT | XVID_HALFPEL,                          // Q 3          XVID_QUARTERPEL,
67          XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V,           // Q 4          XVID_QUARTERPEL | XVID_GMC,
68          XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V,           // Q 5          XVID_QUARTERPEL | XVID_GMC
69          XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V };         // Q 6  };
70    
71    static xvid_vop_t const vop_presets[] = {
72            XVID_DYNAMIC_BFRAMES,
73            XVID_DYNAMIC_BFRAMES,
74            XVID_DYNAMIC_BFRAMES | XVID_HALFPEL,
75            XVID_DYNAMIC_BFRAMES | XVID_HALFPEL | XVID_INTER4V,
76            XVID_DYNAMIC_BFRAMES | XVID_HALFPEL | XVID_INTER4V | XVID_HQACPRED,
77            XVID_DYNAMIC_BFRAMES | XVID_HALFPEL | XVID_INTER4V | XVID_HQACPRED | XVID_MODEDECISION_BITS
78    };
79    
80  /* my default values for encoding */  /*****************************************************************************
81     *                     Command line global variables
82     ****************************************************************************/
83    
84    /* Maximum number of frames to encode */
85    #define ABS_MAXFRAMENR 9999
86    
87    static int   ARG_BITRATE = 900;
88    static int   ARG_QUANTI = 0;
89    static int   ARG_QUALITY = 5;
90    static int   ARG_MINQUANT = 1;
91    static int   ARG_MAXQUANT = 31;
92    static float ARG_FRAMERATE = 25.00f;
93    static int   ARG_MAXFRAMENR = ABS_MAXFRAMENR;
94    static char *ARG_INPUTFILE = NULL;
95    static int   ARG_INPUTTYPE = 0;
96    static int   ARG_SAVEMPEGSTREAM = 0;
97    static char *ARG_OUTPUTFILE = NULL;
98    static int   XDIM = 0;
99    static int   YDIM = 0;
100    static int   ARG_BQRATIO = 150;
101    static int   ARG_BQOFFSET = 100;
102    static int   ARG_MAXBFRAMES = 0;
103    #define IMAGE_SIZE(x,y) ((x)*(y)*3/2)
104    
105  #define ABS_MAXFRAMENR 9999               // max number of frames  #define MAX(A,B) ( ((A)>(B)) ? (A) : (B) )
106    #define SMALL_EPS (1e-10)
107    
108  int ARG_BITRATE=900;  #define SWAP(a) ( (((a)&0x000000ff)<<24) | (((a)&0x0000ff00)<<8) | \
109  int ARG_QUANTI=0;                    (((a)&0x00ff0000)>>8)  | (((a)&0xff000000)>>24) )
110    
111  int ARG_QUALITY =6;  /****************************************************************************
112  int ARG_MINQUANT=1;   *                     Nasty global vars ;-)
113  int ARG_MAXQUANT=31;   ***************************************************************************/
 float ARG_FRAMERATE=25.00;  
114    
115  int ARG_MAXFRAMENR=ABS_MAXFRAMENR;  static int i,filenr = 0;
116    
117  #ifdef BFRAMES  /* the path where to save output */
118    static char filepath[256] = "./";
119    
120  int ARG_MAXBFRAMES=1;  /* Internal structures (handles) for encoding and decoding */
121  int ARG_BQUANTRATIO=200;  static void *enc_handle = NULL;
122    
123  #endif  /*****************************************************************************
124     *               Local prototypes
125     ****************************************************************************/
126    
127  #define MAX(A,B) ( ((A)>(B)) ? (A) : (B) )  /* Prints program usage message */
128  #define SMALL_EPS 1e-10  static void usage();
129    
130  /* these are global variables. Not very elegant, but easy, and this is an easy program */  /* Statistical functions */
131    static double msecond();
132    
133  int XDIM=0;  /* PGM related functions */
134  int YDIM=0;     // will be set when reading first image  static int read_pgmheader(FILE* handle);
135  int i,filenr = 0;  static int read_pgmdata(FILE* handle, unsigned char *image);
136    static int read_yuvdata(FILE* handle, unsigned char *image);
137    
138  int save_m4v_flag = 1;          // output MPEG4-bytestream?  /* Encoder related functions */
139  int save_ref_flag = 0;          // save input image  static int enc_init(int use_assembler);
140    static int enc_stop();
141    static int enc_main(unsigned char* image,
142                                            unsigned char* bitstream,
143                                            long *frametype,
144                                            int stats[3]);
145    
146  int pgmflag = 0;                // a flag, if input is in PGM format, overwritten in init-phase  /*****************************************************************************
147  char filepath[256] = "./";      // the path where to save output   *               Main function
148     ****************************************************************************/
149    
150  void *enc_handle = NULL;                // internal structures (handles) for encoding  int main(int argc, char *argv[])
151    {
152    
153            unsigned char *mp4_buffer = NULL;
154            unsigned char *in_buffer = NULL;
155            unsigned char *out_buffer = NULL;
156    
157  /*********************************************************************/          double enctime;
158  /*                     "statistical" functions                       */          double totalenctime=0.;
 /*                                                                   */  
 /*  these are not needed for encoding or decoding, but for measuring */  
 /*  time and quality, there in nothing specific to XviD in these     */  
 /*                                                                   */  
 /*********************************************************************/  
159    
160  double msecond()          long totalsize;
161  /* return the current time in seconds(!)  */          int status;
162  {          long frame_type;
         struct timeval  tv;  
         gettimeofday(&tv, 0);  
         return tv.tv_sec + tv.tv_usec * 1.0e-6;  
 }  
163    
164  /*********************************************************************/          long m4v_size;
165  /*                    input and output functions                     */          int use_assembler=0;
 /*                                                                   */  
 /* the are small and simple routines to read and write PGM and YUV   */  
 /* image. It's just for convenience, again nothing specific to XviD  */  
 /*                                                                   */  
 /*********************************************************************/  
166    
167  int read_pgmheader(FILE* handle)          char filename[256];
 {  
         int bytes,xsize,ysize,depth;  
         char dummy[2];  
168    
169          bytes = fread(dummy,1,2,handle);          FILE *in_file = stdin;
170            FILE *out_file = NULL;
171    
172          if ( (bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '5' ))          printf("xvid_encraw - raw mpeg4 bitstream encoder ");
173                  return 1;          printf("written by Christoph Lampert 2002-2003\n\n");
174          fscanf(handle,"%d %d %d",&xsize,&ysize,&depth);  
175          if ( (xsize > 1440) || (ysize > 2880 ) || (depth != 255) )  /*****************************************************************************
176          {   *                            Command line parsing
177                  return 2;   ****************************************************************************/
178    
179            for (i=1; i< argc; i++) {
180    
181                    if (strcmp("-asm", argv[i]) == 0 ) {
182                            use_assembler = 1;
183          }          }
184          if ( (XDIM==0) || (YDIM==0) )                  else if (strcmp("-w", argv[i]) == 0 && i < argc - 1 ) {
185          {       XDIM=xsize;                          i++;
186                  YDIM=ysize;                          XDIM = atoi(argv[i]);
187          }          }
188                    else if (strcmp("-h", argv[i]) == 0 && i < argc - 1 ) {
189          return 0;                          i++;
190                            YDIM = atoi(argv[i]);
191                    }
192                    else if (strcmp("-b", argv[i]) == 0 && i < argc - 1 ) {
193                            i++;
194                            ARG_BITRATE = atoi(argv[i]);
195                    }
196                    else if (strcmp("-bn", argv[i]) == 0 && i < argc - 1 ) {
197                            i++;
198                            ARG_MAXBFRAMES = atoi(argv[i]);
199                    }
200                    else if (strcmp("-bqr", argv[i]) == 0 && i < argc - 1 ) {
201                            i++;
202                            ARG_BQRATIO = atoi(argv[i]);
203                    }
204                    else if (strcmp("-bqo", argv[i]) == 0 && i < argc - 1 ) {
205                            i++;
206                            ARG_BQOFFSET = atoi(argv[i]);
207                    }
208                    else if (strcmp("-q", argv[i]) == 0 && i < argc - 1 ) {
209                            i++;
210                            ARG_QUALITY = atoi(argv[i]);
211                    }
212                    else if (strcmp("-f", argv[i]) == 0 && i < argc - 1 ) {
213                            i++;
214                            ARG_FRAMERATE = (float)atof(argv[i]);
215                    }
216                    else if (strcmp("-i", argv[i]) == 0 && i < argc - 1 ) {
217                            i++;
218                            ARG_INPUTFILE = argv[i];
219                    }
220                    else if (strcmp("-t", argv[i]) == 0 && i < argc - 1 ) {
221                            i++;
222                            ARG_INPUTTYPE = atoi(argv[i]);
223                    }
224                    else if(strcmp("-n", argv[i]) == 0 && i < argc - 1 ) {
225                            i++;
226                            ARG_MAXFRAMENR  = atoi(argv[i]);
227                    }
228                    else if (strcmp("-quant", argv[i]) == 0 && i < argc - 1 ) {
229                            i++;
230                            ARG_QUANTI = atoi(argv[i]);
231                    }
232                    else if (strcmp("-m", argv[i]) == 0 && i < argc - 1 ) {
233                            i++;
234                            ARG_SAVEMPEGSTREAM = atoi(argv[i]);
235                    }
236                    else if (strcmp("-o", argv[i]) == 0 && i < argc - 1 ) {
237                            i++;
238                            ARG_OUTPUTFILE = argv[i];
239                    }
240                    else if (strcmp("-help", argv[i])) {
241                            usage();
242                            return(0);
243                    }
244                    else {
245                            usage();
246                            exit(-1);
247  }  }
248    
249  int read_pgmdata(FILE* handle, unsigned char *image)          }
 {  
         int i,status;  
         char dummy;  
250    
251          unsigned char* buff1_ptr2 = image + XDIM*YDIM;  /*****************************************************************************
252          unsigned char* buff1_ptr3 = image + XDIM*YDIM + XDIM/2*YDIM/2;   *                            Arguments checking
253     ****************************************************************************/
254    
255          fread(image,XDIM*YDIM,1,stdin); // read Y component of picture          if (XDIM <= 0 || XDIM >= 2048 || YDIM <=0 || YDIM >= 2048 ) {
256                    fprintf(stderr, "Trying to retreive width and height from PGM header\n");
257                    ARG_INPUTTYPE = 1; /* pgm */
258            }
259    
260          for (i=0;i<YDIM/2;i++)          if ( ARG_QUALITY < 0 || ARG_QUALITY > 5) {
261          {                  fprintf(stderr,"Wrong Quality\n");
262                  fread(buff1_ptr2,XDIM/2,1,stdin);        // read U                  return(-1);
                 buff1_ptr2 += XDIM/2;  
                 fread(buff1_ptr3,XDIM/2,1,stdin);        // read V  
                 buff1_ptr3 += XDIM/2;  
263          }          }
264          fread(&dummy,1,1,handle);       //  I don't know why, but this seems needed  
265          return 0;          if ( ARG_BITRATE <= 0 && ARG_QUANTI == 0) {
266                    fprintf(stderr,"Wrong Bitrate\n");
267                    return(-1);
268  }  }
269    
270  int read_yuvdata(FILE* handle, unsigned char *image)          if ( ARG_FRAMERATE <= 0) {
271  {       int i;                  fprintf(stderr,"Wrong Framerate %s \n",argv[5]);
272          char dummy;                  return(-1);
273            }
274    
275          unsigned char* buff1_ptr2 = image + XDIM*YDIM;          if ( ARG_MAXFRAMENR <= 0) {
276          unsigned char* buff1_ptr3 = image + XDIM*YDIM + XDIM/2*YDIM/2;                  fprintf(stderr,"Wrong number of frames\n");
277                    return(-1);
278            }
279    
280          if (fread(image,XDIM,YDIM*3/2,stdin) != YDIM*3/2)          if ( ARG_INPUTFILE == NULL || strcmp(ARG_INPUTFILE, "stdin") == 0) {
281                  return 1;                  in_file = stdin;
         else  
                 return 0;  
282  }  }
283            else {
284    
285  int write_pgm(char *filename, unsigned char *image)                  in_file = fopen(ARG_INPUTFILE, "rb");
286  {                  if (in_file == NULL) {
287          FILE *filehandle;                          fprintf(stderr, "Error opening input file %s\n", ARG_INPUTFILE);
288          filehandle=fopen(filename,"wb");                          return(-1);
         if (filehandle)  
         {  
                 fprintf(filehandle,"P5\n\n");           //  
                 fprintf(filehandle,"%d %d 255\n",XDIM,YDIM*3/2);  
                 fwrite(image,XDIM,YDIM*3/2,filehandle);  
                 fclose(filehandle);  
                 return 0;  
289          }          }
         else  
                 return 1;  
290  }  }
291    
292  /*********************************************************************/          if (ARG_INPUTTYPE) {
293  /* Routines for encoding: init encoder, frame step, release encoder  */                  if (read_pgmheader(in_file)) {
294  /*********************************************************************/                          fprintf(stderr, "Wrong input format, I want YUV encapsulated in PGM\n");
295                            return(-1);
296                    }
297            }
298    
299  #define FRAMERATE_INCR 1001          /* now we know the sizes, so allocate memory */
300            in_buffer = (unsigned char *) malloc(IMAGE_SIZE(XDIM,YDIM));
301            if (!in_buffer)
302                    goto free_all_memory;
303    
304            /* this should really be enough memory ! */
305            mp4_buffer = (unsigned char *) malloc(IMAGE_SIZE(XDIM,YDIM)*2);
306            if (!mp4_buffer)
307                    goto free_all_memory;
308    
309  int enc_init(int use_assembler)  /*****************************************************************************
310  {       /* initialize encoder for first use, pass all needed parameters to the codec */   *                            XviD PART  Start
311          int xerr;   ****************************************************************************/
312    
         XVID_INIT_PARAM xinit;  
         XVID_ENC_PARAM xparam;  
313    
314          if(use_assembler)          status = enc_init(use_assembler);
315            if (status)
316            {
317                    fprintf(stderr, "Encore INIT problem, return value %d\n", status);
318                    goto release_all;
319            }
320    
321  #ifdef ARCH_IA64  /*****************************************************************************
322                  xinit.cpu_flags = XVID_CPU_FORCE | XVID_CPU_IA64;   *                            Main loop
323  #else   ****************************************************************************/
                 xinit.cpu_flags = 0;  
 #endif  
324    
325          else          if (ARG_SAVEMPEGSTREAM && ARG_OUTPUTFILE) {
                 xinit.cpu_flags = XVID_CPU_FORCE;  
326    
327          xvid_init(NULL, 0, &xinit, NULL);                  if((out_file = fopen(ARG_OUTPUTFILE, "w+b")) == NULL) {
328                            fprintf(stderr, "Error opening output file %s\n", ARG_OUTPUTFILE);
329                            goto release_all;
330                    }
331    
         xparam.width = XDIM;  
         xparam.height = YDIM;  
         if ((ARG_FRAMERATE - (int)ARG_FRAMERATE) < SMALL_EPS)  
         {  
                 xparam.fincr = 1;  
                 xparam.fbase = (int)ARG_FRAMERATE;  
332          }          }
333          else          else {
334          {                  out_file = NULL;
                 xparam.fincr = FRAMERATE_INCR;  
                 xparam.fbase = (int)(FRAMERATE_INCR * ARG_FRAMERATE);  
335          }          }
         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;  
   
 #ifdef BFRAMES  
         xparam.global = XVID_GLOBAL_DX50BVOP;  
         xparam.max_bframes = ARG_MAXBFRAMES;  
         xparam.bquant_ratio = ARG_BQUANTRATIO;  
         xparam.frame_drop_ratio=0;  
 #endif  
336    
337          /* I use a small value here, since will not encode whole movies,  /*****************************************************************************
338                  but short clips */   *                       Encoding loop
339     ****************************************************************************/
340    
341          xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xparam, NULL);          totalsize = 0;
         enc_handle=xparam.handle;  
342    
343          return xerr;          do {
344    
345                    char *type;
346                    int stats[3];
347    
348                    if(ARG_INPUTTYPE) {
349                            /* read PGM data (YUV-format) */
350                            status = read_pgmdata(in_file, in_buffer);
351                    } else {
352                            /* read raw data (YUV-format) */
353                            status = read_yuvdata(in_file, in_buffer);
354  }  }
355    
356  int  enc_stop()                  if(status) {
357  {       int xerr;                          /* Couldn't read image, most likely end-of-file */
358                            continue;
359                    }
360    
361          xerr = xvid_encore(enc_handle, XVID_ENC_DESTROY, NULL, NULL);  /*****************************************************************************
362          return xerr;   *                       Encode and decode this frame
363     ****************************************************************************/
364    
365                    enctime = msecond();
366                    m4v_size = enc_main(in_buffer, mp4_buffer, &frame_type, stats);
367                    enctime = msecond() - enctime;
368    
369                    /* Not coded frames return 0 */
370                    if(m4v_size == 0) goto next_frame;
371    
372                    /* Write the Frame statistics */
373                    switch(frame_type) {
374                    case XVID_TYPE_IVOP:
375                            type = "I";
376                            break;
377                    case XVID_TYPE_PVOP:
378                            type = "P";
379                            break;
380                    case XVID_TYPE_BVOP:
381                            type = "B";
382                            break;
383                    case XVID_TYPE_SVOP:
384                            type = "S";
385                            break;
386                    case XVID_TYPE_NOTHING:
387                            type = "N";
388                            break;
389                    default:
390                            type = "U";
391                            break;
392  }  }
393    
394  int  enc_main(unsigned char* image, unsigned char* bitstream, int *streamlength, int* frametype)                  printf("Frame %5d: type = %s, enctime(ms) =%6.1f, length(bytes) =%7d, "
395  {       int xerr;                             "psnr y = %2.2f, psnr u = %2.2f, psnr v = %2.2f\n",
396                               (int)filenr,
397                               type,
398                               (float)enctime,
399                               (int)m4v_size,
400                               (stats[0] == 0)? 0.0f: 48.131f - 10*(float)log10((float)stats[0]/((float)(XDIM)*(YDIM))),
401                               (stats[1] == 0)? 0.0f: 48.131f - 10*(float)log10((float)stats[1]/((float)(XDIM)*(YDIM)/4)),
402                               (stats[2] == 0)? 0.0f: 48.131f - 10*(float)log10((float)stats[2]/((float)(XDIM)*(YDIM)/4)));
403    
404          XVID_ENC_FRAME xframe;                  /* Update encoding time stats */
405          XVID_ENC_STATS xstats;                  totalenctime += enctime;
406                    totalsize += m4v_size;
407    
408          xframe.bitstream = bitstream;  /*****************************************************************************
409          xframe.length = -1;     // this is written by the routine   *                       Save stream to file
410     ****************************************************************************/
411    
412          xframe.image = image;                  if (ARG_SAVEMPEGSTREAM)
413          xframe.colorspace = XVID_CSP_YV12;      // defined in <xvid.h>                  {
414                            /* Save single files */
415                            if (out_file == NULL) {
416                                    sprintf(filename, "%sframe%05d.m4v", filepath, filenr);
417                                    out_file = fopen(filename, "wb");
418                                    fwrite(mp4_buffer, m4v_size, 1, out_file);
419                                    fclose(out_file);
420                                    out_file = NULL;
421                            }
422                            else {
423    
424          xframe.intra = -1; // let the codec decide between I-frame (1) and P-frame (0)                                  /* Write mp4 data */
425                                    fwrite(mp4_buffer, 1, m4v_size, out_file);
426    
427          xframe.quant = ARG_QUANTI;      // is quant != 0, use a fixed quant (and ignore bitrate)                          }
428                    }
429    
430          xframe.motion = motion_presets[ARG_QUALITY];          next_frame:
431          xframe.general = general_presets[ARG_QUALITY];                  /* Read the header if it's pgm stream */
432          xframe.quant_intra_matrix = xframe.quant_inter_matrix = NULL;                  if (ARG_INPUTTYPE)
433                            status = read_pgmheader(in_file);
434    
435  #ifdef BFRAMES                  filenr++;
         xframe.bquant = 0;  
 #endif  
436    
437          xerr = xvid_encore(enc_handle, XVID_ENC_ENCODE, &xframe, &xstats);          } while ( (!status) && (filenr<ARG_MAXFRAMENR) );
438    
 /*              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;  
 */  
   
 /*  This is statictical data, e.g. for 2-pass.  
     If you are not interested in any of this, you can use  
         NULL instead of &xstats  
 */  
         *frametype = xframe.intra;  
         *streamlength = xframe.length;  
   
         return xerr;  
 }  
   
 /*********************************************************************/  
 /*                          Main program                             */  
 /*********************************************************************/  
439    
 int main(int argc, char *argv[])  
 {  
   unsigned char *divx_buffer = NULL;  
   unsigned char *in_buffer = NULL;  
440    
441    double enctime;  /*****************************************************************************
442    double totalenctime=0.;   *         Calculate totals and averages for output, print results
443     ****************************************************************************/
444    
445    long totalsize=0;          totalsize    /= filenr;
446    int status;          totalenctime /= filenr;
447    
448    int m4v_size;          printf("Avg: enctime(ms) =%7.2f, fps =%7.2f, length(bytes) = %7d\n",
449    int frame_type[ABS_MAXFRAMENR];                     totalenctime, 1000/totalenctime, (int)totalsize);
   int Iframes=0, Pframes=0, Bframes=0;  
   int use_assembler=1;  
450    
   char filename[256];  
451    
452    FILE *filehandle;  /*****************************************************************************
453     *                            XviD PART  Stop
454     ****************************************************************************/
455    
456  /* read YUV in pgm format from stdin */   release_all:
457    if (!pgmflag)  
458            if (enc_handle)
459    {    {
460          pgmflag = 1;                  status = enc_stop();
461                    if (status)
462                            fprintf(stderr, "Encore RELEASE problem return value %d\n", status);
463            }
464    
465  //      if (argc==2 && !strcmp(argv[1],"-noasm"))          if(in_file)
466  //        use_assembler = 0;                  fclose(in_file);
467            if(out_file)
468                    fclose(out_file);
469    
470     free_all_memory:
471            free(out_buffer);
472            free(mp4_buffer);
473            free(in_buffer);
474    
475            return(0);
476    
         if (argc>=3)  
         {       XDIM = atoi(argv[1]);  
                 YDIM = atoi(argv[2]);  
                 if ( (XDIM <= 0) || (XDIM >= 2048) || (YDIM <=0) || (YDIM >= 2048) )  
                 {       fprintf(stderr,"Wrong frames size %d %d, trying PGM \n",XDIM, YDIM);  
477                  }                  }
478                  else  
479    
480    /*****************************************************************************
481     *                        "statistical" functions
482     *
483     *  these are not needed for encoding or decoding, but for measuring
484     *  time and quality, there in nothing specific to XviD in these
485     *
486     *****************************************************************************/
487    
488    /* Return time elapsed time in miliseconds since the program started */
489    static double msecond()
490                  {                  {
491                          YDIM = YDIM*3/2; /* for YUV */  #ifndef WIN32
492                          pgmflag = 0;          struct timeval  tv;
493                  }          gettimeofday(&tv, 0);
494            return(tv.tv_sec*1.0e3 + tv.tv_usec * 1.0e-3);
495    #else
496            clock_t clk;
497            clk = clock();
498            return(clk * 1000 / CLOCKS_PER_SEC);
499    #endif
500          }          }
501    
502    /*****************************************************************************
503     *                             Usage message
504     *****************************************************************************/
505    
506    static void usage()
507    {
508    
509            fprintf(stderr, "Usage : xvid_stat [OPTIONS]\n");
510            fprintf(stderr, "Options :\n");
511            fprintf(stderr, " -w integer     : frame width ([1.2048])\n");
512            fprintf(stderr, " -h integer     : frame height ([1.2048])\n");
513            fprintf(stderr, " -b integer     : target bitrate (>0 | default=900kbit)\n");
514            fprintf(stderr, " -bn integer    : max bframes (default=0)\n");
515            fprintf(stderr, " -bqr integer   : bframe quantizer ratio (default=150)\n");
516            fprintf(stderr, " -bqo integer   : bframe quantizer offset (default=100)\n");
517            fprintf(stderr, " -f float       : target framerate (>0)\n");
518            fprintf(stderr, " -i string      : input filename (default=stdin)\n");
519            fprintf(stderr, " -t integer     : input data type (yuv=0, pgm=1)\n");
520            fprintf(stderr, " -n integer     : number of frames to encode\n");
521            fprintf(stderr, " -q integer     : quality ([0..5])\n");
522            fprintf(stderr, " -d boolean     : save decoder output (0 False*, !=0 True)\n");
523            fprintf(stderr, " -m boolean     : save mpeg4 raw stream (0 False*, !=0 True)\n");
524            fprintf(stderr, " -o string      : output container filename (only usefull when -m 1 is used) :\n");
525            fprintf(stderr, "                  When this option is not used : one file per encoded frame\n");
526            fprintf(stderr, "                  When this option is used : save to 'string' file\n");
527            fprintf(stderr, " -help          : prints this help message\n");
528            fprintf(stderr, " -quant integer : fixed quantizer (disables -b setting)\n");
529            fprintf(stderr, " (* means default)\n");
530    
531    }    }
532    
533    if (pgmflag)  /*****************************************************************************
534    {     if (read_pgmheader(stdin))   *                       Input and output functions
535     *
536     *      the are small and simple routines to read and write PGM and YUV
537     *      image. It's just for convenience, again nothing specific to XviD
538     *
539     *****************************************************************************/
540    
541    static int read_pgmheader(FILE* handle)
542              {              {
543                fprintf(stderr,"Wrong input format, I want YUV encapsulated in PGM\n");          int bytes,xsize,ysize,depth;
544                return 1;          char dummy[2];
545              }  
546    }          bytes = fread(dummy,1,2,handle);
547    if (argc>=4)  
548    {     ARG_QUALITY = atoi(argv[3]);          if ( (bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '5' ))
549          if ( (ARG_QUALITY < 0) || (ARG_QUALITY > 6) )                  return(1);
550                  { fprintf(stderr,"Wrong Quality\n"); return -1; }  
551          else          fscanf(handle,"%d %d %d",&xsize,&ysize,&depth);
552                    fprintf(stderr,"Quality %d\n",ARG_QUALITY);          if ( (xsize > 1440) || (ysize > 2880 ) || (depth != 255) )
553    }          {
554    if (argc>=5)                  fprintf(stderr,"%d %d %d\n",xsize,ysize,depth);
555    {     ARG_BITRATE = atoi(argv[4]);                  return(2);
         if ( (ARG_BITRATE <= 0) )  
                 { fprintf(stderr,"Wrong Bitrate\n"); return -1; }  
         if ( (ARG_BITRATE < 32) )  
                 { ARG_QUANTI = ARG_BITRATE;  
                   ARG_BITRATE=0;  
                   fprintf(stderr,"Quantizer %d\n",ARG_QUANTI);  
556                  }                  }
557          else          if ( (XDIM==0) || (YDIM==0) )
558                    fprintf(stderr,"Bitrate %d kbps\n",ARG_BITRATE);          {
559                    XDIM=xsize;
560                    YDIM=ysize*2/3;
561    }    }
562    if (argc>=6)  
563    {     ARG_FRAMERATE = (float)atof(argv[5]);          return(0);
         if ( (ARG_FRAMERATE <= 0) )  
                 { fprintf(stderr,"Wrong Fraterate %s \n",argv[5]); return -1; }  
         fprintf(stderr,"Framerate %6.3f fps\n",ARG_FRAMERATE);  
   }  
   
   if (argc>=7)  
   {     ARG_MAXFRAMENR = atoi(argv[6]);  
         if ( (ARG_MAXFRAMENR <= 0) )  
          { fprintf(stderr,"Wrong number of frames\n"); return -1; }  
         fprintf(stderr,"max. Framenr. %d\n",ARG_MAXFRAMENR);  
   }  
   
 #ifdef BFRAMES  
   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);  
564    }    }
 #endif  
565    
566  /* now we know the sizes, so allocate memory */  static int read_pgmdata(FILE* handle, unsigned char *image)
567    {
568            int i;
569            char dummy;
570    
571    in_buffer = (unsigned char *) malloc(XDIM*YDIM);          unsigned char *y = image;
572    if (!in_buffer)          unsigned char *u = image + XDIM*YDIM;
573      goto free_all_memory;          unsigned char *v = image + XDIM*YDIM + XDIM/2*YDIM/2;
574    
575    divx_buffer = (unsigned char *) malloc(XDIM*YDIM*2);          /* read Y component of picture */
576    if (!divx_buffer)          fread(y, 1, XDIM*YDIM, handle);
     goto free_all_memory;  
577    
578    YDIM = YDIM*2/3; // PGM is YUV 4:2:0 format, so real image height is *2/3 of PGM picture          for (i=0;i<YDIM/2;i++)
579            {
580                    /* read U */
581                    fread(u, 1, XDIM/2, handle);
582    
583  /*********************************************************************/                  /* read V */
584  /*                         XviD PART  Start                          */                  fread(v, 1, XDIM/2, handle);
 /*********************************************************************/  
585    
586    status = enc_init(use_assembler);                  /* Update pointers */
587          if (status)                  u += XDIM/2;
588          {                  v += XDIM/2;
                 fprintf(stderr,"Encore INIT problem, return value %d\n", status);  
                 goto release_all;  
589          }          }
590    
591  /*********************************************************************/      /*  I don't know why, but this seems needed */
592  /*                               Main loop                           */          fread(&dummy, 1, 1, handle);
 /*********************************************************************/  
593    
594    do          return(0);
595    }
596    
597    static int read_yuvdata(FILE* handle, unsigned char *image)
598      {      {
599          if (pgmflag)  
600                status = read_pgmdata(stdin, in_buffer);  // read PGM data (YUV-format)          if (fread(image, 1, IMAGE_SIZE(XDIM, YDIM), handle) != (unsigned int)IMAGE_SIZE(XDIM, YDIM))
601                    return(1);
602          else          else
603                status = read_yuvdata(stdin, in_buffer);  // read raw data (YUV-format)                  return(0);
604    }
605    
606      if (status)  /*****************************************************************************
607     *     Routines for encoding: init encoder, frame step, release encoder
608     ****************************************************************************/
609    
610    #define FRAMERATE_INCR 1001
611    
612    /* Initialize encoder for first use, pass all needed parameters to the codec */
613    static int enc_init(int use_assembler)
614          {          {
615            // Couldn't read image, most likely end-of-file          int xerr;
616            continue;  
617            xvid_gbl_init_t   xvid_gbl_init;
618            xvid_enc_create_t xvid_enc_create;
619    
620            /*------------------------------------------------------------------------
621             * XviD core initialization
622             *----------------------------------------------------------------------*/
623    
624            /* Set version -- version checking will done by xvidcore*/
625            xvid_gbl_init.version = XVID_VERSION;
626    
627            /* Do we have to enable ASM optimizations ? */
628            if(use_assembler) {
629    
630    #ifdef ARCH_IS_IA64
631                    xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_IA64;
632    #else
633                    xvid_gbl_init.cpu_flags = 0;
634    #endif
635            }
636            else {
637                    xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
638          }          }
639    
640            /* Initialize XviD core -- Should be done once per __process__ */
641            xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
642    
643      if (save_ref_flag)          /*------------------------------------------------------------------------
644          {           * XviD encoder initialization
645                  sprintf(filename, "%s%05d.pgm", filepath, filenr);           *----------------------------------------------------------------------*/
646                  write_pgm(filename,in_buffer);  
647            /* Version again */
648            xvid_enc_create.version = XVID_VERSION;
649    
650            /* Width and Height of input frames */
651            xvid_enc_create.width = XDIM;
652            xvid_enc_create.height = YDIM;
653    
654            /* No fancy thread tests */
655            xvid_enc_create.num_threads = 0;
656    
657            /* Frame rate - Do some quick float fps = fincr/fbase hack */
658            if ((ARG_FRAMERATE - (int)ARG_FRAMERATE) < SMALL_EPS) {
659                    xvid_enc_create.fincr = 1;
660                    xvid_enc_create.fbase = (int)ARG_FRAMERATE;
661            } else {
662                    xvid_enc_create.fincr = FRAMERATE_INCR;
663                    xvid_enc_create.fbase = (int)(FRAMERATE_INCR * ARG_FRAMERATE);
664          }          }
665    
666            /* Maximum key frame interval */
667            xvid_enc_create.max_key_interval = (int)ARG_FRAMERATE*10;
668    
669  /*********************************************************************/          /* Bframes settings */
670  /*               analyse this frame before encoding                  */          xvid_enc_create.max_bframes = ARG_MAXBFRAMES;
671  /*********************************************************************/          xvid_enc_create.bquant_ratio = ARG_BQRATIO;
672            xvid_enc_create.bquant_offset = ARG_BQOFFSET;
673    
674  //      nothing is done here at the moment, but you could e.g. create          /* Dropping ratio frame -- we don't need that */
675  //      histograms or measure entropy or apply preprocessing filters...          xvid_enc_create.frame_drop_ratio = 0;
676    
677  /*********************************************************************/          /* Global encoder options */
678  /*               encode and decode this frame                        */          xvid_enc_create.global = XVID_EXTRASTATS_ENABLE;
 /*********************************************************************/  
679    
680          enctime = -msecond();          /* I use a small value here, since will not encode whole movies, but short clips */
681          status = enc_main(in_buffer, divx_buffer, &m4v_size, &frame_type[filenr]);          xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
         enctime += msecond();  
682    
683          totalenctime += enctime;          /* Retrieve the encoder instance from the structure */
684          totalsize += m4v_size;          enc_handle = xvid_enc_create.handle;
685    
686          fprintf(stderr,"Frame %5d: intra %d, enctime =%6.1f ms length=%7d bytes\n",          return(xerr);
687                   filenr, frame_type[filenr], enctime*1000, m4v_size);  }
688    
689          if (save_m4v_flag)  static int enc_stop()
690          {          {
691                  fwrite(divx_buffer, m4v_size, 1, stdout);          int xerr;
692    
693            /* Destroy the encoder instance */
694            xerr = xvid_encore(enc_handle, XVID_ENC_DESTROY, NULL, NULL);
695    
696            return(xerr);
697          }          }
698    
699          if (pgmflag)  static int enc_main(unsigned char* image,
700                  status = read_pgmheader(stdin);                                          unsigned char* bitstream,
701                                  // because if this was the last PGM, stop now                                          long *frametype,
702                                            int stats[3])
703    {
704            int ret;
705    
706          filenr++;          xvid_enc_frame_t xvid_enc_frame;
707            xvid_enc_stats_t xvid_enc_stats[2];
708    
709     } while ( (!status) && (filenr<ARG_MAXFRAMENR) );          /* Version for the frame and the stats */
710            xvid_enc_frame.version = XVID_VERSION;
711            xvid_enc_stats[0].version = XVID_VERSION;
712            xvid_enc_stats[1].version = XVID_VERSION;
713    
714            /* Bind output buffer */
715            xvid_enc_frame.bitstream = bitstream;
716            xvid_enc_frame.length = -1;
717    
718            /* Initialize input image fields */
719            xvid_enc_frame.input.plane[0]  = image;
720            xvid_enc_frame.input.csp       = XVID_CSP_I420;
721            xvid_enc_frame.input.stride[0] = XDIM;
722    
723  /*********************************************************************/          /* Set up core's general features */
724  /*     calculate totals and averages for output, print results       */          xvid_enc_frame.vol_flags = vol_presets[ARG_QUALITY];
 /*********************************************************************/  
725    
726          totalsize    /= filenr;          /* Set up core's general features */
727          totalenctime /= filenr;          xvid_enc_frame.vop_flags = vop_presets[ARG_QUALITY];
728    
729          for (i=0;i<filenr;i++)          /* Frame type -- let core decide for us */
730          {          xvid_enc_frame.type   = XVID_TYPE_AUTO;
                 switch (frame_type[i])  
                 {  
                 case 0:  
                         Pframes++;  
                         break;  
                 case 1:  
                         Iframes++;  
                         break;  
                 case 2:  
                 default:  
                         Bframes++;  
                         break;  
                 }  
         }  
731    
732          fprintf(stderr,"Avg: enctime %5.2f ms, %5.2f fps, filesize =%d\n",          /* Force the right quantizer */
733                  1000*totalenctime, 1./totalenctime, totalsize);          xvid_enc_frame.quant  = ARG_QUANTI;
734            xvid_enc_frame.bquant = 0;
735    
736  /*********************************************************************/          /* Set up motion estimation flags */
737  /*                         XviD PART  Stop                           */          xvid_enc_frame.motion = motion_presets[ARG_QUALITY];
 /*********************************************************************/  
738    
739  release_all:          /* We don't use special matrices */
740            xvid_enc_frame.quant_intra_matrix = NULL;
741            xvid_enc_frame.quant_inter_matrix = NULL;
742    
743          if (enc_handle)          /* Foll proof */
744          {          xvid_enc_stats[0].sse_y = 0;
745                  status = enc_stop();          xvid_enc_stats[0].sse_v = 0;
746                  if (status)          xvid_enc_stats[0].sse_u = 0;
                         fprintf(stderr,"Encore RELEASE problem return value %d\n", status);  
         }  
747    
748  free_all_memory:          /* Encode the frame */
749          free(divx_buffer);          xvid_enc_frame.vop_flags |= XVID_EXTRASTATS;
750          free(in_buffer);          ret = xvid_encore(enc_handle, XVID_ENC_ENCODE, &xvid_enc_frame, &xvid_enc_stats);
751    
752            *frametype = xvid_enc_stats[0].type;
753            stats[0]   = xvid_enc_stats[0].sse_y;
754            stats[1]   = xvid_enc_stats[0].sse_u;
755            stats[2]   = xvid_enc_stats[0].sse_v;
756    
757    return 0;          return(ret);
758  }  }

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

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