]> git.sesse.net Git - x264/blob - x264.c
6bf75e05fe1227642f4d4cf98509c2fb54d700fe
[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 #ifdef _WIN32
37 #include <windows.h>
38 #else
39 #define SetConsoleTitle(t)
40 #endif
41
42 uint8_t *mux_buffer = NULL;
43 int mux_buffer_size = 0;
44
45 /* Ctrl-C handler */
46 static int     b_ctrl_c = 0;
47 static int     b_exit_on_ctrl_c = 0;
48 static void    SigIntHandler( int a )
49 {
50     if( b_exit_on_ctrl_c )
51         exit(0);
52     b_ctrl_c = 1;
53 }
54
55 typedef struct {
56     int b_progress;
57     int i_seek;
58     hnd_t hin;
59     hnd_t hout;
60     FILE *qpfile;
61 } cli_opt_t;
62
63 /* i/o file operation function pointer structs */
64 cli_input_t input;
65 static cli_output_t output;
66
67 /* i/o modules that work with pipes (and fifos) */
68 static const char * const stdin_format_names[] = { "yuv", "y4m", 0 };
69 static const char * const stdout_format_names[] = { "raw", "mkv", "flv", 0 };
70
71 static void Help( x264_param_t *defaults, int longhelp );
72 static int  Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
73 static int  Encode( x264_param_t *param, cli_opt_t *opt );
74
75
76 /****************************************************************************
77  * main:
78  ****************************************************************************/
79 int main( int argc, char **argv )
80 {
81     x264_param_t param;
82     cli_opt_t opt;
83     int ret;
84
85 #ifdef PTW32_STATIC_LIB
86     pthread_win32_process_attach_np();
87     pthread_win32_thread_attach_np();
88 #endif
89
90 #ifdef _WIN32
91     _setmode(_fileno(stdin), _O_BINARY);
92     _setmode(_fileno(stdout), _O_BINARY);
93 #endif
94
95     x264_param_default( &param );
96
97     /* Parse command line */
98     if( Parse( argc, argv, &param, &opt ) < 0 )
99         return -1;
100
101     /* Control-C handler */
102     signal( SIGINT, SigIntHandler );
103
104     ret = Encode( &param, &opt );
105
106 #ifdef PTW32_STATIC_LIB
107     pthread_win32_thread_detach_np();
108     pthread_win32_process_detach_np();
109 #endif
110
111     return ret;
112 }
113
114 static char const *strtable_lookup( const char * const table[], int index )
115 {
116     int i = 0; while( table[i] ) i++;
117     return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
118 }
119
120 /*****************************************************************************
121  * Help:
122  *****************************************************************************/
123 static void Help( x264_param_t *defaults, int longhelp )
124 {
125 #define H0 printf
126 #define H1 if(longhelp>=1) printf
127 #define H2 if(longhelp==2) printf
128     H0( "x264 core:%d%s\n"
129         "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
130         "\n"
131         "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
132         "  or YUV4MPEG 4:2:0 (*.y4m),\n"
133         "  or AVI or Avisynth if compiled with AVIS support (%s).\n"
134         "Outfile type is selected by filename:\n"
135         " .264 -> Raw bytestream\n"
136         " .mkv -> Matroska\n"
137         " .flv -> Flash Video\n"
138         " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
139         "\n"
140         "Options:\n"
141         "\n"
142         "  -h, --help                  List basic options\n"
143         "      --longhelp              List more options\n"
144         "      --fullhelp              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( "Example usage:\n" );
159     H0( "\n" );
160     H0( "      Constant quality mode:\n" );
161     H0( "            x264 --crf 24 -o output input\n" );
162     H0( "\n" );
163     H0( "      Two-pass with a bitrate of 1000kbps:\n" );
164     H0( "            x264 --pass 1 --bitrate 1000 -o output input\n" );
165     H0( "            x264 --pass 2 --bitrate 1000 -o output input\n" );
166     H0( "\n" );
167     H0( "      Lossless:\n" );
168     H0( "            x264 --crf 0 -o output input\n" );
169     H0( "\n" );
170     H0( "      Maximum PSNR at the cost of speed and visual quality:\n" );
171     H0( "            x264 --preset placebo --tune psnr -o output input\n" );
172     H0( "\n" );
173     H0( "      Constant bitrate at 1000kbps with a 2 second-buffer:\n");
174     H0( "            x264 --vbv-bufsize 2000 --bitrate 1000 -o output input\n" );
175     H0( "\n" );
176     H0( "Presets:\n" );
177     H0( "\n" );
178     H0( "      --profile               Force H.264 profile [high]\n" );
179     H0( "                                  Overrides all settings\n");
180     H0( "                                  - baseline,main,high\n" );
181     H0( "      --preset                Use a preset to select encoding settings [medium]\n" );
182     H0( "                                  Overridden by user settings\n");
183     H0( "                                  - ultrafast,veryfast,faster,fast,medium\n"
184         "                                  - slow,slower,veryslow,placebo\n" );
185     H0( "      --tune                  Tune the settings for a particular type of source\n" );
186     H0( "                                  Overridden by user settings\n");
187     H2( "                                  - film,animation,grain,psnr,ssim\n"
188         "                                  - fastdecode,touhou\n");
189     else H0( "                                  - film,animation,grain,psnr,ssim,fastdecode\n");
190     H1( "      --slow-firstpass        Don't use faster settings with --pass 1\n" );
191     H0( "\n" );
192     H0( "Frame-type options:\n" );
193     H0( "\n" );
194     H0( "  -I, --keyint <integer>      Maximum GOP size [%d]\n", defaults->i_keyint_max );
195     H2( "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n", defaults->i_keyint_min );
196     H2( "      --no-scenecut           Disable adaptive I-frame decision\n" );
197     H2( "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
198     H1( "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n", defaults->i_bframe );
199     H1( "      --b-adapt               Adaptive B-frame decision method [%d]\n"
200         "                                  Higher values may lower threading efficiency.\n"
201         "                                  - 0: Disabled\n"
202         "                                  - 1: Fast\n"
203         "                                  - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
204     H2( "      --b-bias <integer>      Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
205     H1( "      --b-pyramid <string>    Keep some B-frames as references [%s]\n"
206         "                                  - none: Disabled\n"
207         "                                  - strict: Strictly hierarchical pyramid\n"
208         "                                  - normal: Non-strict (not Blu-ray compatible)\n",
209         strtable_lookup( x264_b_pyramid_names, defaults->i_bframe_pyramid ) );
210     H1( "      --no-cabac              Disable CABAC\n" );
211     H1( "  -r, --ref <integer>         Number of reference frames [%d]\n", defaults->i_frame_reference );
212     H1( "      --no-deblock            Disable loop filter\n" );
213     H1( "  -f, --deblock <alpha:beta>  Loop filter parameters [%d:%d]\n",
214                                        defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
215     H2( "      --slices <integer>      Number of slices per frame; forces rectangular\n"
216         "                              slices and is overridden by other slicing options\n" );
217     else H1( "      --slices <integer>      Number of slices per frame\n" );
218     H2( "      --slice-max-size <integer> Limit the size of each slice in bytes\n");
219     H2( "      --slice-max-mbs <integer> Limit the size of each slice in macroblocks\n");
220     H0( "      --interlaced            Enable pure-interlaced mode\n" );
221     H2( "      --constrained-intra     Enable constrained intra prediction.\n" );
222     H0( "\n" );
223     H0( "Ratecontrol:\n" );
224     H0( "\n" );
225     H1( "  -q, --qp <integer>          Force constant QP (0-51, 0=lossless)\n" );
226     H0( "  -B, --bitrate <integer>     Set bitrate (kbit/s)\n" );
227     H0( "      --crf <float>           Quality-based VBR (0-51, 0=lossless) [%.1f]\n", defaults->rc.f_rf_constant );
228     H1( "      --rc-lookahead <integer> Number of frames for frametype lookahead [%d]\n", defaults->rc.i_lookahead );
229     H0( "      --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
230     H0( "      --vbv-bufsize <integer> Set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
231     H2( "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
232     H2( "      --qpmin <integer>       Set min QP [%d]\n", defaults->rc.i_qp_min );
233     H2( "      --qpmax <integer>       Set max QP [%d]\n", defaults->rc.i_qp_max );
234     H2( "      --qpstep <integer>      Set max QP step [%d]\n", defaults->rc.i_qp_step );
235     H2( "      --ratetol <float>       Tolerance of ABR ratecontrol and VBV [%.1f]\n", defaults->rc.f_rate_tolerance );
236     H2( "      --ipratio <float>       QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
237     H2( "      --pbratio <float>       QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
238     H2( "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
239     H2( "      --aq-mode <integer>     AQ method [%d]\n"
240         "                                  - 0: Disabled\n"
241         "                                  - 1: Variance AQ (complexity mask)\n"
242         "                                  - 2: Auto-variance AQ (experimental)\n", defaults->rc.i_aq_mode );
243     H1( "      --aq-strength <float>   Reduces blocking and blurring in flat and\n"
244         "                              textured areas. [%.1f]\n", defaults->rc.f_aq_strength );
245     H1( "\n" );
246     H2( "  -p, --pass <1|2|3>          Enable multipass ratecontrol\n" );
247     else H0( "  -p, --pass <1|2>            Enable multipass ratecontrol\n" );
248     H0( "                                  - 1: First pass, creates stats file\n"
249         "                                  - 2: Last pass, does not overwrite stats file\n" );
250     H2( "                                  - 3: Nth pass, overwrites stats file\n" );
251     H1( "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
252     H2( "      --no-mbtree             Disable mb-tree ratecontrol.\n");
253     H2( "      --qcomp <float>         QP curve compression [%.2f]\n", defaults->rc.f_qcompress );
254     H2( "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
255     H2( "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
256     H2( "      --zones <zone0>/<zone1>/...  Tweak the bitrate of regions of the video\n" );
257     H2( "                              Each zone is of the form\n"
258         "                                  <start frame>,<end frame>,<option>\n"
259         "                                  where <option> is either\n"
260         "                                      q=<integer> (force QP)\n"
261         "                                  or  b=<float> (bitrate multiplier)\n" );
262     H2( "      --qpfile <string>       Force frametypes and QPs for some or all frames\n"
263         "                              Format of each line: framenumber frametype QP\n"
264         "                              QP of -1 lets x264 choose. Frametypes: I,i,P,B,b.\n"
265         "                              QPs are restricted by qpmin/qpmax.\n" );
266     H1( "\n" );
267     H1( "Analysis:\n" );
268     H1( "\n" );
269     H1( "  -A, --partitions <string>   Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
270         "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
271         "                                  - none, all\n"
272         "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
273     H1( "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
274         "                                  - none, spatial, temporal, auto\n",
275                                        strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
276     H2( "      --no-weightb            Disable weighted prediction for B-frames\n" );
277     H1( "      --weightp               Weighted prediction for P-frames [%d]\n"
278         "                              - 0: Disabled\n"
279         "                              - 1: Blind offset\n"
280         "                              - 2: Smart analysis\n", defaults->analyse.i_weighted_pred );
281     H1( "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n",
282                                        strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
283     H2( "                                  - dia: diamond search, radius 1 (fast)\n"
284         "                                  - hex: hexagonal search, radius 2\n"
285         "                                  - umh: uneven multi-hexagon search\n"
286         "                                  - esa: exhaustive search\n"
287         "                                  - tesa: hadamard exhaustive search (slow)\n" );
288     else H1( "                                  - dia, hex, umh\n" );
289     H2( "      --merange <integer>     Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
290     H2( "      --mvrange <integer>     Maximum motion vector length [-1 (auto)]\n" );
291     H2( "      --mvrange-thread <int>  Minimum buffer between threads [-1 (auto)]\n" );
292     H1( "  -m, --subme <integer>       Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
293     H2( "                                  - 0: fullpel only (not recommended)\n"
294         "                                  - 1: SAD mode decision, one qpel iteration\n"
295         "                                  - 2: SATD mode decision\n"
296         "                                  - 3-5: Progressively more qpel\n"
297         "                                  - 6: RD mode decision for I/P-frames\n"
298         "                                  - 7: RD mode decision for all frames\n"
299         "                                  - 8: RD refinement for I/P-frames\n"
300         "                                  - 9: RD refinement for all frames\n"
301         "                                  - 10: QP-RD - requires trellis=2, aq-mode>0\n" );
302     else H1( "                                  decision quality: 1=fast, 10=best.\n"  );
303     H1( "      --psy-rd                Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
304         "                                  #1: RD (requires subme>=6)\n"
305         "                                  #2: Trellis (requires trellis, experimental)\n",
306                                        defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
307     H2( "      --no-psy                Disable all visual optimizations that worsen\n"
308         "                              both PSNR and SSIM.\n" );
309     H2( "      --no-mixed-refs         Don't decide references on a per partition basis\n" );
310     H2( "      --no-chroma-me          Ignore chroma in motion estimation\n" );
311     H1( "      --no-8x8dct             Disable adaptive spatial transform size\n" );
312     H1( "  -t, --trellis <integer>     Trellis RD quantization. Requires CABAC. [%d]\n"
313         "                                  - 0: disabled\n"
314         "                                  - 1: enabled only on the final encode of a MB\n"
315         "                                  - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
316     H2( "      --no-fast-pskip         Disables early SKIP detection on P-frames\n" );
317     H2( "      --no-dct-decimate       Disables coefficient thresholding on P-frames\n" );
318     H1( "      --nr <integer>          Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
319     H2( "\n" );
320     H2( "      --deadzone-inter <int>  Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
321     H2( "      --deadzone-intra <int>  Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
322     H2( "                                  Deadzones should be in the range 0 - 32.\n" );
323     H2( "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
324         "                                  - jvt, flat\n" );
325     H1( "      --cqmfile <string>      Read custom quant matrices from a JM-compatible file\n" );
326     H2( "                                  Overrides any other --cqm* options.\n" );
327     H2( "      --cqm4 <list>           Set all 4x4 quant matrices\n"
328         "                                  Takes a comma-separated list of 16 integers.\n" );
329     H2( "      --cqm8 <list>           Set all 8x8 quant matrices\n"
330         "                                  Takes a comma-separated list of 64 integers.\n" );
331     H2( "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
332         "                              Set both luma and chroma quant matrices\n" );
333     H2( "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
334         "                              Set individual quant matrices\n" );
335     H2( "\n" );
336     H2( "Video Usability Info (Annex E):\n" );
337     H2( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
338     H2( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
339     H2( "\n" );
340     H2( "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
341         "                                  - undef, show, crop\n",
342                                        strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
343     H2( "      --videoformat <string>  Specify video format [\"%s\"]\n"
344         "                                  - component, pal, ntsc, secam, mac, undef\n",
345                                        strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
346     H2( "      --fullrange <string>    Specify full range samples setting [\"%s\"]\n"
347         "                                  - off, on\n",
348                                        strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ) );
349     H2( "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
350         "                                  - undef, bt709, bt470m, bt470bg\n"
351         "                                    smpte170m, smpte240m, film\n",
352                                        strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
353     H2( "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
354         "                                  - undef, bt709, bt470m, bt470bg, linear,\n"
355         "                                    log100, log316, smpte170m, smpte240m\n",
356                                        strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
357     H2( "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
358         "                                  - undef, bt709, fcc, bt470bg\n"
359         "                                    smpte170m, smpte240m, GBR, YCgCo\n",
360                                        strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
361     H2( "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n",
362                                        defaults->vui.i_chroma_loc );
363     H0( "\n" );
364     H0( "Input/Output:\n" );
365     H0( "\n" );
366     H0( "  -o, --output                Specify output file\n" );
367     H1( "      --stdout                Specify stdout format [\"%s\"]\n"
368         "                                  - raw, mkv, flv\n", stdout_format_names[0] );
369     H1( "      --stdin                 Specify stdin format [\"%s\"]\n"
370         "                                  - yuv, y4m\n", stdin_format_names[0] );
371     H0( "      --sar width:height      Specify Sample Aspect Ratio\n" );
372     H0( "      --fps <float|rational>  Specify framerate\n" );
373     H0( "      --seek <integer>        First frame to encode\n" );
374     H0( "      --frames <integer>      Maximum number of frames to encode\n" );
375     H0( "      --level <string>        Specify level (as defined by Annex A)\n" );
376     H1( "\n" );
377     H1( "  -v, --verbose               Print stats for each frame\n" );
378     H1( "      --no-progress           Don't show the progress indicator while encoding\n" );
379     H0( "      --quiet                 Quiet Mode\n" );
380     H1( "      --psnr                  Enable PSNR computation\n" );
381     H1( "      --ssim                  Enable SSIM computation\n" );
382     H1( "      --threads <integer>     Force a specific number of threads\n" );
383     H2( "      --thread-input          Run Avisynth in its own thread\n" );
384     H2( "      --sync-lookahead <integer> Number of buffer frames for threaded lookahead\n" );
385     H2( "      --non-deterministic     Slightly improve quality of SMP, at the cost of repeatability\n" );
386     H2( "      --asm <integer>         Override CPU detection\n" );
387     H2( "      --no-asm                Disable all CPU optimizations\n" );
388     H2( "      --visualize             Show MB types overlayed on the encoded video\n" );
389     H2( "      --dump-yuv <string>     Save reconstructed frames\n" );
390     H2( "      --sps-id <integer>      Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
391     H2( "      --aud                   Use access unit delimiters\n" );
392     H0( "\n" );
393 }
394
395 #define OPT_FRAMES 256
396 #define OPT_SEEK 257
397 #define OPT_QPFILE 258
398 #define OPT_THREAD_INPUT 259
399 #define OPT_QUIET 260
400 #define OPT_NOPROGRESS 261
401 #define OPT_VISUALIZE 262
402 #define OPT_LONGHELP 263
403 #define OPT_PROFILE 264
404 #define OPT_PRESET 265
405 #define OPT_TUNE 266
406 #define OPT_SLOWFIRSTPASS 267
407 #define OPT_FULLHELP 268
408 #define OPT_FPS 269
409 #define OPT_STDOUT_FORMAT 270
410 #define OPT_STDIN_FORMAT 271
411
412 static char short_options[] = "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw";
413 static struct option long_options[] =
414 {
415     { "help",              no_argument, NULL, 'h' },
416     { "longhelp",          no_argument, NULL, OPT_LONGHELP },
417     { "fullhelp",          no_argument, NULL, OPT_FULLHELP },
418     { "version",           no_argument, NULL, 'V' },
419     { "profile",     required_argument, NULL, OPT_PROFILE },
420     { "preset",      required_argument, NULL, OPT_PRESET },
421     { "tune",        required_argument, NULL, OPT_TUNE },
422     { "slow-firstpass",    no_argument, NULL, OPT_SLOWFIRSTPASS },
423     { "bitrate",     required_argument, NULL, 'B' },
424     { "bframes",     required_argument, NULL, 'b' },
425     { "b-adapt",     required_argument, NULL, 0 },
426     { "no-b-adapt",        no_argument, NULL, 0 },
427     { "b-bias",      required_argument, NULL, 0 },
428     { "b-pyramid",   required_argument, NULL, 0 },
429     { "min-keyint",  required_argument, NULL, 'i' },
430     { "keyint",      required_argument, NULL, 'I' },
431     { "scenecut",    required_argument, NULL, 0 },
432     { "no-scenecut",       no_argument, NULL, 0 },
433     { "nf",                no_argument, NULL, 0 },
434     { "no-deblock",        no_argument, NULL, 0 },
435     { "filter",      required_argument, NULL, 0 },
436     { "deblock",     required_argument, NULL, 'f' },
437     { "interlaced",        no_argument, NULL, 0 },
438     { "constrained-intra", no_argument, NULL, 0 },
439     { "cabac",             no_argument, NULL, 0 },
440     { "no-cabac",          no_argument, NULL, 0 },
441     { "qp",          required_argument, NULL, 'q' },
442     { "qpmin",       required_argument, NULL, 0 },
443     { "qpmax",       required_argument, NULL, 0 },
444     { "qpstep",      required_argument, NULL, 0 },
445     { "crf",         required_argument, NULL, 0 },
446     { "rc-lookahead",required_argument, NULL, 0 },
447     { "ref",         required_argument, NULL, 'r' },
448     { "asm",         required_argument, NULL, 0 },
449     { "no-asm",            no_argument, NULL, 0 },
450     { "sar",         required_argument, NULL, 0 },
451     { "fps",         required_argument, NULL, OPT_FPS },
452     { "frames",      required_argument, NULL, OPT_FRAMES },
453     { "seek",        required_argument, NULL, OPT_SEEK },
454     { "output",      required_argument, NULL, 'o' },
455     { "stdout",      required_argument, NULL, OPT_STDOUT_FORMAT },
456     { "stdin",       required_argument, NULL, OPT_STDIN_FORMAT },
457     { "analyse",     required_argument, NULL, 0 },
458     { "partitions",  required_argument, NULL, 'A' },
459     { "direct",      required_argument, NULL, 0 },
460     { "weightb",           no_argument, NULL, 'w' },
461     { "no-weightb",        no_argument, NULL, 0 },
462     { "weightp",     required_argument, NULL, 0 },
463     { "me",          required_argument, NULL, 0 },
464     { "merange",     required_argument, NULL, 0 },
465     { "mvrange",     required_argument, NULL, 0 },
466     { "mvrange-thread", required_argument, NULL, 0 },
467     { "subme",       required_argument, NULL, 'm' },
468     { "psy-rd",      required_argument, NULL, 0 },
469     { "no-psy",            no_argument, NULL, 0 },
470     { "psy",               no_argument, NULL, 0 },
471     { "mixed-refs",        no_argument, NULL, 0 },
472     { "no-mixed-refs",     no_argument, NULL, 0 },
473     { "no-chroma-me",      no_argument, NULL, 0 },
474     { "8x8dct",            no_argument, NULL, 0 },
475     { "no-8x8dct",         no_argument, NULL, 0 },
476     { "trellis",     required_argument, NULL, 't' },
477     { "fast-pskip",        no_argument, NULL, 0 },
478     { "no-fast-pskip",     no_argument, NULL, 0 },
479     { "no-dct-decimate",   no_argument, NULL, 0 },
480     { "aq-strength", required_argument, NULL, 0 },
481     { "aq-mode",     required_argument, NULL, 0 },
482     { "deadzone-inter", required_argument, NULL, '0' },
483     { "deadzone-intra", required_argument, NULL, '0' },
484     { "level",       required_argument, NULL, 0 },
485     { "ratetol",     required_argument, NULL, 0 },
486     { "vbv-maxrate", required_argument, NULL, 0 },
487     { "vbv-bufsize", required_argument, NULL, 0 },
488     { "vbv-init",    required_argument, NULL,  0 },
489     { "ipratio",     required_argument, NULL, 0 },
490     { "pbratio",     required_argument, NULL, 0 },
491     { "chroma-qp-offset", required_argument, NULL, 0 },
492     { "pass",        required_argument, NULL, 'p' },
493     { "stats",       required_argument, NULL, 0 },
494     { "qcomp",       required_argument, NULL, 0 },
495     { "mbtree",            no_argument, NULL, 0 },
496     { "no-mbtree",         no_argument, NULL, 0 },
497     { "qblur",       required_argument, NULL, 0 },
498     { "cplxblur",    required_argument, NULL, 0 },
499     { "zones",       required_argument, NULL, 0 },
500     { "qpfile",      required_argument, NULL, OPT_QPFILE },
501     { "threads",     required_argument, NULL, 0 },
502     { "slice-max-size",    required_argument, NULL, 0 },
503     { "slice-max-mbs",     required_argument, NULL, 0 },
504     { "slices",            required_argument, NULL, 0 },
505     { "thread-input",      no_argument, NULL, OPT_THREAD_INPUT },
506     { "sync-lookahead",    required_argument, NULL, 0 },
507     { "non-deterministic", no_argument, NULL, 0 },
508     { "psnr",              no_argument, NULL, 0 },
509     { "ssim",              no_argument, NULL, 0 },
510     { "quiet",             no_argument, NULL, OPT_QUIET },
511     { "verbose",           no_argument, NULL, 'v' },
512     { "no-progress",       no_argument, NULL, OPT_NOPROGRESS },
513     { "visualize",         no_argument, NULL, OPT_VISUALIZE },
514     { "dump-yuv",    required_argument, NULL, 0 },
515     { "sps-id",      required_argument, NULL, 0 },
516     { "aud",               no_argument, NULL, 0 },
517     { "nr",          required_argument, NULL, 0 },
518     { "cqm",         required_argument, NULL, 0 },
519     { "cqmfile",     required_argument, NULL, 0 },
520     { "cqm4",        required_argument, NULL, 0 },
521     { "cqm4i",       required_argument, NULL, 0 },
522     { "cqm4iy",      required_argument, NULL, 0 },
523     { "cqm4ic",      required_argument, NULL, 0 },
524     { "cqm4p",       required_argument, NULL, 0 },
525     { "cqm4py",      required_argument, NULL, 0 },
526     { "cqm4pc",      required_argument, NULL, 0 },
527     { "cqm8",        required_argument, NULL, 0 },
528     { "cqm8i",       required_argument, NULL, 0 },
529     { "cqm8p",       required_argument, NULL, 0 },
530     { "overscan",    required_argument, NULL, 0 },
531     { "videoformat", required_argument, NULL, 0 },
532     { "fullrange",   required_argument, NULL, 0 },
533     { "colorprim",   required_argument, NULL, 0 },
534     { "transfer",    required_argument, NULL, 0 },
535     { "colormatrix", required_argument, NULL, 0 },
536     { "chromaloc",   required_argument, NULL, 0 },
537     {0, 0, 0, 0}
538 };
539
540 static int select_output( char *filename, const char *pipe_format, x264_param_t *param )
541 {
542     char *ext = filename + strlen( filename ) - 1;
543     while( *ext != '.' && ext > filename )
544         ext--;
545
546     if( !strcasecmp( ext, ".mp4" ) )
547     {
548 #ifdef MP4_OUTPUT
549         output = mp4_output; // FIXME use b_annexb=0
550 #else
551         fprintf( stderr, "x264 [error]: not compiled with MP4 output support\n" );
552         return -1;
553 #endif
554     }
555     else if( !strcasecmp( ext, ".mkv" ) || (!strcmp( filename, "-" ) && !strcasecmp( pipe_format, "mkv" )) )
556         output = mkv_output; // FIXME use b_annexb=0
557     else if( !strcasecmp( ext, ".flv" ) || (!strcmp( filename, "-" ) && !strcasecmp( pipe_format, "flv" )) )
558     {
559         output = flv_output;
560         param->b_annexb = 0;
561     }
562     else
563         output = raw_output;
564     return 0;
565 }
566
567 static int select_input( char *filename, char *resolution, const char *pipe_format, x264_param_t *param )
568 {
569     char *ext = filename + strlen( filename ) - 1;
570     while( ext > filename && *ext != '.' )
571         ext--;
572
573     if( !strcasecmp( ext, ".avi" ) || !strcasecmp( ext, ".avs" ) )
574     {
575 #ifdef AVIS_INPUT
576         input = avis_input;
577 #else
578         fprintf( stderr, "x264 [error]: not compiled with AVIS input support\n" );
579         return -1;
580 #endif
581     }
582     else if( !strcasecmp( ext, ".y4m" ) || (!strcmp( filename, "-" ) && !strcasecmp( pipe_format, "y4m" )) )
583         input = y4m_input;
584     else // yuv
585     {
586         if( !resolution )
587         {
588             /* try to parse the file name */
589             char *p;
590             for( p = filename; *p; p++ )
591                 if( *p >= '0' && *p <= '9' &&
592                     sscanf( p, "%ux%u", &param->i_width, &param->i_height ) == 2 )
593                 {
594                     if( param->i_log_level >= X264_LOG_INFO )
595                         fprintf( stderr, "x264 [info]: %dx%d (given by file name) @ %.2f fps\n", param->i_width,
596                                  param->i_height, (double)param->i_fps_num / param->i_fps_den );
597                     break;
598                 }
599         }
600         else
601         {
602             sscanf( resolution, "%ux%u", &param->i_width, &param->i_height );
603             if( param->i_log_level >= X264_LOG_INFO )
604                 fprintf( stderr, "x264 [info]: %dx%d @ %.2f fps\n", param->i_width, param->i_height,
605                          (double)param->i_fps_num / param->i_fps_den );
606         }
607         if( !param->i_width || !param->i_height )
608         {
609             fprintf( stderr, "x264 [error]: Rawyuv input requires a resolution.\n" );
610             return -1;
611         }
612         input = yuv_input;
613     }
614
615     return 0;
616 }
617
618 /*****************************************************************************
619  * Parse:
620  *****************************************************************************/
621 static int  Parse( int argc, char **argv,
622                    x264_param_t *param, cli_opt_t *opt )
623 {
624     char *input_filename = NULL;
625     const char *stdin_format = stdin_format_names[0];
626     char *output_filename = NULL;
627     const char *stdout_format = stdout_format_names[0];
628     x264_param_t defaults = *param;
629     char *profile = NULL;
630     int b_thread_input = 0;
631     int b_turbo = 1;
632     int b_pass1 = 0;
633     int b_user_ref = 0;
634     int b_user_fps = 0;
635     int i;
636
637     memset( opt, 0, sizeof(cli_opt_t) );
638     opt->b_progress = 1;
639
640     /* Presets are applied before all other options. */
641     for( optind = 0;; )
642     {
643         int c = getopt_long( argc, argv, short_options, long_options, NULL );
644         if( c == -1 )
645             break;
646
647         if( c == OPT_PRESET )
648         {
649             if( !strcasecmp( optarg, "ultrafast" ) )
650             {
651                 param->i_frame_reference = 1;
652                 param->i_scenecut_threshold = 0;
653                 param->b_deblocking_filter = 0;
654                 param->b_cabac = 0;
655                 param->i_bframe = 0;
656                 param->analyse.intra = 0;
657                 param->analyse.inter = 0;
658                 param->analyse.b_transform_8x8 = 0;
659                 param->analyse.i_me_method = X264_ME_DIA;
660                 param->analyse.i_subpel_refine = 0;
661                 param->rc.i_aq_mode = 0;
662                 param->analyse.b_mixed_references = 0;
663                 param->analyse.i_trellis = 0;
664                 param->i_bframe_adaptive = X264_B_ADAPT_NONE;
665                 param->rc.b_mb_tree = 0;
666                 param->analyse.i_weighted_pred = X264_WEIGHTP_NONE;
667             }
668             else if( !strcasecmp( optarg, "veryfast" ) )
669             {
670                 param->analyse.inter = X264_ANALYSE_I8x8|X264_ANALYSE_I4x4;
671                 param->analyse.i_me_method = X264_ME_DIA;
672                 param->analyse.i_subpel_refine = 1;
673                 param->i_frame_reference = 1;
674                 param->analyse.b_mixed_references = 0;
675                 param->analyse.i_trellis = 0;
676                 param->rc.b_mb_tree = 0;
677                 param->analyse.i_weighted_pred = X264_WEIGHTP_NONE;
678             }
679             else if( !strcasecmp( optarg, "faster" ) )
680             {
681                 param->analyse.b_mixed_references = 0;
682                 param->i_frame_reference = 2;
683                 param->analyse.i_subpel_refine = 4;
684                 param->rc.b_mb_tree = 0;
685                 param->analyse.i_weighted_pred = X264_WEIGHTP_BLIND;
686             }
687             else if( !strcasecmp( optarg, "fast" ) )
688             {
689                 param->i_frame_reference = 2;
690                 param->analyse.i_subpel_refine = 6;
691                 param->rc.i_lookahead = 30;
692             }
693             else if( !strcasecmp( optarg, "medium" ) )
694             {
695                 /* Default is medium */
696             }
697             else if( !strcasecmp( optarg, "slow" ) )
698             {
699                 param->analyse.i_me_method = X264_ME_UMH;
700                 param->analyse.i_subpel_refine = 8;
701                 param->i_frame_reference = 5;
702                 param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;
703                 param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
704                 param->rc.i_lookahead = 50;
705             }
706             else if( !strcasecmp( optarg, "slower" ) )
707             {
708                 param->analyse.i_me_method = X264_ME_UMH;
709                 param->analyse.i_subpel_refine = 9;
710                 param->i_frame_reference = 8;
711                 param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;
712                 param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
713                 param->analyse.inter |= X264_ANALYSE_PSUB8x8;
714                 param->analyse.i_trellis = 2;
715                 param->rc.i_lookahead = 60;
716             }
717             else if( !strcasecmp( optarg, "veryslow" ) )
718             {
719                 param->analyse.i_me_method = X264_ME_UMH;
720                 param->analyse.i_subpel_refine = 10;
721                 param->analyse.i_me_range = 24;
722                 param->i_frame_reference = 16;
723                 param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;
724                 param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
725                 param->analyse.inter |= X264_ANALYSE_PSUB8x8;
726                 param->analyse.i_trellis = 2;
727                 param->i_bframe = 8;
728                 param->rc.i_lookahead = 60;
729             }
730             else if( !strcasecmp( optarg, "placebo" ) )
731             {
732                 param->analyse.i_me_method = X264_ME_TESA;
733                 param->analyse.i_subpel_refine = 10;
734                 param->analyse.i_me_range = 24;
735                 param->i_frame_reference = 16;
736                 param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;
737                 param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
738                 param->analyse.inter |= X264_ANALYSE_PSUB8x8;
739                 param->analyse.b_fast_pskip = 0;
740                 param->analyse.i_trellis = 2;
741                 param->i_bframe = 16;
742                 param->rc.i_lookahead = 60;
743                 b_turbo = 0;
744             }
745             else
746             {
747                 fprintf( stderr, "x264 [error]: invalid preset: %s\n", optarg );
748                 return -1;
749             }
750         }
751         else if( c == '?' )
752             return -1;
753     }
754
755     /* Tunings are applied next. */
756     for( optind = 0;; )
757     {
758         int c = getopt_long( argc, argv, short_options, long_options, NULL );
759         if( c == -1 )
760             break;
761
762         if( c == OPT_TUNE )
763         {
764             if( !strcasecmp( optarg, "film" ) )
765             {
766                 param->i_deblocking_filter_alphac0 = -1;
767                 param->i_deblocking_filter_beta = -1;
768                 param->analyse.f_psy_trellis = 0.15;
769             }
770             else if( !strcasecmp( optarg, "animation" ) )
771             {
772                 param->i_frame_reference = param->i_frame_reference > 1 ? param->i_frame_reference*2 : 1;
773                 param->i_deblocking_filter_alphac0 = 1;
774                 param->i_deblocking_filter_beta = 1;
775                 param->analyse.f_psy_rd = 0.4;
776                 param->rc.f_aq_strength = 0.6;
777                 param->i_bframe += 2;
778             }
779             else if( !strcasecmp( optarg, "grain" ) )
780             {
781                 param->i_deblocking_filter_alphac0 = -2;
782                 param->i_deblocking_filter_beta = -2;
783                 param->analyse.f_psy_trellis = 0.25;
784                 param->analyse.b_dct_decimate = 0;
785                 param->rc.f_pb_factor = 1.1;
786                 param->rc.f_ip_factor = 1.1;
787                 param->rc.f_aq_strength = 0.5;
788                 param->analyse.i_luma_deadzone[0] = 6;
789                 param->analyse.i_luma_deadzone[1] = 6;
790                 param->rc.f_qcompress = 0.8;
791             }
792             else if( !strcasecmp( optarg, "psnr" ) )
793             {
794                 param->rc.i_aq_mode = X264_AQ_NONE;
795                 param->analyse.b_psy = 0;
796             }
797             else if( !strcasecmp( optarg, "ssim" ) )
798             {
799                 param->rc.i_aq_mode = X264_AQ_AUTOVARIANCE;
800                 param->analyse.b_psy = 0;
801             }
802             else if( !strcasecmp( optarg, "fastdecode" ) )
803             {
804                 param->b_deblocking_filter = 0;
805                 param->b_cabac = 0;
806                 param->analyse.b_weighted_bipred = 0;
807                 param->analyse.i_weighted_pred = X264_WEIGHTP_NONE;
808             }
809             else if( !strcasecmp( optarg, "touhou" ) )
810             {
811                 param->i_frame_reference = param->i_frame_reference > 1 ? param->i_frame_reference*2 : 1;
812                 param->i_deblocking_filter_alphac0 = -1;
813                 param->i_deblocking_filter_beta = -1;
814                 param->analyse.f_psy_trellis = 0.2;
815                 param->rc.f_aq_strength = 1.3;
816                 if( param->analyse.inter & X264_ANALYSE_PSUB16x16 )
817                     param->analyse.inter |= X264_ANALYSE_PSUB8x8;
818             }
819             else
820             {
821                 fprintf( stderr, "x264 [error]: invalid tune: %s\n", optarg );
822                 return -1;
823             }
824         }
825         else if( c == '?' )
826             return -1;
827     }
828
829     /* Parse command line options */
830     for( optind = 0;; )
831     {
832         int b_error = 0;
833         int long_options_index = -1;
834
835         int c = getopt_long( argc, argv, short_options, long_options, &long_options_index );
836
837         if( c == -1 )
838         {
839             break;
840         }
841
842         switch( c )
843         {
844             case 'h':
845                 Help( &defaults, 0 );
846                 exit(0);
847             case OPT_LONGHELP:
848                 Help( &defaults, 1 );
849                 exit(0);
850             case OPT_FULLHELP:
851                 Help( &defaults, 2 );
852                 exit(0);
853             case 'V':
854 #ifdef X264_POINTVER
855                 printf( "x264 "X264_POINTVER"\n" );
856 #else
857                 printf( "x264 0.%d.X\n", X264_BUILD );
858 #endif
859                 printf( "built on " __DATE__ ", " );
860 #ifdef __GNUC__
861                 printf( "gcc: " __VERSION__ "\n" );
862 #else
863                 printf( "using a non-gcc compiler\n" );
864 #endif
865                 exit(0);
866             case OPT_FRAMES:
867                 param->i_frame_total = atoi( optarg );
868                 break;
869             case OPT_SEEK:
870                 opt->i_seek = atoi( optarg );
871                 break;
872             case 'o':
873                 output_filename = optarg;
874                 break;
875             case OPT_STDOUT_FORMAT:
876                 for( i = 0; stdout_format_names[i] && strcasecmp( stdout_format_names[i], optarg ); )
877                     i++;
878                 if( !stdout_format_names[i] )
879                 {
880                     fprintf( stderr, "x264 [error]: invalid stdout format `%s'\n", optarg );
881                     return -1;
882                 }
883                 stdout_format = optarg;
884                 break;
885             case OPT_STDIN_FORMAT:
886                 for( i = 0; stdin_format_names[i] && strcasecmp( stdin_format_names[i], optarg ); )
887                     i++;
888                 if( !stdin_format_names[i] )
889                 {
890                     fprintf( stderr, "x264 [error]: invalid stdin format `%s'\n", optarg );
891                     return -1;
892                 }
893                 stdin_format = optarg;
894                 break;
895             case OPT_QPFILE:
896                 opt->qpfile = fopen( optarg, "rb" );
897                 if( !opt->qpfile )
898                 {
899                     fprintf( stderr, "x264 [error]: can't open `%s'\n", optarg );
900                     return -1;
901                 }
902                 else if( !x264_is_regular_file( opt->qpfile ) )
903                 {
904                     fprintf( stderr, "x264 [error]: qpfile incompatible with non-regular file `%s'\n", optarg );
905                     fclose( opt->qpfile );
906                     return -1;
907                 }
908                 break;
909             case OPT_THREAD_INPUT:
910                 b_thread_input = 1;
911                 break;
912             case OPT_QUIET:
913                 param->i_log_level = X264_LOG_NONE;
914                 break;
915             case 'v':
916                 param->i_log_level = X264_LOG_DEBUG;
917                 break;
918             case OPT_NOPROGRESS:
919                 opt->b_progress = 0;
920                 break;
921             case OPT_VISUALIZE:
922 #ifdef VISUALIZE
923                 param->b_visualize = 1;
924                 b_exit_on_ctrl_c = 1;
925 #else
926                 fprintf( stderr, "x264 [warning]: not compiled with visualization support\n" );
927 #endif
928                 break;
929             case OPT_TUNE:
930             case OPT_PRESET:
931                 break;
932             case OPT_PROFILE:
933                 profile = optarg;
934                 break;
935             case OPT_SLOWFIRSTPASS:
936                 b_turbo = 0;
937                 break;
938             case 'r':
939                 b_user_ref = 1;
940                 goto generic_option;
941             case 'p':
942                 b_pass1 = atoi( optarg ) == 1;
943                 goto generic_option;
944             case OPT_FPS:
945                 b_user_fps = 1;
946                 goto generic_option;
947             default:
948 generic_option:
949             {
950                 int i;
951                 if( long_options_index < 0 )
952                 {
953                     for( i = 0; long_options[i].name; i++ )
954                         if( long_options[i].val == c )
955                         {
956                             long_options_index = i;
957                             break;
958                         }
959                     if( long_options_index < 0 )
960                     {
961                         /* getopt_long already printed an error message */
962                         return -1;
963                     }
964                 }
965
966                 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
967             }
968         }
969
970         if( b_error )
971         {
972             const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
973             fprintf( stderr, "x264 [error]: invalid argument: %s = %s\n", name, optarg );
974             return -1;
975         }
976     }
977
978     /* Set faster options in case of turbo firstpass. */
979     if( b_turbo && b_pass1 )
980     {
981         param->i_frame_reference = 1;
982         param->analyse.b_transform_8x8 = 0;
983         param->analyse.inter = 0;
984         param->analyse.i_me_method = X264_ME_DIA;
985         param->analyse.i_subpel_refine = X264_MIN( 2, param->analyse.i_subpel_refine );
986         param->analyse.i_trellis = 0;
987     }
988
989     /* Apply profile restrictions. */
990     if( profile )
991     {
992         if( !strcasecmp( profile, "baseline" ) )
993         {
994             param->analyse.b_transform_8x8 = 0;
995             param->b_cabac = 0;
996             param->i_cqm_preset = X264_CQM_FLAT;
997             param->i_bframe = 0;
998             param->analyse.i_weighted_pred = X264_WEIGHTP_NONE;
999             if( param->b_interlaced )
1000             {
1001                 fprintf( stderr, "x264 [error]: baseline profile doesn't support interlacing\n" );
1002                 return -1;
1003             }
1004         }
1005         else if( !strcasecmp( profile, "main" ) )
1006         {
1007             param->analyse.b_transform_8x8 = 0;
1008             param->i_cqm_preset = X264_CQM_FLAT;
1009         }
1010         else if( !strcasecmp( profile, "high" ) )
1011         {
1012             /* Default */
1013         }
1014         else
1015         {
1016             fprintf( stderr, "x264 [error]: invalid profile: %s\n", profile );
1017             return -1;
1018         }
1019         if( (param->rc.i_rc_method == X264_RC_CQP && param->rc.i_qp_constant == 0) ||
1020             (param->rc.i_rc_method == X264_RC_CRF && param->rc.f_rf_constant == 0) )
1021         {
1022             fprintf( stderr, "x264 [error]: %s profile doesn't support lossless\n", profile );
1023             return -1;
1024         }
1025     }
1026
1027     /* Get the file name */
1028     if( optind > argc - 1 || !output_filename )
1029     {
1030         fprintf( stderr, "x264 [error]: No %s file. Run x264 --help for a list of options.\n",
1031                  optind > argc - 1 ? "input" : "output" );
1032         return -1;
1033     }
1034     input_filename = argv[optind++];
1035
1036     if( select_output( output_filename, stdout_format, param ) )
1037         return -1;
1038     if( output.open_file( output_filename, &opt->hout ) )
1039     {
1040         fprintf( stderr, "x264 [error]: could not open output file `%s'\n", output_filename );
1041         return -1;
1042     }
1043
1044     if( select_input( input_filename, optind < argc ? argv[optind++] : NULL, stdin_format, param ) )
1045         return -1;
1046
1047     {
1048         int i_fps_num = param->i_fps_num;
1049         int i_fps_den = param->i_fps_den;
1050
1051         if( input.open_file( input_filename, &opt->hin, param ) )
1052         {
1053             fprintf( stderr, "x264 [error]: could not open input file `%s'\n", input_filename );
1054             return -1;
1055         }
1056         /* Restore the user's frame rate if fps has been explicitly set on the commandline. */
1057         if( b_user_fps )
1058         {
1059             param->i_fps_num = i_fps_num;
1060             param->i_fps_den = i_fps_den;
1061         }
1062     }
1063
1064 #ifdef HAVE_PTHREAD
1065     if( b_thread_input || param->i_threads > 1
1066         || (param->i_threads == X264_THREADS_AUTO && x264_cpu_num_processors() > 1) )
1067     {
1068         if( thread_input.open_file( NULL, &opt->hin, param ) )
1069         {
1070             fprintf( stderr, "x264 [error]: threaded input failed\n" );
1071             return -1;
1072         }
1073         else
1074             input = thread_input;
1075     }
1076 #endif
1077
1078
1079     /* Automatically reduce reference frame count to match the user's target level
1080      * if the user didn't explicitly set a reference frame count. */
1081     if( !b_user_ref )
1082     {
1083         int mbs = (((param->i_width)+15)>>4) * (((param->i_height)+15)>>4);
1084         int i;
1085         for( i = 0; x264_levels[i].level_idc != 0; i++ )
1086             if( param->i_level_idc == x264_levels[i].level_idc )
1087             {
1088                 while( mbs * 384 * param->i_frame_reference > x264_levels[i].dpb
1089                        && param->i_frame_reference > 1 )
1090                 {
1091                     param->i_frame_reference--;
1092                 }
1093                 break;
1094             }
1095     }
1096
1097
1098     return 0;
1099 }
1100
1101 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
1102 {
1103     int num = -1, qp, ret;
1104     char type;
1105     uint64_t file_pos;
1106     while( num < i_frame )
1107     {
1108         file_pos = ftell( opt->qpfile );
1109         ret = fscanf( opt->qpfile, "%d %c %d\n", &num, &type, &qp );
1110         if( num > i_frame || ret == EOF )
1111         {
1112             pic->i_type = X264_TYPE_AUTO;
1113             pic->i_qpplus1 = 0;
1114             fseek( opt->qpfile, file_pos, SEEK_SET );
1115             break;
1116         }
1117         if( num < i_frame && ret == 3 )
1118             continue;
1119         pic->i_qpplus1 = qp+1;
1120         if     ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
1121         else if( type == 'i' ) pic->i_type = X264_TYPE_I;
1122         else if( type == 'P' ) pic->i_type = X264_TYPE_P;
1123         else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
1124         else if( type == 'b' ) pic->i_type = X264_TYPE_B;
1125         else ret = 0;
1126         if( ret != 3 || qp < -1 || qp > 51 )
1127         {
1128             fprintf( stderr, "x264 [error]: can't parse qpfile for frame %d\n", i_frame );
1129             fclose( opt->qpfile );
1130             opt->qpfile = NULL;
1131             pic->i_type = X264_TYPE_AUTO;
1132             pic->i_qpplus1 = 0;
1133             break;
1134         }
1135     }
1136 }
1137
1138 /*****************************************************************************
1139  * Encode:
1140  *****************************************************************************/
1141
1142 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
1143 {
1144     x264_picture_t pic_out;
1145     x264_nal_t *nal;
1146     int i_nal, i, i_nalu_size;
1147     int i_file = 0;
1148
1149     if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
1150     {
1151         fprintf( stderr, "x264 [error]: x264_encoder_encode failed\n" );
1152         return -1;
1153     }
1154
1155     for( i = 0; i < i_nal; i++ )
1156     {
1157         i_nalu_size = output.write_nalu( hout, nal[i].p_payload, nal[i].i_payload, &pic_out );
1158         if( i_nalu_size < 0 )
1159             return -1;
1160         i_file += i_nalu_size;
1161     }
1162     if( i_nal )
1163         output.set_eop( hout, &pic_out );
1164
1165     return i_file;
1166 }
1167
1168 static void Print_status( int64_t i_start, int i_frame, int i_frame_total, int64_t i_file, x264_param_t *param )
1169 {
1170     char    buf[200];
1171     int64_t i_elapsed = x264_mdate() - i_start;
1172     double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1173     double bitrate = (double) i_file * 8 * param->i_fps_num / ( (double) param->i_fps_den * i_frame * 1000 );
1174     if( i_frame_total )
1175     {
1176         int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1177         sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
1178                  100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
1179                  eta/3600, (eta/60)%60, eta%60 );
1180     }
1181     else
1182     {
1183         sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
1184     }
1185     fprintf( stderr, "%s  \r", buf+5 );
1186     SetConsoleTitle( buf );
1187     fflush( stderr ); // needed in windows
1188 }
1189
1190 static int  Encode( x264_param_t *param, cli_opt_t *opt )
1191 {
1192     x264_t *h;
1193     x264_picture_t pic;
1194
1195     int     i_frame, i_frame_total, i_frame_output;
1196     int64_t i_start, i_end;
1197     int64_t i_file;
1198     int     i_frame_size;
1199     int     i_update_interval;
1200
1201     opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
1202     i_frame_total = input.get_frame_total( opt->hin );
1203     i_frame_total = X264_MAX( i_frame_total - opt->i_seek, 0 );
1204     if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
1205         && param->i_frame_total > 0 )
1206         i_frame_total = param->i_frame_total;
1207     param->i_frame_total = i_frame_total;
1208     i_update_interval = i_frame_total ? x264_clip3( i_frame_total / 1000, 1, 10 ) : 10;
1209
1210     if( ( h = x264_encoder_open( param ) ) == NULL )
1211     {
1212         fprintf( stderr, "x264 [error]: x264_encoder_open failed\n" );
1213         input.close_file( opt->hin );
1214         return -1;
1215     }
1216
1217     if( output.set_param( opt->hout, param ) )
1218     {
1219         fprintf( stderr, "x264 [error]: can't set outfile param\n" );
1220         input.close_file( opt->hin );
1221         output.close_file( opt->hout );
1222         return -1;
1223     }
1224
1225     /* Create a new pic */
1226     if( x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height ) < 0 )
1227     {
1228         fprintf( stderr, "x264 [error]: malloc failed\n" );
1229         return -1;
1230     }
1231
1232     i_start = x264_mdate();
1233
1234     /* Encode frames */
1235     for( i_frame = 0, i_file = 0, i_frame_output = 0; b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1236     {
1237         if( input.read_frame( &pic, opt->hin, i_frame + opt->i_seek ) )
1238             break;
1239
1240         pic.i_pts = (int64_t)i_frame * param->i_fps_den;
1241
1242         if( opt->qpfile )
1243             parse_qpfile( opt, &pic, i_frame + opt->i_seek );
1244         else
1245         {
1246             /* Do not force any parameters */
1247             pic.i_type = X264_TYPE_AUTO;
1248             pic.i_qpplus1 = 0;
1249         }
1250
1251         i_frame_size = Encode_frame( h, opt->hout, &pic );
1252         if( i_frame_size < 0 )
1253             return -1;
1254         i_file += i_frame_size;
1255         if( i_frame_size )
1256             i_frame_output++;
1257
1258         i_frame++;
1259
1260         /* update status line (up to 1000 times per input file) */
1261         if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1262             Print_status( i_start, i_frame_output, i_frame_total, i_file, param );
1263     }
1264     /* Flush delayed frames */
1265     while( !b_ctrl_c && x264_encoder_delayed_frames( h ) )
1266     {
1267         i_frame_size = Encode_frame( h, opt->hout, NULL );
1268         if( i_frame_size < 0 )
1269             return -1;
1270         i_file += i_frame_size;
1271         if( i_frame_size )
1272             i_frame_output++;
1273         if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1274             Print_status( i_start, i_frame_output, i_frame_total, i_file, param );
1275     }
1276
1277     i_end = x264_mdate();
1278     x264_picture_clean( &pic );
1279     /* Erase progress indicator before printing encoding stats. */
1280     if( opt->b_progress )
1281         fprintf( stderr, "                                                                               \r" );
1282     x264_encoder_close( h );
1283     x264_free( mux_buffer );
1284     fprintf( stderr, "\n" );
1285
1286     if( b_ctrl_c )
1287         fprintf( stderr, "aborted at input frame %d, output frame %d\n", opt->i_seek + i_frame, i_frame_output );
1288
1289     input.close_file( opt->hin );
1290     output.close_file( opt->hout );
1291
1292     if( i_frame_output > 0 )
1293     {
1294         double fps = (double)i_frame_output * (double)1000000 /
1295                      (double)( i_end - i_start );
1296
1297         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame_output, fps,
1298                  (double) i_file * 8 * param->i_fps_num /
1299                  ( (double) param->i_fps_den * i_frame_output * 1000 ) );
1300     }
1301
1302     return 0;
1303 }