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