]> git.sesse.net Git - x264/blob - x264.c
temporal predictors for 16x16 motion search.
[x264] / x264.c
1 /*****************************************************************************
2  * x264: h264 encoder/decoder testing program.
3  *****************************************************************************
4  * Copyright (C) 2003 Laurent Aimar
5  * $Id: x264.c,v 1.1 2004/06/03 19:24:12 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27
28 #include <math.h>
29
30 #include <signal.h>
31 #define _GNU_SOURCE
32 #include <getopt.h>
33
34 #ifdef _MSC_VER
35 #include <io.h>     /* _setmode() */
36 #include <fcntl.h>  /* _O_BINARY */
37 #endif
38
39 #ifdef AVIS_INPUT
40 #include <windows.h>
41 #include <vfw.h>
42 #endif
43
44 #ifdef MP4_OUTPUT
45 #include <gpac/isomedia.h>
46 #endif
47
48
49 #include "common/common.h"
50 #include "x264.h"
51
52 #ifndef _MSC_VER
53 #include "config.h"
54 #endif
55
56 #include "matroska.h"
57
58 #define DATA_MAX 3000000
59 uint8_t data[DATA_MAX];
60
61 typedef void *hnd_t;
62
63 /* Ctrl-C handler */
64 static int     b_ctrl_c = 0;
65 static int     b_exit_on_ctrl_c = 0;
66 static void    SigIntHandler( int a )
67 {
68     if( b_exit_on_ctrl_c )
69         exit(0);
70     b_ctrl_c = 1;
71 }
72
73 typedef struct {
74     int b_decompress;
75     int b_progress;
76     int i_maxframes;
77     int i_seek;
78     hnd_t hin;
79     hnd_t hout;
80 } cli_opt_t;
81
82 /* input file operation function pointers */
83 static int (*p_open_infile)( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
84 static int (*p_get_frame_total)( hnd_t handle, int i_width, int i_height );
85 static int (*p_read_frame)( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
86 static int (*p_close_infile)( hnd_t handle );
87
88 static int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
89 static int get_frame_total_yuv( hnd_t handle, int i_width, int i_height );
90 static int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
91 static int close_file_yuv( hnd_t handle );
92
93 #ifdef AVIS_INPUT
94 static int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
95 static int get_frame_total_avis( hnd_t handle, int i_width, int i_height );
96 static int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
97 static int close_file_avis( hnd_t handle );
98 #endif
99
100 /* output file operation function pointers */
101 static int (*p_open_outfile)( char *psz_filename, hnd_t *p_handle );
102 static int (*p_set_outfile_param)( hnd_t handle, x264_param_t *p_param );
103 static int (*p_write_nalu)( hnd_t handle, uint8_t *p_nal, int i_size );
104 static int (*p_set_eop)( hnd_t handle, x264_picture_t *p_picture );
105 static int (*p_close_outfile)( hnd_t handle );
106
107 static int open_file_bsf( char *psz_filename, hnd_t *p_handle );
108 static int set_param_bsf( hnd_t handle, x264_param_t *p_param );
109 static int write_nalu_bsf( hnd_t handle, uint8_t *p_nal, int i_size );
110 static int set_eop_bsf( hnd_t handle,  x264_picture_t *p_picture );
111 static int close_file_bsf( hnd_t handle );
112
113 #ifdef MP4_OUTPUT
114 static int open_file_mp4( char *psz_filename, hnd_t *p_handle );
115 static int set_param_mp4( hnd_t handle, x264_param_t *p_param );
116 static int write_nalu_mp4( hnd_t handle, uint8_t *p_nal, int i_size );
117 static int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture );
118 static int close_file_mp4( hnd_t handle );
119 #endif
120
121 static int open_file_mkv( char *psz_filename, hnd_t *p_handle );
122 static int set_param_mkv( hnd_t handle, x264_param_t *p_param );
123 static int write_nalu_mkv( hnd_t handle, uint8_t *p_nal, int i_size );
124 static int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture );
125 static int close_file_mkv( hnd_t handle );
126
127 static void Help( x264_param_t *defaults );
128 static int  Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
129 static int  Encode( x264_param_t *param, cli_opt_t *opt );
130
131
132 /****************************************************************************
133  * main:
134  ****************************************************************************/
135 int main( int argc, char **argv )
136 {
137     x264_param_t param;
138     cli_opt_t opt;
139
140 #ifdef _MSC_VER
141     _setmode(_fileno(stdin), _O_BINARY);    /* thanks to Marcos Morais <morais at dee.ufcg.edu.br> */
142     _setmode(_fileno(stdout), _O_BINARY);
143 #endif
144
145     x264_param_default( &param );
146
147     /* Parse command line */
148     if( Parse( argc, argv, &param, &opt ) < 0 )
149         return -1;
150
151     /* Control-C handler */
152     signal( SIGINT, SigIntHandler );
153
154     return Encode( &param, &opt );
155 }
156
157 /*****************************************************************************
158  * Help:
159  *****************************************************************************/
160 static void Help( x264_param_t *defaults )
161 {
162     fprintf( stderr,
163              "x264 core:%d%s\n"
164              "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
165              "\n"
166              "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
167              "  or AVI or Avisynth if compiled with AVIS support (%s).\n"
168              "Outfile type is selected by filename:\n"
169              " .264 -> Raw bytestream\n"
170              " .mkv -> Matroska\n"
171              " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
172              "\n"
173              "Options:\n"
174              "\n"
175              "  -h, --help                  Print this help\n"
176              "\n"
177              "Frame-type options:\n"
178              "\n"
179              "  -I, --keyint <integer>      Maximum GOP size [%d]\n"
180              "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n"
181              "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n"
182              "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n"
183              "      --no-b-adapt            Disable adaptive B-frame decision\n"
184              "      --b-bias <integer>      Influences how often B-frames are used [%d]\n"
185              "      --b-pyramid             Keep some B-frames as references\n"
186              "\n"
187              "      --no-cabac              Disable CABAC\n"
188              "  -r, --ref <integer>         Number of reference frames [%d]\n"
189              "      --nf                    Disable loop filter\n"
190              "  -f, --filter <alpha:beta>   Loop filter AlphaC0 and Beta parameters [%d:%d]\n"
191              "\n"
192              "Ratecontrol:\n"
193              "\n"
194              "  -q, --qp <integer>          Set QP (0=lossless) [%d]\n"
195              "  -B, --bitrate <integer>     Set bitrate\n"
196              "      --qpmin <integer>       Set min QP [%d]\n"
197              "      --qpmax <integer>       Set max QP [%d]\n"
198              "      --qpstep <integer>      Set max QP step [%d]\n"
199              "      --ratetol <float>       Allowed variance of average bitrate [%.1f]\n"
200              "      --vbv-maxrate <integer> Max local bitrate [%d]\n"
201              "      --vbv-bufsize <integer> Size of VBV buffer [%d]\n"
202              "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n"
203              "\n"
204              "      --ipratio <float>       QP factor between I and P [%.2f]\n"
205              "      --pbratio <float>       QP factor between P and B [%.2f]\n"
206              "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n"
207              "\n"
208              "  -p, --pass <1|2|3>          Enable multipass ratecontrol:\n"
209              "                                  - 1: First pass, creates stats file\n"
210              "                                  - 2: Last pass, does not overwrite stats file\n"
211              "                                  - 3: Nth pass, overwrites stats file\n"
212              "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n"
213              "      --rceq <string>         Ratecontrol equation [\"%s\"]\n"
214              "      --qcomp <float>         QP curve compression: 0.0 => CBR, 1.0 => CQP [%.2f]\n"
215              "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n"
216              "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n"
217              "\n"
218              "      --zones <zone0>/<zone1>/...\n"
219              "                              Tweak the bitrate of some regions of the video\n"
220              "                              Each zone is of the form\n"
221              "                                  <start frame>,<end frame>,<option>\n"
222              "                                  where <option> is either\n"
223              "                                      q=<integer> (force QP)\n"
224              "                                  or  b=<float> (bitrate multiplier)\n"
225              "\n"
226              "Analysis:\n"
227              "\n"
228              "  -A, --analyse <string>      Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
229              "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
230              "                                  - none, all\n"
231              "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n"
232              "      --direct <string>       Direct MV prediction mode [\"temporal\"]\n"
233              "                                  - none, spatial, temporal\n"
234              "  -w, --weightb               Weighted prediction for B-frames\n"
235              "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n"
236              "                                  - dia: diamond search, radius 1 (fast)\n"
237              "                                  - hex: hexagonal search, radius 2\n"
238              "                                  - umh: uneven multi-hexagon search\n"
239              "                                  - esa: exhaustive search (slow)\n"
240              "      --merange <integer>     Maximum motion vector search range [%d]\n"
241              "  -m, --subme <integer>       Subpixel motion estimation and partition\n"
242              "                                  decision quality: 1=fast, 6=best. [%d]\n"
243              "      --no-chroma-me          Ignore chroma in motion estimation\n"
244              "  -8, --8x8dct                Adaptive spatial transform size\n"
245              "\n"
246              "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
247              "                                  - jvt, flat\n"
248              "      --cqmfile <string>      Read quant matrices from a JM-compatible file\n"
249              "                                  Overrides any other --cqm* options.\n"
250              "      --cqm4 <list>           Set all 4x4 quant matrices\n"
251              "                                  Takes a comma-separated list of 16 integers.\n"
252              "      --cqm8 <list>           Set all 8x8 quant matrices\n"
253              "                                  Takes a comma-separated list of 64 integers.\n"
254              "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
255              "                              Set both luma and chroma quant matrices\n"
256              "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
257              "                              Set individual quant matrices\n"
258              "\n"
259              "Input/Output:\n"
260              "\n"
261              "      --level <integer>       Specify level (as defined by Annex A)\n"
262              "      --sar width:height      Specify Sample Aspect Ratio\n"
263              "      --fps <float|rational>  Specify framerate\n"
264              "      --seek <integer>        First frame to encode\n"
265              "      --frames <integer>      Maximum number of frames to encode\n"
266              "  -o, --output                Specify output file\n"
267              "\n"
268              "      --threads <integer>     Parallel encoding (uses slices)\n"
269              "      --no-asm                Disable all CPU optimizations\n"
270              "      --no-psnr               Disable PSNR computation\n"
271              "      --quiet                 Quiet Mode\n"
272              "  -v, --verbose               Print stats for each frame\n"
273              "      --progress              Show a progress indicator while encoding\n"
274              "      --visualize             Show MB types overlayed on the encoded video\n"
275              "      --aud                   Use access unit delimiters\n"
276              "\n",
277             X264_BUILD, X264_VERSION,
278 #ifdef AVIS_INPUT
279             "yes",
280 #else
281             "no",
282 #endif
283 #ifdef MP4_OUTPUT
284             "yes",
285 #else
286             "no",
287 #endif
288             defaults->i_keyint_max,
289             defaults->i_keyint_min,
290             defaults->i_scenecut_threshold,
291             defaults->i_bframe,
292             defaults->i_bframe_bias,
293             defaults->i_frame_reference,
294             defaults->i_deblocking_filter_alphac0,
295             defaults->i_deblocking_filter_beta,
296             defaults->rc.i_qp_constant,
297             defaults->rc.i_qp_min,
298             defaults->rc.i_qp_max,
299             defaults->rc.i_qp_step,
300             defaults->rc.f_rate_tolerance,
301             defaults->rc.i_vbv_max_bitrate,
302             defaults->rc.i_vbv_buffer_size,
303             defaults->rc.f_vbv_buffer_init,
304             defaults->rc.f_ip_factor,
305             defaults->rc.f_pb_factor,
306             defaults->analyse.i_chroma_qp_offset,
307             defaults->rc.psz_stat_out,
308             defaults->rc.psz_rc_eq,
309             defaults->rc.f_qcompress,
310             defaults->rc.f_complexity_blur,
311             defaults->rc.f_qblur,
312             defaults->analyse.i_me_method==X264_ME_DIA ? "dia"
313             : defaults->analyse.i_me_method==X264_ME_HEX ? "hex"
314             : defaults->analyse.i_me_method==X264_ME_UMH ? "umh"
315             : defaults->analyse.i_me_method==X264_ME_ESA ? "esa" : NULL,
316             defaults->analyse.i_me_range,
317             defaults->analyse.i_subpel_refine
318            );
319 }
320
321 static int parse_cqm( const char *str, uint8_t *cqm, int length )
322 {
323     int i = 0;
324     do {
325         int coef;
326         if( !sscanf( str, "%d", &coef ) || coef < 1 || coef > 255 )
327             return -1;
328         cqm[i++] = coef;
329     } while( i < length && (str = strchr( str, ',' )) && str++ );
330     return (i == length) ? 0 : -1;
331 }
332
333 /*****************************************************************************
334  * Parse:
335  *****************************************************************************/
336 static int  Parse( int argc, char **argv,
337                    x264_param_t *param, cli_opt_t *opt )
338 {
339     char *psz_filename = NULL;
340     x264_param_t defaults = *param;
341     char *psz;
342     char b_avis = 0;
343
344     memset( opt, 0, sizeof(cli_opt_t) );
345
346     /* Default input file driver */
347     p_open_infile = open_file_yuv;
348     p_get_frame_total = get_frame_total_yuv;
349     p_read_frame = read_frame_yuv;
350     p_close_infile = close_file_yuv;
351
352     /* Default output file driver */
353     p_open_outfile = open_file_bsf;
354     p_set_outfile_param = set_param_bsf;
355     p_write_nalu = write_nalu_bsf;
356     p_set_eop = set_eop_bsf;
357     p_close_outfile = close_file_bsf;
358
359     /* Parse command line options */
360     opterr = 0; // no error message
361     for( ;; )
362     {
363         int b_error = 0;
364         int long_options_index;
365 #define OPT_QPMIN 256
366 #define OPT_QPMAX 257
367 #define OPT_QPSTEP 258
368 #define OPT_IPRATIO 260
369 #define OPT_PBRATIO 261
370 #define OPT_RATETOL 262
371 #define OPT_RCSTATS 264
372 #define OPT_RCEQ 265
373 #define OPT_QCOMP 266
374 #define OPT_NOPSNR 267
375 #define OPT_QUIET 268
376 #define OPT_SCENECUT 270
377 #define OPT_QBLUR 271
378 #define OPT_CPLXBLUR 272
379 #define OPT_FRAMES 273
380 #define OPT_FPS 274
381 #define OPT_DIRECT 275
382 #define OPT_LEVEL 276
383 #define OPT_NOBADAPT 277
384 #define OPT_BBIAS 278
385 #define OPT_BPYRAMID 279
386 #define OPT_CHROMA_QP 280
387 #define OPT_NO_CHROMA_ME 281
388 #define OPT_NO_CABAC 282
389 #define OPT_AUD 283
390 #define OPT_PROGRESS 284
391 #define OPT_ME 285
392 #define OPT_MERANGE 286
393 #define OPT_VBVMAXRATE 287
394 #define OPT_VBVBUFSIZE 288
395 #define OPT_VBVINIT 289
396 #define OPT_VISUALIZE 290
397 #define OPT_SEEK 291
398 #define OPT_ZONES 292
399 #define OPT_THREADS 293
400 #define OPT_CQM 294
401 #define OPT_CQM4 295
402 #define OPT_CQM4I 296
403 #define OPT_CQM4IY 297
404 #define OPT_CQM4IC 298
405 #define OPT_CQM4P 299
406 #define OPT_CQM4PY 300
407 #define OPT_CQM4PC 301
408 #define OPT_CQM8 302
409 #define OPT_CQM8I 303
410 #define OPT_CQM8P 304
411 #define OPT_CQMFILE 305
412
413         static struct option long_options[] =
414         {
415             { "help",    no_argument,       NULL, 'h' },
416             { "bitrate", required_argument, NULL, 'B' },
417             { "bframes", required_argument, NULL, 'b' },
418             { "no-b-adapt", no_argument,    NULL, OPT_NOBADAPT },
419             { "b-bias",  required_argument, NULL, OPT_BBIAS },
420             { "b-pyramid", no_argument,     NULL, OPT_BPYRAMID },
421             { "min-keyint",required_argument,NULL,'i' },
422             { "keyint",  required_argument, NULL, 'I' },
423             { "scenecut",required_argument, NULL, OPT_SCENECUT },
424             { "nf",      no_argument,       NULL, 'n' },
425             { "filter",  required_argument, NULL, 'f' },
426             { "no-cabac",no_argument,       NULL, OPT_NO_CABAC },
427             { "qp",      required_argument, NULL, 'q' },
428             { "qpmin",   required_argument, NULL, OPT_QPMIN },
429             { "qpmax",   required_argument, NULL, OPT_QPMAX },
430             { "qpstep",  required_argument, NULL, OPT_QPSTEP },
431             { "ref",     required_argument, NULL, 'r' },
432             { "no-asm",  no_argument,       NULL, 'C' },
433             { "sar",     required_argument, NULL, 's' },
434             { "fps",     required_argument, NULL, OPT_FPS },
435             { "frames",  required_argument, NULL, OPT_FRAMES },
436             { "seek",    required_argument, NULL, OPT_SEEK },
437             { "output",  required_argument, NULL, 'o' },
438             { "analyse", required_argument, NULL, 'A' },
439             { "direct",  required_argument, NULL, OPT_DIRECT },
440             { "weightb", no_argument,       NULL, 'w' },
441             { "me",      required_argument, NULL, OPT_ME },
442             { "merange", required_argument, NULL, OPT_MERANGE },
443             { "subme",   required_argument, NULL, 'm' },
444             { "no-chroma-me", no_argument,  NULL, OPT_NO_CHROMA_ME },
445             { "8x8dct",  no_argument,       NULL, '8' },
446             { "level",   required_argument, NULL, OPT_LEVEL },
447             { "ratetol", required_argument, NULL, OPT_RATETOL },
448             { "vbv-maxrate", required_argument, NULL, OPT_VBVMAXRATE },
449             { "vbv-bufsize", required_argument, NULL, OPT_VBVBUFSIZE },
450             { "vbv-init", required_argument,NULL,  OPT_VBVINIT },
451             { "ipratio", required_argument, NULL, OPT_IPRATIO },
452             { "pbratio", required_argument, NULL, OPT_PBRATIO },
453             { "chroma-qp-offset", required_argument, NULL, OPT_CHROMA_QP },
454             { "pass",    required_argument, NULL, 'p' },
455             { "stats",   required_argument, NULL, OPT_RCSTATS },
456             { "rceq",    required_argument, NULL, OPT_RCEQ },
457             { "qcomp",   required_argument, NULL, OPT_QCOMP },
458             { "qblur",   required_argument, NULL, OPT_QBLUR },
459             { "cplxblur",required_argument, NULL, OPT_CPLXBLUR },
460             { "zones",   required_argument, NULL, OPT_ZONES },
461             { "threads", required_argument, NULL, OPT_THREADS },
462             { "no-psnr", no_argument,       NULL, OPT_NOPSNR },
463             { "quiet",   no_argument,       NULL, OPT_QUIET },
464             { "verbose", no_argument,       NULL, 'v' },
465             { "progress",no_argument,       NULL, OPT_PROGRESS },
466             { "visualize",no_argument,      NULL, OPT_VISUALIZE },
467             { "aud",     no_argument,       NULL, OPT_AUD },
468             { "cqm",     required_argument, NULL, OPT_CQM },
469             { "cqmfile", required_argument, NULL, OPT_CQMFILE },
470             { "cqm4",    required_argument, NULL, OPT_CQM4 },
471             { "cqm4i",   required_argument, NULL, OPT_CQM4I },
472             { "cqm4iy",  required_argument, NULL, OPT_CQM4IY },
473             { "cqm4ic",  required_argument, NULL, OPT_CQM4IC },
474             { "cqm4p",   required_argument, NULL, OPT_CQM4P },
475             { "cqm4py",  required_argument, NULL, OPT_CQM4PY },
476             { "cqm4pc",  required_argument, NULL, OPT_CQM4PC },
477             { "cqm8",    required_argument, NULL, OPT_CQM8 },
478             { "cqm8i",   required_argument, NULL, OPT_CQM8I },
479             { "cqm8p",   required_argument, NULL, OPT_CQM8P },
480             {0, 0, 0, 0}
481         };
482
483         int c;
484
485         c = getopt_long( argc, argv, "hi:I:b:r:cxB:q:f:o:A:m:p:vw8",
486                          long_options, &long_options_index);
487
488         if( c == -1 )
489         {
490             break;
491         }
492
493         switch( c )
494         {
495             case 'h':
496                 Help( &defaults );
497                 return -1;
498
499             case 0:
500                 break;
501             case 'B':
502                 param->rc.i_bitrate = atol( optarg );
503                 param->rc.b_cbr = 1;
504                 break;
505             case 'b':
506                 param->i_bframe = atol( optarg );
507                 break;
508             case OPT_NOBADAPT:
509                 param->b_bframe_adaptive = 0;
510                 break;
511             case OPT_BBIAS:
512                 param->i_bframe_bias = atol( optarg );
513                 break;
514             case OPT_BPYRAMID:
515                 param->b_bframe_pyramid = 1;
516                 break;
517             case 'i':
518                 param->i_keyint_min = atol( optarg );
519                 if( param->i_keyint_max < param->i_keyint_min )
520                     param->i_keyint_max = param->i_keyint_min;
521                 break;
522             case 'I':
523                 param->i_keyint_max = atol( optarg );
524                 if( param->i_keyint_min > param->i_keyint_max )
525                     param->i_keyint_min = param->i_keyint_max;
526                 break;
527             case OPT_SCENECUT:
528                 param->i_scenecut_threshold = atol( optarg );
529                 break;
530             case 'n':
531                 param->b_deblocking_filter = 0;
532                 break;
533             case 'f':
534             {
535                 char *p = strchr( optarg, ':' );
536                 param->i_deblocking_filter_alphac0 = atoi( optarg );
537                 param->i_deblocking_filter_beta = p ? atoi( p+1 ) : param->i_deblocking_filter_alphac0;
538                 break;
539             }
540             case 'q':
541                 param->rc.i_qp_constant = atoi( optarg );
542                 break;
543             case OPT_QPMIN:
544                 param->rc.i_qp_min = atoi( optarg );
545                 break;
546             case OPT_QPMAX:
547                 param->rc.i_qp_max = atoi( optarg );
548                 break;
549             case OPT_QPSTEP:
550                 param->rc.i_qp_step = atoi( optarg );
551                 break;
552             case 'r':
553                 param->i_frame_reference = atoi( optarg );
554                 break;
555             case OPT_NO_CABAC:
556                 param->b_cabac = 0;
557                 break;
558             case 'x':
559                 opt->b_decompress = 1;
560                 break;
561             case 'C':
562                 param->cpu = 0;
563                 break;
564             case OPT_FRAMES:
565                 opt->i_maxframes = atoi( optarg );
566                 break;
567             case OPT_SEEK:
568                 opt->i_seek = atoi( optarg );
569                 break;
570             case 'o':
571                 if( !strncasecmp(optarg + strlen(optarg) - 4, ".mp4", 4) )
572                 {
573 #ifdef MP4_OUTPUT
574                     p_open_outfile = open_file_mp4;
575                     p_write_nalu = write_nalu_mp4;
576                     p_set_outfile_param = set_param_mp4;
577                     p_set_eop = set_eop_mp4;
578                     p_close_outfile = close_file_mp4;
579 #else
580                     fprintf( stderr, "not compiled with MP4 output support\n" );
581                     return -1;
582 #endif
583                 }
584                 else if( !strncasecmp(optarg + strlen(optarg) - 4, ".mkv", 4) )
585                 {
586                     p_open_outfile = open_file_mkv;
587                     p_write_nalu = write_nalu_mkv;
588                     p_set_outfile_param = set_param_mkv;
589                     p_set_eop = set_eop_mkv;
590                     p_close_outfile = close_file_mkv;
591                 }
592                 if( !strcmp(optarg, "-") )
593                     opt->hout = stdout;
594                 else if( p_open_outfile( optarg, &opt->hout ) )
595                 {
596                     fprintf( stderr, "cannot open output file `%s'\n", optarg );
597                     return -1;
598                 }
599                 break;
600             case 's':
601             {
602                 char *p = strchr( optarg, ':' );
603                 if( p )
604                 {
605                     param->vui.i_sar_width = atoi( optarg );
606                     param->vui.i_sar_height = atoi( p + 1 );
607                 }
608                 break;
609             }
610             case OPT_FPS:
611             {
612                 float fps;
613                 if( sscanf( optarg, "%d/%d", &param->i_fps_num, &param->i_fps_den ) == 2 )
614                     ;
615                 else if( sscanf( optarg, "%f", &fps ) )
616                 {
617                     param->i_fps_num = (int)(fps * 1000 + .5);
618                     param->i_fps_den = 1000;
619                 }
620                 else
621                 {
622                     fprintf( stderr, "bad fps `%s'\n", optarg );
623                     return -1;
624                 }
625                 break;
626             }
627             case 'A':
628                 param->analyse.inter = 0;
629                 if( strstr( optarg, "none" ) )  param->analyse.inter =  0;
630                 if( strstr( optarg, "all" ) )   param->analyse.inter = ~0;
631
632                 if( strstr( optarg, "i4x4" ) )  param->analyse.inter |= X264_ANALYSE_I4x4;
633                 if( strstr( optarg, "i8x8" ) )  param->analyse.inter |= X264_ANALYSE_I8x8;
634                 if( strstr( optarg, "p8x8" ) )  param->analyse.inter |= X264_ANALYSE_PSUB16x16;
635                 if( strstr( optarg, "p4x4" ) )  param->analyse.inter |= X264_ANALYSE_PSUB8x8;
636                 if( strstr( optarg, "b8x8" ) )  param->analyse.inter |= X264_ANALYSE_BSUB16x16;
637                 break;
638             case OPT_DIRECT:
639                 if( strstr( optarg, "temporal" ) )
640                     param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_TEMPORAL;
641                 else if( strstr( optarg, "spatial" ) )
642                     param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
643                 else if( strstr( optarg, "none" ) )
644                     param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_NONE;
645                 else
646                     param->analyse.i_direct_mv_pred = atoi( optarg );
647                 break;
648             case 'w':
649                 param->analyse.b_weighted_bipred = 1;
650                 break;
651             case OPT_ME:
652                 param->analyse.i_me_method = 
653                     strstr( optarg, "dia" ) ? X264_ME_DIA :
654                     strstr( optarg, "hex" ) ? X264_ME_HEX :
655                     strstr( optarg, "umh" ) ? X264_ME_UMH :
656                     strstr( optarg, "esa" ) ? X264_ME_ESA : -1;
657                 if( param->analyse.i_me_method == -1 )
658                 {
659                     fprintf( stderr, "bad ME method `%s'\n", optarg );
660                     return -1;
661                 }
662                 break;
663             case OPT_MERANGE:
664                 param->analyse.i_me_range = atoi(optarg);
665                 break;
666             case 'm':
667                 param->analyse.i_subpel_refine = atoi(optarg);
668                 break;
669             case OPT_NO_CHROMA_ME:
670                 param->analyse.b_chroma_me = 0;
671                 break;
672             case '8':
673                 param->analyse.b_transform_8x8 = 1;
674                 break;
675             case OPT_LEVEL:
676                 param->i_level_idc = atoi(optarg);
677                 break;
678             case OPT_RATETOL:
679                 param->rc.f_rate_tolerance = !strncmp("inf", optarg, 3) ? 1e9 : atof(optarg);
680                 break;
681             case OPT_VBVMAXRATE:
682                 param->rc.i_vbv_max_bitrate = atoi( optarg );
683                 break;
684             case OPT_VBVBUFSIZE:
685                 param->rc.i_vbv_buffer_size = atoi( optarg );
686                 break;
687             case OPT_VBVINIT:
688                 param->rc.f_vbv_buffer_init = atof(optarg);
689                 break;
690             case OPT_IPRATIO:
691                 param->rc.f_ip_factor = atof(optarg);
692                 break;
693             case OPT_PBRATIO:
694                 param->rc.f_pb_factor = atof(optarg);
695                 break;
696             case OPT_CHROMA_QP:
697                 param->analyse.i_chroma_qp_offset = atoi(optarg);
698                 break;
699             case 'p':
700             {
701                 int i_pass = atoi(optarg);
702                 if( i_pass == 1 )
703                     param->rc.b_stat_write = 1;
704                 else if( i_pass == 2 )
705                     param->rc.b_stat_read = 1;
706                 else if( i_pass > 2 )
707                     param->rc.b_stat_read =
708                     param->rc.b_stat_write = 1;
709                 break;
710             }
711             case OPT_RCSTATS:
712                 param->rc.psz_stat_in = optarg;
713                 param->rc.psz_stat_out = optarg;
714                 break;
715             case OPT_RCEQ:
716                 param->rc.psz_rc_eq = optarg;
717                break;
718             case OPT_QCOMP:
719                 param->rc.f_qcompress = atof(optarg);
720                 break;
721             case OPT_QBLUR:
722                 param->rc.f_qblur = atof(optarg);
723                 break;
724             case OPT_CPLXBLUR:
725                 param->rc.f_complexity_blur = atof(optarg);
726                 break;
727             case OPT_ZONES:
728                 param->rc.psz_zones = optarg;
729                 break;
730             case OPT_THREADS:
731                 param->i_threads = atoi(optarg);
732                 break;
733             case OPT_NOPSNR:
734                 param->analyse.b_psnr = 0;
735                 break;
736             case OPT_QUIET:
737                 param->i_log_level = X264_LOG_NONE;
738                 break;
739             case 'v':
740                 param->i_log_level = X264_LOG_DEBUG;
741                 break;
742             case OPT_AUD:
743                 param->b_aud = 1;
744                 break;
745             case OPT_PROGRESS:
746                 opt->b_progress = 1;
747                 break;
748             case OPT_VISUALIZE:
749 #ifdef VISUALIZE
750                 param->b_visualize = 1;
751                 b_exit_on_ctrl_c = 1;
752 #else
753                 fprintf( stderr, "not compiled with visualization support\n" );
754 #endif
755                 break;
756             case OPT_CQM:
757                 if( strstr( optarg, "flat" ) )
758                     param->i_cqm_preset = X264_CQM_FLAT;
759                 else if( strstr( optarg, "jvt" ) )
760                     param->i_cqm_preset = X264_CQM_JVT;
761                 else
762                 {
763                     fprintf( stderr, "bad CQM preset `%s'\n", optarg );
764                     return -1;
765                 }
766                 break;
767             case OPT_CQMFILE:
768                 param->psz_cqm_file = optarg;
769                 break;
770             case OPT_CQM4:
771                 param->i_cqm_preset = X264_CQM_CUSTOM;
772                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
773                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
774                 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
775                 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
776                 break;
777             case OPT_CQM8:
778                 param->i_cqm_preset = X264_CQM_CUSTOM;
779                 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
780                 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
781                 break;
782             case OPT_CQM4I:
783                 param->i_cqm_preset = X264_CQM_CUSTOM;
784                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
785                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
786                 break;
787             case OPT_CQM4P:
788                 param->i_cqm_preset = X264_CQM_CUSTOM;
789                 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
790                 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
791                 break;
792             case OPT_CQM4IY:
793                 param->i_cqm_preset = X264_CQM_CUSTOM;
794                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
795                 break;
796             case OPT_CQM4IC:
797                 param->i_cqm_preset = X264_CQM_CUSTOM;
798                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
799                 break;
800             case OPT_CQM4PY:
801                 param->i_cqm_preset = X264_CQM_CUSTOM;
802                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
803                 break;
804             case OPT_CQM4PC:
805                 param->i_cqm_preset = X264_CQM_CUSTOM;
806                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
807                 break;
808             case OPT_CQM8I:
809                 param->i_cqm_preset = X264_CQM_CUSTOM;
810                 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
811                 break;
812             case OPT_CQM8P:
813                 param->i_cqm_preset = X264_CQM_CUSTOM;
814                 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
815                 break;
816             default:
817                 fprintf( stderr, "unknown option (%c)\n", optopt );
818                 return -1;
819         }
820
821         if( b_error )
822         {
823             fprintf( stderr, "bad argument (%s)\n", optarg );
824             return -1;
825         }
826     }
827
828     /* Get the file name */
829     if( optind > argc - 1 || !opt->hout )
830     {
831         Help( &defaults );
832         return -1;
833     }
834     psz_filename = argv[optind++];
835
836     if( !opt->b_decompress )
837     {
838         if( optind > argc - 1 )
839         {
840             /* try to parse the file name */
841             for( psz = psz_filename; *psz; psz++ )
842             {
843                 if( *psz >= '0' && *psz <= '9'
844                     && sscanf( psz, "%ux%u", &param->i_width, &param->i_height ) == 2 )
845                 {
846                     if( param->i_log_level >= X264_LOG_INFO )
847                         fprintf( stderr, "x264 [info]: file name gives %dx%d\n", param->i_width, param->i_height );
848                     break;
849                 }
850             }
851         }
852         else
853         {
854             sscanf( argv[optind++], "%ux%u", &param->i_width, &param->i_height );
855         }
856         
857         /* check avis input */
858         psz = psz_filename + strlen(psz_filename) - 1;
859         while( psz > psz_filename && *psz != '.' )
860             psz--;
861
862         if( !strncasecmp( psz, ".avi", 4 ) || !strncasecmp( psz, ".avs", 4 ) )
863             b_avis = 1;
864
865         if( !b_avis && ( !param->i_width || !param->i_height ) )
866         {
867             Help( &defaults );
868             return -1;
869         }
870     }
871
872     /* open the input */
873     if( !strcmp( psz_filename, "-" ) )
874     {
875         opt->hin = stdin;
876         optind++;
877     }
878     else
879     {
880         if( b_avis )
881         {
882 #ifdef AVIS_INPUT
883             p_open_infile = open_file_avis;
884             p_get_frame_total = get_frame_total_avis;
885             p_read_frame = read_frame_avis;
886             p_close_infile = close_file_avis;
887 #else
888             fprintf( stderr, "not compiled with AVIS input support\n" );
889             return -1;
890 #endif
891         }
892         if( p_open_infile( psz_filename, &opt->hin, param ) )
893         {
894             fprintf( stderr, "could not open input file '%s'\n", psz_filename );
895             return -1;
896         }
897     }
898
899     return 0;
900 }
901
902 /*****************************************************************************
903  * Decode:
904  *****************************************************************************/
905 #if 0
906 static int  Decode( x264_param_t  *param, FILE *fh26l, hnd_t hout )
907 {
908     fprintf( stderr, "decompressor not working (help is welcome)\n" );
909     return -1;
910     x264_nal_t nal;
911     int i_data;
912     int b_eof;
913
914     //param.cpu = 0;
915     if( ( h = x264_decoder_open( &param ) ) == NULL )
916     {
917         fprintf( stderr, "x264_decoder_open failed\n" );
918         return -1;
919     }
920
921     i_start = x264_mdate();
922     b_eof = 0;
923     i_frame = 0;
924     i_data  = 0;
925     nal.p_payload = malloc( DATA_MAX );
926
927     while( !b_ctrl_c )
928     {
929         uint8_t *p, *p_next, *end;
930         int i_size;
931         /* fill buffer */
932         if( i_data < DATA_MAX && !b_eof )
933         {
934             int i_read = fread( &data[i_data], 1, DATA_MAX - i_data, fh26l );
935             if( i_read <= 0 )
936             {
937                 b_eof = 1;
938             }
939             else
940             {
941                 i_data += i_read;
942             }
943         }
944
945         if( i_data < 3 )
946         {
947             break;
948         }
949
950         end = &data[i_data];
951
952         /* extract one nal */
953         p = &data[0];
954         while( p < end - 3 )
955         {
956             if( p[0] == 0x00 && p[1] == 0x00 && p[2] == 0x01 )
957             {
958                 break;
959             }
960             p++;
961         }
962
963         if( p >= end - 3 )
964         {
965             fprintf( stderr, "garbage (i_data = %d)\n", i_data );
966             i_data = 0;
967             continue;
968         }
969
970         p_next = p + 3;
971         while( p_next < end - 3 )
972         {
973             if( p_next[0] == 0x00 && p_next[1] == 0x00 && p_next[2] == 0x01 )
974             {
975                 break;
976             }
977             p_next++;
978         }
979
980         if( p_next == end - 3 && i_data < DATA_MAX )
981         {
982             p_next = end;
983         }
984
985         /* decode this nal */
986         i_size = p_next - p - 3;
987         if( i_size <= 0 )
988         {
989             if( b_eof )
990             {
991                 break;
992             }
993             fprintf( stderr, "nal too large (FIXME) ?\n" );
994             i_data = 0;
995             continue;
996         }
997
998         x264_nal_decode( &nal, p +3, i_size );
999
1000         /* decode the content of the nal */
1001         x264_decoder_decode( h, &pic, &nal );
1002
1003         if( pic != NULL )
1004         {
1005             int i;
1006
1007             i_frame++;
1008
1009             for( i = 0; i < pic->i_plane;i++ )
1010             {
1011                 int i_line;
1012                 int i_div;
1013
1014                 i_div = i==0 ? 1 : 2;
1015                 for( i_line = 0; i_line < pic->i_height/i_div; i_line++ )
1016                 {
1017                     fwrite( pic->plane[i]+i_line*pic->i_stride[i], 1, pic->i_width/i_div, hout );
1018                 }
1019             }
1020         }
1021
1022         memmove( &data[0], p_next, end - p_next );
1023         i_data -= p_next - &data[0];
1024     }
1025
1026     i_end = x264_mdate();
1027     free( nal.p_payload );
1028     fprintf( stderr, "\n" );
1029
1030     x264_decoder_close( h );
1031
1032     fclose( fh26l );
1033     if( hout != stdout )
1034     {
1035         fclose( hout );
1036     }
1037     if( i_frame > 0 )
1038     {
1039         double fps = (double)i_frame * (double)1000000 /
1040                      (double)( i_end - i_start );
1041         fprintf( stderr, "decoded %d frames %ffps\n", i_frame, fps );
1042     }
1043 }
1044 #endif
1045
1046 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
1047 {
1048     x264_picture_t pic_out;
1049     x264_nal_t *nal;
1050     int i_nal, i;
1051     int i_file = 0;
1052
1053     /* Do not force any parameters */
1054     if( pic )
1055     {
1056         pic->i_type = X264_TYPE_AUTO;
1057         pic->i_qpplus1 = 0;
1058     }
1059     if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
1060     {
1061         fprintf( stderr, "x264_encoder_encode failed\n" );
1062     }
1063
1064     for( i = 0; i < i_nal; i++ )
1065     {
1066         int i_size;
1067         int i_data;
1068
1069         i_data = DATA_MAX;
1070         if( ( i_size = x264_nal_encode( data, &i_data, 1, &nal[i] ) ) > 0 )
1071         {
1072             i_file += p_write_nalu( hout, data, i_size );
1073         }
1074         else if( i_size < 0 )
1075         {
1076             fprintf( stderr, "need to increase buffer size (size=%d)\n", -i_size );
1077         }
1078     }
1079     if (i_nal)
1080         p_set_eop( hout, &pic_out );
1081
1082     return i_file;
1083 }
1084
1085 /*****************************************************************************
1086  * Encode:
1087  *****************************************************************************/
1088 static int  Encode( x264_param_t *param, cli_opt_t *opt )
1089 {
1090     x264_t *h;
1091     x264_picture_t pic;
1092
1093     int     i_frame, i_frame_total;
1094     int64_t i_start, i_end;
1095     int64_t i_file;
1096     int     i_frame_size;
1097     int     i_progress;
1098
1099     i_frame_total = p_get_frame_total( opt->hin, param->i_width, param->i_height );
1100
1101     if( ( h = x264_encoder_open( param ) ) == NULL )
1102     {
1103         fprintf( stderr, "x264_encoder_open failed\n" );
1104         p_close_infile( opt->hin );
1105         p_close_outfile( opt->hout );
1106         return -1;
1107     }
1108
1109     if( p_set_outfile_param( opt->hout, param ) )
1110     {
1111         fprintf( stderr, "can't set outfile param\n" );
1112         p_close_infile( opt->hin );
1113         p_close_outfile( opt->hout );
1114         return -1;
1115     }
1116
1117     /* Create a new pic */
1118     x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height );
1119
1120     i_start = x264_mdate();
1121     /* Encode frames */
1122     i_frame_total -= opt->i_seek;
1123     if( opt->i_maxframes > 0 && opt->i_maxframes < i_frame_total )
1124         i_frame_total = opt->i_maxframes;
1125     for( i_frame = 0, i_file = 0, i_progress = 0;
1126          b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1127     {
1128         if( p_read_frame( &pic, opt->hin, i_frame + opt->i_seek, param->i_width, param->i_height ) )
1129             break;
1130
1131         pic.i_pts = (int64_t)i_frame * param->i_fps_den;
1132
1133         i_file += Encode_frame( h, opt->hout, &pic );
1134
1135         i_frame++;
1136
1137         /* update status line (up to 1000 times per input file) */
1138         if( opt->b_progress && param->i_log_level < X264_LOG_DEBUG && 
1139             ( i_frame_total ? i_frame * 1000 / i_frame_total > i_progress
1140                             : i_frame % 10 == 0 ) )
1141         {
1142             int64_t i_elapsed = x264_mdate() - i_start;
1143             double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1144             if( i_frame_total )
1145             {
1146                 i_progress = i_frame * 1000 / i_frame_total;
1147                 fprintf( stderr, "encoded frames: %d/%d (%.1f%%), %.2f fps   \r", i_frame,
1148                          i_frame_total, (float)i_progress / 10, fps );
1149             }
1150             else
1151                 fprintf( stderr, "encoded frames: %d, %.2f fps   \r", i_frame, fps );
1152             fflush( stderr ); // needed in windows
1153         }
1154     }
1155     /* Flush delayed B-frames */
1156     do {
1157         i_file +=
1158         i_frame_size = Encode_frame( h, opt->hout, NULL );
1159     } while( i_frame_size );
1160
1161     i_end = x264_mdate();
1162     x264_picture_clean( &pic );
1163     x264_encoder_close( h );
1164     fprintf( stderr, "\n" );
1165
1166     if( b_ctrl_c )
1167         fprintf( stderr, "aborted at input frame %d\n", opt->i_seek + i_frame );
1168
1169     p_close_infile( opt->hin );
1170     p_close_outfile( opt->hout );
1171
1172     if( i_frame > 0 )
1173     {
1174         double fps = (double)i_frame * (double)1000000 /
1175                      (double)( i_end - i_start );
1176
1177         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame, fps,
1178                  (double) i_file * 8 * param->i_fps_num / ( param->i_fps_den * i_frame * 1000 ) );
1179     }
1180
1181     return 0;
1182 }
1183
1184 /* raw 420 yuv file operation */
1185 static int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1186 {
1187     if ((*p_handle = fopen(psz_filename, "rb")) == NULL)
1188         return -1;
1189     return 0;
1190 }
1191
1192 static int get_frame_total_yuv( hnd_t handle, int i_width, int i_height )
1193 {
1194     FILE *f = (FILE *)handle;
1195     int i_frame_total = 0;
1196
1197     if( !fseek( f, 0, SEEK_END ) )
1198     {
1199         int64_t i_size = ftell( f );
1200         fseek( f, 0, SEEK_SET );
1201         i_frame_total = (int)(i_size / ( i_width * i_height * 3 / 2 ));
1202     }
1203
1204     return i_frame_total;
1205 }
1206
1207 static int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1208 {
1209     static int prev_frame = -1;
1210     FILE *f = (FILE *)handle;
1211
1212     if( i_frame != prev_frame+1 )
1213         if( fseek( f, i_frame * i_width * i_height * 3 / 2, SEEK_SET ) )
1214             return -1;
1215
1216     if( fread( p_pic->img.plane[0], 1, i_width * i_height, f ) <= 0
1217             || fread( p_pic->img.plane[1], 1, i_width * i_height / 4, f ) <= 0
1218             || fread( p_pic->img.plane[2], 1, i_width * i_height / 4, f ) <= 0 )
1219         return -1;
1220
1221     prev_frame = i_frame;
1222
1223     return 0;
1224 }
1225
1226 static int close_file_yuv(hnd_t handle)
1227 {
1228     if (handle == NULL)
1229         return 0;
1230     return fclose((FILE *)handle);
1231 }
1232
1233
1234 /* avs/avi input file support under cygwin */
1235
1236 #ifdef AVIS_INPUT
1237
1238 static int gcd(int a, int b)
1239 {
1240     int c;
1241
1242     while (1)
1243     {
1244         c = a % b;
1245         if (!c)
1246             return b;
1247         a = b;
1248         b = c;
1249     }
1250 }
1251
1252 static int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1253 {
1254     AVISTREAMINFO info;
1255     PAVISTREAM p_avi = NULL;
1256     int i;
1257
1258     *p_handle = NULL;
1259
1260     AVIFileInit();
1261     if( AVIStreamOpenFromFile( &p_avi, psz_filename, streamtypeVIDEO, 0, OF_READ, NULL ) )
1262     {
1263         AVIFileExit();
1264         return -1;
1265     }
1266
1267     if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1268     {
1269         AVIStreamRelease(p_avi);
1270         AVIFileExit();
1271         return -1;
1272     }
1273
1274     // check input format
1275     if (info.fccHandler != MAKEFOURCC('Y', 'V', '1', '2'))
1276     {
1277         fprintf( stderr, "avis [error]: unsupported input format (%c%c%c%c)\n",
1278             (char)(info.fccHandler & 0xff), (char)((info.fccHandler >> 8) & 0xff),
1279             (char)((info.fccHandler >> 16) & 0xff), (char)((info.fccHandler >> 24)) );
1280
1281         AVIStreamRelease(p_avi);
1282         AVIFileExit();
1283
1284         return -1;
1285     }
1286
1287     p_param->i_width = info.rcFrame.right - info.rcFrame.left;
1288     p_param->i_height = info.rcFrame.bottom - info.rcFrame.top;
1289     i = gcd(info.dwRate, info.dwScale);
1290     p_param->i_fps_den = info.dwScale / i;
1291     p_param->i_fps_num = info.dwRate / i;
1292
1293     fprintf( stderr, "avis [info]: %dx%d @ %.2f fps (%d frames)\n",  
1294         p_param->i_width, p_param->i_height,
1295         (double)p_param->i_fps_num / (double)p_param->i_fps_den,
1296         (int)info.dwLength );
1297
1298     *p_handle = (hnd_t)p_avi;
1299
1300     return 0;
1301 }
1302
1303 static int get_frame_total_avis( hnd_t handle, int i_width, int i_height )
1304 {
1305     PAVISTREAM p_avi = (PAVISTREAM)handle;
1306     AVISTREAMINFO info;
1307
1308     if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1309         return -1;
1310
1311     return info.dwLength;
1312 }
1313
1314 static int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1315 {
1316     PAVISTREAM p_avi = (PAVISTREAM)handle;
1317     
1318     p_pic->img.i_csp = X264_CSP_YV12;
1319     
1320     if( AVIStreamRead(p_avi, i_frame, 1, p_pic->img.plane[0], i_width * i_height * 3 / 2, NULL, NULL ) )
1321         return -1;
1322
1323     return 0;
1324 }
1325
1326 static int close_file_avis( hnd_t handle )
1327 {
1328     PAVISTREAM p_avi = (PAVISTREAM)handle;
1329
1330     AVIStreamRelease(p_avi);
1331     AVIFileExit();
1332
1333     return 0;
1334 }
1335
1336 #endif
1337
1338
1339 static int open_file_bsf( char *psz_filename, hnd_t *p_handle )
1340 {
1341     if ((*p_handle = fopen(psz_filename, "w+b")) == NULL)
1342         return -1;
1343
1344     return 0;
1345 }
1346
1347 static int set_param_bsf( hnd_t handle, x264_param_t *p_param )
1348 {
1349     return 0;
1350 }
1351
1352 static int write_nalu_bsf( hnd_t handle, uint8_t *p_nalu, int i_size )
1353 {
1354     if (fwrite(p_nalu, i_size, 1, (FILE *)handle) > 0)
1355         return i_size;
1356     return -1;
1357 }
1358
1359 static int set_eop_bsf( hnd_t handle,  x264_picture_t *p_picture )
1360 {
1361     return 0;
1362 }
1363
1364 static int close_file_bsf( hnd_t handle )
1365 {
1366     if ((handle == NULL) || (handle == stdout))
1367         return 0;
1368
1369     return fclose((FILE *)handle);
1370 }
1371
1372 /* -- mp4 muxing support ------------------------------------------------- */
1373 #ifdef MP4_OUTPUT
1374
1375 typedef struct
1376 {
1377     GF_ISOFile *p_file;
1378     GF_AVCConfig *p_config;
1379     GF_ISOSample *p_sample;
1380     int i_track;
1381     int i_descidx;
1382     int i_time_inc;
1383     int i_time_res;
1384     int i_numframe;
1385     int i_init_delay;
1386     uint8_t b_sps;
1387     uint8_t b_pps;
1388 } mp4_t;
1389
1390
1391 static void recompute_bitrate_mp4(GF_ISOFile *p_file, int i_track)
1392 {
1393     u32 i, count, di, timescale, time_wnd, rate;
1394     u64 offset;
1395     Double br;
1396     GF_ESD *esd;
1397
1398     esd = gf_isom_get_esd(p_file, i_track, 1);
1399     if (!esd) return;
1400
1401     esd->decoderConfig->avgBitrate = 0;
1402     esd->decoderConfig->maxBitrate = 0;
1403     rate = time_wnd = 0;
1404
1405     timescale = gf_isom_get_media_timescale(p_file, i_track);
1406     count = gf_isom_get_sample_count(p_file, i_track);
1407     for (i=0; i<count; i++) {
1408         GF_ISOSample *samp = gf_isom_get_sample_info(p_file, i_track, i+1, &di, &offset);
1409
1410         if (samp->dataLength>esd->decoderConfig->bufferSizeDB) esd->decoderConfig->bufferSizeDB = samp->dataLength;
1411
1412         if (esd->decoderConfig->bufferSizeDB < samp->dataLength) esd->decoderConfig->bufferSizeDB = samp->dataLength;
1413         esd->decoderConfig->avgBitrate += samp->dataLength;
1414         rate += samp->dataLength;
1415         if (samp->DTS > time_wnd + timescale) {
1416             if (rate > esd->decoderConfig->maxBitrate) esd->decoderConfig->maxBitrate = rate;
1417             time_wnd = samp->DTS;
1418             rate = 0;
1419         }
1420
1421         gf_isom_sample_del(&samp);
1422     }
1423
1424     br = (Double) (s64) gf_isom_get_media_duration(p_file, i_track);
1425     br /= timescale;
1426     esd->decoderConfig->avgBitrate = (u32) (esd->decoderConfig->avgBitrate / br);
1427     /*move to bps*/
1428     esd->decoderConfig->avgBitrate *= 8;
1429     esd->decoderConfig->maxBitrate *= 8;
1430
1431     gf_isom_change_mpeg4_description(p_file, i_track, 1, esd);
1432     gf_odf_desc_del((GF_Descriptor *) esd);
1433 }
1434
1435
1436 static int close_file_mp4( hnd_t handle )
1437 {
1438     mp4_t *p_mp4 = (mp4_t *)handle;
1439
1440     if (p_mp4 == NULL)
1441         return 0;
1442
1443     if (p_mp4->p_config)
1444         gf_odf_avc_cfg_del(p_mp4->p_config);
1445
1446     if (p_mp4->p_sample)
1447     {
1448         if (p_mp4->p_sample->data)
1449             free(p_mp4->p_sample->data);
1450
1451         gf_isom_sample_del(&p_mp4->p_sample);
1452     }
1453
1454     if (p_mp4->p_file)
1455     {
1456         recompute_bitrate_mp4(p_mp4->p_file, p_mp4->i_track);
1457         gf_isom_set_pl_indication(p_mp4->p_file, GF_ISOM_PL_VISUAL, 0x15);
1458         gf_isom_set_storage_mode(p_mp4->p_file, GF_ISOM_STORE_FLAT);
1459         gf_isom_close(p_mp4->p_file);
1460     }
1461
1462     free(p_mp4);
1463
1464     return 0;
1465 }
1466
1467 static int open_file_mp4( char *psz_filename, hnd_t *p_handle )
1468 {
1469     mp4_t *p_mp4;
1470
1471     *p_handle = NULL;
1472
1473     if ((p_mp4 = (mp4_t *)malloc(sizeof(mp4_t))) == NULL)
1474         return -1;
1475
1476     memset(p_mp4, 0, sizeof(mp4_t));
1477     p_mp4->p_file = gf_isom_open(psz_filename, GF_ISOM_OPEN_WRITE, NULL);
1478
1479     if ((p_mp4->p_sample = gf_isom_sample_new()) == NULL)
1480     {
1481         close_file_mp4( p_mp4 );
1482         return -1;
1483     }
1484
1485     gf_isom_set_brand_info(p_mp4->p_file, GF_ISOM_BRAND_AVC1, 0);
1486
1487     *p_handle = p_mp4;
1488
1489     return 0;
1490 }
1491
1492
1493 static int set_param_mp4( hnd_t handle, x264_param_t *p_param )
1494 {
1495     mp4_t *p_mp4 = (mp4_t *)handle;
1496
1497     p_mp4->i_track = gf_isom_new_track(p_mp4->p_file, 0, GF_ISOM_MEDIA_VISUAL, 
1498         p_param->i_fps_num);
1499
1500     p_mp4->p_config = gf_odf_avc_cfg_new();
1501     gf_isom_avc_config_new(p_mp4->p_file, p_mp4->i_track, p_mp4->p_config, 
1502         NULL, NULL, &p_mp4->i_descidx);
1503
1504     gf_isom_set_visual_info(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, 
1505         p_param->i_width, p_param->i_height);
1506
1507     p_mp4->p_sample->data = (char *)malloc(p_param->i_width * p_param->i_height * 3 / 2);
1508     if (p_mp4->p_sample->data == NULL)
1509         return -1;
1510
1511     p_mp4->i_time_res = p_param->i_fps_num;
1512     p_mp4->i_time_inc = p_param->i_fps_den;
1513     p_mp4->i_init_delay = p_param->i_bframe ? (p_param->b_bframe_pyramid ? 2 : 1) : 0;
1514     p_mp4->i_init_delay *= p_mp4->i_time_inc;
1515     fprintf(stderr, "mp4 [info]: initial delay %d (scale %d)\n", 
1516         p_mp4->i_init_delay, p_mp4->i_time_res);
1517
1518     return 0;
1519 }
1520
1521
1522 static int write_nalu_mp4( hnd_t handle, uint8_t *p_nalu, int i_size )
1523 {
1524     mp4_t *p_mp4 = (mp4_t *)handle;
1525     GF_AVCConfigSlot *p_slot;
1526     uint8_t type = p_nalu[4] & 0x1f;
1527     int psize;
1528
1529     switch(type)
1530     {
1531     // sps
1532     case 0x07:
1533         if (!p_mp4->b_sps)
1534         {
1535             p_mp4->p_config->configurationVersion = 1;
1536             p_mp4->p_config->AVCProfileIndication = p_nalu[5];
1537             p_mp4->p_config->profile_compatibility = p_nalu[6];
1538             p_mp4->p_config->AVCLevelIndication = p_nalu[7];
1539             p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
1540             p_slot->size = i_size - 4;
1541             p_slot->data = (char *)malloc(p_slot->size);
1542             memcpy(p_slot->data, p_nalu + 4, i_size - 4);
1543             gf_list_add(p_mp4->p_config->sequenceParameterSets, p_slot);
1544             p_slot = NULL;
1545             p_mp4->b_sps = 1;
1546         }
1547         break;
1548
1549     // pps      
1550     case 0x08:
1551         if (!p_mp4->b_pps)
1552         {
1553             p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
1554             p_slot->size = i_size - 4;
1555             p_slot->data = (char *)malloc(p_slot->size);
1556             memcpy(p_slot->data, p_nalu + 4, i_size - 4);
1557             gf_list_add(p_mp4->p_config->pictureParameterSets, p_slot);
1558             p_slot = NULL;
1559             p_mp4->b_pps = 1;
1560             if (p_mp4->b_sps)
1561                 gf_isom_avc_config_update(p_mp4->p_file, p_mp4->i_track, 1, p_mp4->p_config);
1562         }
1563         break;
1564
1565     // slice, sei
1566     case 0x1:
1567     case 0x5:
1568     case 0x6:
1569         psize = i_size - 4 ;
1570         memcpy(p_mp4->p_sample->data + p_mp4->p_sample->dataLength, p_nalu, i_size);
1571         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 0] = (psize >> 24) & 0xff;
1572         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 1] = (psize >> 16) & 0xff;
1573         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 2] = (psize >> 8) & 0xff;
1574         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 3] = (psize >> 0) & 0xff;
1575         p_mp4->p_sample->dataLength += i_size;
1576         break;
1577     }
1578
1579     return i_size;
1580 }
1581
1582 static int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture )
1583 {
1584     mp4_t *p_mp4 = (mp4_t *)handle;
1585     uint32_t dts = p_mp4->i_numframe * p_mp4->i_time_inc;
1586     uint32_t pts = p_picture->i_pts;
1587     int offset = p_mp4->i_init_delay + pts - dts;
1588
1589     p_mp4->p_sample->IsRAP = p_picture->i_type == X264_TYPE_IDR ? 1 : 0;
1590     p_mp4->p_sample->DTS = dts;
1591     p_mp4->p_sample->CTS_Offset = offset;
1592     gf_isom_add_sample(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, p_mp4->p_sample);
1593
1594     p_mp4->p_sample->dataLength = 0;
1595     p_mp4->i_numframe++;
1596
1597     return 0;
1598 }
1599
1600 #endif
1601
1602
1603 /* -- mkv muxing support ------------------------------------------------- */
1604 typedef struct
1605 {
1606     mk_Writer *w;
1607
1608     uint8_t   *sps, *pps;
1609     int       sps_len, pps_len;
1610
1611     int       width, height, d_width, d_height;
1612
1613     int64_t   frame_duration;
1614     int       fps_num;
1615
1616     int       b_header_written;
1617     char      b_writing_frame;
1618 } mkv_t;
1619
1620 static int write_header_mkv( mkv_t *p_mkv )
1621 {
1622     int       ret;
1623     uint8_t   *avcC;
1624     int  avcC_len;
1625
1626     if( p_mkv->sps == NULL || p_mkv->pps == NULL ||
1627         p_mkv->width == 0 || p_mkv->height == 0 ||
1628         p_mkv->d_width == 0 || p_mkv->d_height == 0)
1629         return -1;
1630
1631     avcC_len = 5 + 1 + 2 + p_mkv->sps_len + 1 + 2 + p_mkv->pps_len;
1632     avcC = malloc(avcC_len);
1633     if (avcC == NULL)
1634         return -1;
1635
1636     avcC[0] = 1;
1637     avcC[1] = p_mkv->sps[1];
1638     avcC[2] = p_mkv->sps[2];
1639     avcC[3] = p_mkv->sps[3];
1640     avcC[4] = 0xfe; // nalu size length is three bytes
1641     avcC[5] = 0xe1; // one sps
1642
1643     avcC[6] = p_mkv->sps_len >> 8;
1644     avcC[7] = p_mkv->sps_len;
1645
1646     memcpy(avcC+8, p_mkv->sps, p_mkv->sps_len);
1647
1648     avcC[8+p_mkv->sps_len] = 1; // one pps
1649     avcC[9+p_mkv->sps_len] = p_mkv->pps_len >> 8;
1650     avcC[10+p_mkv->sps_len] = p_mkv->pps_len;
1651
1652     memcpy( avcC+11+p_mkv->sps_len, p_mkv->pps, p_mkv->pps_len );
1653
1654     ret = mk_writeHeader( p_mkv->w, "x264", "V_MPEG4/ISO/AVC",
1655                           avcC, avcC_len, p_mkv->frame_duration, 50000,
1656                           p_mkv->width, p_mkv->height,
1657                           p_mkv->d_width, p_mkv->d_height );
1658
1659     free( avcC );
1660
1661     p_mkv->b_header_written = 1;
1662
1663     return ret;
1664 }
1665
1666 static int open_file_mkv( char *psz_filename, hnd_t *p_handle )
1667 {
1668     mkv_t *p_mkv;
1669
1670     *p_handle = NULL;
1671
1672     p_mkv  = malloc(sizeof(*p_mkv));
1673     if (p_mkv == NULL)
1674         return -1;
1675
1676     memset(p_mkv, 0, sizeof(*p_mkv));
1677
1678     p_mkv->w = mk_createWriter(psz_filename);
1679     if (p_mkv->w == NULL)
1680     {
1681         free(p_mkv);
1682         return -1;
1683     }
1684
1685     *p_handle = p_mkv;
1686
1687     return 0;
1688 }
1689
1690 static int set_param_mkv( hnd_t handle, x264_param_t *p_param )
1691 {
1692     mkv_t   *p_mkv = handle;
1693     int64_t dw, dh;
1694
1695     if( p_param->i_fps_num > 0 )
1696     {
1697         p_mkv->frame_duration = (int64_t)p_param->i_fps_den *
1698                                 (int64_t)1000000000 / p_param->i_fps_num;
1699         p_mkv->fps_num = p_param->i_fps_num;
1700     }
1701     else
1702     {
1703         p_mkv->frame_duration = 0;
1704         p_mkv->fps_num = 1;
1705     }
1706
1707     p_mkv->width = p_param->i_width;
1708     p_mkv->height = p_param->i_height;
1709
1710     if( p_param->vui.i_sar_width && p_param->vui.i_sar_height )
1711     {
1712         dw = (int64_t)p_param->i_width  * p_param->vui.i_sar_width;
1713         dh = (int64_t)p_param->i_height * p_param->vui.i_sar_height;
1714     }
1715     else
1716     {
1717         dw = p_param->i_width;
1718         dh = p_param->i_height;
1719     }
1720
1721     if( dw > 0 && dh > 0 )
1722     {
1723         int64_t a = dw, b = dh;
1724
1725         for (;;)
1726         {
1727             int64_t c = a % b;
1728             if( c == 0 )
1729               break;
1730             a = b;
1731             b = c;
1732         }
1733
1734         dw /= b;
1735         dh /= b;
1736     }
1737
1738     p_mkv->d_width = (int)dw;
1739     p_mkv->d_height = (int)dh;
1740
1741     return 0;
1742 }
1743
1744 static int write_nalu_mkv( hnd_t handle, uint8_t *p_nalu, int i_size )
1745 {
1746     mkv_t *p_mkv = handle;
1747     uint8_t type = p_nalu[4] & 0x1f;
1748     uint8_t dsize[3];
1749     int psize;
1750
1751     switch( type )
1752     {
1753     // sps
1754     case 0x07:
1755         if( !p_mkv->sps )
1756         {
1757             p_mkv->sps = malloc(i_size - 4);
1758             if (p_mkv->sps == NULL)
1759                 return -1;
1760             p_mkv->sps_len = i_size - 4;
1761             memcpy(p_mkv->sps, p_nalu + 4, i_size - 4);
1762         }
1763         break;
1764
1765     // pps
1766     case 0x08:
1767         if( !p_mkv->pps )
1768         {
1769             p_mkv->pps = malloc(i_size - 4);
1770             if (p_mkv->pps == NULL)
1771                 return -1;
1772             p_mkv->pps_len = i_size - 4;
1773             memcpy(p_mkv->pps, p_nalu + 4, i_size - 4);
1774         }
1775         break;
1776
1777     // slice, sei
1778     case 0x1:
1779     case 0x5:
1780     case 0x6:
1781         if( !p_mkv->b_writing_frame )
1782         {
1783             if( mk_startFrame(p_mkv->w) < 0 )
1784                 return -1;
1785             p_mkv->b_writing_frame = 1;
1786         }
1787         psize = i_size - 4 ;
1788         dsize[0] = psize >> 16;
1789         dsize[1] = psize >> 8;
1790         dsize[2] = psize;
1791         if( mk_addFrameData(p_mkv->w, dsize, 3) < 0 ||
1792             mk_addFrameData(p_mkv->w, p_nalu + 4, i_size - 4) < 0 )
1793             return -1;
1794         break;
1795
1796     default:
1797         break;
1798     }
1799
1800     if( !p_mkv->b_header_written && p_mkv->pps && p_mkv->sps &&
1801         write_header_mkv(p_mkv) < 0 )
1802         return -1;
1803
1804     return i_size;
1805 }
1806
1807 static int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture )
1808 {
1809     mkv_t *p_mkv = handle;
1810     int64_t i_stamp = (int64_t)(p_picture->i_pts * 1e9 / p_mkv->fps_num);
1811
1812     p_mkv->b_writing_frame = 0;
1813
1814     return mk_setFrameFlags( p_mkv->w, i_stamp,
1815                              p_picture->i_type == X264_TYPE_IDR );
1816 }
1817
1818 static int close_file_mkv( hnd_t handle )
1819 {
1820     mkv_t *p_mkv = handle;
1821     int   ret;
1822
1823     if( p_mkv->sps )
1824         free( p_mkv->sps );
1825     if( p_mkv->pps )
1826         free( p_mkv->pps );
1827
1828     ret = mk_close(p_mkv->w);
1829
1830     free( p_mkv );
1831
1832     return ret;
1833 }
1834