]> git.sesse.net Git - x264/blob - x264.c
20bb57b2459ab2528d734ac5ddba69cafb6e1ec0
[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_NONE )
847                         fprintf( stderr, "x264: 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 * 1000 / i_frame_total > i_progress )
1140         {
1141             int64_t i_elapsed = x264_mdate() - i_start;
1142             double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1143             i_progress = i_frame * 1000 / i_frame_total;
1144             fprintf( stderr, "encoded frames: %d/%d (%.1f%%), %.2f fps   \r", i_frame,
1145                      i_frame_total, (float)i_progress / 10, fps );
1146             fflush( stderr ); // needed in windows
1147         }
1148     }
1149     /* Flush delayed B-frames */
1150     do {
1151         i_file +=
1152         i_frame_size = Encode_frame( h, opt->hout, NULL );
1153     } while( i_frame_size );
1154
1155     i_end = x264_mdate();
1156     x264_picture_clean( &pic );
1157     x264_encoder_close( h );
1158     fprintf( stderr, "\n" );
1159
1160     if( b_ctrl_c )
1161         fprintf( stderr, "aborted at input frame %d\n", opt->i_seek + i_frame );
1162
1163     p_close_infile( opt->hin );
1164     p_close_outfile( opt->hout );
1165
1166     if( i_frame > 0 )
1167     {
1168         double fps = (double)i_frame * (double)1000000 /
1169                      (double)( i_end - i_start );
1170
1171         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame, fps,
1172                  (double) i_file * 8 * param->i_fps_num / ( param->i_fps_den * i_frame * 1000 ) );
1173     }
1174
1175     return 0;
1176 }
1177
1178 /* raw 420 yuv file operation */
1179 static int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1180 {
1181     if ((*p_handle = fopen(psz_filename, "rb")) == NULL)
1182         return -1;
1183     return 0;
1184 }
1185
1186 static int get_frame_total_yuv( hnd_t handle, int i_width, int i_height )
1187 {
1188     FILE *f = (FILE *)handle;
1189     int i_frame_total = 0;
1190
1191     if( !fseek( f, 0, SEEK_END ) )
1192     {
1193         int64_t i_size = ftell( f );
1194         fseek( f, 0, SEEK_SET );
1195         i_frame_total = (int)(i_size / ( i_width * i_height * 3 / 2 ));
1196     }
1197
1198     return i_frame_total;
1199 }
1200
1201 static int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1202 {
1203     static int prev_frame = -1;
1204     FILE *f = (FILE *)handle;
1205
1206     if( i_frame != prev_frame+1 )
1207         if( fseek( f, i_frame * i_width * i_height * 3 / 2, SEEK_SET ) )
1208             return -1;
1209
1210     if( fread( p_pic->img.plane[0], 1, i_width * i_height, f ) <= 0
1211             || fread( p_pic->img.plane[1], 1, i_width * i_height / 4, f ) <= 0
1212             || fread( p_pic->img.plane[2], 1, i_width * i_height / 4, f ) <= 0 )
1213         return -1;
1214
1215     prev_frame = i_frame;
1216
1217     return 0;
1218 }
1219
1220 static int close_file_yuv(hnd_t handle)
1221 {
1222     if (handle == NULL)
1223         return 0;
1224     return fclose((FILE *)handle);
1225 }
1226
1227
1228 /* avs/avi input file support under cygwin */
1229
1230 #ifdef AVIS_INPUT
1231
1232 static int gcd(int a, int b)
1233 {
1234     int c;
1235
1236     while (1)
1237     {
1238         c = a % b;
1239         if (!c)
1240             return b;
1241         a = b;
1242         b = c;
1243     }
1244 }
1245
1246 static int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1247 {
1248     AVISTREAMINFO info;
1249     PAVISTREAM p_avi = NULL;
1250     int i;
1251
1252     *p_handle = NULL;
1253
1254     AVIFileInit();
1255     if( AVIStreamOpenFromFile( &p_avi, psz_filename, streamtypeVIDEO, 0, OF_READ, NULL ) )
1256     {
1257         AVIFileExit();
1258         return -1;
1259     }
1260
1261     if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1262     {
1263         AVIStreamRelease(p_avi);
1264         AVIFileExit();
1265         return -1;
1266     }
1267
1268     // check input format
1269     if (info.fccHandler != MAKEFOURCC('Y', 'V', '1', '2'))
1270     {
1271         fprintf( stderr, "avis [error]: unsupported input format (%c%c%c%c)\n",
1272             (char)(info.fccHandler & 0xff), (char)((info.fccHandler >> 8) & 0xff),
1273             (char)((info.fccHandler >> 16) & 0xff), (char)((info.fccHandler >> 24)) );
1274
1275         AVIStreamRelease(p_avi);
1276         AVIFileExit();
1277
1278         return -1;
1279     }
1280
1281     p_param->i_width = info.rcFrame.right - info.rcFrame.left;
1282     p_param->i_height = info.rcFrame.bottom - info.rcFrame.top;
1283     i = gcd(info.dwRate, info.dwScale);
1284     p_param->i_fps_den = info.dwScale / i;
1285     p_param->i_fps_num = info.dwRate / i;
1286
1287     fprintf( stderr, "avis [info]: %dx%d @ %.2f fps (%d frames)\n",  
1288         p_param->i_width, p_param->i_height,
1289         (double)p_param->i_fps_num / (double)p_param->i_fps_den,
1290         (int)info.dwLength );
1291
1292     *p_handle = (hnd_t)p_avi;
1293
1294     return 0;
1295 }
1296
1297 static int get_frame_total_avis( hnd_t handle, int i_width, int i_height )
1298 {
1299     PAVISTREAM p_avi = (PAVISTREAM)handle;
1300     AVISTREAMINFO info;
1301
1302     if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1303         return -1;
1304
1305     return info.dwLength;
1306 }
1307
1308 static int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1309 {
1310     PAVISTREAM p_avi = (PAVISTREAM)handle;
1311     
1312     p_pic->img.i_csp = X264_CSP_YV12;
1313     
1314     if( AVIStreamRead(p_avi, i_frame, 1, p_pic->img.plane[0], i_width * i_height * 3 / 2, NULL, NULL ) )
1315         return -1;
1316
1317     return 0;
1318 }
1319
1320 static int close_file_avis( hnd_t handle )
1321 {
1322     PAVISTREAM p_avi = (PAVISTREAM)handle;
1323
1324     AVIStreamRelease(p_avi);
1325     AVIFileExit();
1326
1327     return 0;
1328 }
1329
1330 #endif
1331
1332
1333 static int open_file_bsf( char *psz_filename, hnd_t *p_handle )
1334 {
1335     if ((*p_handle = fopen(psz_filename, "w+b")) == NULL)
1336         return -1;
1337
1338     return 0;
1339 }
1340
1341 static int set_param_bsf( hnd_t handle, x264_param_t *p_param )
1342 {
1343     return 0;
1344 }
1345
1346 static int write_nalu_bsf( hnd_t handle, uint8_t *p_nalu, int i_size )
1347 {
1348     if (fwrite(p_nalu, i_size, 1, (FILE *)handle) > 0)
1349         return i_size;
1350     return -1;
1351 }
1352
1353 static int set_eop_bsf( hnd_t handle,  x264_picture_t *p_picture )
1354 {
1355     return 0;
1356 }
1357
1358 static int close_file_bsf( hnd_t handle )
1359 {
1360     if ((handle == NULL) || (handle == stdout))
1361         return 0;
1362
1363     return fclose((FILE *)handle);
1364 }
1365
1366 /* -- mp4 muxing support ------------------------------------------------- */
1367 #ifdef MP4_OUTPUT
1368
1369 typedef struct
1370 {
1371     GF_ISOFile *p_file;
1372     GF_AVCConfig *p_config;
1373     GF_ISOSample *p_sample;
1374     int i_track;
1375     int i_descidx;
1376     int i_time_inc;
1377     int i_time_res;
1378     int i_numframe;
1379     int i_init_delay;
1380     uint8_t b_sps;
1381     uint8_t b_pps;
1382 } mp4_t;
1383
1384
1385 static void recompute_bitrate_mp4(GF_ISOFile *p_file, int i_track)
1386 {
1387     u32 i, count, di, timescale, time_wnd, rate;
1388     u64 offset;
1389     Double br;
1390     GF_ESD *esd;
1391
1392     esd = gf_isom_get_esd(p_file, i_track, 1);
1393     if (!esd) return;
1394
1395     esd->decoderConfig->avgBitrate = 0;
1396     esd->decoderConfig->maxBitrate = 0;
1397     rate = time_wnd = 0;
1398
1399     timescale = gf_isom_get_media_timescale(p_file, i_track);
1400     count = gf_isom_get_sample_count(p_file, i_track);
1401     for (i=0; i<count; i++) {
1402         GF_ISOSample *samp = gf_isom_get_sample_info(p_file, i_track, i+1, &di, &offset);
1403
1404         if (samp->dataLength>esd->decoderConfig->bufferSizeDB) esd->decoderConfig->bufferSizeDB = samp->dataLength;
1405
1406         if (esd->decoderConfig->bufferSizeDB < samp->dataLength) esd->decoderConfig->bufferSizeDB = samp->dataLength;
1407         esd->decoderConfig->avgBitrate += samp->dataLength;
1408         rate += samp->dataLength;
1409         if (samp->DTS > time_wnd + timescale) {
1410             if (rate > esd->decoderConfig->maxBitrate) esd->decoderConfig->maxBitrate = rate;
1411             time_wnd = samp->DTS;
1412             rate = 0;
1413         }
1414
1415         gf_isom_sample_del(&samp);
1416     }
1417
1418     br = (Double) (s64) gf_isom_get_media_duration(p_file, i_track);
1419     br /= timescale;
1420     esd->decoderConfig->avgBitrate = (u32) (esd->decoderConfig->avgBitrate / br);
1421     /*move to bps*/
1422     esd->decoderConfig->avgBitrate *= 8;
1423     esd->decoderConfig->maxBitrate *= 8;
1424
1425     gf_isom_change_mpeg4_description(p_file, i_track, 1, esd);
1426     gf_odf_desc_del((GF_Descriptor *) esd);
1427 }
1428
1429
1430 static int close_file_mp4( hnd_t handle )
1431 {
1432     mp4_t *p_mp4 = (mp4_t *)handle;
1433
1434     if (p_mp4 == NULL)
1435         return 0;
1436
1437     if (p_mp4->p_config)
1438         gf_odf_avc_cfg_del(p_mp4->p_config);
1439
1440     if (p_mp4->p_sample)
1441     {
1442         if (p_mp4->p_sample->data)
1443             free(p_mp4->p_sample->data);
1444
1445         gf_isom_sample_del(&p_mp4->p_sample);
1446     }
1447
1448     if (p_mp4->p_file)
1449     {
1450         recompute_bitrate_mp4(p_mp4->p_file, p_mp4->i_track);
1451         gf_isom_set_pl_indication(p_mp4->p_file, GF_ISOM_PL_VISUAL, 0x15);
1452         gf_isom_set_storage_mode(p_mp4->p_file, GF_ISOM_STORE_FLAT);
1453         gf_isom_close(p_mp4->p_file);
1454     }
1455
1456     free(p_mp4);
1457
1458     return 0;
1459 }
1460
1461 static int open_file_mp4( char *psz_filename, hnd_t *p_handle )
1462 {
1463     mp4_t *p_mp4;
1464
1465     *p_handle = NULL;
1466
1467     if ((p_mp4 = (mp4_t *)malloc(sizeof(mp4_t))) == NULL)
1468         return -1;
1469
1470     memset(p_mp4, 0, sizeof(mp4_t));
1471     p_mp4->p_file = gf_isom_open(psz_filename, GF_ISOM_OPEN_WRITE, NULL);
1472
1473     if ((p_mp4->p_sample = gf_isom_sample_new()) == NULL)
1474     {
1475         close_file_mp4( p_mp4 );
1476         return -1;
1477     }
1478
1479     gf_isom_set_brand_info(p_mp4->p_file, GF_ISOM_BRAND_AVC1, 0);
1480
1481     *p_handle = p_mp4;
1482
1483     return 0;
1484 }
1485
1486
1487 static int set_param_mp4( hnd_t handle, x264_param_t *p_param )
1488 {
1489     mp4_t *p_mp4 = (mp4_t *)handle;
1490
1491     p_mp4->i_track = gf_isom_new_track(p_mp4->p_file, 0, GF_ISOM_MEDIA_VISUAL, 
1492         p_param->i_fps_num);
1493
1494     p_mp4->p_config = gf_odf_avc_cfg_new();
1495     gf_isom_avc_config_new(p_mp4->p_file, p_mp4->i_track, p_mp4->p_config, 
1496         NULL, NULL, &p_mp4->i_descidx);
1497
1498     gf_isom_set_visual_info(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, 
1499         p_param->i_width, p_param->i_height);
1500
1501     p_mp4->p_sample->data = (char *)malloc(p_param->i_width * p_param->i_height * 3 / 2);
1502     if (p_mp4->p_sample->data == NULL)
1503         return -1;
1504
1505     p_mp4->i_time_res = p_param->i_fps_num;
1506     p_mp4->i_time_inc = p_param->i_fps_den;
1507     p_mp4->i_init_delay = p_param->i_bframe ? (p_param->b_bframe_pyramid ? 2 : 1) : 0;
1508     p_mp4->i_init_delay *= p_mp4->i_time_inc;
1509     fprintf(stderr, "mp4 [info]: initial delay %d (scale %d)\n", 
1510         p_mp4->i_init_delay, p_mp4->i_time_res);
1511
1512     return 0;
1513 }
1514
1515
1516 static int write_nalu_mp4( hnd_t handle, uint8_t *p_nalu, int i_size )
1517 {
1518     mp4_t *p_mp4 = (mp4_t *)handle;
1519     GF_AVCConfigSlot *p_slot;
1520     uint8_t type = p_nalu[4] & 0x1f;
1521     int psize;
1522
1523     switch(type)
1524     {
1525     // sps
1526     case 0x07:
1527         if (!p_mp4->b_sps)
1528         {
1529             p_mp4->p_config->configurationVersion = 1;
1530             p_mp4->p_config->AVCProfileIndication = p_nalu[5];
1531             p_mp4->p_config->profile_compatibility = p_nalu[6];
1532             p_mp4->p_config->AVCLevelIndication = p_nalu[7];
1533             p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
1534             p_slot->size = i_size - 4;
1535             p_slot->data = (char *)malloc(p_slot->size);
1536             memcpy(p_slot->data, p_nalu + 4, i_size - 4);
1537             gf_list_add(p_mp4->p_config->sequenceParameterSets, p_slot);
1538             p_slot = NULL;
1539             p_mp4->b_sps = 1;
1540         }
1541         break;
1542
1543     // pps      
1544     case 0x08:
1545         if (!p_mp4->b_pps)
1546         {
1547             p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
1548             p_slot->size = i_size - 4;
1549             p_slot->data = (char *)malloc(p_slot->size);
1550             memcpy(p_slot->data, p_nalu + 4, i_size - 4);
1551             gf_list_add(p_mp4->p_config->pictureParameterSets, p_slot);
1552             p_slot = NULL;
1553             p_mp4->b_pps = 1;
1554             if (p_mp4->b_sps)
1555                 gf_isom_avc_config_update(p_mp4->p_file, p_mp4->i_track, 1, p_mp4->p_config);
1556         }
1557         break;
1558
1559     // slice, sei
1560     case 0x1:
1561     case 0x5:
1562     case 0x6:
1563         psize = i_size - 4 ;
1564         memcpy(p_mp4->p_sample->data + p_mp4->p_sample->dataLength, p_nalu, i_size);
1565         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 0] = (psize >> 24) & 0xff;
1566         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 1] = (psize >> 16) & 0xff;
1567         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 2] = (psize >> 8) & 0xff;
1568         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 3] = (psize >> 0) & 0xff;
1569         p_mp4->p_sample->dataLength += i_size;
1570         break;
1571     }
1572
1573     return i_size;
1574 }
1575
1576 static int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture )
1577 {
1578     mp4_t *p_mp4 = (mp4_t *)handle;
1579     uint32_t dts = p_mp4->i_numframe * p_mp4->i_time_inc;
1580     uint32_t pts = p_picture->i_pts;
1581     int offset = p_mp4->i_init_delay + pts - dts;
1582
1583     p_mp4->p_sample->IsRAP = p_picture->i_type == X264_TYPE_IDR ? 1 : 0;
1584     p_mp4->p_sample->DTS = dts;
1585     p_mp4->p_sample->CTS_Offset = offset;
1586     gf_isom_add_sample(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, p_mp4->p_sample);
1587
1588     p_mp4->p_sample->dataLength = 0;
1589     p_mp4->i_numframe++;
1590
1591     return 0;
1592 }
1593
1594 #endif
1595
1596
1597 /* -- mkv muxing support ------------------------------------------------- */
1598 typedef struct
1599 {
1600     mk_Writer *w;
1601
1602     uint8_t   *sps, *pps;
1603     int       sps_len, pps_len;
1604
1605     int       width, height, d_width, d_height;
1606
1607     int64_t   frame_duration;
1608     int       fps_num;
1609
1610     int       b_header_written;
1611     char      b_writing_frame;
1612 } mkv_t;
1613
1614 static int write_header_mkv( mkv_t *p_mkv )
1615 {
1616     int       ret;
1617     uint8_t   *avcC;
1618     int  avcC_len;
1619
1620     if( p_mkv->sps == NULL || p_mkv->pps == NULL ||
1621         p_mkv->width == 0 || p_mkv->height == 0 ||
1622         p_mkv->d_width == 0 || p_mkv->d_height == 0)
1623         return -1;
1624
1625     avcC_len = 5 + 1 + 2 + p_mkv->sps_len + 1 + 2 + p_mkv->pps_len;
1626     avcC = malloc(avcC_len);
1627     if (avcC == NULL)
1628         return -1;
1629
1630     avcC[0] = 1;
1631     avcC[1] = p_mkv->sps[1];
1632     avcC[2] = p_mkv->sps[2];
1633     avcC[3] = p_mkv->sps[3];
1634     avcC[4] = 0xfe; // nalu size length is three bytes
1635     avcC[5] = 0xe1; // one sps
1636
1637     avcC[6] = p_mkv->sps_len >> 8;
1638     avcC[7] = p_mkv->sps_len;
1639
1640     memcpy(avcC+8, p_mkv->sps, p_mkv->sps_len);
1641
1642     avcC[8+p_mkv->sps_len] = 1; // one pps
1643     avcC[9+p_mkv->sps_len] = p_mkv->pps_len >> 8;
1644     avcC[10+p_mkv->sps_len] = p_mkv->pps_len;
1645
1646     memcpy( avcC+11+p_mkv->sps_len, p_mkv->pps, p_mkv->pps_len );
1647
1648     ret = mk_writeHeader( p_mkv->w, "x264", "V_MPEG4/ISO/AVC",
1649                           avcC, avcC_len, p_mkv->frame_duration, 50000,
1650                           p_mkv->width, p_mkv->height,
1651                           p_mkv->d_width, p_mkv->d_height );
1652
1653     free( avcC );
1654
1655     p_mkv->b_header_written = 1;
1656
1657     return ret;
1658 }
1659
1660 static int open_file_mkv( char *psz_filename, hnd_t *p_handle )
1661 {
1662     mkv_t *p_mkv;
1663
1664     *p_handle = NULL;
1665
1666     p_mkv  = malloc(sizeof(*p_mkv));
1667     if (p_mkv == NULL)
1668         return -1;
1669
1670     memset(p_mkv, 0, sizeof(*p_mkv));
1671
1672     p_mkv->w = mk_createWriter(psz_filename);
1673     if (p_mkv->w == NULL)
1674     {
1675         free(p_mkv);
1676         return -1;
1677     }
1678
1679     *p_handle = p_mkv;
1680
1681     return 0;
1682 }
1683
1684 static int set_param_mkv( hnd_t handle, x264_param_t *p_param )
1685 {
1686     mkv_t   *p_mkv = handle;
1687     int64_t dw, dh;
1688
1689     if( p_param->i_fps_num > 0 )
1690     {
1691         p_mkv->frame_duration = (int64_t)p_param->i_fps_den *
1692                                 (int64_t)1000000000 / p_param->i_fps_num;
1693         p_mkv->fps_num = p_param->i_fps_num;
1694     }
1695     else
1696     {
1697         p_mkv->frame_duration = 0;
1698         p_mkv->fps_num = 1;
1699     }
1700
1701     p_mkv->width = p_param->i_width;
1702     p_mkv->height = p_param->i_height;
1703
1704     if( p_param->vui.i_sar_width && p_param->vui.i_sar_height )
1705     {
1706         dw = (int64_t)p_param->i_width  * p_param->vui.i_sar_width;
1707         dh = (int64_t)p_param->i_height * p_param->vui.i_sar_height;
1708     }
1709     else
1710     {
1711         dw = p_param->i_width;
1712         dh = p_param->i_height;
1713     }
1714
1715     if( dw > 0 && dh > 0 )
1716     {
1717         int64_t a = dw, b = dh;
1718
1719         for (;;)
1720         {
1721             int64_t c = a % b;
1722             if( c == 0 )
1723               break;
1724             a = b;
1725             b = c;
1726         }
1727
1728         dw /= b;
1729         dh /= b;
1730     }
1731
1732     p_mkv->d_width = (int)dw;
1733     p_mkv->d_height = (int)dh;
1734
1735     return 0;
1736 }
1737
1738 static int write_nalu_mkv( hnd_t handle, uint8_t *p_nalu, int i_size )
1739 {
1740     mkv_t *p_mkv = handle;
1741     uint8_t type = p_nalu[4] & 0x1f;
1742     uint8_t dsize[3];
1743     int psize;
1744
1745     switch( type )
1746     {
1747     // sps
1748     case 0x07:
1749         if( !p_mkv->sps )
1750         {
1751             p_mkv->sps = malloc(i_size - 4);
1752             if (p_mkv->sps == NULL)
1753                 return -1;
1754             p_mkv->sps_len = i_size - 4;
1755             memcpy(p_mkv->sps, p_nalu + 4, i_size - 4);
1756         }
1757         break;
1758
1759     // pps
1760     case 0x08:
1761         if( !p_mkv->pps )
1762         {
1763             p_mkv->pps = malloc(i_size - 4);
1764             if (p_mkv->pps == NULL)
1765                 return -1;
1766             p_mkv->pps_len = i_size - 4;
1767             memcpy(p_mkv->pps, p_nalu + 4, i_size - 4);
1768         }
1769         break;
1770
1771     // slice, sei
1772     case 0x1:
1773     case 0x5:
1774     case 0x6:
1775         if( !p_mkv->b_writing_frame )
1776         {
1777             if( mk_startFrame(p_mkv->w) < 0 )
1778                 return -1;
1779             p_mkv->b_writing_frame = 1;
1780         }
1781         psize = i_size - 4 ;
1782         dsize[0] = psize >> 16;
1783         dsize[1] = psize >> 8;
1784         dsize[2] = psize;
1785         if( mk_addFrameData(p_mkv->w, dsize, 3) < 0 ||
1786             mk_addFrameData(p_mkv->w, p_nalu + 4, i_size - 4) < 0 )
1787             return -1;
1788         break;
1789
1790     default:
1791         break;
1792     }
1793
1794     if( !p_mkv->b_header_written && p_mkv->pps && p_mkv->sps &&
1795         write_header_mkv(p_mkv) < 0 )
1796         return -1;
1797
1798     return i_size;
1799 }
1800
1801 static int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture )
1802 {
1803     mkv_t *p_mkv = handle;
1804     int64_t i_stamp = (int64_t)(p_picture->i_pts * 1e9 / p_mkv->fps_num);
1805
1806     p_mkv->b_writing_frame = 0;
1807
1808     return mk_setFrameFlags( p_mkv->w, i_stamp,
1809                              p_picture->i_type == X264_TYPE_IDR );
1810 }
1811
1812 static int close_file_mkv( hnd_t handle )
1813 {
1814     mkv_t *p_mkv = handle;
1815     int   ret;
1816
1817     if( p_mkv->sps )
1818         free( p_mkv->sps );
1819     if( p_mkv->pps )
1820         free( p_mkv->pps );
1821
1822     ret = mk_close(p_mkv->w);
1823
1824     free( p_mkv );
1825
1826     return ret;
1827 }
1828