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

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

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