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