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