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