]> git.sesse.net Git - x264/blob - x264.c
Document slow/fast firstpass in --fullhelp
[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  *          Steven Walters <kemuri9@gmail.com>
9  *          Kieran Kunhya <kieran@kunhya.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 #include <stdlib.h>
27 #include <math.h>
28
29 #include <signal.h>
30 #define _GNU_SOURCE
31 #include <getopt.h>
32
33 #include "common/common.h"
34 #include "common/cpu.h"
35 #include "x264.h"
36 #include "muxers.h"
37
38 #ifdef _WIN32
39 #include <windows.h>
40 #else
41 #define SetConsoleTitle(t)
42 #endif
43
44 /* Ctrl-C handler */
45 static int     b_ctrl_c = 0;
46 static int     b_exit_on_ctrl_c = 0;
47 static void    SigIntHandler( int a )
48 {
49     if( b_exit_on_ctrl_c )
50         exit(0);
51     b_ctrl_c = 1;
52 }
53
54 typedef struct {
55     int b_progress;
56     int i_seek;
57     hnd_t hin;
58     hnd_t hout;
59     FILE *qpfile;
60     FILE *tcfile_out;
61     double timebase_convert_multiplier;
62     int i_pulldown;
63 } cli_opt_t;
64
65 /* i/o file operation function pointer structs */
66 cli_input_t input;
67 static cli_output_t output;
68
69 static const char * const demuxer_names[] =
70 {
71     "auto",
72     "yuv",
73     "y4m",
74 #ifdef AVS_INPUT
75     "avs",
76 #endif
77 #ifdef LAVF_INPUT
78     "lavf",
79 #endif
80 #ifdef FFMS_INPUT
81     "ffms",
82 #endif
83     0
84 };
85
86 static const char * const muxer_names[] =
87 {
88     "auto",
89     "raw",
90     "mkv",
91     "flv",
92 #ifdef MP4_OUTPUT
93     "mp4",
94 #endif
95     0
96 };
97
98 static const char * const pulldown_names[] = { "none", "22", "32", "64", "double", "triple", "euro", 0 };
99
100 typedef struct{
101     int mod;
102     uint8_t pattern[24];
103     float fps_factor;
104 } cli_pulldown_t;
105
106 enum pulldown_type_e
107 {
108     X264_PULLDOWN_22 = 1,
109     X264_PULLDOWN_32,
110     X264_PULLDOWN_64,
111     X264_PULLDOWN_DOUBLE,
112     X264_PULLDOWN_TRIPLE,
113     X264_PULLDOWN_EURO
114 };
115
116 #define TB  PIC_STRUCT_TOP_BOTTOM
117 #define BT  PIC_STRUCT_BOTTOM_TOP
118 #define TBT PIC_STRUCT_TOP_BOTTOM_TOP
119 #define BTB PIC_STRUCT_BOTTOM_TOP_BOTTOM
120
121 static const cli_pulldown_t pulldown_values[] =
122 {
123     [X264_PULLDOWN_22]     = {1,  {TB},                                   2.0},
124     [X264_PULLDOWN_32]     = {4,  {TBT, BT, BTB, TB},                     1.25},
125     [X264_PULLDOWN_64]     = {2,  {PIC_STRUCT_DOUBLE, PIC_STRUCT_TRIPLE}, 1.0},
126     [X264_PULLDOWN_DOUBLE] = {1,  {PIC_STRUCT_DOUBLE},                    2.0},
127     [X264_PULLDOWN_TRIPLE] = {1,  {PIC_STRUCT_TRIPLE},                    3.0},
128     [X264_PULLDOWN_EURO]   = {24, {TBT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT,
129                                    BTB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB}, 25.0/24.0}
130 };
131
132 #undef TB
133 #undef BT
134 #undef TBT
135 #undef BTB
136
137 // indexed by pic_struct enum
138 static const float pulldown_frame_duration[10] = { 0.0, 1, 0.5, 0.5, 1, 1, 1.5, 1.5, 2, 3 };
139
140 static void Help( x264_param_t *defaults, int longhelp );
141 static int  Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
142 static int  Encode( x264_param_t *param, cli_opt_t *opt );
143
144 /****************************************************************************
145  * main:
146  ****************************************************************************/
147 int main( int argc, char **argv )
148 {
149     x264_param_t param;
150     cli_opt_t opt;
151     int ret;
152
153 #ifdef PTW32_STATIC_LIB
154     pthread_win32_process_attach_np();
155     pthread_win32_thread_attach_np();
156 #endif
157
158 #ifdef _WIN32
159     _setmode(_fileno(stdin), _O_BINARY);
160     _setmode(_fileno(stdout), _O_BINARY);
161 #endif
162
163     /* Parse command line */
164     if( Parse( argc, argv, &param, &opt ) < 0 )
165         return -1;
166
167     /* Control-C handler */
168     signal( SIGINT, SigIntHandler );
169
170     ret = Encode( &param, &opt );
171
172 #ifdef PTW32_STATIC_LIB
173     pthread_win32_thread_detach_np();
174     pthread_win32_process_detach_np();
175 #endif
176
177     return ret;
178 }
179
180 static char const *strtable_lookup( const char * const table[], int index )
181 {
182     int i = 0; while( table[i] ) i++;
183     return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
184 }
185
186 static char *stringify_names( char *buf, const char * const names[] )
187 {
188     int i = 0;
189     char *p = buf;
190     for( p[0] = 0; names[i]; i++ )
191     {
192         p += sprintf( p, "%s", names[i] );
193         if( names[i+1] )
194             p += sprintf( p, ", " );
195     }
196     return buf;
197 }
198
199 /*****************************************************************************
200  * Help:
201  *****************************************************************************/
202 static void Help( x264_param_t *defaults, int longhelp )
203 {
204     char buf[50];
205 #define H0 printf
206 #define H1 if(longhelp>=1) printf
207 #define H2 if(longhelp==2) printf
208     H0( "x264 core:%d%s\n"
209         "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
210         "\n"
211         "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
212         "  or YUV4MPEG 4:2:0 (*.y4m),\n"
213         "  or Avisynth if compiled with support (%s).\n"
214         "  or libav* formats if compiled with lavf support (%s) or ffms support (%s).\n"
215         "Outfile type is selected by filename:\n"
216         " .264 -> Raw bytestream\n"
217         " .mkv -> Matroska\n"
218         " .flv -> Flash Video\n"
219         " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
220         "\n"
221         "Options:\n"
222         "\n"
223         "  -h, --help                  List basic options\n"
224         "      --longhelp              List more options\n"
225         "      --fullhelp              List all options\n"
226         "\n",
227         X264_BUILD, X264_VERSION,
228 #ifdef AVS_INPUT
229         "yes",
230 #else
231         "no",
232 #endif
233 #ifdef LAVF_INPUT
234         "yes",
235 #else
236         "no",
237 #endif
238 #ifdef FFMS_INPUT
239         "yes",
240 #else
241         "no",
242 #endif
243 #ifdef MP4_OUTPUT
244         "yes"
245 #else
246         "no"
247 #endif
248       );
249     H0( "Example usage:\n" );
250     H0( "\n" );
251     H0( "      Constant quality mode:\n" );
252     H0( "            x264 --crf 24 -o <output> <input>\n" );
253     H0( "\n" );
254     H0( "      Two-pass with a bitrate of 1000kbps:\n" );
255     H0( "            x264 --pass 1 --bitrate 1000 -o <output> <input>\n" );
256     H0( "            x264 --pass 2 --bitrate 1000 -o <output> <input>\n" );
257     H0( "\n" );
258     H0( "      Lossless:\n" );
259     H0( "            x264 --crf 0 -o <output> <input>\n" );
260     H0( "\n" );
261     H0( "      Maximum PSNR at the cost of speed and visual quality:\n" );
262     H0( "            x264 --preset placebo --tune psnr -o <output> <input>\n" );
263     H0( "\n" );
264     H0( "      Constant bitrate at 1000kbps with a 2 second-buffer:\n");
265     H0( "            x264 --vbv-bufsize 2000 --bitrate 1000 -o <output> <input>\n" );
266     H0( "\n" );
267     H0( "Presets:\n" );
268     H0( "\n" );
269     H0( "      --profile               Force the limits of an H.264 profile [high]\n"
270         "                                  Overrides all settings.\n" );
271     H2( "                                  - baseline:\n"
272         "                                    --no-8x8dct --bframes 0 --no-cabac\n"
273         "                                    --cqm flat --weightp 0\n"
274         "                                    No interlaced.\n"
275         "                                    No lossless.\n"
276         "                                  - main:\n"
277         "                                    --no-8x8dct --cqm flat\n"
278         "                                    No lossless.\n"
279         "                                  - high:\n"
280         "                                    No lossless.\n" );
281         else H0( "                                  - baseline,main,high\n" );
282     H0( "      --preset                Use a preset to select encoding settings [medium]\n"
283         "                                  Overridden by user settings.\n" );
284     H2( "                                  - ultrafast:\n"
285         "                                    --no-8x8dct --aq-mode 0 --b-adapt 0\n"
286         "                                    --bframes 0 --no-cabac --no-deblock\n"
287         "                                    --no-mbtree --me dia --no-mixed-refs\n"
288         "                                    --partitions none --ref 1 --scenecut 0\n"
289         "                                    --subme 0 --trellis 0 --no-weightb\n"
290         "                                    --weightp 0\n"
291         "                                  - veryfast:\n"
292         "                                    --no-mbtree --me dia --no-mixed-refs\n"
293         "                                    --partitions i8x8,i4x4 --ref 1\n"
294         "                                    --subme 1 --trellis 0 --weightp 0\n"
295         "                                  - faster:\n"
296         "                                    --no-mbtree --no-mixed-refs --ref 2\n"
297         "                                    --subme 4 --weightp 1\n"
298         "                                  - fast:\n"
299         "                                    --rc-lookahead 30 --ref 2 --subme 6\n"
300         "                                  - medium:\n"
301         "                                    Default settings apply.\n"
302         "                                  - slow:\n"
303         "                                    --b-adapt 2 --direct auto --me umh\n"
304         "                                    --rc-lookahead 50 --ref 5 --subme 8\n"
305         "                                  - slower:\n"
306         "                                    --b-adapt 2 --direct auto --me umh\n"
307         "                                    --partitions all --rc-lookahead 60\n"
308         "                                    --ref 8 --subme 9 --trellis 2\n"
309         "                                  - veryslow:\n"
310         "                                    --b-adapt 2 --bframes 8 --direct auto\n"
311         "                                    --me umh --merange 24 --partitions all\n"
312         "                                    --ref 16 --subme 10 --trellis 2\n"
313         "                                    --rc-lookahead 60\n"
314         "                                  - placebo:\n"
315         "                                    --bframes 16 --b-adapt 2 --direct auto\n"
316         "                                    --slow-firstpass --no-fast-pskip\n"
317         "                                    --me tesa --merange 24 --partitions all\n"
318         "                                    --rc-lookahead 60 --ref 16 --subme 10\n"
319         "                                    --trellis 2\n" );
320     else H0( "                                  - ultrafast,veryfast,faster,fast,medium\n"
321              "                                  - slow,slower,veryslow,placebo\n" );
322     H0( "      --tune                  Tune the settings for a particular type of source\n"
323         "                              or situation\n"
324         "                                  Overridden by user settings.\n"
325         "                                  Multiple tunings are separated by commas.\n"
326         "                                  Only one psy tuning can be used at a time.\n" );
327     H2( "                                  - film (psy tuning):\n"
328         "                                    --deblock -1:-1 --psy-rd <unset>:0.15\n"
329         "                                  - animation (psy tuning):\n"
330         "                                    --bframes {+2} --deblock 1:1\n"
331         "                                    --psy-rd 0.4:<unset> --aq-strength 0.6\n"
332         "                                    --ref {Double if >1 else 1}\n"
333         "                                  - grain (psy tuning):\n"
334         "                                    --aq-strength 0.5 --no-dct-decimate\n"
335         "                                    --deadzone-inter 6 --deadzone-intra 6\n"
336         "                                    --deblock -2:-2 --ipratio 1.1 \n"
337         "                                    --pbratio 1.1 --psy-rd <unset>:0.25\n"
338         "                                    --qcomp 0.8\n"
339         "                                  - psnr (psy tuning):\n"
340         "                                    --aq-mode 0 --no-psy\n"
341         "                                  - ssim (psy tuning):\n"
342         "                                    --aq-mode 2 --no-psy\n"
343         "                                  - fastdecode:\n"
344         "                                    --no-cabac --no-deblock --no-weightb\n"
345         "                                    --weightp 0\n"
346         "                                  - zerolatency:\n"
347         "                                    --bframes 0 --force-cfr --rc-lookahead 0\n"
348         "                                    --sync-lookahead 0 --sliced-threads\n" );
349     else H0( "                                  - psy tunings: film,animation,grain,psnr,ssim\n"
350              "                                  - other tunings: fastdecode,zerolatency\n" );
351     H2( "      --slow-firstpass        Don't force these faster settings with --pass 1:\n"
352         "                                  --no-8x8dct --me dia --partitions none --ref 1\n"
353         "                                  --subme {2 if >2 else unchanged} --trellis 0\n" );
354     else H1( "      --slow-firstpass        Don't force faster settings with --pass 1\n" );
355     H0( "\n" );
356     H0( "Frame-type options:\n" );
357     H0( "\n" );
358     H0( "  -I, --keyint <integer>      Maximum GOP size [%d]\n", defaults->i_keyint_max );
359     H2( "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n", defaults->i_keyint_min );
360     H2( "      --no-scenecut           Disable adaptive I-frame decision\n" );
361     H2( "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
362     H2( "      --intra-refresh         Use Periodic Intra Refresh instead of IDR frames\n" );
363     H1( "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n", defaults->i_bframe );
364     H1( "      --b-adapt <integer>     Adaptive B-frame decision method [%d]\n"
365         "                                  Higher values may lower threading efficiency.\n"
366         "                                  - 0: Disabled\n"
367         "                                  - 1: Fast\n"
368         "                                  - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
369     H2( "      --b-bias <integer>      Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
370     H1( "      --b-pyramid <string>    Keep some B-frames as references [%s]\n"
371         "                                  - none: Disabled\n"
372         "                                  - strict: Strictly hierarchical pyramid\n"
373         "                                  - normal: Non-strict (not Blu-ray compatible)\n",
374         strtable_lookup( x264_b_pyramid_names, defaults->i_bframe_pyramid ) );
375     H1( "      --no-cabac              Disable CABAC\n" );
376     H1( "  -r, --ref <integer>         Number of reference frames [%d]\n", defaults->i_frame_reference );
377     H1( "      --no-deblock            Disable loop filter\n" );
378     H1( "  -f, --deblock <alpha:beta>  Loop filter parameters [%d:%d]\n",
379                                        defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
380     H2( "      --slices <integer>      Number of slices per frame; forces rectangular\n"
381         "                              slices and is overridden by other slicing options\n" );
382     else H1( "      --slices <integer>      Number of slices per frame\n" );
383     H2( "      --slice-max-size <integer> Limit the size of each slice in bytes\n");
384     H2( "      --slice-max-mbs <integer> Limit the size of each slice in macroblocks\n");
385     H0( "      --tff                   Enable interlaced mode (top field first)\n" );
386     H0( "      --bff                   Enable interlaced mode (bottom field first)\n" );
387     H2( "      --constrained-intra     Enable constrained intra prediction.\n" );
388     H0( "\n" );
389     H0( "Ratecontrol:\n" );
390     H0( "\n" );
391     H1( "  -q, --qp <integer>          Force constant QP (0-51, 0=lossless)\n" );
392     H0( "  -B, --bitrate <integer>     Set bitrate (kbit/s)\n" );
393     H0( "      --crf <float>           Quality-based VBR (0-51, 0=lossless) [%.1f]\n", defaults->rc.f_rf_constant );
394     H1( "      --rc-lookahead <integer> Number of frames for frametype lookahead [%d]\n", defaults->rc.i_lookahead );
395     H0( "      --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
396     H0( "      --vbv-bufsize <integer> Set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
397     H2( "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
398     H2( "      --crf-max <float>       With CRF+VBV, limit RF to this value\n"
399         "                                  May cause VBV underflows!\n" );
400     H2( "      --qpmin <integer>       Set min QP [%d]\n", defaults->rc.i_qp_min );
401     H2( "      --qpmax <integer>       Set max QP [%d]\n", defaults->rc.i_qp_max );
402     H2( "      --qpstep <integer>      Set max QP step [%d]\n", defaults->rc.i_qp_step );
403     H2( "      --ratetol <float>       Tolerance of ABR ratecontrol and VBV [%.1f]\n", defaults->rc.f_rate_tolerance );
404     H2( "      --ipratio <float>       QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
405     H2( "      --pbratio <float>       QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
406     H2( "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
407     H2( "      --aq-mode <integer>     AQ method [%d]\n"
408         "                                  - 0: Disabled\n"
409         "                                  - 1: Variance AQ (complexity mask)\n"
410         "                                  - 2: Auto-variance AQ (experimental)\n", defaults->rc.i_aq_mode );
411     H1( "      --aq-strength <float>   Reduces blocking and blurring in flat and\n"
412         "                              textured areas. [%.1f]\n", defaults->rc.f_aq_strength );
413     H1( "\n" );
414     H0( "  -p, --pass <integer>        Enable multipass ratecontrol\n"
415         "                                  - 1: First pass, creates stats file\n"
416         "                                  - 2: Last pass, does not overwrite stats file\n" );
417     H2( "                                  - 3: Nth pass, overwrites stats file\n" );
418     H1( "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
419     H2( "      --no-mbtree             Disable mb-tree ratecontrol.\n");
420     H2( "      --qcomp <float>         QP curve compression [%.2f]\n", defaults->rc.f_qcompress );
421     H2( "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
422     H2( "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
423     H2( "      --zones <zone0>/<zone1>/...  Tweak the bitrate of regions of the video\n" );
424     H2( "                              Each zone is of the form\n"
425         "                                  <start frame>,<end frame>,<option>\n"
426         "                                  where <option> is either\n"
427         "                                      q=<integer> (force QP)\n"
428         "                                  or  b=<float> (bitrate multiplier)\n" );
429     H2( "      --qpfile <string>       Force frametypes and QPs for some or all frames\n"
430         "                              Format of each line: framenumber frametype QP\n"
431         "                              QP of -1 lets x264 choose. Frametypes: I,i,P,B,b.\n"
432         "                              QPs are restricted by qpmin/qpmax.\n" );
433     H1( "\n" );
434     H1( "Analysis:\n" );
435     H1( "\n" );
436     H1( "  -A, --partitions <string>   Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
437         "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
438         "                                  - none, all\n"
439         "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
440     H1( "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
441         "                                  - none, spatial, temporal, auto\n",
442                                        strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
443     H2( "      --no-weightb            Disable weighted prediction for B-frames\n" );
444     H1( "      --weightp <integer>     Weighted prediction for P-frames [%d]\n"
445         "                                  - 0: Disabled\n"
446         "                                  - 1: Blind offset\n"
447         "                                  - 2: Smart analysis\n", defaults->analyse.i_weighted_pred );
448     H1( "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n",
449                                        strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
450     H2( "                                  - dia: diamond search, radius 1 (fast)\n"
451         "                                  - hex: hexagonal search, radius 2\n"
452         "                                  - umh: uneven multi-hexagon search\n"
453         "                                  - esa: exhaustive search\n"
454         "                                  - tesa: hadamard exhaustive search (slow)\n" );
455     else H1( "                                  - dia, hex, umh\n" );
456     H2( "      --merange <integer>     Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
457     H2( "      --mvrange <integer>     Maximum motion vector length [-1 (auto)]\n" );
458     H2( "      --mvrange-thread <int>  Minimum buffer between threads [-1 (auto)]\n" );
459     H1( "  -m, --subme <integer>       Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
460     H2( "                                  - 0: fullpel only (not recommended)\n"
461         "                                  - 1: SAD mode decision, one qpel iteration\n"
462         "                                  - 2: SATD mode decision\n"
463         "                                  - 3-5: Progressively more qpel\n"
464         "                                  - 6: RD mode decision for I/P-frames\n"
465         "                                  - 7: RD mode decision for all frames\n"
466         "                                  - 8: RD refinement for I/P-frames\n"
467         "                                  - 9: RD refinement for all frames\n"
468         "                                  - 10: QP-RD - requires trellis=2, aq-mode>0\n" );
469     else H1( "                                  decision quality: 1=fast, 10=best.\n"  );
470     H1( "      --psy-rd                Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
471         "                                  #1: RD (requires subme>=6)\n"
472         "                                  #2: Trellis (requires trellis, experimental)\n",
473                                        defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
474     H2( "      --no-psy                Disable all visual optimizations that worsen\n"
475         "                              both PSNR and SSIM.\n" );
476     H2( "      --no-mixed-refs         Don't decide references on a per partition basis\n" );
477     H2( "      --no-chroma-me          Ignore chroma in motion estimation\n" );
478     H1( "      --no-8x8dct             Disable adaptive spatial transform size\n" );
479     H1( "  -t, --trellis <integer>     Trellis RD quantization. Requires CABAC. [%d]\n"
480         "                                  - 0: disabled\n"
481         "                                  - 1: enabled only on the final encode of a MB\n"
482         "                                  - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
483     H2( "      --no-fast-pskip         Disables early SKIP detection on P-frames\n" );
484     H2( "      --no-dct-decimate       Disables coefficient thresholding on P-frames\n" );
485     H1( "      --nr <integer>          Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
486     H2( "\n" );
487     H2( "      --deadzone-inter <int>  Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
488     H2( "      --deadzone-intra <int>  Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
489     H2( "                                  Deadzones should be in the range 0 - 32.\n" );
490     H2( "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
491         "                                  - jvt, flat\n" );
492     H1( "      --cqmfile <string>      Read custom quant matrices from a JM-compatible file\n" );
493     H2( "                                  Overrides any other --cqm* options.\n" );
494     H2( "      --cqm4 <list>           Set all 4x4 quant matrices\n"
495         "                                  Takes a comma-separated list of 16 integers.\n" );
496     H2( "      --cqm8 <list>           Set all 8x8 quant matrices\n"
497         "                                  Takes a comma-separated list of 64 integers.\n" );
498     H2( "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
499         "                              Set both luma and chroma quant matrices\n" );
500     H2( "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
501         "                              Set individual quant matrices\n" );
502     H2( "\n" );
503     H2( "Video Usability Info (Annex E):\n" );
504     H2( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
505     H2( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
506     H2( "\n" );
507     H2( "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
508         "                                  - undef, show, crop\n",
509                                        strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
510     H2( "      --videoformat <string>  Specify video format [\"%s\"]\n"
511         "                                  - component, pal, ntsc, secam, mac, undef\n",
512                                        strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
513     H2( "      --fullrange <string>    Specify full range samples setting [\"%s\"]\n"
514         "                                  - off, on\n",
515                                        strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ) );
516     H2( "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
517         "                                  - undef, bt709, bt470m, bt470bg\n"
518         "                                    smpte170m, smpte240m, film\n",
519                                        strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
520     H2( "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
521         "                                  - undef, bt709, bt470m, bt470bg, linear,\n"
522         "                                    log100, log316, smpte170m, smpte240m\n",
523                                        strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
524     H2( "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
525         "                                  - undef, bt709, fcc, bt470bg\n"
526         "                                    smpte170m, smpte240m, GBR, YCgCo\n",
527                                        strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
528     H2( "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n",
529                                        defaults->vui.i_chroma_loc );
530
531     H2( "      --nal-hrd <string>      Signal HRD information (requires vbv-bufsize)\n"
532         "                                  - none, vbr, cbr (cbr not allowed in .mp4)\n" );
533     H2( "      --pic-struct            Force pic_struct in Picture Timing SEI\n" );
534
535     H0( "\n" );
536     H0( "Input/Output:\n" );
537     H0( "\n" );
538     H0( "  -o, --output                Specify output file\n" );
539     H1( "      --muxer <string>        Specify output container format [\"%s\"]\n"
540         "                                  - %s\n", muxer_names[0], stringify_names( buf, muxer_names ) );
541     H1( "      --demuxer <string>      Specify input container format [\"%s\"]\n"
542         "                                  - %s\n", demuxer_names[0], stringify_names( buf, demuxer_names ) );
543     H1( "      --index <string>        Filename for input index file\n" );
544     H0( "      --sar width:height      Specify Sample Aspect Ratio\n" );
545     H0( "      --fps <float|rational>  Specify framerate\n" );
546     H0( "      --seek <integer>        First frame to encode\n" );
547     H0( "      --frames <integer>      Maximum number of frames to encode\n" );
548     H0( "      --level <string>        Specify level (as defined by Annex A)\n" );
549     H1( "\n" );
550     H1( "  -v, --verbose               Print stats for each frame\n" );
551     H1( "      --no-progress           Don't show the progress indicator while encoding\n" );
552     H0( "      --quiet                 Quiet Mode\n" );
553     H1( "      --psnr                  Enable PSNR computation\n" );
554     H1( "      --ssim                  Enable SSIM computation\n" );
555     H1( "      --threads <integer>     Force a specific number of threads\n" );
556     H2( "      --sliced-threads        Low-latency but lower-efficiency threading\n" );
557     H2( "      --thread-input          Run Avisynth in its own thread\n" );
558     H2( "      --sync-lookahead <integer> Number of buffer frames for threaded lookahead\n" );
559     H2( "      --non-deterministic     Slightly improve quality of SMP, at the cost of repeatability\n" );
560     H2( "      --asm <integer>         Override CPU detection\n" );
561     H2( "      --no-asm                Disable all CPU optimizations\n" );
562     H2( "      --visualize             Show MB types overlayed on the encoded video\n" );
563     H2( "      --dump-yuv <string>     Save reconstructed frames\n" );
564     H2( "      --sps-id <integer>      Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
565     H2( "      --aud                   Use access unit delimiters\n" );
566     H2( "      --force-cfr             Force constant framerate timestamp generation\n" );
567     H2( "      --tcfile-in <string>    Force timestamp generation with timecode file\n" );
568     H2( "      --tcfile-out <string>   Output timecode v2 file from input timestamps\n" );
569     H2( "      --timebase <int/int>    Specify timebase numerator and denominator\n"
570         "                 <integer>    Specify timebase numerator for input timecode file\n"
571         "                              or specify timebase denominator for other input\n" );
572     H0( "      --pulldown <string>     Use soft pulldown to change frame rate\n"
573         "                                  - none, 22, 32, 64, double, triple, euro (requires cfr input)\n" );
574     H0( "\n" );
575 }
576
577 #define OPT_FRAMES 256
578 #define OPT_SEEK 257
579 #define OPT_QPFILE 258
580 #define OPT_THREAD_INPUT 259
581 #define OPT_QUIET 260
582 #define OPT_NOPROGRESS 261
583 #define OPT_VISUALIZE 262
584 #define OPT_LONGHELP 263
585 #define OPT_PROFILE 264
586 #define OPT_PRESET 265
587 #define OPT_TUNE 266
588 #define OPT_SLOWFIRSTPASS 267
589 #define OPT_FULLHELP 268
590 #define OPT_FPS 269
591 #define OPT_MUXER 270
592 #define OPT_DEMUXER 271
593 #define OPT_INDEX 272
594 #define OPT_INTERLACED 273
595 #define OPT_TCFILE_IN 274
596 #define OPT_TCFILE_OUT 275
597 #define OPT_TIMEBASE 276
598 #define OPT_PULLDOWN 277
599
600 static char short_options[] = "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw";
601 static struct option long_options[] =
602 {
603     { "help",              no_argument, NULL, 'h' },
604     { "longhelp",          no_argument, NULL, OPT_LONGHELP },
605     { "fullhelp",          no_argument, NULL, OPT_FULLHELP },
606     { "version",           no_argument, NULL, 'V' },
607     { "profile",     required_argument, NULL, OPT_PROFILE },
608     { "preset",      required_argument, NULL, OPT_PRESET },
609     { "tune",        required_argument, NULL, OPT_TUNE },
610     { "slow-firstpass",    no_argument, NULL, OPT_SLOWFIRSTPASS },
611     { "bitrate",     required_argument, NULL, 'B' },
612     { "bframes",     required_argument, NULL, 'b' },
613     { "b-adapt",     required_argument, NULL, 0 },
614     { "no-b-adapt",        no_argument, NULL, 0 },
615     { "b-bias",      required_argument, NULL, 0 },
616     { "b-pyramid",   required_argument, NULL, 0 },
617     { "min-keyint",  required_argument, NULL, 'i' },
618     { "keyint",      required_argument, NULL, 'I' },
619     { "intra-refresh",     no_argument, NULL, 0 },
620     { "scenecut",    required_argument, NULL, 0 },
621     { "no-scenecut",       no_argument, NULL, 0 },
622     { "nf",                no_argument, NULL, 0 },
623     { "no-deblock",        no_argument, NULL, 0 },
624     { "filter",      required_argument, NULL, 0 },
625     { "deblock",     required_argument, NULL, 'f' },
626     { "interlaced",        no_argument, NULL, OPT_INTERLACED },
627     { "tff",               no_argument, NULL, OPT_INTERLACED },
628     { "bff",               no_argument, NULL, OPT_INTERLACED },
629     { "no-interlaced",     no_argument, NULL, OPT_INTERLACED },
630     { "constrained-intra", no_argument, NULL, 0 },
631     { "cabac",             no_argument, NULL, 0 },
632     { "no-cabac",          no_argument, NULL, 0 },
633     { "qp",          required_argument, NULL, 'q' },
634     { "qpmin",       required_argument, NULL, 0 },
635     { "qpmax",       required_argument, NULL, 0 },
636     { "qpstep",      required_argument, NULL, 0 },
637     { "crf",         required_argument, NULL, 0 },
638     { "rc-lookahead",required_argument, NULL, 0 },
639     { "ref",         required_argument, NULL, 'r' },
640     { "asm",         required_argument, NULL, 0 },
641     { "no-asm",            no_argument, NULL, 0 },
642     { "sar",         required_argument, NULL, 0 },
643     { "fps",         required_argument, NULL, OPT_FPS },
644     { "frames",      required_argument, NULL, OPT_FRAMES },
645     { "seek",        required_argument, NULL, OPT_SEEK },
646     { "output",      required_argument, NULL, 'o' },
647     { "muxer",       required_argument, NULL, OPT_MUXER },
648     { "demuxer",     required_argument, NULL, OPT_DEMUXER },
649     { "stdout",      required_argument, NULL, OPT_MUXER },
650     { "stdin",       required_argument, NULL, OPT_DEMUXER },
651     { "index",       required_argument, NULL, OPT_INDEX },
652     { "analyse",     required_argument, NULL, 0 },
653     { "partitions",  required_argument, NULL, 'A' },
654     { "direct",      required_argument, NULL, 0 },
655     { "weightb",           no_argument, NULL, 'w' },
656     { "no-weightb",        no_argument, NULL, 0 },
657     { "weightp",     required_argument, NULL, 0 },
658     { "me",          required_argument, NULL, 0 },
659     { "merange",     required_argument, NULL, 0 },
660     { "mvrange",     required_argument, NULL, 0 },
661     { "mvrange-thread", required_argument, NULL, 0 },
662     { "subme",       required_argument, NULL, 'm' },
663     { "psy-rd",      required_argument, NULL, 0 },
664     { "no-psy",            no_argument, NULL, 0 },
665     { "psy",               no_argument, NULL, 0 },
666     { "mixed-refs",        no_argument, NULL, 0 },
667     { "no-mixed-refs",     no_argument, NULL, 0 },
668     { "no-chroma-me",      no_argument, NULL, 0 },
669     { "8x8dct",            no_argument, NULL, 0 },
670     { "no-8x8dct",         no_argument, NULL, 0 },
671     { "trellis",     required_argument, NULL, 't' },
672     { "fast-pskip",        no_argument, NULL, 0 },
673     { "no-fast-pskip",     no_argument, NULL, 0 },
674     { "no-dct-decimate",   no_argument, NULL, 0 },
675     { "aq-strength", required_argument, NULL, 0 },
676     { "aq-mode",     required_argument, NULL, 0 },
677     { "deadzone-inter", required_argument, NULL, '0' },
678     { "deadzone-intra", required_argument, NULL, '0' },
679     { "level",       required_argument, NULL, 0 },
680     { "ratetol",     required_argument, NULL, 0 },
681     { "vbv-maxrate", required_argument, NULL, 0 },
682     { "vbv-bufsize", required_argument, NULL, 0 },
683     { "vbv-init",    required_argument, NULL, 0 },
684     { "crf-max",     required_argument, NULL, 0 },
685     { "ipratio",     required_argument, NULL, 0 },
686     { "pbratio",     required_argument, NULL, 0 },
687     { "chroma-qp-offset", required_argument, NULL, 0 },
688     { "pass",        required_argument, NULL, 'p' },
689     { "stats",       required_argument, NULL, 0 },
690     { "qcomp",       required_argument, NULL, 0 },
691     { "mbtree",            no_argument, NULL, 0 },
692     { "no-mbtree",         no_argument, NULL, 0 },
693     { "qblur",       required_argument, NULL, 0 },
694     { "cplxblur",    required_argument, NULL, 0 },
695     { "zones",       required_argument, NULL, 0 },
696     { "qpfile",      required_argument, NULL, OPT_QPFILE },
697     { "threads",     required_argument, NULL, 0 },
698     { "sliced-threads",    no_argument, NULL, 0 },
699     { "no-sliced-threads", no_argument, NULL, 0 },
700     { "slice-max-size",    required_argument, NULL, 0 },
701     { "slice-max-mbs",     required_argument, NULL, 0 },
702     { "slices",            required_argument, NULL, 0 },
703     { "thread-input",      no_argument, NULL, OPT_THREAD_INPUT },
704     { "sync-lookahead",    required_argument, NULL, 0 },
705     { "non-deterministic", no_argument, NULL, 0 },
706     { "psnr",              no_argument, NULL, 0 },
707     { "ssim",              no_argument, NULL, 0 },
708     { "quiet",             no_argument, NULL, OPT_QUIET },
709     { "verbose",           no_argument, NULL, 'v' },
710     { "no-progress",       no_argument, NULL, OPT_NOPROGRESS },
711     { "visualize",         no_argument, NULL, OPT_VISUALIZE },
712     { "dump-yuv",    required_argument, NULL, 0 },
713     { "sps-id",      required_argument, NULL, 0 },
714     { "aud",               no_argument, NULL, 0 },
715     { "nr",          required_argument, NULL, 0 },
716     { "cqm",         required_argument, NULL, 0 },
717     { "cqmfile",     required_argument, NULL, 0 },
718     { "cqm4",        required_argument, NULL, 0 },
719     { "cqm4i",       required_argument, NULL, 0 },
720     { "cqm4iy",      required_argument, NULL, 0 },
721     { "cqm4ic",      required_argument, NULL, 0 },
722     { "cqm4p",       required_argument, NULL, 0 },
723     { "cqm4py",      required_argument, NULL, 0 },
724     { "cqm4pc",      required_argument, NULL, 0 },
725     { "cqm8",        required_argument, NULL, 0 },
726     { "cqm8i",       required_argument, NULL, 0 },
727     { "cqm8p",       required_argument, NULL, 0 },
728     { "overscan",    required_argument, NULL, 0 },
729     { "videoformat", required_argument, NULL, 0 },
730     { "fullrange",   required_argument, NULL, 0 },
731     { "colorprim",   required_argument, NULL, 0 },
732     { "transfer",    required_argument, NULL, 0 },
733     { "colormatrix", required_argument, NULL, 0 },
734     { "chromaloc",   required_argument, NULL, 0 },
735     { "force-cfr",         no_argument, NULL, 0 },
736     { "tcfile-in",   required_argument, NULL, OPT_TCFILE_IN },
737     { "tcfile-out",  required_argument, NULL, OPT_TCFILE_OUT },
738     { "timebase",    required_argument, NULL, OPT_TIMEBASE },
739     { "pic-struct",        no_argument, NULL, 0 },
740     { "nal-hrd",     required_argument, NULL, 0 },
741     { "pulldown",    required_argument, NULL, OPT_PULLDOWN },
742     {0, 0, 0, 0}
743 };
744
745 static int select_output( const char *muxer, char *filename, x264_param_t *param )
746 {
747     const char *ext = get_filename_extension( filename );
748     if( !strcmp( filename, "-" ) || strcasecmp( muxer, "auto" ) )
749         ext = muxer;
750
751     if( !strcasecmp( ext, "mp4" ) )
752     {
753 #ifdef MP4_OUTPUT
754         output = mp4_output;
755         param->b_annexb = 0;
756         param->b_dts_compress = 0;
757         param->b_repeat_headers = 0;
758         if( param->i_nal_hrd == X264_NAL_HRD_CBR )
759         {
760             fprintf( stderr, "x264 [warning]: cbr nal-hrd is not compatible with mp4\n" );
761             param->i_nal_hrd = X264_NAL_HRD_VBR;
762         }
763 #else
764         fprintf( stderr, "x264 [error]: not compiled with MP4 output support\n" );
765         return -1;
766 #endif
767     }
768     else if( !strcasecmp( ext, "mkv" ) )
769     {
770         output = mkv_output;
771         param->b_annexb = 0;
772         param->b_dts_compress = 0;
773         param->b_repeat_headers = 0;
774     }
775     else if( !strcasecmp( ext, "flv" ) )
776     {
777         output = flv_output;
778         param->b_annexb = 0;
779         param->b_dts_compress = 1;
780         param->b_repeat_headers = 0;
781     }
782     else
783         output = raw_output;
784     return 0;
785 }
786
787 static int select_input( const char *demuxer, char *used_demuxer, char *filename,
788                          hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
789 {
790     const char *ext = get_filename_extension( filename );
791     int b_regular = strcmp( filename, "-" );
792     int b_auto = !strcasecmp( demuxer, "auto" );
793     if( !b_regular && b_auto )
794         ext = "yuv";
795     if( b_regular )
796     {
797         FILE *f = fopen( filename, "r" );
798         if( f )
799         {
800             b_regular = x264_is_regular_file( f );
801             fclose( f );
802         }
803     }
804     const char *module = b_auto ? ext : demuxer;
805
806     if( !strcasecmp( module, "avs" ) || !strcasecmp( ext, "d2v" ) || !strcasecmp( ext, "dga" ) )
807     {
808 #ifdef AVS_INPUT
809         input = avs_input;
810         module = "avs";
811 #else
812         fprintf( stderr, "x264 [error]: not compiled with AVS input support\n" );
813         return -1;
814 #endif
815     }
816     else if( !strcasecmp( module, "y4m" ) )
817         input = y4m_input;
818     else if( !strcasecmp( module, "yuv" ) )
819         input = yuv_input;
820     else
821     {
822 #ifdef FFMS_INPUT
823         if( b_regular && (b_auto || !strcasecmp( demuxer, "ffms" )) &&
824             !ffms_input.open_file( filename, p_handle, info, opt ) )
825         {
826             module = "ffms";
827             b_auto = 0;
828             input = ffms_input;
829         }
830 #endif
831 #ifdef LAVF_INPUT
832         if( (b_auto || !strcasecmp( demuxer, "lavf" )) &&
833             !lavf_input.open_file( filename, p_handle, info, opt ) )
834         {
835             module = "lavf";
836             b_auto = 0;
837             input = lavf_input;
838         }
839 #endif
840 #ifdef AVS_INPUT
841         if( b_regular && (b_auto || !strcasecmp( demuxer, "avs" )) &&
842             !avs_input.open_file( filename, p_handle, info, opt ) )
843         {
844             module = "avs";
845             b_auto = 0;
846             input = avs_input;
847         }
848 #endif
849         if( b_auto && !yuv_input.open_file( filename, p_handle, info, opt ) )
850         {
851             module = "yuv";
852             b_auto = 0;
853             input = yuv_input;
854         }
855
856         if( !(*p_handle) )
857         {
858             fprintf( stderr, "x264 [error]: could not open input file `%s' via any method!\n", filename );
859             return -1;
860         }
861     }
862     strcpy( used_demuxer, module );
863
864     return 0;
865 }
866
867 /*****************************************************************************
868  * Parse:
869  *****************************************************************************/
870 static int Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt )
871 {
872     char *input_filename = NULL;
873     const char *demuxer = demuxer_names[0];
874     char *output_filename = NULL;
875     const char *muxer = muxer_names[0];
876     char *tcfile_name = NULL;
877     x264_param_t defaults;
878     char *profile = NULL;
879     int b_thread_input = 0;
880     int b_turbo = 1;
881     int b_user_ref = 0;
882     int b_user_fps = 0;
883     int b_user_interlaced = 0;
884     int i;
885     cli_input_opt_t input_opt;
886     char *preset = NULL;
887     char *tune = NULL;
888
889     x264_param_default( &defaults );
890
891     memset( opt, 0, sizeof(cli_opt_t) );
892     memset( &input_opt, 0, sizeof(cli_input_opt_t) );
893     opt->b_progress = 1;
894
895     /* Presets are applied before all other options. */
896     for( optind = 0;; )
897     {
898         int c = getopt_long( argc, argv, short_options, long_options, NULL );
899         if( c == -1 )
900             break;
901         if( c == OPT_PRESET )
902             preset = optarg;
903         if( c == OPT_TUNE )
904             tune = optarg;
905         else if( c == '?' )
906             return -1;
907     }
908
909     if( preset && !strcasecmp( preset, "placebo" ) )
910         b_turbo = 0;
911
912     if( x264_param_default_preset( param, preset, tune ) < 0 )
913         return -1;
914
915     /* Parse command line options */
916     for( optind = 0;; )
917     {
918         int b_error = 0;
919         int long_options_index = -1;
920
921         int c = getopt_long( argc, argv, short_options, long_options, &long_options_index );
922
923         if( c == -1 )
924         {
925             break;
926         }
927
928         switch( c )
929         {
930             case 'h':
931                 Help( &defaults, 0 );
932                 exit(0);
933             case OPT_LONGHELP:
934                 Help( &defaults, 1 );
935                 exit(0);
936             case OPT_FULLHELP:
937                 Help( &defaults, 2 );
938                 exit(0);
939             case 'V':
940 #ifdef X264_POINTVER
941                 printf( "x264 "X264_POINTVER"\n" );
942 #else
943                 printf( "x264 0.%d.X\n", X264_BUILD );
944 #endif
945                 printf( "built on " __DATE__ ", " );
946 #ifdef __GNUC__
947                 printf( "gcc: " __VERSION__ "\n" );
948 #else
949                 printf( "using a non-gcc compiler\n" );
950 #endif
951                 exit(0);
952             case OPT_FRAMES:
953                 param->i_frame_total = X264_MAX( atoi( optarg ), 0 );
954                 break;
955             case OPT_SEEK:
956                 opt->i_seek = input_opt.seek = X264_MAX( atoi( optarg ), 0 );
957                 break;
958             case 'o':
959                 output_filename = optarg;
960                 break;
961             case OPT_MUXER:
962                 for( i = 0; muxer_names[i] && strcasecmp( muxer_names[i], optarg ); )
963                     i++;
964                 if( !muxer_names[i] )
965                 {
966                     fprintf( stderr, "x264 [error]: invalid muxer '%s'\n", optarg );
967                     return -1;
968                 }
969                 muxer = optarg;
970                 break;
971             case OPT_DEMUXER:
972                 for( i = 0; demuxer_names[i] && strcasecmp( demuxer_names[i], optarg ); )
973                     i++;
974                 if( !demuxer_names[i] )
975                 {
976                     fprintf( stderr, "x264 [error]: invalid demuxer '%s'\n", optarg );
977                     return -1;
978                 }
979                 demuxer = optarg;
980                 break;
981             case OPT_INDEX:
982                 input_opt.index = optarg;
983                 break;
984             case OPT_QPFILE:
985                 opt->qpfile = fopen( optarg, "rb" );
986                 if( !opt->qpfile )
987                 {
988                     fprintf( stderr, "x264 [error]: can't open qpfile `%s'\n", optarg );
989                     return -1;
990                 }
991                 else if( !x264_is_regular_file( opt->qpfile ) )
992                 {
993                     fprintf( stderr, "x264 [error]: qpfile incompatible with non-regular file `%s'\n", optarg );
994                     fclose( opt->qpfile );
995                     return -1;
996                 }
997                 break;
998             case OPT_THREAD_INPUT:
999                 b_thread_input = 1;
1000                 break;
1001             case OPT_QUIET:
1002                 param->i_log_level = X264_LOG_NONE;
1003                 break;
1004             case 'v':
1005                 param->i_log_level = X264_LOG_DEBUG;
1006                 break;
1007             case OPT_NOPROGRESS:
1008                 opt->b_progress = 0;
1009                 break;
1010             case OPT_VISUALIZE:
1011 #ifdef VISUALIZE
1012                 param->b_visualize = 1;
1013                 b_exit_on_ctrl_c = 1;
1014 #else
1015                 fprintf( stderr, "x264 [warning]: not compiled with visualization support\n" );
1016 #endif
1017                 break;
1018             case OPT_TUNE:
1019             case OPT_PRESET:
1020                 break;
1021             case OPT_PROFILE:
1022                 profile = optarg;
1023                 break;
1024             case OPT_SLOWFIRSTPASS:
1025                 b_turbo = 0;
1026                 break;
1027             case 'r':
1028                 b_user_ref = 1;
1029                 goto generic_option;
1030             case OPT_FPS:
1031                 b_user_fps = 1;
1032                 param->b_vfr_input = 0;
1033                 goto generic_option;
1034             case OPT_INTERLACED:
1035                 b_user_interlaced = 1;
1036                 goto generic_option;
1037             case OPT_TCFILE_IN:
1038                 tcfile_name = optarg;
1039                 break;
1040             case OPT_TCFILE_OUT:
1041                 opt->tcfile_out = fopen( optarg, "wb" );
1042                 if( !opt->tcfile_out )
1043                 {
1044                     fprintf( stderr, "x264 [error]: can't open `%s'\n", optarg );
1045                     return -1;
1046                 }
1047                 break;
1048             case OPT_TIMEBASE:
1049                 input_opt.timebase = optarg;
1050                 break;
1051             case OPT_PULLDOWN:
1052                 for( i = 0; pulldown_names[i] && strcasecmp( pulldown_names[i], optarg ); )
1053                     i++;
1054                 if( !pulldown_names[i] )
1055                 {
1056                     fprintf( stderr, "x264 [error]: invalid pulldown '%s'\n", optarg );
1057                     return -1;
1058                 }
1059                 opt->i_pulldown = i;
1060                 break;
1061             default:
1062 generic_option:
1063             {
1064                 int i;
1065                 if( long_options_index < 0 )
1066                 {
1067                     for( i = 0; long_options[i].name; i++ )
1068                         if( long_options[i].val == c )
1069                         {
1070                             long_options_index = i;
1071                             break;
1072                         }
1073                     if( long_options_index < 0 )
1074                     {
1075                         /* getopt_long already printed an error message */
1076                         return -1;
1077                     }
1078                 }
1079
1080                 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
1081             }
1082         }
1083
1084         if( b_error )
1085         {
1086             const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
1087             fprintf( stderr, "x264 [error]: invalid argument: %s = %s\n", name, optarg );
1088             return -1;
1089         }
1090     }
1091
1092     /* If first pass mode is used, apply faster settings. */
1093     if( b_turbo )
1094         x264_param_apply_fastfirstpass( param );
1095
1096     /* Apply profile restrictions. */
1097     if( x264_param_apply_profile( param, profile ) < 0 )
1098         return -1;
1099
1100     /* Get the file name */
1101     if( optind > argc - 1 || !output_filename )
1102     {
1103         fprintf( stderr, "x264 [error]: No %s file. Run x264 --help for a list of options.\n",
1104                  optind > argc - 1 ? "input" : "output" );
1105         return -1;
1106     }
1107
1108     if( select_output( muxer, output_filename, param ) )
1109         return -1;
1110     if( output.open_file( output_filename, &opt->hout ) )
1111     {
1112         fprintf( stderr, "x264 [error]: could not open output file `%s'\n", output_filename );
1113         return -1;
1114     }
1115
1116     input_filename = argv[optind++];
1117     input_opt.resolution = optind < argc ? argv[optind++] : NULL;
1118     video_info_t info = {0};
1119     char demuxername[5];
1120
1121     /* set info flags to param flags to be overwritten by demuxer as necessary. */
1122     info.csp        = param->i_csp;
1123     info.fps_num    = param->i_fps_num;
1124     info.fps_den    = param->i_fps_den;
1125     info.interlaced = param->b_interlaced;
1126     info.sar_width  = param->vui.i_sar_width;
1127     info.sar_height = param->vui.i_sar_height;
1128     info.vfr        = param->b_vfr_input;
1129
1130     if( select_input( demuxer, demuxername, input_filename, &opt->hin, &info, &input_opt ) )
1131         return -1;
1132
1133     if( !opt->hin && input.open_file( input_filename, &opt->hin, &info, &input_opt ) )
1134     {
1135         fprintf( stderr, "x264 [error]: could not open input file `%s'\n", input_filename );
1136         return -1;
1137     }
1138
1139     x264_reduce_fraction( &info.sar_width, &info.sar_height );
1140     x264_reduce_fraction( &info.fps_num, &info.fps_den );
1141     if( param->i_log_level >= X264_LOG_INFO )
1142         fprintf( stderr, "%s [info]: %dx%d%c %d:%d @ %d/%d fps (%cfr)\n", demuxername, info.width,
1143                  info.height, info.interlaced ? 'i' : 'p', info.sar_width, info.sar_height,
1144                  info.fps_num, info.fps_den, info.vfr ? 'v' : 'c' );
1145
1146     if( tcfile_name )
1147     {
1148         if( b_user_fps )
1149         {
1150             fprintf( stderr, "x264 [error]: --fps + --tcfile-in is incompatible.\n" );
1151             return -1;
1152         }
1153         if( timecode_input.open_file( tcfile_name, &opt->hin, &info, &input_opt ) )
1154         {
1155             fprintf( stderr, "x264 [error]: timecode input failed\n" );
1156             return -1;
1157         }
1158         else
1159             input = timecode_input;
1160     }
1161     else if( !info.vfr && input_opt.timebase )
1162     {
1163         fprintf( stderr, "x264 [error]: --timebase is incompatible with cfr input\n" );
1164         return -1;
1165     }
1166
1167     /* set param flags from the info flags as necessary */
1168     param->i_csp       = info.csp;
1169     param->i_height    = info.height;
1170     param->b_vfr_input = info.vfr;
1171     param->i_width     = info.width;
1172     if( !b_user_interlaced && info.interlaced )
1173     {
1174         fprintf( stderr, "x264 [warning]: input appears to be interlaced, enabling interlaced mode.\n"
1175                          "                If you want otherwise, use --no-interlaced\n" );
1176         param->b_interlaced = 1;
1177     }
1178     if( !b_user_fps )
1179     {
1180         param->i_fps_num = info.fps_num;
1181         param->i_fps_den = info.fps_den;
1182     }
1183     if( param->b_vfr_input )
1184     {
1185         param->i_timebase_num = info.timebase_num;
1186         param->i_timebase_den = info.timebase_den;
1187     }
1188     else
1189     {
1190         param->i_timebase_num = param->i_fps_den;
1191         param->i_timebase_den = param->i_fps_num;
1192     }
1193     if( !tcfile_name && input_opt.timebase )
1194     {
1195         int i_user_timebase_num;
1196         int i_user_timebase_den;
1197         int ret = sscanf( input_opt.timebase, "%d/%d", &i_user_timebase_num, &i_user_timebase_den );
1198         if( !ret )
1199         {
1200             fprintf( stderr, "x264 [error]: invalid argument: timebase = %s\n", input_opt.timebase );
1201             return -1;
1202         }
1203         else if( ret == 1 )
1204         {
1205             i_user_timebase_num = param->i_timebase_num;
1206             i_user_timebase_den = atoi( input_opt.timebase );
1207         }
1208         opt->timebase_convert_multiplier = ((double)i_user_timebase_den / param->i_timebase_den)
1209                                          * ((double)param->i_timebase_num / i_user_timebase_num);
1210         if( opt->timebase_convert_multiplier < 1 )
1211         {
1212             fprintf( stderr, "x264 [error]: timebase you specified will generate nonmonotonic pts: %d/%d\n",
1213                      i_user_timebase_num, i_user_timebase_den );
1214             return -1;
1215         }
1216         param->i_timebase_num = i_user_timebase_num;
1217         param->i_timebase_den = i_user_timebase_den;
1218         param->b_vfr_input = 1;
1219     }
1220     if( !param->vui.i_sar_width || !param->vui.i_sar_height )
1221     {
1222         param->vui.i_sar_width  = info.sar_width;
1223         param->vui.i_sar_height = info.sar_height;
1224     }
1225
1226 #ifdef HAVE_PTHREAD
1227     if( b_thread_input || param->i_threads > 1
1228         || (param->i_threads == X264_THREADS_AUTO && x264_cpu_num_processors() > 1) )
1229     {
1230         if( thread_input.open_file( NULL, &opt->hin, &info, NULL ) )
1231         {
1232             fprintf( stderr, "x264 [error]: threaded input failed\n" );
1233             return -1;
1234         }
1235         else
1236             input = thread_input;
1237     }
1238 #endif
1239
1240
1241     /* Automatically reduce reference frame count to match the user's target level
1242      * if the user didn't explicitly set a reference frame count. */
1243     if( !b_user_ref )
1244     {
1245         int mbs = (((param->i_width)+15)>>4) * (((param->i_height)+15)>>4);
1246         int i;
1247         for( i = 0; x264_levels[i].level_idc != 0; i++ )
1248             if( param->i_level_idc == x264_levels[i].level_idc )
1249             {
1250                 while( mbs * 384 * param->i_frame_reference > x264_levels[i].dpb
1251                        && param->i_frame_reference > 1 )
1252                 {
1253                     param->i_frame_reference--;
1254                 }
1255                 break;
1256             }
1257     }
1258
1259
1260     return 0;
1261 }
1262
1263 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
1264 {
1265     int num = -1, qp, ret;
1266     char type;
1267     uint64_t file_pos;
1268     while( num < i_frame )
1269     {
1270         file_pos = ftell( opt->qpfile );
1271         ret = fscanf( opt->qpfile, "%d %c %d\n", &num, &type, &qp );
1272         if( num > i_frame || ret == EOF )
1273         {
1274             pic->i_type = X264_TYPE_AUTO;
1275             pic->i_qpplus1 = 0;
1276             fseek( opt->qpfile, file_pos, SEEK_SET );
1277             break;
1278         }
1279         if( num < i_frame && ret == 3 )
1280             continue;
1281         pic->i_qpplus1 = qp+1;
1282         if     ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
1283         else if( type == 'i' ) pic->i_type = X264_TYPE_I;
1284         else if( type == 'P' ) pic->i_type = X264_TYPE_P;
1285         else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
1286         else if( type == 'b' ) pic->i_type = X264_TYPE_B;
1287         else ret = 0;
1288         if( ret != 3 || qp < -1 || qp > 51 )
1289         {
1290             fprintf( stderr, "x264 [error]: can't parse qpfile for frame %d\n", i_frame );
1291             fclose( opt->qpfile );
1292             opt->qpfile = NULL;
1293             pic->i_type = X264_TYPE_AUTO;
1294             pic->i_qpplus1 = 0;
1295             break;
1296         }
1297     }
1298 }
1299
1300 /*****************************************************************************
1301  * Encode:
1302  *****************************************************************************/
1303
1304 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic, int64_t *last_pts )
1305 {
1306     x264_picture_t pic_out;
1307     x264_nal_t *nal;
1308     int i_nal;
1309     int i_frame_size = 0;
1310
1311     i_frame_size = x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out );
1312
1313     if( i_frame_size < 0 )
1314     {
1315         fprintf( stderr, "x264 [error]: x264_encoder_encode failed\n" );
1316         return -1;
1317     }
1318
1319     if( i_frame_size )
1320     {
1321         i_frame_size = output.write_frame( hout, nal[0].p_payload, i_frame_size, &pic_out );
1322         *last_pts = pic_out.i_pts;
1323     }
1324
1325     return i_frame_size;
1326 }
1327
1328 static void Print_status( int64_t i_start, int i_frame, int i_frame_total, int64_t i_file, x264_param_t *param, int64_t last_pts )
1329 {
1330     char    buf[200];
1331     int64_t i_elapsed = x264_mdate() - i_start;
1332     double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1333     double bitrate = (double) i_file * 8 / ( (double) last_pts * 1000 * param->i_timebase_num / param->i_timebase_den );
1334     if( i_frame_total )
1335     {
1336         int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1337         sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
1338                  100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
1339                  eta/3600, (eta/60)%60, eta%60 );
1340     }
1341     else
1342     {
1343         sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
1344     }
1345     fprintf( stderr, "%s  \r", buf+5 );
1346     SetConsoleTitle( buf );
1347     fflush( stderr ); // needed in windows
1348 }
1349
1350 static int  Encode( x264_param_t *param, cli_opt_t *opt )
1351 {
1352     x264_t *h;
1353     x264_picture_t pic;
1354     const cli_pulldown_t *pulldown = NULL; // shut up gcc
1355
1356     int     i_frame, i_frame_total, i_frame_output;
1357     int64_t i_start, i_end;
1358     int64_t i_file = 0;
1359     int     i_frame_size;
1360     int     i_update_interval;
1361     int64_t last_pts = 0;
1362 #   define  MAX_PTS_WARNING 3 /* arbitrary */
1363     int     pts_warning_cnt = 0;
1364     int64_t largest_pts = -1;
1365     int64_t second_largest_pts = -1;
1366     int64_t ticks_per_frame;
1367     double  duration;
1368     int     prev_timebase_den = param->i_timebase_den / gcd( param->i_timebase_num, param->i_timebase_den );
1369     int     dts_compress_multiplier;
1370     double  pulldown_pts = 0;
1371
1372     opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
1373     i_frame_total = input.get_frame_total( opt->hin );
1374     i_frame_total = X264_MAX( i_frame_total - opt->i_seek, 0 );
1375     if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
1376         && param->i_frame_total > 0 )
1377         i_frame_total = param->i_frame_total;
1378     param->i_frame_total = i_frame_total;
1379     i_update_interval = i_frame_total ? x264_clip3( i_frame_total / 1000, 1, 10 ) : 10;
1380
1381     /* set up pulldown */
1382     if( opt->i_pulldown && !param->b_vfr_input )
1383     {
1384         param->b_pic_struct = 1;
1385         pulldown = &pulldown_values[opt->i_pulldown];
1386         param->i_timebase_num = param->i_fps_den;
1387         if( fmod( param->i_fps_num * pulldown->fps_factor, 1 ) )
1388         {
1389             fprintf( stderr, "x264 [error]: unsupported framerate for chosen pulldown\n" );
1390             return -1;
1391         }
1392         param->i_timebase_den = param->i_fps_num * pulldown->fps_factor;
1393     }
1394
1395     if( ( h = x264_encoder_open( param ) ) == NULL )
1396     {
1397         fprintf( stderr, "x264 [error]: x264_encoder_open failed\n" );
1398         input.close_file( opt->hin );
1399         return -1;
1400     }
1401
1402     x264_encoder_parameters( h, param );
1403
1404     dts_compress_multiplier = param->i_timebase_den / prev_timebase_den;
1405
1406     if( output.set_param( opt->hout, param ) )
1407     {
1408         fprintf( stderr, "x264 [error]: can't set outfile param\n" );
1409         input.close_file( opt->hin );
1410         output.close_file( opt->hout, largest_pts, second_largest_pts );
1411         return -1;
1412     }
1413
1414     /* Create a new pic */
1415     if( input.picture_alloc( &pic, param->i_csp, param->i_width, param->i_height ) )
1416     {
1417         fprintf( stderr, "x264 [error]: malloc failed\n" );
1418         return -1;
1419     }
1420
1421     i_start = x264_mdate();
1422     /* ticks/frame = ticks/second / frames/second */
1423     ticks_per_frame = (int64_t)param->i_timebase_den * param->i_fps_den / param->i_timebase_num / param->i_fps_num;
1424     if( ticks_per_frame < 1 )
1425     {
1426         fprintf( stderr, "x264 [error]: ticks_per_frame invalid: %"PRId64"\n", ticks_per_frame );
1427         return -1;
1428     }
1429
1430     if( !param->b_repeat_headers )
1431     {
1432         // Write SPS/PPS/SEI
1433         x264_nal_t *headers;
1434         int i_nal;
1435
1436         if( x264_encoder_headers( h, &headers, &i_nal ) < 0 )
1437         {
1438             fprintf( stderr, "x264 [error]: x264_encoder_headers failed\n" );
1439             return -1;
1440         }
1441
1442         if( (i_file = output.write_headers( opt->hout, headers )) < 0 )
1443             return -1;
1444     }
1445
1446     if( opt->tcfile_out )
1447         fprintf( opt->tcfile_out, "# timecode format v2\n" );
1448
1449     /* Encode frames */
1450     for( i_frame = 0, i_frame_output = 0; b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1451     {
1452         if( input.read_frame( &pic, opt->hin, i_frame + opt->i_seek ) )
1453             break;
1454
1455         if( !param->b_vfr_input )
1456             pic.i_pts = i_frame;
1457
1458         if( opt->i_pulldown && !param->b_vfr_input )
1459         {
1460             pic.i_pic_struct = pulldown->pattern[ i_frame % pulldown->mod ];
1461             pic.i_pts = (int64_t)( pulldown_pts + 0.5 );
1462             pulldown_pts += pulldown_frame_duration[pic.i_pic_struct];
1463         }
1464         else if( opt->timebase_convert_multiplier )
1465             pic.i_pts = (int64_t)( pic.i_pts * opt->timebase_convert_multiplier + 0.5 );
1466
1467         int64_t output_pts = pic.i_pts * dts_compress_multiplier;   /* pts libx264 returns */
1468
1469         if( pic.i_pts <= largest_pts )
1470         {
1471             if( param->i_log_level >= X264_LOG_WARNING )
1472             {
1473                 if( param->i_log_level >= X264_LOG_DEBUG || pts_warning_cnt < MAX_PTS_WARNING )
1474                     fprintf( stderr, "x264 [warning]: non-strictly-monotonic pts at frame %d (%"PRId64" <= %"PRId64")\n",
1475                              i_frame, output_pts, largest_pts * dts_compress_multiplier );
1476                 else if( pts_warning_cnt == MAX_PTS_WARNING )
1477                     fprintf( stderr, "x264 [warning]: too many nonmonotonic pts warnings, suppressing further ones\n" );
1478                 pts_warning_cnt++;
1479             }
1480             pic.i_pts = largest_pts + ticks_per_frame;
1481             output_pts = pic.i_pts * dts_compress_multiplier;
1482         }
1483
1484         second_largest_pts = largest_pts;
1485         largest_pts = pic.i_pts;
1486         if( opt->tcfile_out )
1487             fprintf( opt->tcfile_out, "%.6f\n", output_pts * ((double)param->i_timebase_num / param->i_timebase_den) * 1e3 );
1488
1489         if( opt->qpfile )
1490             parse_qpfile( opt, &pic, i_frame + opt->i_seek );
1491         else
1492         {
1493             /* Do not force any parameters */
1494             pic.i_type = X264_TYPE_AUTO;
1495             pic.i_qpplus1 = 0;
1496         }
1497
1498         i_frame_size = Encode_frame( h, opt->hout, &pic, &last_pts );
1499         if( i_frame_size < 0 )
1500             return -1;
1501         i_file += i_frame_size;
1502         if( i_frame_size )
1503             i_frame_output++;
1504
1505         i_frame++;
1506
1507         if( input.release_frame && input.release_frame( &pic, opt->hin ) )
1508             break;
1509
1510         /* update status line (up to 1000 times per input file) */
1511         if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1512             Print_status( i_start, i_frame_output, i_frame_total, i_file, param, last_pts );
1513     }
1514     /* Flush delayed frames */
1515     while( !b_ctrl_c && x264_encoder_delayed_frames( h ) )
1516     {
1517         i_frame_size = Encode_frame( h, opt->hout, NULL, &last_pts );
1518         if( i_frame_size < 0 )
1519             return -1;
1520         i_file += i_frame_size;
1521         if( i_frame_size )
1522             i_frame_output++;
1523         if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1524             Print_status( i_start, i_frame_output, i_frame_total, i_file, param, last_pts );
1525     }
1526     if( pts_warning_cnt >= MAX_PTS_WARNING && param->i_log_level < X264_LOG_DEBUG )
1527         fprintf( stderr, "x264 [warning]: %d suppressed nonmonotonic pts warnings\n", pts_warning_cnt-MAX_PTS_WARNING );
1528
1529     /* duration algorithm fails when only 1 frame is output */
1530     if( i_frame_output == 1 )
1531         duration = (double)param->i_fps_den / param->i_fps_num;
1532     else
1533         duration = (double)(2 * largest_pts - second_largest_pts) * param->i_timebase_num / param->i_timebase_den;
1534     if( !(opt->i_pulldown && !param->b_vfr_input) )
1535         duration *= dts_compress_multiplier;
1536
1537     i_end = x264_mdate();
1538     input.picture_clean( &pic );
1539     /* Erase progress indicator before printing encoding stats. */
1540     if( opt->b_progress )
1541         fprintf( stderr, "                                                                               \r" );
1542     x264_encoder_close( h );
1543     fprintf( stderr, "\n" );
1544
1545     if( b_ctrl_c )
1546         fprintf( stderr, "aborted at input frame %d, output frame %d\n", opt->i_seek + i_frame, i_frame_output );
1547
1548     if( opt->tcfile_out )
1549     {
1550         fclose( opt->tcfile_out );
1551         opt->tcfile_out = NULL;
1552     }
1553
1554     input.close_file( opt->hin );
1555     output.close_file( opt->hout, largest_pts, second_largest_pts );
1556
1557     if( i_frame_output > 0 )
1558     {
1559         double fps = (double)i_frame_output * (double)1000000 /
1560                      (double)( i_end - i_start );
1561
1562         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame_output, fps,
1563                  (double) i_file * 8 / ( 1000 * duration ) );
1564     }
1565
1566     return 0;
1567 }