--- trunk/xvidcore/examples/xvid_encraw.c 2002/08/17 20:03:36 376 +++ branches/dev-api-4/xvidcore/examples/xvid_encraw.c 2003/03/16 12:05:09 926 @@ -1,572 +1,882 @@ -/************************************************************************** +/***************************************************************************** * - * XVID MPEG-4 VIDEO CODEC - Example for encoding and decoding + * XVID MPEG-4 VIDEO CODEC + * - Console based test application - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * Copyright(C) 2002-2003 Christoph Lampert * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * - *************************************************************************/ + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * $Id: xvid_encraw.c,v 1.11.2.8 2003-03-16 12:04:13 suxen_drol Exp $ + * + ****************************************************************************/ -/************************************************************************ +/***************************************************************************** + * Application notes : * - * Speed test routine for XviD using the XviD-API - * (C) Christoph Lampert, 2002/08/17 - * - * A sequence of YUV pics in PGM or RAW file format is encoded and the - * raw MPEG-4 stream is written to stdout. - * The encoding speed of this is measured, too. + * A sequence of raw YUV I420 pics or YUV I420 PGM file format is encoded + * The speed is measured and frames' PSNR are taken from core. * * The program is plain C and needs no libraries except for libxvidcore, - * and maths-lib, so with UN*X you simply compile by - * - * 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 + * and maths-lib. * ************************************************************************/ -/************************************************************************ - * - * For EXAMPLES how to use this, see the seperate file xvid_stat.examples - * - ************************************************************************/ - #include #include -#include // needed for log10 -#include // only needed for gettimeofday +#include +#include +#ifndef WIN32 +#include +#else +#include +#endif -#include "../src/xvid.h" /* comes with XviD */ +#include "xvid.h" -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 - }; - -int general_presets[7] = { - XVID_H263QUANT, /* or use XVID_MPEGQUANT */ // Q 0 - XVID_MPEGQUANT, // Q 1 - XVID_H263QUANT, // Q 2 - XVID_H263QUANT | XVID_HALFPEL, // Q 3 - XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V, // Q 4 - XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V, // Q 5 - XVID_H263QUANT | XVID_HALFPEL | XVID_INTER4V }; // Q 6 - - -/* my default values for encoding */ - -#define ABS_MAXFRAMENR 9999 // max number of frames - -int ARG_BITRATE=900; -int ARG_QUANTI=0; - -int ARG_QUALITY =6; -int ARG_MINQUANT=1; -int ARG_MAXQUANT=31; -float ARG_FRAMERATE=25.00; -int ARG_MAXFRAMENR=ABS_MAXFRAMENR; +/***************************************************************************** + * Quality presets + ****************************************************************************/ + +static xvid_motion_t const motion_presets[] = { + 0, + PMV_HALFPELREFINE16, + PMV_HALFPELREFINE16, + PMV_HALFPELREFINE16 | PMV_HALFPELREFINE8, + PMV_HALFPELREFINE16 | PMV_HALFPELREFINE8 | PMV_EXTSEARCH16 | PMV_USESQUARES16, + PMV_HALFPELREFINE16 | PMV_HALFPELREFINE8 | PMV_EXTSEARCH16 | PMV_USESQUARES16 | PMV_CHROMA16 | PMV_CHROMA8, +}; + +static xvid_vol_t const vol_presets[] = { + XVID_MPEGQUANT, + 0, + 0, + XVID_QUARTERPEL, + XVID_QUARTERPEL | XVID_GMC, + XVID_QUARTERPEL | XVID_GMC +}; + +static xvid_vop_t const vop_presets[] = { + XVID_DYNAMIC_BFRAMES, + XVID_DYNAMIC_BFRAMES, + XVID_DYNAMIC_BFRAMES | XVID_HALFPEL, + XVID_DYNAMIC_BFRAMES | XVID_HALFPEL | XVID_INTER4V, + XVID_DYNAMIC_BFRAMES | XVID_HALFPEL | XVID_INTER4V | XVID_HQACPRED, + XVID_DYNAMIC_BFRAMES | XVID_HALFPEL | XVID_INTER4V | XVID_HQACPRED | XVID_MODEDECISION_BITS +}; + +/***************************************************************************** + * Command line global variables + ****************************************************************************/ + +/* Maximum number of frames to encode */ +#define ABS_MAXFRAMENR 9999 + +static int ARG_STATS = 0; +static int ARG_DUMP = 0; +static int ARG_LUMIMASKING = 0; +static int ARG_BITRATE = 900; +static int ARG_QUANTI = 0; +static int ARG_QUALITY = 5; +static int ARG_MINQUANT = 1; +static int ARG_MAXQUANT = 31; +static float ARG_FRAMERATE = 25.00f; +static int ARG_MAXFRAMENR = ABS_MAXFRAMENR; +static char *ARG_INPUTFILE = NULL; +static int ARG_INPUTTYPE = 0; +static int ARG_SAVEMPEGSTREAM = 0; +static char *ARG_OUTPUTFILE = NULL; +static int XDIM = 0; +static int YDIM = 0; +static int ARG_BQRATIO = 150; +static int ARG_BQOFFSET = 100; +static int ARG_MAXBFRAMES = 0; +static int ARG_PACKED = 0; +#define IMAGE_SIZE(x,y) ((x)*(y)*3/2) -#ifdef BFRAMES +#define MAX(A,B) ( ((A)>(B)) ? (A) : (B) ) +#define SMALL_EPS (1e-10) -int ARG_MAXBFRAMES=1; -int ARG_BQUANTRATIO=200; +#define SWAP(a) ( (((a)&0x000000ff)<<24) | (((a)&0x0000ff00)<<8) | \ + (((a)&0x00ff0000)>>8) | (((a)&0xff000000)>>24) ) -#endif +/**************************************************************************** + * Nasty global vars ;-) + ***************************************************************************/ + +static int i; + +/* the path where to save output */ +static char filepath[256] = "./"; + +/* Internal structures (handles) for encoding and decoding */ +static void *enc_handle = NULL; + +/***************************************************************************** + * Local prototypes + ****************************************************************************/ + +/* Prints program usage message */ +static void usage(); + +/* Statistical functions */ +static double msecond(); + +/* PGM related functions */ +static int read_pgmheader(FILE* handle); +static int read_pgmdata(FILE* handle, unsigned char *image); +static int read_yuvdata(FILE* handle, unsigned char *image); + +/* Encoder related functions */ +static int enc_init(int use_assembler); +static int enc_stop(); +static int enc_main(unsigned char* image, + unsigned char* bitstream, + int *key, + int *stats_type, + int *stats_quant, + int *stats_length, + int stats[3]); + +/***************************************************************************** + * Main function + ****************************************************************************/ -#define MAX(A,B) ( ((A)>(B)) ? (A) : (B) ) -#define SMALL_EPS 1e-10 +int main(int argc, char *argv[]) +{ -/* these are global variables. Not very elegant, but easy, and this is an easy program */ - -int XDIM=0; -int YDIM=0; // will be set when reading first image -int i,filenr = 0; + unsigned char *mp4_buffer = NULL; + unsigned char *in_buffer = NULL; + unsigned char *out_buffer = NULL; -int save_m4v_flag = 1; // output MPEG4-bytestream? -int save_ref_flag = 0; // save input image + double enctime; + double totalenctime=0.; + + int totalsize; + int result; + int m4v_size; + int key; + int stats_type; + int stats_quant; + int stats_length; + int use_assembler=0; -int pgmflag = 0; // a flag, if input is in PGM format, overwritten in init-phase -char filepath[256] = "./"; // the path where to save output + int input_num; + int output_num; + + char filename[256]; + + FILE *in_file = stdin; + FILE *out_file = NULL; -void *enc_handle = NULL; // internal structures (handles) for encoding + printf("xvid_encraw - raw mpeg4 bitstream encoder "); + printf("written by Christoph Lampert 2002-2003\n\n"); +/***************************************************************************** + * Command line parsing + ****************************************************************************/ -/*********************************************************************/ -/* "statistical" functions */ -/* */ -/* these are not needed for encoding or decoding, but for measuring */ -/* time and quality, there in nothing specific to XviD in these */ -/* */ -/*********************************************************************/ + for (i=1; i< argc; i++) { + + if (strcmp("-asm", argv[i]) == 0 ) { + use_assembler = 1; + } + else if (strcmp("-w", argv[i]) == 0 && i < argc - 1 ) { + i++; + XDIM = atoi(argv[i]); + } + else if (strcmp("-h", argv[i]) == 0 && i < argc - 1 ) { + i++; + YDIM = atoi(argv[i]); + } + else if (strcmp("-b", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_BITRATE = atoi(argv[i]); + } + else if (strcmp("-bn", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_MAXBFRAMES = atoi(argv[i]); + } + else if (strcmp("-p", argv[i]) == 0) { + ARG_PACKED = 1; + } + else if (strcmp("-bqr", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_BQRATIO = atoi(argv[i]); + } + else if (strcmp("-bqo", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_BQOFFSET = atoi(argv[i]); + } + else if (strcmp("-q", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_QUALITY = atoi(argv[i]); + } + else if (strcmp("-f", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_FRAMERATE = (float)atof(argv[i]); + } + else if (strcmp("-i", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_INPUTFILE = argv[i]; + } + else if (strcmp("-s", argv[i]) == 0) { + ARG_STATS = 1; + } + else if (strcmp("-dump", argv[i]) == 0) { + ARG_DUMP = 1; + } + else if (strcmp("-lumimasking", argv[i]) == 0) { + ARG_LUMIMASKING = 1; + } + else if (strcmp("-t", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_INPUTTYPE = atoi(argv[i]); + } + else if(strcmp("-n", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_MAXFRAMENR = atoi(argv[i]); + } + else if (strcmp("-quant", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_QUANTI = atoi(argv[i]); + } + else if (strcmp("-m", argv[i]) == 0) { + ARG_SAVEMPEGSTREAM = 1; + } + else if (strcmp("-o", argv[i]) == 0 && i < argc - 1 ) { + i++; + ARG_OUTPUTFILE = argv[i]; + } + else if (strcmp("-help", argv[i])) { + usage(); + return(0); + } + else { + usage(); + exit(-1); + } + + } + +/***************************************************************************** + * Arguments checking + ****************************************************************************/ + + if (XDIM <= 0 || XDIM >= 2048 || YDIM <=0 || YDIM >= 2048 ) { + fprintf(stderr, "Trying to retreive width and height from PGM header\n"); + ARG_INPUTTYPE = 1; /* pgm */ + } + + if ( ARG_QUALITY < 0 || ARG_QUALITY > 5) { + fprintf(stderr,"Wrong Quality\n"); + return(-1); + } -double msecond() -/* return the current time in seconds(!) */ -{ - struct timeval tv; - gettimeofday(&tv, 0); - return tv.tv_sec + tv.tv_usec * 1.0e-6; -} + if ( ARG_BITRATE <= 0 && ARG_QUANTI == 0) { + fprintf(stderr,"Wrong Bitrate\n"); + return(-1); + } -/*********************************************************************/ -/* 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 */ -/* */ -/*********************************************************************/ + if ( ARG_FRAMERATE <= 0) { + fprintf(stderr,"Wrong Framerate %s \n",argv[5]); + return(-1); + } -int read_pgmheader(FILE* handle) -{ - int bytes,xsize,ysize,depth; - char dummy[2]; - - bytes = fread(dummy,1,2,handle); + if ( ARG_MAXFRAMENR <= 0) { + fprintf(stderr,"Wrong number of frames\n"); + return(-1); + } - if ( (bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '5' )) - return 1; - fscanf(handle,"%d %d %d",&xsize,&ysize,&depth); - if ( (xsize > 1440) || (ysize > 2880 ) || (depth != 255) ) - { - return 2; + if ( ARG_INPUTFILE == NULL || strcmp(ARG_INPUTFILE, "stdin") == 0) { + in_file = stdin; } - if ( (XDIM==0) || (YDIM==0) ) - { XDIM=xsize; - YDIM=ysize; + else { + + in_file = fopen(ARG_INPUTFILE, "rb"); + if (in_file == NULL) { + fprintf(stderr, "Error opening input file %s\n", ARG_INPUTFILE); + return(-1); + } } - return 0; -} + if (ARG_INPUTTYPE) { + if (read_pgmheader(in_file)) { + fprintf(stderr, "Wrong input format, I want YUV encapsulated in PGM\n"); + return(-1); + } + } -int read_pgmdata(FILE* handle, unsigned char *image) -{ - int i,status; - char dummy; - - unsigned char* buff1_ptr2 = image + XDIM*YDIM; - unsigned char* buff1_ptr3 = image + XDIM*YDIM + XDIM/2*YDIM/2; + /* now we know the sizes, so allocate memory */ + in_buffer = (unsigned char *) malloc(IMAGE_SIZE(XDIM,YDIM)); + if (!in_buffer) + goto free_all_memory; + + /* this should really be enough memory ! */ + mp4_buffer = (unsigned char *) malloc(IMAGE_SIZE(XDIM,YDIM)*2); + if (!mp4_buffer) + goto free_all_memory; + +/***************************************************************************** + * XviD PART Start + ****************************************************************************/ - fread(image,XDIM*YDIM,1,stdin); // read Y component of picture - - for (i=0;i= ARG_MAXFRAMENR) { - 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; - } - else - return 1; -} + result = 1; + } -/*********************************************************************/ -/* Routines for encoding: init encoder, frame step, release encoder */ -/*********************************************************************/ + if (!result) + { + if(ARG_INPUTTYPE) { + /* read PGM data (YUV-format) */ + result = read_pgmdata(in_file, in_buffer); + } else { + /* read raw data (YUV-format) */ + result = read_yuvdata(in_file, in_buffer); + } + } + +/***************************************************************************** + * Encode and decode this frame + ****************************************************************************/ + + enctime = msecond(); + m4v_size = enc_main(!result?in_buffer:0, mp4_buffer, &key, &stats_type, &stats_quant, &stats_length, stats); + enctime = msecond() - enctime; + + /* Write the Frame statistics */ + + printf("%5d: key=%i, time(ms)=%6.1f, length=%7d", + !result?input_num:-1, + key, + (float)enctime, + (int)m4v_size); + + if (stats_type > 0) { /* !XVID_TYPE_NOTHING */ + + switch(stats_type) { + case XVID_TYPE_IVOP: + type = "I"; + break; + case XVID_TYPE_PVOP: + type = "P"; + break; + case XVID_TYPE_BVOP: + type = "B"; + break; + case XVID_TYPE_SVOP: + type = "S"; + break; + default: + type = "U"; + break; + } + + printf(" | type=%s quant=%2d, length=%7d", type, stats_quant, stats_length); + + if(ARG_STATS) { + printf(", psnr y = %2.2f, psnr u = %2.2f, psnr v = %2.2f", + (stats[0] == 0)? 0.0f: 48.131f - 10*(float)log10((float)stats[0]/((float)(XDIM)*(YDIM))), + (stats[1] == 0)? 0.0f: 48.131f - 10*(float)log10((float)stats[1]/((float)(XDIM)*(YDIM)/4)), + (stats[2] == 0)? 0.0f: 48.131f - 10*(float)log10((float)stats[2]/((float)(XDIM)*(YDIM)/4))); + } -#define FRAMERATE_INCR 1001 + } + printf("\n"); + + if (m4v_size < 0) { + break; + } + + /* Update encoding time stats */ + totalenctime += enctime; + totalsize += m4v_size; + +/***************************************************************************** + * Save stream to file + ****************************************************************************/ + + if (m4v_size>0 && ARG_SAVEMPEGSTREAM) + { + /* Save single files */ + if (out_file == NULL) { + sprintf(filename, "%sframe%05d.m4v", filepath, output_num); + out_file = fopen(filename, "wb"); + fwrite(mp4_buffer, m4v_size, 1, out_file); + fclose(out_file); + out_file = NULL; + output_num++; + } + else { + + /* Write mp4 data */ + fwrite(mp4_buffer, 1, m4v_size, out_file); + + } + } + + input_num++; + + /* Read the header if it's pgm stream */ + if (!result && ARG_INPUTTYPE) + result = read_pgmheader(in_file); + + } while (1); -int enc_init(int use_assembler) -{ /* initialize encoder for first use, pass all needed parameters to the codec */ - int xerr; - XVID_INIT_PARAM xinit; - XVID_ENC_PARAM xparam; + +/***************************************************************************** + * Calculate totals and averages for output, print results + ****************************************************************************/ - if(use_assembler) + printf("Tot: enctime(ms) =%7.2f, length(bytes) = %7d\n", + totalenctime, (int)totalsize); -#ifdef ARCH_IA64 - xinit.cpu_flags = XVID_CPU_FORCE | XVID_CPU_IA64; -#else - xinit.cpu_flags = 0; -#endif + if (input_num > 0) { + totalsize /= input_num; + totalenctime /= input_num; + }else{ + totalsize = -1; + totalenctime = -1; + } - else - xinit.cpu_flags = XVID_CPU_FORCE; + printf("Avg: enctime(ms) =%7.2f, fps =%7.2f, length(bytes) = %7d\n", + totalenctime, 1000/totalenctime, (int)totalsize); - xvid_init(NULL, 0, &xinit, NULL); - xparam.width = XDIM; - xparam.height = YDIM; - if ((ARG_FRAMERATE - (int)ARG_FRAMERATE) < SMALL_EPS) - { - xparam.fincr = 1; - xparam.fbase = (int)ARG_FRAMERATE; - } - else - { - xparam.fincr = FRAMERATE_INCR; - xparam.fbase = (int)(FRAMERATE_INCR * ARG_FRAMERATE); +/***************************************************************************** + * XviD PART Stop + ****************************************************************************/ + + release_all: + + if (enc_handle) + { + result = enc_stop(); + if (result) + fprintf(stderr, "Encore RELEASE problem return value %d\n", result); } - 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 - /* I use a small value here, since will not encode whole movies, - but short clips */ + if(in_file) + fclose(in_file); + if(out_file) + fclose(out_file); + + free_all_memory: + free(out_buffer); + free(mp4_buffer); + free(in_buffer); - xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xparam, NULL); - enc_handle=xparam.handle; + return(0); - return xerr; } -int enc_stop() -{ int xerr; - xerr = xvid_encore(enc_handle, XVID_ENC_DESTROY, NULL, NULL); - return xerr; +/***************************************************************************** + * "statistical" functions + * + * these are not needed for encoding or decoding, but for measuring + * time and quality, there in nothing specific to XviD in these + * + *****************************************************************************/ + +/* Return time elapsed time in miliseconds since the program started */ +static double msecond() +{ +#ifndef WIN32 + struct timeval tv; + gettimeofday(&tv, 0); + return(tv.tv_sec*1.0e3 + tv.tv_usec * 1.0e-3); +#else + clock_t clk; + clk = clock(); + return(clk * 1000 / CLOCKS_PER_SEC); +#endif } -int enc_main(unsigned char* image, unsigned char* bitstream, int *streamlength, int* frametype) -{ int xerr; +/***************************************************************************** + * Usage message + *****************************************************************************/ + +static void usage() +{ + + fprintf(stderr, "Usage : xvid_stat [OPTIONS]\n"); + fprintf(stderr, "Options :\n"); + fprintf(stderr, " -w integer : frame width ([1.2048])\n"); + fprintf(stderr, " -h integer : frame height ([1.2048])\n"); + fprintf(stderr, " -b integer : target bitrate (>0 | default=900kbit)\n"); + fprintf(stderr, " -bn integer : max bframes (default=0)\n"); + fprintf(stderr, " -p : packed mode\n"); + fprintf(stderr, " -bqr integer : bframe quantizer ratio (default=150)\n"); + fprintf(stderr, " -bqo integer : bframe quantizer offset (default=100)\n"); + fprintf(stderr, " -f float : target framerate (>0)\n"); + fprintf(stderr, " -i string : input filename (default=stdin)\n"); + fprintf(stderr, " -s : print stats about encoded frames\n"); + fprintf(stderr, " -t integer : input data type (yuv=0, pgm=1)\n"); + fprintf(stderr, " -n integer : number of frames to encode\n"); + fprintf(stderr, " -q integer : quality ([0..5])\n"); + fprintf(stderr, " -dump : save decoder output\n"); + fprintf(stderr, " -m : save mpeg4 raw stream\n"); + fprintf(stderr, " -o string : output container filename (only usefull when -m 1 is used) :\n"); + fprintf(stderr, " When this option is not used : one file per encoded frame\n"); + fprintf(stderr, " When this option is used : save to 'string' file\n"); + fprintf(stderr, " -help : prints this help message\n"); + fprintf(stderr, " -quant integer : fixed quantizer (disables -b setting)\n"); + fprintf(stderr, " (* means default)\n"); + +} + +/***************************************************************************** + * 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 + * + *****************************************************************************/ + +static int read_pgmheader(FILE* handle) +{ + int bytes,xsize,ysize,depth; + char dummy[2]; + + bytes = fread(dummy,1,2,handle); - XVID_ENC_FRAME xframe; - XVID_ENC_STATS xstats; + if ( (bytes < 2) || (dummy[0] != 'P') || (dummy[1] != '5' )) + return(1); - xframe.bitstream = bitstream; - xframe.length = -1; // this is written by the routine + fscanf(handle,"%d %d %d",&xsize,&ysize,&depth); + if ( (xsize > 1440) || (ysize > 2880 ) || (depth != 255) ) + { + fprintf(stderr,"%d %d %d\n",xsize,ysize,depth); + return(2); + } + if ( (XDIM==0) || (YDIM==0) ) + { + XDIM=xsize; + YDIM=ysize*2/3; + } - xframe.image = image; - xframe.colorspace = XVID_CSP_YV12; // defined in + return(0); +} - xframe.intra = -1; // let the codec decide between I-frame (1) and P-frame (0) +static int read_pgmdata(FILE* handle, unsigned char *image) +{ + int i; + char dummy; + + unsigned char *y = image; + unsigned char *u = image + XDIM*YDIM; + unsigned char *v = image + XDIM*YDIM + XDIM/2*YDIM/2; - xframe.quant = ARG_QUANTI; // is quant != 0, use a fixed quant (and ignore bitrate) + /* read Y component of picture */ + fread(y, 1, XDIM*YDIM, handle); + + for (i=0;iis_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(0); +} - return xerr; +static int read_yuvdata(FILE* handle, unsigned char *image) +{ + + if (fread(image, 1, IMAGE_SIZE(XDIM, YDIM), handle) != (unsigned int)IMAGE_SIZE(XDIM, YDIM)) + return(1); + else + return(0); } -/*********************************************************************/ -/* Main program */ -/*********************************************************************/ +/***************************************************************************** + * Routines for encoding: init encoder, frame step, release encoder + ****************************************************************************/ -int main(int argc, char *argv[]) +/* sample plugin */ + +int rawenc_debug(void * handle, int opt, void * param1, void * param2) { - unsigned char *divx_buffer = NULL; - unsigned char *in_buffer = NULL; + switch(opt) + { + case XVID_PLG_INFO : + { + xvid_plg_info_t * info = (xvid_plg_info_t*)param1; + info->flags = XVID_REQDQUANTS; + return 0; + } + + case XVID_PLG_CREATE : + case XVID_PLG_DESTROY : + case XVID_PLG_BEFORE : + return 0; - double enctime; - double totalenctime=0.; - - long totalsize=0; - int status; - - int m4v_size; - int frame_type[ABS_MAXFRAMENR]; - int Iframes=0, Pframes=0, Bframes=0; - int use_assembler=1; - - char filename[256]; - - FILE *filehandle; + case XVID_PLG_AFTER : + { + xvid_plg_data_t * data = (xvid_plg_data_t*)param1; + int i,j; -/* read YUV in pgm format from stdin */ - if (!pgmflag) - { - pgmflag = 1; - -// if (argc==2 && !strcmp(argv[1],"-noasm")) -// use_assembler = 0; - - 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); - } - else - { - YDIM = YDIM*3/2; /* for YUV */ - pgmflag = 0; - } - } - } - - if (pgmflag) - { if (read_pgmheader(stdin)) - { - fprintf(stderr,"Wrong input format, I want YUV encapsulated in PGM\n"); - return 1; - } - } - if (argc>=4) - { ARG_QUALITY = atoi(argv[3]); - if ( (ARG_QUALITY < 0) || (ARG_QUALITY > 6) ) - { fprintf(stderr,"Wrong Quality\n"); return -1; } - else - fprintf(stderr,"Quality %d\n",ARG_QUALITY); - } - if (argc>=5) - { ARG_BITRATE = atoi(argv[4]); - 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); - } - else - fprintf(stderr,"Bitrate %d kbps\n",ARG_BITRATE); - } - if (argc>=6) - { ARG_FRAMERATE = (float)atof(argv[5]); - 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); - } -#endif + printf("---[ frame: %5i quant: %2i length: %6i ]---\n", data->frame_num, data->quant, data->length); + for (j=0; jmb_height; j++) { + for (i = 0; imb_width; i++) + printf("%2i ", data->dquant[j*data->dquant_stride + i]); + printf("\n"); + } + + return 0; + } + } -/* now we know the sizes, so allocate memory */ + return XVID_ERR_FAIL; +} - in_buffer = (unsigned char *) malloc(XDIM*YDIM); - if (!in_buffer) - goto free_all_memory; - - divx_buffer = (unsigned char *) malloc(XDIM*YDIM*2); - if (!divx_buffer) - goto free_all_memory; - - YDIM = YDIM*2/3; // PGM is YUV 4:2:0 format, so real image height is *2/3 of PGM picture -/*********************************************************************/ -/* XviD PART Start */ -/*********************************************************************/ +#define FRAMERATE_INCR 1001 - status = enc_init(use_assembler); - if (status) - { - fprintf(stderr,"Encore INIT problem, return value %d\n", status); - goto release_all; - } +/* Initialize encoder for first use, pass all needed parameters to the codec */ +static int enc_init(int use_assembler) +{ + int xerr; -/*********************************************************************/ -/* Main loop */ -/*********************************************************************/ + xvid_enc_plugin_t plugins[2]; - do - { - 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) - - if (status) - { - // Couldn't read image, most likely end-of-file - continue; + xvid_gbl_init_t xvid_gbl_init; + xvid_enc_create_t xvid_enc_create; + + /*------------------------------------------------------------------------ + * XviD core initialization + *----------------------------------------------------------------------*/ + + /* Set version -- version checking will done by xvidcore*/ + memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init)); + xvid_gbl_init.version = XVID_VERSION; + + + /* Do we have to enable ASM optimizations ? */ + if(use_assembler) { + +#ifdef ARCH_IS_IA64 + xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_IA64; +#else + xvid_gbl_init.cpu_flags = 0; +#endif + } + else { + xvid_gbl_init.cpu_flags = XVID_CPU_FORCE; } + /* Initialize XviD core -- Should be done once per __process__ */ + xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL); - if (save_ref_flag) - { - sprintf(filename, "%s%05d.pgm", filepath, filenr); - write_pgm(filename,in_buffer); - } + /*------------------------------------------------------------------------ + * XviD encoder initialization + *----------------------------------------------------------------------*/ + /* Version again */ + memset(&xvid_enc_create, 0, sizeof(xvid_enc_create)); + xvid_enc_create.version = XVID_VERSION; -/*********************************************************************/ -/* analyse this frame before encoding */ -/*********************************************************************/ + /* Width and Height of input frames */ + xvid_enc_create.width = XDIM; + xvid_enc_create.height = YDIM; -// nothing is done here at the moment, but you could e.g. create -// histograms or measure entropy or apply preprocessing filters... + /* init plugins */ -/*********************************************************************/ -/* encode and decode this frame */ -/*********************************************************************/ + xvid_enc_create.plugins = plugins; + xvid_enc_create.num_plugins = 0; + + if (ARG_LUMIMASKING) { + plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking; + plugins[xvid_enc_create.num_plugins].param = NULL; + xvid_enc_create.num_plugins++; + } + + if (ARG_DUMP) { + plugins[xvid_enc_create.num_plugins].func = xvid_plugin_dump; + plugins[xvid_enc_create.num_plugins].param = NULL; + xvid_enc_create.num_plugins++; + } + +/* plugins[xvid_enc_create.num_plugins].func = rawenc_debug; + plugins[xvid_enc_create.num_plugins].param = NULL; + xvid_enc_create.num_plugins++; */ + + /* No fancy thread tests */ + xvid_enc_create.num_threads = 0; + + /* Frame rate - Do some quick float fps = fincr/fbase hack */ + if ((ARG_FRAMERATE - (int)ARG_FRAMERATE) < SMALL_EPS) { + xvid_enc_create.fincr = 1; + xvid_enc_create.fbase = (int)ARG_FRAMERATE; + } else { + xvid_enc_create.fincr = FRAMERATE_INCR; + xvid_enc_create.fbase = (int)(FRAMERATE_INCR * ARG_FRAMERATE); + } + + /* Maximum key frame interval */ + xvid_enc_create.max_key_interval = (int)ARG_FRAMERATE*10; + + /* Bframes settings */ + xvid_enc_create.max_bframes = ARG_MAXBFRAMES; + xvid_enc_create.bquant_ratio = ARG_BQRATIO; + xvid_enc_create.bquant_offset = ARG_BQOFFSET; + + /* Dropping ratio frame -- we don't need that */ + xvid_enc_create.frame_drop_ratio = 0; + + /* Global encoder options */ + xvid_enc_create.global = 0; + if (ARG_PACKED) xvid_enc_create.global |= XVID_PACKED; + if (ARG_STATS) xvid_enc_create.global |= XVID_EXTRASTATS_ENABLE; - enctime = -msecond(); - status = enc_main(in_buffer, divx_buffer, &m4v_size, &frame_type[filenr]); - enctime += msecond(); + /* I use a small value here, since will not encode whole movies, but short clips */ + xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL); - totalenctime += enctime; - totalsize += m4v_size; + /* Retrieve the encoder instance from the structure */ + enc_handle = xvid_enc_create.handle; - fprintf(stderr,"Frame %5d: intra %d, enctime =%6.1f ms length=%7d bytes\n", - filenr, frame_type[filenr], enctime*1000, m4v_size); + return(xerr); +} - if (save_m4v_flag) - { - fwrite(divx_buffer, m4v_size, 1, stdout); - } - - if (pgmflag) - status = read_pgmheader(stdin); - // because if this was the last PGM, stop now +static int enc_stop() +{ + int xerr; - filenr++; + /* Destroy the encoder instance */ + xerr = xvid_encore(enc_handle, XVID_ENC_DESTROY, NULL, NULL); - } while ( (!status) && (filenr