]> git.sesse.net Git - x264/blob - x264.c
1324c83fd243b3995bdd6f669612a9681677a052
[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 #define _LARGEFILE_SOURCE
25 #define _FILE_OFFSET_BITS 64
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <math.h>
31
32 #include <signal.h>
33 #define _GNU_SOURCE
34 #include <getopt.h>
35
36 #ifdef _MSC_VER
37 #include <io.h>     /* _setmode() */
38 #include <fcntl.h>  /* _O_BINARY */
39 #endif
40
41 #ifndef _MSC_VER
42 #include "config.h"
43 #endif
44
45 #include "common/common.h"
46 #include "x264.h"
47 #include "muxers.h"
48
49 #define DATA_MAX 3000000
50 uint8_t data[DATA_MAX];
51
52 /* Ctrl-C handler */
53 static int     b_ctrl_c = 0;
54 static int     b_exit_on_ctrl_c = 0;
55 static void    SigIntHandler( int a )
56 {
57     if( b_exit_on_ctrl_c )
58         exit(0);
59     b_ctrl_c = 1;
60 }
61
62 typedef struct {
63     int b_progress;
64     int i_seek;
65     hnd_t hin;
66     hnd_t hout;
67     FILE *qpfile;
68 } cli_opt_t;
69
70 /* input file operation function pointers */
71 int (*p_open_infile)( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
72 int (*p_get_frame_total)( hnd_t handle );
73 int (*p_read_frame)( x264_picture_t *p_pic, hnd_t handle, int i_frame );
74 int (*p_close_infile)( hnd_t handle );
75
76 /* output file operation function pointers */
77 static int (*p_open_outfile)( char *psz_filename, hnd_t *p_handle );
78 static int (*p_set_outfile_param)( hnd_t handle, x264_param_t *p_param );
79 static int (*p_write_nalu)( hnd_t handle, uint8_t *p_nal, int i_size );
80 static int (*p_set_eop)( hnd_t handle, x264_picture_t *p_picture );
81 static int (*p_close_outfile)( hnd_t handle );
82
83 static void Help( x264_param_t *defaults );
84 static int  Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
85 static int  Encode( x264_param_t *param, cli_opt_t *opt );
86
87
88 /****************************************************************************
89  * main:
90  ****************************************************************************/
91 int main( int argc, char **argv )
92 {
93     x264_param_t param;
94     cli_opt_t opt;
95
96 #ifdef _MSC_VER
97     _setmode(_fileno(stdin), _O_BINARY);
98     _setmode(_fileno(stdout), _O_BINARY);
99 #endif
100
101     x264_param_default( &param );
102
103     /* Parse command line */
104     if( Parse( argc, argv, &param, &opt ) < 0 )
105         return -1;
106
107     /* Control-C handler */
108     signal( SIGINT, SigIntHandler );
109
110     return Encode( &param, &opt );
111 }
112
113 static char const *strtable_lookup( const char * const table[], int index )
114 {
115     int i = 0; while( table[i] ) i++;
116     return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
117 }
118
119 /*****************************************************************************
120  * Help:
121  *****************************************************************************/
122 static void Help( x264_param_t *defaults )
123 {
124     fprintf( stderr,
125              "x264 core:%d%s\n"
126              "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
127              "\n"
128              "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
129              "  or YUV4MPEG 4:2:0 (*.y4m),\n"
130              "  or AVI or Avisynth if compiled with AVIS support (%s).\n"
131              "Outfile type is selected by filename:\n"
132              " .264 -> Raw bytestream\n"
133              " .mkv -> Matroska\n"
134              " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
135              "\n"
136              "Options:\n"
137              "\n"
138              "  -h, --help                  Print this help\n"
139              "\n"
140              "Frame-type options:\n"
141              "\n"
142              "  -I, --keyint <integer>      Maximum GOP size [%d]\n"
143              "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n"
144              "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n"
145              "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n"
146              "      --no-b-adapt            Disable adaptive B-frame decision\n"
147              "      --b-bias <integer>      Influences how often B-frames are used [%d]\n"
148              "      --b-pyramid             Keep some B-frames as references\n"
149              "\n"
150              "      --no-cabac              Disable CABAC\n"
151              "  -r, --ref <integer>         Number of reference frames [%d]\n"
152              "      --nf                    Disable loop filter\n"
153              "  -f, --filter <alpha:beta>   Loop filter AlphaC0 and Beta parameters [%d:%d]\n"
154              "\n"
155              "Ratecontrol:\n"
156              "\n"
157              "  -q, --qp <integer>          Set QP (0=lossless) [%d]\n"
158              "  -B, --bitrate <integer>     Set bitrate\n"
159              "      --crf <integer>         Quality-based VBR (nominal QP)\n"
160              "      --qpmin <integer>       Set min QP [%d]\n"
161              "      --qpmax <integer>       Set max QP [%d]\n"
162              "      --qpstep <integer>      Set max QP step [%d]\n"
163              "      --ratetol <float>       Allowed variance of average bitrate [%.1f]\n"
164              "      --vbv-maxrate <integer> Max local bitrate [%d]\n"
165              "      --vbv-bufsize <integer> Size of VBV buffer [%d]\n"
166              "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n"
167              "\n"
168              "      --ipratio <float>       QP factor between I and P [%.2f]\n"
169              "      --pbratio <float>       QP factor between P and B [%.2f]\n"
170              "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n"
171              "\n"
172              "  -p, --pass <1|2|3>          Enable multipass ratecontrol:\n"
173              "                                  - 1: First pass, creates stats file\n"
174              "                                  - 2: Last pass, does not overwrite stats file\n"
175              "                                  - 3: Nth pass, overwrites stats file\n"
176              "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n"
177              "      --rceq <string>         Ratecontrol equation [\"%s\"]\n"
178              "      --qcomp <float>         QP curve compression: 0.0 => CBR, 1.0 => CQP [%.2f]\n"
179              "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n"
180              "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n"
181              "\n"
182              "      --zones <zone0>/<zone1>/...\n"
183              "                              Tweak the bitrate of some regions of the video\n"
184              "                              Each zone is of the form\n"
185              "                                  <start frame>,<end frame>,<option>\n"
186              "                                  where <option> is either\n"
187              "                                      q=<integer> (force QP)\n"
188              "                                  or  b=<float> (bitrate multiplier)\n"
189              "      --qpfile <string>       Force frametypes and QPs\n"
190              "\n"
191              "Analysis:\n"
192              "\n"
193              "  -A, --analyse <string>      Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
194              "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
195              "                                  - none, all\n"
196              "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n"
197              "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
198              "                                  - none, spatial, temporal, auto\n"
199              "  -w, --weightb               Weighted prediction for B-frames\n"
200              "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n"
201              "                                  - dia: diamond search, radius 1 (fast)\n"
202              "                                  - hex: hexagonal search, radius 2\n"
203              "                                  - umh: uneven multi-hexagon search\n"
204              "                                  - esa: exhaustive search (slow)\n"
205              "      --merange <integer>     Maximum motion vector search range [%d]\n"
206              "  -m, --subme <integer>       Subpixel motion estimation and partition\n"
207              "                                  decision quality: 1=fast, 7=best. [%d]\n"
208              "      --b-rdo                 RD based mode decision for B-frames. Requires subme 6.\n"
209              "      --mixed-refs            Decide references on a per partition basis\n"
210              "      --no-chroma-me          Ignore chroma in motion estimation\n"
211              "      --bime                  Jointly optimize both MVs in B-frames\n"
212              "  -8, --8x8dct                Adaptive spatial transform size\n"
213              "  -t, --trellis <integer>     Trellis RD quantization. Requires CABAC. [%d]\n"
214              "                                  - 0: disabled\n"
215              "                                  - 1: enabled only on the final encode of a MB\n"
216              "                                  - 2: enabled on all mode decisions\n"
217              "      --no-fast-pskip         Disables early SKIP detection on P-frames\n"
218              "      --no-dct-decimate       Disables coefficient thresholding on P-frames\n"
219              "      --nr <integer>          Noise reduction [%d]\n"
220              "\n"
221              "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
222              "                                  - jvt, flat\n"
223              "      --cqmfile <string>      Read quant matrices from a JM-compatible file\n"
224              "                                  Overrides any other --cqm* options.\n"
225              "      --cqm4 <list>           Set all 4x4 quant matrices\n"
226              "                                  Takes a comma-separated list of 16 integers.\n"
227              "      --cqm8 <list>           Set all 8x8 quant matrices\n"
228              "                                  Takes a comma-separated list of 64 integers.\n"
229              "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
230              "                              Set both luma and chroma quant matrices\n"
231              "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
232              "                              Set individual quant matrices\n"
233              "\n"
234              "Video Usability Info (Annex E):\n"
235              "The VUI settings are not used by the encoder but are merely suggestions to\n"
236              "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n"
237              "\n"
238              "      --sar width:height      Specify Sample Aspect Ratio\n"
239              "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
240              "                                  - undef, show, crop\n"
241              "      --videoformat <string>  Specify video format [\"%s\"]\n"
242              "                                  - component, pal, ntsc, secam, mac, undef\n"
243              "      --fullrange <string>    Specify full range samples setting [\"%s\"]\n"
244              "                                  - off, on\n"
245              "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
246              "                                  - undef, bt709, bt470m, bt470bg\n"
247              "                                    smpte170m, smpte240m, film\n"
248              "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
249              "                                  - undef, bt709, bt470m, bt470bg, linear,\n"
250              "                                    log100, log316, smpte170m, smpte240m\n"
251              "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
252              "                                  - undef, bt709, fcc, bt470bg\n"
253              "                                    smpte170m, smpte240m, GBR, YCgCo\n"
254              "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n"
255              "\n"
256              "Input/Output:\n"
257              "\n"
258              "      --level <string>        Specify level (as defined by Annex A)\n"
259              "      --fps <float|rational>  Specify framerate\n"
260              "      --seek <integer>        First frame to encode\n"
261              "      --frames <integer>      Maximum number of frames to encode\n"
262              "  -o, --output                Specify output file\n"
263              "\n"
264              "      --threads <integer>     Parallel encoding (uses slices)\n"
265              "      --thread-input          Run Avisynth in its own thread\n"
266              "      --no-asm                Disable all CPU optimizations\n"
267              "      --no-psnr               Disable PSNR computation\n"
268              "      --quiet                 Quiet Mode\n"
269              "  -v, --verbose               Print stats for each frame\n"
270              "      --progress              Show a progress indicator while encoding\n"
271              "      --visualize             Show MB types overlayed on the encoded video\n"
272              "      --sps-id <integer>      Set SPS and PPS id numbers [%d]\n"
273              "      --aud                   Use access unit delimiters\n"
274              "\n",
275             X264_BUILD, X264_VERSION,
276 #ifdef AVIS_INPUT
277             "yes",
278 #else
279             "no",
280 #endif
281 #ifdef MP4_OUTPUT
282             "yes",
283 #else
284             "no",
285 #endif
286             defaults->i_keyint_max,
287             defaults->i_keyint_min,
288             defaults->i_scenecut_threshold,
289             defaults->i_bframe,
290             defaults->i_bframe_bias,
291             defaults->i_frame_reference,
292             defaults->i_deblocking_filter_alphac0,
293             defaults->i_deblocking_filter_beta,
294             defaults->rc.i_qp_constant,
295             defaults->rc.i_qp_min,
296             defaults->rc.i_qp_max,
297             defaults->rc.i_qp_step,
298             defaults->rc.f_rate_tolerance,
299             defaults->rc.i_vbv_max_bitrate,
300             defaults->rc.i_vbv_buffer_size,
301             defaults->rc.f_vbv_buffer_init,
302             defaults->rc.f_ip_factor,
303             defaults->rc.f_pb_factor,
304             defaults->analyse.i_chroma_qp_offset,
305             defaults->rc.psz_stat_out,
306             defaults->rc.psz_rc_eq,
307             defaults->rc.f_qcompress,
308             defaults->rc.f_complexity_blur,
309             defaults->rc.f_qblur,
310             strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ),
311             strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ),
312             defaults->analyse.i_me_range,
313             defaults->analyse.i_subpel_refine,
314             defaults->analyse.i_trellis,
315             defaults->analyse.i_noise_reduction,
316             strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ),
317             strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ),
318             strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ),
319             strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ),
320             strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ),
321             strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ),
322             defaults->vui.i_chroma_loc,
323             defaults->i_sps_id
324            );
325 }
326
327 /*****************************************************************************
328  * Parse:
329  *****************************************************************************/
330 static int  Parse( int argc, char **argv,
331                    x264_param_t *param, cli_opt_t *opt )
332 {
333     char *psz_filename = NULL;
334     x264_param_t defaults = *param;
335     char *psz;
336     int b_avis = 0;
337     int b_y4m = 0;
338     int b_thread_input = 0;
339
340     memset( opt, 0, sizeof(cli_opt_t) );
341
342     /* Default input file driver */
343     p_open_infile = open_file_yuv;
344     p_get_frame_total = get_frame_total_yuv;
345     p_read_frame = read_frame_yuv;
346     p_close_infile = close_file_yuv;
347
348     /* Default output file driver */
349     p_open_outfile = open_file_bsf;
350     p_set_outfile_param = set_param_bsf;
351     p_write_nalu = write_nalu_bsf;
352     p_set_eop = set_eop_bsf;
353     p_close_outfile = close_file_bsf;
354
355     /* Parse command line options */
356     for( ;; )
357     {
358         int b_error = 0;
359         int long_options_index = -1;
360
361 #define OPT_FRAMES 256
362 #define OPT_SEEK 257
363 #define OPT_QPFILE 258
364 #define OPT_THREAD_INPUT 259
365 #define OPT_QUIET 260
366 #define OPT_PROGRESS 261
367 #define OPT_VISUALIZE 262
368
369         static struct option long_options[] =
370         {
371             { "help",    no_argument,       NULL, 'h' },
372             { "bitrate", required_argument, NULL, 'B' },
373             { "bframes", required_argument, NULL, 'b' },
374             { "no-b-adapt", no_argument,    NULL, 0 },
375             { "b-bias",  required_argument, NULL, 0 },
376             { "b-pyramid", no_argument,     NULL, 0 },
377             { "min-keyint",required_argument,NULL,'i' },
378             { "keyint",  required_argument, NULL, 'I' },
379             { "scenecut",required_argument, NULL, 0 },
380             { "nf",      no_argument,       NULL, 0 },
381             { "filter",  required_argument, NULL, 'f' },
382             { "no-cabac",no_argument,       NULL, 0 },
383             { "qp",      required_argument, NULL, 'q' },
384             { "qpmin",   required_argument, NULL, 0 },
385             { "qpmax",   required_argument, NULL, 0 },
386             { "qpstep",  required_argument, NULL, 0 },
387             { "crf",     required_argument, NULL, 0 },
388             { "ref",     required_argument, NULL, 'r' },
389             { "no-asm",  no_argument,       NULL, 0 },
390             { "sar",     required_argument, NULL, 0 },
391             { "fps",     required_argument, NULL, 0 },
392             { "frames",  required_argument, NULL, OPT_FRAMES },
393             { "seek",    required_argument, NULL, OPT_SEEK },
394             { "output",  required_argument, NULL, 'o' },
395             { "analyse", required_argument, NULL, 'A' },
396             { "direct",  required_argument, NULL, 0 },
397             { "weightb", no_argument,       NULL, 'w' },
398             { "me",      required_argument, NULL, 0 },
399             { "merange", required_argument, NULL, 0 },
400             { "subme",   required_argument, NULL, 'm' },
401             { "b-rdo",   no_argument,       NULL, 0 },
402             { "mixed-refs", no_argument,    NULL, 0 },
403             { "no-chroma-me", no_argument,  NULL, 0 },
404             { "bime",    no_argument,       NULL, 0 },
405             { "8x8dct",  no_argument,       NULL, '8' },
406             { "trellis", required_argument, NULL, 't' },
407             { "no-fast-pskip", no_argument, NULL, 0 },
408             { "no-dct-decimate", no_argument, NULL, 0 },
409             { "level",   required_argument, NULL, 0 },
410             { "ratetol", required_argument, NULL, 0 },
411             { "vbv-maxrate", required_argument, NULL, 0 },
412             { "vbv-bufsize", required_argument, NULL, 0 },
413             { "vbv-init", required_argument,NULL,  0 },
414             { "ipratio", required_argument, NULL, 0 },
415             { "pbratio", required_argument, NULL, 0 },
416             { "chroma-qp-offset", required_argument, NULL, 0 },
417             { "pass",    required_argument, NULL, 'p' },
418             { "stats",   required_argument, NULL, 0 },
419             { "rceq",    required_argument, NULL, 0 },
420             { "qcomp",   required_argument, NULL, 0 },
421             { "qblur",   required_argument, NULL, 0 },
422             { "cplxblur",required_argument, NULL, 0 },
423             { "zones",   required_argument, NULL, 0 },
424             { "qpfile",  required_argument, NULL, OPT_QPFILE },
425             { "threads", required_argument, NULL, 0 },
426             { "thread-input", no_argument,  NULL, OPT_THREAD_INPUT },
427             { "no-psnr", no_argument,       NULL, 0 },
428             { "quiet",   no_argument,       NULL, OPT_QUIET },
429             { "verbose", no_argument,       NULL, 'v' },
430             { "progress",no_argument,       NULL, OPT_PROGRESS },
431             { "visualize",no_argument,      NULL, OPT_VISUALIZE },
432             { "sps-id",  required_argument, NULL, 0 },
433             { "aud",     no_argument,       NULL, 0 },
434             { "nr",      required_argument, NULL, 0 },
435             { "cqm",     required_argument, NULL, 0 },
436             { "cqmfile", required_argument, NULL, 0 },
437             { "cqm4",    required_argument, NULL, 0 },
438             { "cqm4i",   required_argument, NULL, 0 },
439             { "cqm4iy",  required_argument, NULL, 0 },
440             { "cqm4ic",  required_argument, NULL, 0 },
441             { "cqm4p",   required_argument, NULL, 0 },
442             { "cqm4py",  required_argument, NULL, 0 },
443             { "cqm4pc",  required_argument, NULL, 0 },
444             { "cqm8",    required_argument, NULL, 0 },
445             { "cqm8i",   required_argument, NULL, 0 },
446             { "cqm8p",   required_argument, NULL, 0 },
447             { "overscan", required_argument, NULL, 0 },
448             { "videoformat", required_argument, NULL, 0 },
449             { "fullrange", required_argument, NULL, 0 },
450             { "colorprim", required_argument, NULL, 0 },
451             { "transfer", required_argument, NULL, 0 },
452             { "colormatrix", required_argument, NULL, 0 },
453             { "chromaloc", required_argument, NULL, 0 },
454             {0, 0, 0, 0}
455         };
456
457         int c = getopt_long( argc, argv, "8A:B:b:f:hI:i:m:o:p:q:r:t:vw",
458                              long_options, &long_options_index);
459
460         if( c == -1 )
461         {
462             break;
463         }
464
465         switch( c )
466         {
467             case 'h':
468                 Help( &defaults );
469                 return -1;
470             case OPT_FRAMES:
471                 param->i_frame_total = atoi( optarg );
472                 break;
473             case OPT_SEEK:
474                 opt->i_seek = atoi( optarg );
475                 break;
476             case 'o':
477                 if( !strncasecmp(optarg + strlen(optarg) - 4, ".mp4", 4) )
478                 {
479 #ifdef MP4_OUTPUT
480                     p_open_outfile = open_file_mp4;
481                     p_write_nalu = write_nalu_mp4;
482                     p_set_outfile_param = set_param_mp4;
483                     p_set_eop = set_eop_mp4;
484                     p_close_outfile = close_file_mp4;
485 #else
486                     fprintf( stderr, "not compiled with MP4 output support\n" );
487                     return -1;
488 #endif
489                 }
490                 else if( !strncasecmp(optarg + strlen(optarg) - 4, ".mkv", 4) )
491                 {
492                     p_open_outfile = open_file_mkv;
493                     p_write_nalu = write_nalu_mkv;
494                     p_set_outfile_param = set_param_mkv;
495                     p_set_eop = set_eop_mkv;
496                     p_close_outfile = close_file_mkv;
497                 }
498                 if( !strcmp(optarg, "-") )
499                     opt->hout = stdout;
500                 else if( p_open_outfile( optarg, &opt->hout ) )
501                 {
502                     fprintf( stderr, "cannot open output file `%s'\n", optarg );
503                     return -1;
504                 }
505                 break;
506             case OPT_QPFILE:
507                 opt->qpfile = fopen( optarg, "r" );
508                 if( !opt->qpfile )
509                 {
510                     fprintf( stderr, "can't open `%s'\n", optarg );
511                     return -1;
512                 }
513                 param->i_scenecut_threshold = -1;
514                 param->b_bframe_adaptive = 0;
515                 break;
516             case OPT_THREAD_INPUT:
517                 b_thread_input = 1;
518                 break;
519             case OPT_QUIET:
520                 param->i_log_level = X264_LOG_NONE;
521                 param->analyse.b_psnr = 0;
522                 break;
523             case 'v':
524                 param->i_log_level = X264_LOG_DEBUG;
525                 break;
526             case OPT_PROGRESS:
527                 opt->b_progress = 1;
528                 break;
529             case OPT_VISUALIZE:
530 #ifdef VISUALIZE
531                 param->b_visualize = 1;
532                 b_exit_on_ctrl_c = 1;
533 #else
534                 fprintf( stderr, "not compiled with visualization support\n" );
535 #endif
536                 break;
537             default:
538             {
539                 int i;
540                 if( long_options_index < 0 )
541                 {
542                     for( i = 0; long_options[i].name; i++ )
543                         if( long_options[i].val == c )
544                         {
545                             long_options_index = i;
546                             break;
547                         }
548                     if( long_options_index < 0 )
549                     {
550                         /* getopt_long already printed an error message */
551                         return -1;
552                     }
553                 }
554
555                 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg ? optarg : "true" );
556             }
557         }
558
559         if( b_error )
560         {
561             const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
562             fprintf( stderr, "x264 [error]: invalid argument: %s = %s\n", name, optarg );
563             return -1;
564         }
565     }
566
567     /* Get the file name */
568     if( optind > argc - 1 || !opt->hout )
569     {
570         Help( &defaults );
571         return -1;
572     }
573     psz_filename = argv[optind++];
574
575     /* check demuxer type */
576     psz = psz_filename + strlen(psz_filename) - 1;
577     while( psz > psz_filename && *psz != '.' )
578         psz--;
579     if( !strncasecmp( psz, ".avi", 4 ) || !strncasecmp( psz, ".avs", 4 ) )
580         b_avis = 1;
581     if( !strncasecmp( psz, ".y4m", 4 ) )
582         b_y4m = 1;
583
584     if( !(b_avis || b_y4m) ) // raw yuv
585     {
586         if( optind > argc - 1 )
587         {
588             /* try to parse the file name */
589             for( psz = psz_filename; *psz; psz++ )
590             {
591                 if( *psz >= '0' && *psz <= '9'
592                     && sscanf( psz, "%ux%u", &param->i_width, &param->i_height ) == 2 )
593                 {
594                     if( param->i_log_level >= X264_LOG_INFO )
595                         fprintf( stderr, "x264 [info]: file name gives %dx%d\n", param->i_width, param->i_height );
596                     break;
597                 }
598             }
599         }
600         else
601         {
602             sscanf( argv[optind++], "%ux%u", &param->i_width, &param->i_height );
603         }
604     }
605         
606     if( !(b_avis || b_y4m) && ( !param->i_width || !param->i_height ) )
607     {
608         Help( &defaults );
609         return -1;
610     }
611
612     /* open the input */
613     {
614         if( b_avis )
615         {
616 #ifdef AVIS_INPUT
617             p_open_infile = open_file_avis;
618             p_get_frame_total = get_frame_total_avis;
619             p_read_frame = read_frame_avis;
620             p_close_infile = close_file_avis;
621 #else
622             fprintf( stderr, "not compiled with AVIS input support\n" );
623             return -1;
624 #endif
625         }
626         if ( b_y4m )
627         {
628             p_open_infile = open_file_y4m;
629             p_get_frame_total = get_frame_total_y4m;
630             p_read_frame = read_frame_y4m;
631             p_close_infile = close_file_y4m;
632         }
633
634         if( p_open_infile( psz_filename, &opt->hin, param ) )
635         {
636             fprintf( stderr, "could not open input file '%s'\n", psz_filename );
637             return -1;
638         }
639     }
640
641 #ifdef HAVE_PTHREAD
642     if( b_thread_input || param->i_threads > 1 )
643     {
644         if( open_file_thread( NULL, &opt->hin, param ) )
645         {
646             fprintf( stderr, "threaded input failed\n" );
647         }
648         else
649         {
650             p_open_infile = open_file_thread;
651             p_get_frame_total = get_frame_total_thread;
652             p_read_frame = read_frame_thread;
653             p_close_infile = close_file_thread;
654         }
655     }
656 #endif
657
658     return 0;
659 }
660
661 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
662 {
663     int num = -1, qp;
664     char type;
665     while( num < i_frame )
666     {
667         int ret = fscanf( opt->qpfile, "%d %c %d\n", &num, &type, &qp );
668         if( num < i_frame )
669             continue;
670         pic->i_qpplus1 = qp+1;
671         if     ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
672         else if( type == 'i' ) pic->i_type = X264_TYPE_I;
673         else if( type == 'P' ) pic->i_type = X264_TYPE_P;
674         else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
675         else if( type == 'b' ) pic->i_type = X264_TYPE_B;
676         else ret = 0;
677         if( ret != 3 || qp < 0 || qp > 51 || num > i_frame )
678         {
679             fprintf( stderr, "can't parse qpfile for frame %d\n", i_frame );
680             fclose( opt->qpfile );
681             opt->qpfile = NULL;
682             pic->i_type = X264_TYPE_AUTO;
683             pic->i_qpplus1 = 0;
684             break;
685         }
686     }
687 }
688
689 /*****************************************************************************
690  * Decode:
691  *****************************************************************************/
692
693 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
694 {
695     x264_picture_t pic_out;
696     x264_nal_t *nal;
697     int i_nal, i;
698     int i_file = 0;
699
700     if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
701     {
702         fprintf( stderr, "x264_encoder_encode failed\n" );
703     }
704
705     for( i = 0; i < i_nal; i++ )
706     {
707         int i_size;
708         int i_data;
709
710         i_data = DATA_MAX;
711         if( ( i_size = x264_nal_encode( data, &i_data, 1, &nal[i] ) ) > 0 )
712         {
713             i_file += p_write_nalu( hout, data, i_size );
714         }
715         else if( i_size < 0 )
716         {
717             fprintf( stderr, "need to increase buffer size (size=%d)\n", -i_size );
718         }
719     }
720     if (i_nal)
721         p_set_eop( hout, &pic_out );
722
723     return i_file;
724 }
725
726 /*****************************************************************************
727  * Encode:
728  *****************************************************************************/
729 static int  Encode( x264_param_t *param, cli_opt_t *opt )
730 {
731     x264_t *h;
732     x264_picture_t pic;
733
734     int     i_frame, i_frame_total;
735     int64_t i_start, i_end;
736     int64_t i_file;
737     int     i_frame_size;
738     int     i_progress;
739
740     i_frame_total = p_get_frame_total( opt->hin );
741     i_frame_total -= opt->i_seek;
742     if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
743         && param->i_frame_total > 0 )
744         i_frame_total = param->i_frame_total;
745     param->i_frame_total = i_frame_total;
746
747     if( ( h = x264_encoder_open( param ) ) == NULL )
748     {
749         fprintf( stderr, "x264_encoder_open failed\n" );
750         p_close_infile( opt->hin );
751         p_close_outfile( opt->hout );
752         return -1;
753     }
754
755     if( p_set_outfile_param( opt->hout, param ) )
756     {
757         fprintf( stderr, "can't set outfile param\n" );
758         p_close_infile( opt->hin );
759         p_close_outfile( opt->hout );
760         return -1;
761     }
762
763     /* Create a new pic */
764     x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height );
765
766     i_start = x264_mdate();
767
768     /* Encode frames */
769     for( i_frame = 0, i_file = 0, i_progress = 0;
770          b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
771     {
772         if( p_read_frame( &pic, opt->hin, i_frame + opt->i_seek ) )
773             break;
774
775         pic.i_pts = (int64_t)i_frame * param->i_fps_den;
776
777         if( opt->qpfile )
778             parse_qpfile( opt, &pic, i_frame + opt->i_seek );
779         else
780         {
781             /* Do not force any parameters */
782             pic.i_type = X264_TYPE_AUTO;
783             pic.i_qpplus1 = 0;
784         }
785
786         i_file += Encode_frame( h, opt->hout, &pic );
787
788         i_frame++;
789
790         /* update status line (up to 1000 times per input file) */
791         if( opt->b_progress && param->i_log_level < X264_LOG_DEBUG && 
792             ( i_frame_total ? i_frame * 1000 / i_frame_total > i_progress
793                             : i_frame % 10 == 0 ) )
794         {
795             int64_t i_elapsed = x264_mdate() - i_start;
796             double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
797             if( i_frame_total )
798             {
799                 int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
800                 i_progress = i_frame * 1000 / i_frame_total;
801                 fprintf( stderr, "encoded frames: %d/%d (%.1f%%), %.2f fps, eta %d:%02d:%02d  \r",
802                          i_frame, i_frame_total, (float)i_progress / 10, fps,
803                          eta/3600, (eta/60)%60, eta%60 );
804             }
805             else
806                 fprintf( stderr, "encoded frames: %d, %.2f fps   \r", i_frame, fps );
807             fflush( stderr ); // needed in windows
808         }
809     }
810     /* Flush delayed B-frames */
811     do {
812         i_file +=
813         i_frame_size = Encode_frame( h, opt->hout, NULL );
814     } while( i_frame_size );
815
816     i_end = x264_mdate();
817     x264_picture_clean( &pic );
818     x264_encoder_close( h );
819     fprintf( stderr, "\n" );
820
821     if( b_ctrl_c )
822         fprintf( stderr, "aborted at input frame %d\n", opt->i_seek + i_frame );
823
824     p_close_infile( opt->hin );
825     p_close_outfile( opt->hout );
826
827     if( i_frame > 0 )
828     {
829         double fps = (double)i_frame * (double)1000000 /
830                      (double)( i_end - i_start );
831
832         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame, fps,
833                  (double) i_file * 8 * param->i_fps_num /
834                  ( (double) param->i_fps_den * i_frame * 1000 ) );
835     }
836
837     return 0;
838 }