]> git.sesse.net Git - x264/blob - x264.c
4d6465e86126030f226c4ce659f8031174604890
[x264] / x264.c
1 /*****************************************************************************
2  * x264: top-level x264cli functions
3  *****************************************************************************
4  * Copyright (C) 2003-2013 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  *          Fiona Glaser <fiona@x264.com>
10  *          Kieran Kunhya <kieran@kunhya.com>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
25  *
26  * This program is also available under a commercial proprietary license.
27  * For more information, contact us at licensing@x264.com.
28  *****************************************************************************/
29
30 #include <signal.h>
31 #define _GNU_SOURCE
32 #include <getopt.h>
33 #include "common/common.h"
34 #include "x264cli.h"
35 #include "input/input.h"
36 #include "output/output.h"
37 #include "filters/filters.h"
38
39 #define FAIL_IF_ERROR( cond, ... ) FAIL_IF_ERR( cond, "x264", __VA_ARGS__ )
40
41 #ifdef _WIN32
42 #include <windows.h>
43 #else
44 #define GetConsoleTitle(t,n)
45 #define SetConsoleTitle(t)
46 #endif
47
48 #if HAVE_LAVF
49 #undef DECLARE_ALIGNED
50 #include <libavformat/avformat.h>
51 #include <libavutil/pixfmt.h>
52 #include <libavutil/pixdesc.h>
53 #endif
54
55 #if HAVE_SWSCALE
56 #undef DECLARE_ALIGNED
57 #include <libswscale/swscale.h>
58 #endif
59
60 #if HAVE_FFMS
61 #include <ffms.h>
62 #endif
63
64 /* Ctrl-C handler */
65 static volatile int b_ctrl_c = 0;
66 static int          b_exit_on_ctrl_c = 0;
67 static void sigint_handler( int a )
68 {
69     if( b_exit_on_ctrl_c )
70         exit(0);
71     b_ctrl_c = 1;
72 }
73
74 static char UNUSED originalCTitle[200] = "";
75
76 typedef struct {
77     int b_progress;
78     int i_seek;
79     hnd_t hin;
80     hnd_t hout;
81     FILE *qpfile;
82     FILE *tcfile_out;
83     double timebase_convert_multiplier;
84     int i_pulldown;
85 } cli_opt_t;
86
87 /* file i/o operation structs */
88 cli_input_t cli_input;
89 static cli_output_t cli_output;
90
91 /* video filter operation struct */
92 static cli_vid_filter_t filter;
93
94 static const char * const demuxer_names[] =
95 {
96     "auto",
97     "raw",
98     "y4m",
99 #if HAVE_AVS
100     "avs",
101 #endif
102 #if HAVE_LAVF
103     "lavf",
104 #endif
105 #if HAVE_FFMS
106     "ffms",
107 #endif
108     0
109 };
110
111 static const char * const muxer_names[] =
112 {
113     "auto",
114     "raw",
115     "mkv",
116     "flv",
117 #if HAVE_GPAC
118     "mp4",
119 #endif
120     0
121 };
122
123 static const char * const pulldown_names[] = { "none", "22", "32", "64", "double", "triple", "euro", 0 };
124 static const char * const log_level_names[] = { "none", "error", "warning", "info", "debug", 0 };
125 static const char * const output_csp_names[] =
126 {
127 #if !X264_CHROMA_FORMAT || X264_CHROMA_FORMAT == X264_CSP_I420
128     "i420",
129 #endif
130 #if !X264_CHROMA_FORMAT || X264_CHROMA_FORMAT == X264_CSP_I422
131     "i422",
132 #endif
133 #if !X264_CHROMA_FORMAT || X264_CHROMA_FORMAT == X264_CSP_I444
134     "i444", "rgb",
135 #endif
136     0
137 };
138
139 static const char * const range_names[] = { "auto", "tv", "pc", 0 };
140
141 typedef struct
142 {
143     int mod;
144     uint8_t pattern[24];
145     float fps_factor;
146 } cli_pulldown_t;
147
148 enum pulldown_type_e
149 {
150     X264_PULLDOWN_22 = 1,
151     X264_PULLDOWN_32,
152     X264_PULLDOWN_64,
153     X264_PULLDOWN_DOUBLE,
154     X264_PULLDOWN_TRIPLE,
155     X264_PULLDOWN_EURO
156 };
157
158 #define TB  PIC_STRUCT_TOP_BOTTOM
159 #define BT  PIC_STRUCT_BOTTOM_TOP
160 #define TBT PIC_STRUCT_TOP_BOTTOM_TOP
161 #define BTB PIC_STRUCT_BOTTOM_TOP_BOTTOM
162
163 static const cli_pulldown_t pulldown_values[] =
164 {
165     [X264_PULLDOWN_22]     = {1,  {TB},                                   1.0},
166     [X264_PULLDOWN_32]     = {4,  {TBT, BT, BTB, TB},                     1.25},
167     [X264_PULLDOWN_64]     = {2,  {PIC_STRUCT_DOUBLE, PIC_STRUCT_TRIPLE}, 1.0},
168     [X264_PULLDOWN_DOUBLE] = {1,  {PIC_STRUCT_DOUBLE},                    2.0},
169     [X264_PULLDOWN_TRIPLE] = {1,  {PIC_STRUCT_TRIPLE},                    3.0},
170     [X264_PULLDOWN_EURO]   = {24, {TBT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT,
171                                    BTB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB}, 25.0/24.0}
172 };
173
174 #undef TB
175 #undef BT
176 #undef TBT
177 #undef BTB
178
179 // indexed by pic_struct enum
180 static const float pulldown_frame_duration[10] = { 0.0, 1, 0.5, 0.5, 1, 1, 1.5, 1.5, 2, 3 };
181
182 static void help( x264_param_t *defaults, int longhelp );
183 static int  parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
184 static int  encode( x264_param_t *param, cli_opt_t *opt );
185
186 /* logging and printing for within the cli system */
187 static int cli_log_level;
188 void x264_cli_log( const char *name, int i_level, const char *fmt, ... )
189 {
190     if( i_level > cli_log_level )
191         return;
192     char *s_level;
193     switch( i_level )
194     {
195         case X264_LOG_ERROR:
196             s_level = "error";
197             break;
198         case X264_LOG_WARNING:
199             s_level = "warning";
200             break;
201         case X264_LOG_INFO:
202             s_level = "info";
203             break;
204         case X264_LOG_DEBUG:
205             s_level = "debug";
206             break;
207         default:
208             s_level = "unknown";
209             break;
210     }
211     fprintf( stderr, "%s [%s]: ", name, s_level );
212     va_list arg;
213     va_start( arg, fmt );
214     vfprintf( stderr, fmt, arg );
215     va_end( arg );
216 }
217
218 void x264_cli_printf( int i_level, const char *fmt, ... )
219 {
220     if( i_level > cli_log_level )
221         return;
222     va_list arg;
223     va_start( arg, fmt );
224     vfprintf( stderr, fmt, arg );
225     va_end( arg );
226 }
227
228 static void print_version_info( void )
229 {
230 #ifdef X264_POINTVER
231     printf( "x264 "X264_POINTVER"\n" );
232 #else
233     printf( "x264 0.%d.X\n", X264_BUILD );
234 #endif
235 #if HAVE_SWSCALE
236     printf( "(libswscale %d.%d.%d)\n", LIBSWSCALE_VERSION_MAJOR, LIBSWSCALE_VERSION_MINOR, LIBSWSCALE_VERSION_MICRO );
237 #endif
238 #if HAVE_LAVF
239     printf( "(libavformat %d.%d.%d)\n", LIBAVFORMAT_VERSION_MAJOR, LIBAVFORMAT_VERSION_MINOR, LIBAVFORMAT_VERSION_MICRO );
240 #endif
241 #if HAVE_FFMS
242     printf( "(ffmpegsource %d.%d.%d.%d)\n", FFMS_VERSION >> 24, (FFMS_VERSION & 0xff0000) >> 16, (FFMS_VERSION & 0xff00) >> 8, FFMS_VERSION & 0xff );
243 #endif
244     printf( "built on " __DATE__ ", " );
245 #ifdef __INTEL_COMPILER
246     printf( "intel: %.2f (%d)\n", __INTEL_COMPILER / 100.f, __INTEL_COMPILER_BUILD_DATE );
247 #elif defined(__GNUC__)
248     printf( "gcc: " __VERSION__ "\n" );
249 #else
250     printf( "using an unknown compiler\n" );
251 #endif
252     printf( "configuration: --bit-depth=%d --chroma-format=%s\n", x264_bit_depth, X264_CHROMA_FORMAT ? (output_csp_names[0]+1) : "all" );
253     printf( "x264 license: " );
254 #if HAVE_GPL
255     printf( "GPL version 2 or later\n" );
256 #else
257     printf( "Non-GPL commercial\n" );
258 #endif
259 #if HAVE_SWSCALE
260     const char *license = swscale_license();
261     printf( "libswscale%s%s license: %s\n", HAVE_LAVF ? "/libavformat" : "", HAVE_FFMS ? "/ffmpegsource" : "" , license );
262     if( !strcmp( license, "nonfree and unredistributable" ) ||
263        (!HAVE_GPL && (!strcmp( license, "GPL version 2 or later" )
264                   ||  !strcmp( license, "GPL version 3 or later" ))))
265         printf( "WARNING: This binary is unredistributable!\n" );
266 #endif
267 }
268
269 int main( int argc, char **argv )
270 {
271     x264_param_t param;
272     cli_opt_t opt = {0};
273     int ret = 0;
274
275     FAIL_IF_ERROR( x264_threading_init(), "unable to initialize threading\n" )
276
277 #ifdef _WIN32
278     _setmode(_fileno(stdin), _O_BINARY);
279     _setmode(_fileno(stdout), _O_BINARY);
280 #endif
281
282     GetConsoleTitle( originalCTitle, sizeof(originalCTitle) );
283
284     /* Parse command line */
285     if( parse( argc, argv, &param, &opt ) < 0 )
286         ret = -1;
287
288     /* Restore title; it can be changed by input modules */
289     SetConsoleTitle( originalCTitle );
290
291     /* Control-C handler */
292     signal( SIGINT, sigint_handler );
293
294     if( !ret )
295         ret = encode( &param, &opt );
296
297     /* clean up handles */
298     if( filter.free )
299         filter.free( opt.hin );
300     else if( opt.hin )
301         cli_input.close_file( opt.hin );
302     if( opt.hout )
303         cli_output.close_file( opt.hout, 0, 0 );
304     if( opt.tcfile_out )
305         fclose( opt.tcfile_out );
306     if( opt.qpfile )
307         fclose( opt.qpfile );
308
309     SetConsoleTitle( originalCTitle );
310
311     return ret;
312 }
313
314 static char const *strtable_lookup( const char * const table[], int idx )
315 {
316     int i = 0; while( table[i] ) i++;
317     return ( ( idx >= 0 && idx < i ) ? table[ idx ] : "???" );
318 }
319
320 static char *stringify_names( char *buf, const char * const names[] )
321 {
322     int i = 0;
323     char *p = buf;
324     for( p[0] = 0; names[i]; i++ )
325     {
326         p += sprintf( p, "%s", names[i] );
327         if( names[i+1] )
328             p += sprintf( p, ", " );
329     }
330     return buf;
331 }
332
333 static void print_csp_names( int longhelp )
334 {
335     if( longhelp < 2 )
336         return;
337 #   define INDENT "                                "
338     printf( "                              - valid csps for `raw' demuxer:\n" );
339     printf( INDENT );
340     for( int i = X264_CSP_NONE+1; i < X264_CSP_CLI_MAX; i++ )
341     {
342         printf( "%s", x264_cli_csps[i].name );
343         if( i+1 < X264_CSP_CLI_MAX )
344             printf( ", " );
345     }
346 #if HAVE_LAVF
347     printf( "\n" );
348     printf( "                              - valid csps for `lavf' demuxer:\n" );
349     printf( INDENT );
350     size_t line_len = strlen( INDENT );
351     for( enum PixelFormat i = PIX_FMT_NONE+1; i < PIX_FMT_NB; i++ )
352     {
353         const char *pfname = av_get_pix_fmt_name( i );
354         if( pfname )
355         {
356             size_t name_len = strlen( pfname );
357             if( line_len + name_len > (80 - strlen( ", " )) )
358             {
359                 printf( "\n" INDENT );
360                 line_len = strlen( INDENT );
361             }
362             printf( "%s", pfname );
363             line_len += name_len;
364             if( i+1 < PIX_FMT_NB )
365             {
366                 printf( ", " );
367                 line_len += 2;
368             }
369         }
370     }
371 #endif
372     printf( "\n" );
373 }
374
375 static void help( x264_param_t *defaults, int longhelp )
376 {
377     char buf[50];
378 #define H0 printf
379 #define H1 if(longhelp>=1) printf
380 #define H2 if(longhelp==2) printf
381     H0( "x264 core:%d%s\n"
382         "Syntax: x264 [options] -o outfile infile\n"
383         "\n"
384         "Infile can be raw (in which case resolution is required),\n"
385         "  or YUV4MPEG (*.y4m),\n"
386         "  or Avisynth if compiled with support (%s).\n"
387         "  or libav* formats if compiled with lavf support (%s) or ffms support (%s).\n"
388         "Outfile type is selected by filename:\n"
389         " .264 -> Raw bytestream\n"
390         " .mkv -> Matroska\n"
391         " .flv -> Flash Video\n"
392         " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
393         "Output bit depth: %d (configured at compile time)\n"
394         "\n"
395         "Options:\n"
396         "\n"
397         "  -h, --help                  List basic options\n"
398         "      --longhelp              List more options\n"
399         "      --fullhelp              List all options\n"
400         "\n",
401         X264_BUILD, X264_VERSION,
402 #if HAVE_AVS
403         "yes",
404 #else
405         "no",
406 #endif
407 #if HAVE_LAVF
408         "yes",
409 #else
410         "no",
411 #endif
412 #if HAVE_FFMS
413         "yes",
414 #else
415         "no",
416 #endif
417 #if HAVE_GPAC
418         "yes",
419 #else
420         "no",
421 #endif
422         x264_bit_depth
423       );
424     H0( "Example usage:\n" );
425     H0( "\n" );
426     H0( "      Constant quality mode:\n" );
427     H0( "            x264 --crf 24 -o <output> <input>\n" );
428     H0( "\n" );
429     H0( "      Two-pass with a bitrate of 1000kbps:\n" );
430     H0( "            x264 --pass 1 --bitrate 1000 -o <output> <input>\n" );
431     H0( "            x264 --pass 2 --bitrate 1000 -o <output> <input>\n" );
432     H0( "\n" );
433     H0( "      Lossless:\n" );
434     H0( "            x264 --qp 0 -o <output> <input>\n" );
435     H0( "\n" );
436     H0( "      Maximum PSNR at the cost of speed and visual quality:\n" );
437     H0( "            x264 --preset placebo --tune psnr -o <output> <input>\n" );
438     H0( "\n" );
439     H0( "      Constant bitrate at 1000kbps with a 2 second-buffer:\n");
440     H0( "            x264 --vbv-bufsize 2000 --bitrate 1000 -o <output> <input>\n" );
441     H0( "\n" );
442     H0( "Presets:\n" );
443     H0( "\n" );
444     H0( "      --profile <string>      Force the limits of an H.264 profile\n"
445         "                                  Overrides all settings.\n" );
446     H2(
447 #if X264_CHROMA_FORMAT <= X264_CSP_I420
448 #if BIT_DEPTH==8
449         "                                  - baseline:\n"
450         "                                    --no-8x8dct --bframes 0 --no-cabac\n"
451         "                                    --cqm flat --weightp 0\n"
452         "                                    No interlaced.\n"
453         "                                    No lossless.\n"
454         "                                  - main:\n"
455         "                                    --no-8x8dct --cqm flat\n"
456         "                                    No lossless.\n"
457         "                                  - high:\n"
458         "                                    No lossless.\n"
459 #endif
460         "                                  - high10:\n"
461         "                                    No lossless.\n"
462         "                                    Support for bit depth 8-10.\n"
463 #endif
464 #if X264_CHROMA_FORMAT <= X264_CSP_I422
465         "                                  - high422:\n"
466         "                                    No lossless.\n"
467         "                                    Support for bit depth 8-10.\n"
468         "                                    Support for 4:2:0/4:2:2 chroma subsampling.\n"
469 #endif
470         "                                  - high444:\n"
471         "                                    Support for bit depth 8-10.\n"
472         "                                    Support for 4:2:0/4:2:2/4:4:4 chroma subsampling.\n" );
473         else H0(
474         "                                  - "
475 #if X264_CHROMA_FORMAT <= X264_CSP_I420
476 #if BIT_DEPTH==8
477         "baseline,main,high,"
478 #endif
479         "high10,"
480 #endif
481 #if X264_CHROMA_FORMAT <= X264_CSP_I422
482         "high422,"
483 #endif
484         "high444\n"
485                );
486     H0( "      --preset <string>       Use a preset to select encoding settings [medium]\n"
487         "                                  Overridden by user settings.\n" );
488     H2( "                                  - ultrafast:\n"
489         "                                    --no-8x8dct --aq-mode 0 --b-adapt 0\n"
490         "                                    --bframes 0 --no-cabac --no-deblock\n"
491         "                                    --no-mbtree --me dia --no-mixed-refs\n"
492         "                                    --partitions none --rc-lookahead 0 --ref 1\n"
493         "                                    --scenecut 0 --subme 0 --trellis 0\n"
494         "                                    --no-weightb --weightp 0\n"
495         "                                  - superfast:\n"
496         "                                    --no-mbtree --me dia --no-mixed-refs\n"
497         "                                    --partitions i8x8,i4x4 --rc-lookahead 0\n"
498         "                                    --ref 1 --subme 1 --trellis 0 --weightp 1\n"
499         "                                  - veryfast:\n"
500         "                                    --no-mixed-refs --rc-lookahead 10\n"
501         "                                    --ref 1 --subme 2 --trellis 0 --weightp 1\n"
502         "                                  - faster:\n"
503         "                                    --no-mixed-refs --rc-lookahead 20\n"
504         "                                    --ref 2 --subme 4 --weightp 1\n"
505         "                                  - fast:\n"
506         "                                    --rc-lookahead 30 --ref 2 --subme 6\n"
507         "                                    --weightp 1\n"
508         "                                  - medium:\n"
509         "                                    Default settings apply.\n"
510         "                                  - slow:\n"
511         "                                    --b-adapt 2 --direct auto --me umh\n"
512         "                                    --rc-lookahead 50 --ref 5 --subme 8\n"
513         "                                  - slower:\n"
514         "                                    --b-adapt 2 --direct auto --me umh\n"
515         "                                    --partitions all --rc-lookahead 60\n"
516         "                                    --ref 8 --subme 9 --trellis 2\n"
517         "                                  - veryslow:\n"
518         "                                    --b-adapt 2 --bframes 8 --direct auto\n"
519         "                                    --me umh --merange 24 --partitions all\n"
520         "                                    --ref 16 --subme 10 --trellis 2\n"
521         "                                    --rc-lookahead 60\n"
522         "                                  - placebo:\n"
523         "                                    --bframes 16 --b-adapt 2 --direct auto\n"
524         "                                    --slow-firstpass --no-fast-pskip\n"
525         "                                    --me tesa --merange 24 --partitions all\n"
526         "                                    --rc-lookahead 60 --ref 16 --subme 11\n"
527         "                                    --trellis 2\n" );
528     else H0( "                                  - ultrafast,superfast,veryfast,faster,fast\n"
529              "                                  - medium,slow,slower,veryslow,placebo\n" );
530     H0( "      --tune <string>         Tune the settings for a particular type of source\n"
531         "                              or situation\n"
532         "                                  Overridden by user settings.\n"
533         "                                  Multiple tunings are separated by commas.\n"
534         "                                  Only one psy tuning can be used at a time.\n" );
535     H2( "                                  - film (psy tuning):\n"
536         "                                    --deblock -1:-1 --psy-rd <unset>:0.15\n"
537         "                                  - animation (psy tuning):\n"
538         "                                    --bframes {+2} --deblock 1:1\n"
539         "                                    --psy-rd 0.4:<unset> --aq-strength 0.6\n"
540         "                                    --ref {Double if >1 else 1}\n"
541         "                                  - grain (psy tuning):\n"
542         "                                    --aq-strength 0.5 --no-dct-decimate\n"
543         "                                    --deadzone-inter 6 --deadzone-intra 6\n"
544         "                                    --deblock -2:-2 --ipratio 1.1 \n"
545         "                                    --pbratio 1.1 --psy-rd <unset>:0.25\n"
546         "                                    --qcomp 0.8\n"
547         "                                  - stillimage (psy tuning):\n"
548         "                                    --aq-strength 1.2 --deblock -3:-3\n"
549         "                                    --psy-rd 2.0:0.7\n"
550         "                                  - psnr (psy tuning):\n"
551         "                                    --aq-mode 0 --no-psy\n"
552         "                                  - ssim (psy tuning):\n"
553         "                                    --aq-mode 2 --no-psy\n"
554         "                                  - fastdecode:\n"
555         "                                    --no-cabac --no-deblock --no-weightb\n"
556         "                                    --weightp 0\n"
557         "                                  - zerolatency:\n"
558         "                                    --bframes 0 --force-cfr --no-mbtree\n"
559         "                                    --sync-lookahead 0 --sliced-threads\n"
560         "                                    --rc-lookahead 0\n" );
561     else H0( "                                  - psy tunings: film,animation,grain,\n"
562              "                                                 stillimage,psnr,ssim\n"
563              "                                  - other tunings: fastdecode,zerolatency\n" );
564     H2( "      --slow-firstpass        Don't force these faster settings with --pass 1:\n"
565         "                                  --no-8x8dct --me dia --partitions none\n"
566         "                                  --ref 1 --subme {2 if >2 else unchanged}\n"
567         "                                  --trellis 0 --fast-pskip\n" );
568     else H1( "      --slow-firstpass        Don't force faster settings with --pass 1\n" );
569     H0( "\n" );
570     H0( "Frame-type options:\n" );
571     H0( "\n" );
572     H0( "  -I, --keyint <integer or \"infinite\"> Maximum GOP size [%d]\n", defaults->i_keyint_max );
573     H2( "  -i, --min-keyint <integer>  Minimum GOP size [auto]\n" );
574     H2( "      --no-scenecut           Disable adaptive I-frame decision\n" );
575     H2( "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
576     H2( "      --intra-refresh         Use Periodic Intra Refresh instead of IDR frames\n" );
577     H1( "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n", defaults->i_bframe );
578     H1( "      --b-adapt <integer>     Adaptive B-frame decision method [%d]\n"
579         "                                  Higher values may lower threading efficiency.\n"
580         "                                  - 0: Disabled\n"
581         "                                  - 1: Fast\n"
582         "                                  - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
583     H2( "      --b-bias <integer>      Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
584     H1( "      --b-pyramid <string>    Keep some B-frames as references [%s]\n"
585         "                                  - none: Disabled\n"
586         "                                  - strict: Strictly hierarchical pyramid\n"
587         "                                  - normal: Non-strict (not Blu-ray compatible)\n",
588         strtable_lookup( x264_b_pyramid_names, defaults->i_bframe_pyramid ) );
589     H1( "      --open-gop              Use recovery points to close GOPs\n"
590         "                              Only available with b-frames\n" );
591     H1( "      --no-cabac              Disable CABAC\n" );
592     H1( "  -r, --ref <integer>         Number of reference frames [%d]\n", defaults->i_frame_reference );
593     H1( "      --no-deblock            Disable loop filter\n" );
594     H1( "  -f, --deblock <alpha:beta>  Loop filter parameters [%d:%d]\n",
595                                        defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
596     H2( "      --slices <integer>      Number of slices per frame; forces rectangular\n"
597         "                              slices and is overridden by other slicing options\n" );
598     else H1( "      --slices <integer>      Number of slices per frame\n" );
599     H2( "      --slices-max <integer>  Absolute maximum slices per frame; overrides\n"
600         "                              slice-max-size/slice-max-mbs when necessary\n" );
601     H2( "      --slice-max-size <integer> Limit the size of each slice in bytes\n");
602     H2( "      --slice-max-mbs <integer> Limit the size of each slice in macroblocks (max)\n");
603     H2( "      --slice-min-mbs <integer> Limit the size of each slice in macroblocks (min)\n");
604     H0( "      --tff                   Enable interlaced mode (top field first)\n" );
605     H0( "      --bff                   Enable interlaced mode (bottom field first)\n" );
606     H2( "      --constrained-intra     Enable constrained intra prediction.\n" );
607     H0( "      --pulldown <string>     Use soft pulldown to change frame rate\n"
608         "                                  - none, 22, 32, 64, double, triple, euro (requires cfr input)\n" );
609     H2( "      --fake-interlaced       Flag stream as interlaced but encode progressive.\n"
610         "                              Makes it possible to encode 25p and 30p Blu-Ray\n"
611         "                              streams. Ignored in interlaced mode.\n" );
612     H2( "      --frame-packing <integer> For stereoscopic videos define frame arrangement\n"
613         "                                  - 0: checkerboard - pixels are alternatively from L and R\n"
614         "                                  - 1: column alternation - L and R are interlaced by column\n"
615         "                                  - 2: row alternation - L and R are interlaced by row\n"
616         "                                  - 3: side by side - L is on the left, R on the right\n"
617         "                                  - 4: top bottom - L is on top, R on bottom\n"
618         "                                  - 5: frame alternation - one view per frame\n" );
619     H0( "\n" );
620     H0( "Ratecontrol:\n" );
621     H0( "\n" );
622     H1( "  -q, --qp <integer>          Force constant QP (0-%d, 0=lossless)\n", QP_MAX );
623     H0( "  -B, --bitrate <integer>     Set bitrate (kbit/s)\n" );
624     H0( "      --crf <float>           Quality-based VBR (%d-51) [%.1f]\n", 51 - QP_MAX_SPEC, defaults->rc.f_rf_constant );
625     H1( "      --rc-lookahead <integer> Number of frames for frametype lookahead [%d]\n", defaults->rc.i_lookahead );
626     H0( "      --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
627     H0( "      --vbv-bufsize <integer> Set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
628     H2( "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
629     H2( "      --crf-max <float>       With CRF+VBV, limit RF to this value\n"
630         "                                  May cause VBV underflows!\n" );
631     H2( "      --qpmin <integer>       Set min QP [%d]\n", defaults->rc.i_qp_min );
632     H2( "      --qpmax <integer>       Set max QP [%d]\n", defaults->rc.i_qp_max );
633     H2( "      --qpstep <integer>      Set max QP step [%d]\n", defaults->rc.i_qp_step );
634     H2( "      --ratetol <float>       Tolerance of ABR ratecontrol and VBV [%.1f]\n", defaults->rc.f_rate_tolerance );
635     H2( "      --ipratio <float>       QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
636     H2( "      --pbratio <float>       QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
637     H2( "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
638     H2( "      --aq-mode <integer>     AQ method [%d]\n"
639         "                                  - 0: Disabled\n"
640         "                                  - 1: Variance AQ (complexity mask)\n"
641         "                                  - 2: Auto-variance AQ (experimental)\n", defaults->rc.i_aq_mode );
642     H1( "      --aq-strength <float>   Reduces blocking and blurring in flat and\n"
643         "                              textured areas. [%.1f]\n", defaults->rc.f_aq_strength );
644     H1( "\n" );
645     H0( "  -p, --pass <integer>        Enable multipass ratecontrol\n"
646         "                                  - 1: First pass, creates stats file\n"
647         "                                  - 2: Last pass, does not overwrite stats file\n" );
648     H2( "                                  - 3: Nth pass, overwrites stats file\n" );
649     H1( "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
650     H2( "      --no-mbtree             Disable mb-tree ratecontrol.\n");
651     H2( "      --qcomp <float>         QP curve compression [%.2f]\n", defaults->rc.f_qcompress );
652     H2( "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
653     H2( "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
654     H2( "      --zones <zone0>/<zone1>/...  Tweak the bitrate of regions of the video\n" );
655     H2( "                              Each zone is of the form\n"
656         "                                  <start frame>,<end frame>,<option>\n"
657         "                                  where <option> is either\n"
658         "                                      q=<integer> (force QP)\n"
659         "                                  or  b=<float> (bitrate multiplier)\n" );
660     H2( "      --qpfile <string>       Force frametypes and QPs for some or all frames\n"
661         "                              Format of each line: framenumber frametype QP\n"
662         "                              QP is optional (none lets x264 choose). Frametypes: I,i,K,P,B,b.\n"
663         "                                  K=<I or i> depending on open-gop setting\n"
664         "                              QPs are restricted by qpmin/qpmax.\n" );
665     H1( "\n" );
666     H1( "Analysis:\n" );
667     H1( "\n" );
668     H1( "  -A, --partitions <string>   Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
669         "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
670         "                                  - none, all\n"
671         "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
672     H1( "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
673         "                                  - none, spatial, temporal, auto\n",
674                                        strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
675     H2( "      --no-weightb            Disable weighted prediction for B-frames\n" );
676     H1( "      --weightp <integer>     Weighted prediction for P-frames [%d]\n"
677         "                                  - 0: Disabled\n"
678         "                                  - 1: Weighted refs\n"
679         "                                  - 2: Weighted refs + Duplicates\n", defaults->analyse.i_weighted_pred );
680     H1( "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n",
681                                        strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
682     H2( "                                  - dia: diamond search, radius 1 (fast)\n"
683         "                                  - hex: hexagonal search, radius 2\n"
684         "                                  - umh: uneven multi-hexagon search\n"
685         "                                  - esa: exhaustive search\n"
686         "                                  - tesa: hadamard exhaustive search (slow)\n" );
687     else H1( "                                  - dia, hex, umh\n" );
688     H2( "      --merange <integer>     Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
689     H2( "      --mvrange <integer>     Maximum motion vector length [-1 (auto)]\n" );
690     H2( "      --mvrange-thread <int>  Minimum buffer between threads [-1 (auto)]\n" );
691     H1( "  -m, --subme <integer>       Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
692     H2( "                                  - 0: fullpel only (not recommended)\n"
693         "                                  - 1: SAD mode decision, one qpel iteration\n"
694         "                                  - 2: SATD mode decision\n"
695         "                                  - 3-5: Progressively more qpel\n"
696         "                                  - 6: RD mode decision for I/P-frames\n"
697         "                                  - 7: RD mode decision for all frames\n"
698         "                                  - 8: RD refinement for I/P-frames\n"
699         "                                  - 9: RD refinement for all frames\n"
700         "                                  - 10: QP-RD - requires trellis=2, aq-mode>0\n"
701         "                                  - 11: Full RD: disable all early terminations\n" );
702     else H1( "                                  decision quality: 1=fast, 11=best\n" );
703     H1( "      --psy-rd <float:float>  Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
704         "                                  #1: RD (requires subme>=6)\n"
705         "                                  #2: Trellis (requires trellis, experimental)\n",
706                                        defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
707     H2( "      --no-psy                Disable all visual optimizations that worsen\n"
708         "                              both PSNR and SSIM.\n" );
709     H2( "      --no-mixed-refs         Don't decide references on a per partition basis\n" );
710     H2( "      --no-chroma-me          Ignore chroma in motion estimation\n" );
711     H1( "      --no-8x8dct             Disable adaptive spatial transform size\n" );
712     H1( "  -t, --trellis <integer>     Trellis RD quantization. [%d]\n"
713         "                                  - 0: disabled\n"
714         "                                  - 1: enabled only on the final encode of a MB\n"
715         "                                  - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
716     H2( "      --no-fast-pskip         Disables early SKIP detection on P-frames\n" );
717     H2( "      --no-dct-decimate       Disables coefficient thresholding on P-frames\n" );
718     H1( "      --nr <integer>          Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
719     H2( "\n" );
720     H2( "      --deadzone-inter <int>  Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
721     H2( "      --deadzone-intra <int>  Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
722     H2( "                                  Deadzones should be in the range 0 - 32.\n" );
723     H2( "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
724         "                                  - jvt, flat\n" );
725     H1( "      --cqmfile <string>      Read custom quant matrices from a JM-compatible file\n" );
726     H2( "                                  Overrides any other --cqm* options.\n" );
727     H2( "      --cqm4 <list>           Set all 4x4 quant matrices\n"
728         "                                  Takes a comma-separated list of 16 integers.\n" );
729     H2( "      --cqm8 <list>           Set all 8x8 quant matrices\n"
730         "                                  Takes a comma-separated list of 64 integers.\n" );
731     H2( "      --cqm4i, --cqm4p, --cqm8i, --cqm8p <list>\n"
732         "                              Set both luma and chroma quant matrices\n" );
733     H2( "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc <list>\n"
734         "                              Set individual quant matrices\n" );
735     H2( "\n" );
736     H2( "Video Usability Info (Annex E):\n" );
737     H2( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
738     H2( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
739     H2( "\n" );
740     H2( "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
741         "                                  - undef, show, crop\n",
742                                        strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
743     H2( "      --videoformat <string>  Specify video format [\"%s\"]\n"
744         "                                  - component, pal, ntsc, secam, mac, undef\n",
745                                        strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
746     H2( "      --range <string>        Specify color range [\"%s\"]\n"
747         "                                  - %s\n", range_names[0], stringify_names( buf, range_names ) );
748     H2( "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
749         "                                  - undef, bt709, bt470m, bt470bg, smpte170m,\n"
750         "                                    smpte240m, film, bt2020\n",
751                                        strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
752     H2( "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
753         "                                  - undef, bt709, bt470m, bt470bg, smpte170m,\n"
754         "                                    smpte240m, linear, log100, log316,\n"
755         "                                    iec61966-2-4, bt1361e, iec61966-2-1,\n"
756         "                                    bt2020-10, bt2020-12\n",
757                                        strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
758     H2( "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
759         "                                  - undef, bt709, fcc, bt470bg, smpte170m,\n"
760         "                                    smpte240m, GBR, YCgCo, bt2020nc, bt2020c\n",
761                                        strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
762     H2( "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n",
763                                        defaults->vui.i_chroma_loc );
764
765     H2( "      --nal-hrd <string>      Signal HRD information (requires vbv-bufsize)\n"
766         "                                  - none, vbr, cbr (cbr not allowed in .mp4)\n" );
767     H2( "      --pic-struct            Force pic_struct in Picture Timing SEI\n" );
768     H2( "      --crop-rect <string>    Add 'left,top,right,bottom' to the bitstream-level\n"
769         "                              cropping rectangle\n" );
770
771     H0( "\n" );
772     H0( "Input/Output:\n" );
773     H0( "\n" );
774     H0( "  -o, --output <string>       Specify output file\n" );
775     H1( "      --muxer <string>        Specify output container format [\"%s\"]\n"
776         "                                  - %s\n", muxer_names[0], stringify_names( buf, muxer_names ) );
777     H1( "      --demuxer <string>      Specify input container format [\"%s\"]\n"
778         "                                  - %s\n", demuxer_names[0], stringify_names( buf, demuxer_names ) );
779     H1( "      --input-fmt <string>    Specify input file format (requires lavf support)\n" );
780     H1( "      --input-csp <string>    Specify input colorspace format for raw input\n" );
781     print_csp_names( longhelp );
782     H1( "      --output-csp <string>   Specify output colorspace [\"%s\"]\n"
783         "                                  - %s\n", output_csp_names[0], stringify_names( buf, output_csp_names ) );
784     H1( "      --input-depth <integer> Specify input bit depth for raw input\n" );
785     H1( "      --input-range <string>  Specify input color range [\"%s\"]\n"
786         "                                  - %s\n", range_names[0], stringify_names( buf, range_names ) );
787     H1( "      --input-res <intxint>   Specify input resolution (width x height)\n" );
788     H1( "      --index <string>        Filename for input index file\n" );
789     H0( "      --sar width:height      Specify Sample Aspect Ratio\n" );
790     H0( "      --fps <float|rational>  Specify framerate\n" );
791     H0( "      --seek <integer>        First frame to encode\n" );
792     H0( "      --frames <integer>      Maximum number of frames to encode\n" );
793     H0( "      --level <string>        Specify level (as defined by Annex A)\n" );
794     H1( "      --bluray-compat         Enable compatibility hacks for Blu-ray support\n" );
795     H1( "      --stitchable            Don't optimize headers based on video content\n"
796         "                              Ensures ability to recombine a segmented encode\n" );
797     H1( "\n" );
798     H1( "  -v, --verbose               Print stats for each frame\n" );
799     H1( "      --no-progress           Don't show the progress indicator while encoding\n" );
800     H0( "      --quiet                 Quiet Mode\n" );
801     H1( "      --log-level <string>    Specify the maximum level of logging [\"%s\"]\n"
802         "                                  - %s\n", strtable_lookup( log_level_names, cli_log_level - X264_LOG_NONE ),
803                                        stringify_names( buf, log_level_names ) );
804     H1( "      --psnr                  Enable PSNR computation\n" );
805     H1( "      --ssim                  Enable SSIM computation\n" );
806     H1( "      --threads <integer>     Force a specific number of threads\n" );
807     H2( "      --lookahead-threads <integer> Force a specific number of lookahead threads\n" );
808     H2( "      --sliced-threads        Low-latency but lower-efficiency threading\n" );
809     H2( "      --thread-input          Run Avisynth in its own thread\n" );
810     H2( "      --sync-lookahead <integer> Number of buffer frames for threaded lookahead\n" );
811     H2( "      --non-deterministic     Slightly improve quality of SMP, at the cost of repeatability\n" );
812     H2( "      --cpu-independent       Ensure exact reproducibility across different cpus,\n"
813         "                                  as opposed to letting them select different algorithms\n" );
814     H2( "      --asm <integer>         Override CPU detection\n" );
815     H2( "      --no-asm                Disable all CPU optimizations\n" );
816     H2( "      --opencl                Enable use of OpenCL\n" );
817     H2( "      --opencl-clbin <string> Specify path of compiled OpenCL kernel cache\n" );
818     H2( "      --opencl-device <integer>  Specify OpenCL device ordinal\n" );
819     H2( "      --visualize             Show MB types overlayed on the encoded video\n" );
820     H2( "      --dump-yuv <string>     Save reconstructed frames\n" );
821     H2( "      --sps-id <integer>      Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
822     H2( "      --aud                   Use access unit delimiters\n" );
823     H2( "      --force-cfr             Force constant framerate timestamp generation\n" );
824     H2( "      --tcfile-in <string>    Force timestamp generation with timecode file\n" );
825     H2( "      --tcfile-out <string>   Output timecode v2 file from input timestamps\n" );
826     H2( "      --timebase <int/int>    Specify timebase numerator and denominator\n"
827         "                 <integer>    Specify timebase numerator for input timecode file\n"
828         "                              or specify timebase denominator for other input\n" );
829     H2( "      --dts-compress          Eliminate initial delay with container DTS hack\n" );
830     H0( "\n" );
831     H0( "Filtering:\n" );
832     H0( "\n" );
833     H0( "      --vf, --video-filter <filter0>/<filter1>/... Apply video filtering to the input file\n" );
834     H0( "\n" );
835     H0( "      Filter options may be specified in <filter>:<option>=<value> format.\n" );
836     H0( "\n" );
837     H0( "      Available filters:\n" );
838     x264_register_vid_filters();
839     x264_vid_filter_help( longhelp );
840     H0( "\n" );
841 }
842
843 typedef enum
844 {
845     OPT_FRAMES = 256,
846     OPT_SEEK,
847     OPT_QPFILE,
848     OPT_THREAD_INPUT,
849     OPT_QUIET,
850     OPT_NOPROGRESS,
851     OPT_VISUALIZE,
852     OPT_LONGHELP,
853     OPT_PROFILE,
854     OPT_PRESET,
855     OPT_TUNE,
856     OPT_SLOWFIRSTPASS,
857     OPT_FULLHELP,
858     OPT_FPS,
859     OPT_MUXER,
860     OPT_DEMUXER,
861     OPT_INDEX,
862     OPT_INTERLACED,
863     OPT_TCFILE_IN,
864     OPT_TCFILE_OUT,
865     OPT_TIMEBASE,
866     OPT_PULLDOWN,
867     OPT_LOG_LEVEL,
868     OPT_VIDEO_FILTER,
869     OPT_INPUT_FMT,
870     OPT_INPUT_RES,
871     OPT_INPUT_CSP,
872     OPT_INPUT_DEPTH,
873     OPT_DTS_COMPRESSION,
874     OPT_OUTPUT_CSP,
875     OPT_INPUT_RANGE,
876     OPT_RANGE
877 } OptionsOPT;
878
879 static char short_options[] = "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw";
880 static struct option long_options[] =
881 {
882     { "help",              no_argument, NULL, 'h' },
883     { "longhelp",          no_argument, NULL, OPT_LONGHELP },
884     { "fullhelp",          no_argument, NULL, OPT_FULLHELP },
885     { "version",           no_argument, NULL, 'V' },
886     { "profile",     required_argument, NULL, OPT_PROFILE },
887     { "preset",      required_argument, NULL, OPT_PRESET },
888     { "tune",        required_argument, NULL, OPT_TUNE },
889     { "slow-firstpass",    no_argument, NULL, OPT_SLOWFIRSTPASS },
890     { "bitrate",     required_argument, NULL, 'B' },
891     { "bframes",     required_argument, NULL, 'b' },
892     { "b-adapt",     required_argument, NULL, 0 },
893     { "no-b-adapt",        no_argument, NULL, 0 },
894     { "b-bias",      required_argument, NULL, 0 },
895     { "b-pyramid",   required_argument, NULL, 0 },
896     { "open-gop",          no_argument, NULL, 0 },
897     { "bluray-compat",     no_argument, NULL, 0 },
898     { "min-keyint",  required_argument, NULL, 'i' },
899     { "keyint",      required_argument, NULL, 'I' },
900     { "intra-refresh",     no_argument, NULL, 0 },
901     { "scenecut",    required_argument, NULL, 0 },
902     { "no-scenecut",       no_argument, NULL, 0 },
903     { "nf",                no_argument, NULL, 0 },
904     { "no-deblock",        no_argument, NULL, 0 },
905     { "filter",      required_argument, NULL, 0 },
906     { "deblock",     required_argument, NULL, 'f' },
907     { "interlaced",        no_argument, NULL, OPT_INTERLACED },
908     { "tff",               no_argument, NULL, OPT_INTERLACED },
909     { "bff",               no_argument, NULL, OPT_INTERLACED },
910     { "no-interlaced",     no_argument, NULL, OPT_INTERLACED },
911     { "constrained-intra", no_argument, NULL, 0 },
912     { "cabac",             no_argument, NULL, 0 },
913     { "no-cabac",          no_argument, NULL, 0 },
914     { "qp",          required_argument, NULL, 'q' },
915     { "qpmin",       required_argument, NULL, 0 },
916     { "qpmax",       required_argument, NULL, 0 },
917     { "qpstep",      required_argument, NULL, 0 },
918     { "crf",         required_argument, NULL, 0 },
919     { "rc-lookahead",required_argument, NULL, 0 },
920     { "ref",         required_argument, NULL, 'r' },
921     { "asm",         required_argument, NULL, 0 },
922     { "no-asm",            no_argument, NULL, 0 },
923     { "opencl",            no_argument, NULL, 1 },
924     { "opencl-clbin",required_argument, NULL, 0 },
925     { "opencl-device",required_argument, NULL, 0 },
926     { "sar",         required_argument, NULL, 0 },
927     { "fps",         required_argument, NULL, OPT_FPS },
928     { "frames",      required_argument, NULL, OPT_FRAMES },
929     { "seek",        required_argument, NULL, OPT_SEEK },
930     { "output",      required_argument, NULL, 'o' },
931     { "muxer",       required_argument, NULL, OPT_MUXER },
932     { "demuxer",     required_argument, NULL, OPT_DEMUXER },
933     { "stdout",      required_argument, NULL, OPT_MUXER },
934     { "stdin",       required_argument, NULL, OPT_DEMUXER },
935     { "index",       required_argument, NULL, OPT_INDEX },
936     { "analyse",     required_argument, NULL, 0 },
937     { "partitions",  required_argument, NULL, 'A' },
938     { "direct",      required_argument, NULL, 0 },
939     { "weightb",           no_argument, NULL, 'w' },
940     { "no-weightb",        no_argument, NULL, 0 },
941     { "weightp",     required_argument, NULL, 0 },
942     { "me",          required_argument, NULL, 0 },
943     { "merange",     required_argument, NULL, 0 },
944     { "mvrange",     required_argument, NULL, 0 },
945     { "mvrange-thread", required_argument, NULL, 0 },
946     { "subme",       required_argument, NULL, 'm' },
947     { "psy-rd",      required_argument, NULL, 0 },
948     { "no-psy",            no_argument, NULL, 0 },
949     { "psy",               no_argument, NULL, 0 },
950     { "mixed-refs",        no_argument, NULL, 0 },
951     { "no-mixed-refs",     no_argument, NULL, 0 },
952     { "no-chroma-me",      no_argument, NULL, 0 },
953     { "8x8dct",            no_argument, NULL, '8' },
954     { "no-8x8dct",         no_argument, NULL, 0 },
955     { "trellis",     required_argument, NULL, 't' },
956     { "fast-pskip",        no_argument, NULL, 0 },
957     { "no-fast-pskip",     no_argument, NULL, 0 },
958     { "no-dct-decimate",   no_argument, NULL, 0 },
959     { "aq-strength", required_argument, NULL, 0 },
960     { "aq-mode",     required_argument, NULL, 0 },
961     { "deadzone-inter", required_argument, NULL, 0 },
962     { "deadzone-intra", required_argument, NULL, 0 },
963     { "level",       required_argument, NULL, 0 },
964     { "ratetol",     required_argument, NULL, 0 },
965     { "vbv-maxrate", required_argument, NULL, 0 },
966     { "vbv-bufsize", required_argument, NULL, 0 },
967     { "vbv-init",    required_argument, NULL, 0 },
968     { "crf-max",     required_argument, NULL, 0 },
969     { "ipratio",     required_argument, NULL, 0 },
970     { "pbratio",     required_argument, NULL, 0 },
971     { "chroma-qp-offset", required_argument, NULL, 0 },
972     { "pass",        required_argument, NULL, 'p' },
973     { "stats",       required_argument, NULL, 0 },
974     { "qcomp",       required_argument, NULL, 0 },
975     { "mbtree",            no_argument, NULL, 0 },
976     { "no-mbtree",         no_argument, NULL, 0 },
977     { "qblur",       required_argument, NULL, 0 },
978     { "cplxblur",    required_argument, NULL, 0 },
979     { "zones",       required_argument, NULL, 0 },
980     { "qpfile",      required_argument, NULL, OPT_QPFILE },
981     { "threads",     required_argument, NULL, 0 },
982     { "lookahead-threads", required_argument, NULL, 0 },
983     { "sliced-threads",    no_argument, NULL, 0 },
984     { "no-sliced-threads", no_argument, NULL, 0 },
985     { "slice-max-size",    required_argument, NULL, 0 },
986     { "slice-max-mbs",     required_argument, NULL, 0 },
987     { "slice-min-mbs",     required_argument, NULL, 0 },
988     { "slices",            required_argument, NULL, 0 },
989     { "slices-max",        required_argument, NULL, 0 },
990     { "thread-input",      no_argument, NULL, OPT_THREAD_INPUT },
991     { "sync-lookahead",    required_argument, NULL, 0 },
992     { "non-deterministic", no_argument, NULL, 0 },
993     { "cpu-independent",   no_argument, NULL, 0 },
994     { "psnr",              no_argument, NULL, 0 },
995     { "ssim",              no_argument, NULL, 0 },
996     { "quiet",             no_argument, NULL, OPT_QUIET },
997     { "verbose",           no_argument, NULL, 'v' },
998     { "log-level",   required_argument, NULL, OPT_LOG_LEVEL },
999     { "no-progress",       no_argument, NULL, OPT_NOPROGRESS },
1000     { "visualize",         no_argument, NULL, OPT_VISUALIZE },
1001     { "dump-yuv",    required_argument, NULL, 0 },
1002     { "sps-id",      required_argument, NULL, 0 },
1003     { "aud",               no_argument, NULL, 0 },
1004     { "nr",          required_argument, NULL, 0 },
1005     { "cqm",         required_argument, NULL, 0 },
1006     { "cqmfile",     required_argument, NULL, 0 },
1007     { "cqm4",        required_argument, NULL, 0 },
1008     { "cqm4i",       required_argument, NULL, 0 },
1009     { "cqm4iy",      required_argument, NULL, 0 },
1010     { "cqm4ic",      required_argument, NULL, 0 },
1011     { "cqm4p",       required_argument, NULL, 0 },
1012     { "cqm4py",      required_argument, NULL, 0 },
1013     { "cqm4pc",      required_argument, NULL, 0 },
1014     { "cqm8",        required_argument, NULL, 0 },
1015     { "cqm8i",       required_argument, NULL, 0 },
1016     { "cqm8p",       required_argument, NULL, 0 },
1017     { "overscan",    required_argument, NULL, 0 },
1018     { "videoformat", required_argument, NULL, 0 },
1019     { "range",       required_argument, NULL, OPT_RANGE },
1020     { "colorprim",   required_argument, NULL, 0 },
1021     { "transfer",    required_argument, NULL, 0 },
1022     { "colormatrix", required_argument, NULL, 0 },
1023     { "chromaloc",   required_argument, NULL, 0 },
1024     { "force-cfr",         no_argument, NULL, 0 },
1025     { "tcfile-in",   required_argument, NULL, OPT_TCFILE_IN },
1026     { "tcfile-out",  required_argument, NULL, OPT_TCFILE_OUT },
1027     { "timebase",    required_argument, NULL, OPT_TIMEBASE },
1028     { "pic-struct",        no_argument, NULL, 0 },
1029     { "crop-rect",   required_argument, NULL, 0 },
1030     { "nal-hrd",     required_argument, NULL, 0 },
1031     { "pulldown",    required_argument, NULL, OPT_PULLDOWN },
1032     { "fake-interlaced",   no_argument, NULL, 0 },
1033     { "frame-packing",     required_argument, NULL, 0 },
1034     { "vf",          required_argument, NULL, OPT_VIDEO_FILTER },
1035     { "video-filter", required_argument, NULL, OPT_VIDEO_FILTER },
1036     { "input-fmt",   required_argument, NULL, OPT_INPUT_FMT },
1037     { "input-res",   required_argument, NULL, OPT_INPUT_RES },
1038     { "input-csp",   required_argument, NULL, OPT_INPUT_CSP },
1039     { "input-depth", required_argument, NULL, OPT_INPUT_DEPTH },
1040     { "dts-compress",      no_argument, NULL, OPT_DTS_COMPRESSION },
1041     { "output-csp",  required_argument, NULL, OPT_OUTPUT_CSP },
1042     { "input-range", required_argument, NULL, OPT_INPUT_RANGE },
1043     { "stitchable",        no_argument, NULL, 0 },
1044     {0, 0, 0, 0}
1045 };
1046
1047 static int select_output( const char *muxer, char *filename, x264_param_t *param )
1048 {
1049     const char *ext = get_filename_extension( filename );
1050     if( !strcmp( filename, "-" ) || strcasecmp( muxer, "auto" ) )
1051         ext = muxer;
1052
1053     if( !strcasecmp( ext, "mp4" ) )
1054     {
1055 #if HAVE_GPAC
1056         cli_output = mp4_output;
1057         param->b_annexb = 0;
1058         param->b_repeat_headers = 0;
1059         if( param->i_nal_hrd == X264_NAL_HRD_CBR )
1060         {
1061             x264_cli_log( "x264", X264_LOG_WARNING, "cbr nal-hrd is not compatible with mp4\n" );
1062             param->i_nal_hrd = X264_NAL_HRD_VBR;
1063         }
1064 #else
1065         x264_cli_log( "x264", X264_LOG_ERROR, "not compiled with MP4 output support\n" );
1066         return -1;
1067 #endif
1068     }
1069     else if( !strcasecmp( ext, "mkv" ) )
1070     {
1071         cli_output = mkv_output;
1072         param->b_annexb = 0;
1073         param->b_repeat_headers = 0;
1074     }
1075     else if( !strcasecmp( ext, "flv" ) )
1076     {
1077         cli_output = flv_output;
1078         param->b_annexb = 0;
1079         param->b_repeat_headers = 0;
1080     }
1081     else
1082         cli_output = raw_output;
1083     return 0;
1084 }
1085
1086 static int select_input( const char *demuxer, char *used_demuxer, char *filename,
1087                          hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
1088 {
1089     int b_auto = !strcasecmp( demuxer, "auto" );
1090     const char *ext = b_auto ? get_filename_extension( filename ) : "";
1091     int b_regular = strcmp( filename, "-" );
1092     if( !b_regular && b_auto )
1093         ext = "raw";
1094     b_regular = b_regular && x264_is_regular_file_path( filename );
1095     if( b_regular )
1096     {
1097         FILE *f = fopen( filename, "r" );
1098         if( f )
1099         {
1100             b_regular = x264_is_regular_file( f );
1101             fclose( f );
1102         }
1103     }
1104     const char *module = b_auto ? ext : demuxer;
1105
1106     if( !strcasecmp( module, "avs" ) || !strcasecmp( ext, "d2v" ) || !strcasecmp( ext, "dga" ) )
1107     {
1108 #if HAVE_AVS
1109         cli_input = avs_input;
1110         module = "avs";
1111 #else
1112         x264_cli_log( "x264", X264_LOG_ERROR, "not compiled with AVS input support\n" );
1113         return -1;
1114 #endif
1115     }
1116     else if( !strcasecmp( module, "y4m" ) )
1117         cli_input = y4m_input;
1118     else if( !strcasecmp( module, "raw" ) || !strcasecmp( ext, "yuv" ) )
1119         cli_input = raw_input;
1120     else
1121     {
1122 #if HAVE_FFMS
1123         if( b_regular && (b_auto || !strcasecmp( demuxer, "ffms" )) &&
1124             !ffms_input.open_file( filename, p_handle, info, opt ) )
1125         {
1126             module = "ffms";
1127             b_auto = 0;
1128             cli_input = ffms_input;
1129         }
1130 #endif
1131 #if HAVE_LAVF
1132         if( (b_auto || !strcasecmp( demuxer, "lavf" )) &&
1133             !lavf_input.open_file( filename, p_handle, info, opt ) )
1134         {
1135             module = "lavf";
1136             b_auto = 0;
1137             cli_input = lavf_input;
1138         }
1139 #endif
1140 #if HAVE_AVS
1141         if( b_regular && (b_auto || !strcasecmp( demuxer, "avs" )) &&
1142             !avs_input.open_file( filename, p_handle, info, opt ) )
1143         {
1144             module = "avs";
1145             b_auto = 0;
1146             cli_input = avs_input;
1147         }
1148 #endif
1149         if( b_auto && !raw_input.open_file( filename, p_handle, info, opt ) )
1150         {
1151             module = "raw";
1152             b_auto = 0;
1153             cli_input = raw_input;
1154         }
1155
1156         FAIL_IF_ERROR( !(*p_handle), "could not open input file `%s' via any method!\n", filename )
1157     }
1158     strcpy( used_demuxer, module );
1159
1160     return 0;
1161 }
1162
1163 static int init_vid_filters( char *sequence, hnd_t *handle, video_info_t *info, x264_param_t *param, int output_csp )
1164 {
1165     x264_register_vid_filters();
1166
1167     /* intialize baseline filters */
1168     if( x264_init_vid_filter( "source", handle, &filter, info, param, NULL ) ) /* wrap demuxer into a filter */
1169         return -1;
1170     if( x264_init_vid_filter( "resize", handle, &filter, info, param, "normcsp" ) ) /* normalize csps to be of a known/supported format */
1171         return -1;
1172     if( x264_init_vid_filter( "fix_vfr_pts", handle, &filter, info, param, NULL ) ) /* fix vfr pts */
1173         return -1;
1174
1175     /* parse filter chain */
1176     for( char *p = sequence; p && *p; )
1177     {
1178         int tok_len = strcspn( p, "/" );
1179         int p_len = strlen( p );
1180         p[tok_len] = 0;
1181         int name_len = strcspn( p, ":" );
1182         p[name_len] = 0;
1183         name_len += name_len != tok_len;
1184         if( x264_init_vid_filter( p, handle, &filter, info, param, p + name_len ) )
1185             return -1;
1186         p += X264_MIN( tok_len+1, p_len );
1187     }
1188
1189     /* force end result resolution */
1190     if( !param->i_width && !param->i_height )
1191     {
1192         param->i_height = info->height;
1193         param->i_width  = info->width;
1194     }
1195     /* force the output csp to what the user specified (or the default) */
1196     param->i_csp = info->csp;
1197     int csp = info->csp & X264_CSP_MASK;
1198     if( output_csp == X264_CSP_I420 && (csp < X264_CSP_I420 || csp > X264_CSP_NV12) )
1199         param->i_csp = X264_CSP_I420;
1200     else if( output_csp == X264_CSP_I422 && (csp < X264_CSP_I422 || csp > X264_CSP_NV16) )
1201         param->i_csp = X264_CSP_I422;
1202     else if( output_csp == X264_CSP_I444 && (csp < X264_CSP_I444 || csp > X264_CSP_YV24) )
1203         param->i_csp = X264_CSP_I444;
1204     else if( output_csp == X264_CSP_RGB && (csp < X264_CSP_BGR || csp > X264_CSP_RGB) )
1205         param->i_csp = X264_CSP_RGB;
1206     param->i_csp |= info->csp & X264_CSP_HIGH_DEPTH;
1207     /* if the output range is not forced, assign it to the input one now */
1208     if( param->vui.b_fullrange == RANGE_AUTO )
1209         param->vui.b_fullrange = info->fullrange;
1210
1211     if( x264_init_vid_filter( "resize", handle, &filter, info, param, NULL ) )
1212         return -1;
1213
1214     char args[20];
1215     sprintf( args, "bit_depth=%d", x264_bit_depth );
1216
1217     if( x264_init_vid_filter( "depth", handle, &filter, info, param, args ) )
1218         return -1;
1219
1220     return 0;
1221 }
1222
1223 static int parse_enum_name( const char *arg, const char * const *names, const char **dst )
1224 {
1225     for( int i = 0; names[i]; i++ )
1226         if( !strcasecmp( arg, names[i] ) )
1227         {
1228             *dst = names[i];
1229             return 0;
1230         }
1231     return -1;
1232 }
1233
1234 static int parse_enum_value( const char *arg, const char * const *names, int *dst )
1235 {
1236     for( int i = 0; names[i]; i++ )
1237         if( !strcasecmp( arg, names[i] ) )
1238         {
1239             *dst = i;
1240             return 0;
1241         }
1242     return -1;
1243 }
1244
1245 static int parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt )
1246 {
1247     char *input_filename = NULL;
1248     const char *demuxer = demuxer_names[0];
1249     char *output_filename = NULL;
1250     const char *muxer = muxer_names[0];
1251     char *tcfile_name = NULL;
1252     x264_param_t defaults;
1253     char *profile = NULL;
1254     char *vid_filters = NULL;
1255     int b_thread_input = 0;
1256     int b_turbo = 1;
1257     int b_user_ref = 0;
1258     int b_user_fps = 0;
1259     int b_user_interlaced = 0;
1260     cli_input_opt_t input_opt;
1261     cli_output_opt_t output_opt;
1262     char *preset = NULL;
1263     char *tune = NULL;
1264
1265     x264_param_default( &defaults );
1266     cli_log_level = defaults.i_log_level;
1267
1268     memset( &input_opt, 0, sizeof(cli_input_opt_t) );
1269     memset( &output_opt, 0, sizeof(cli_output_opt_t) );
1270     input_opt.bit_depth = 8;
1271     input_opt.input_range = input_opt.output_range = param->vui.b_fullrange = RANGE_AUTO;
1272     int output_csp = defaults.i_csp;
1273     opt->b_progress = 1;
1274
1275     /* Presets are applied before all other options. */
1276     for( optind = 0;; )
1277     {
1278         int c = getopt_long( argc, argv, short_options, long_options, NULL );
1279         if( c == -1 )
1280             break;
1281         if( c == OPT_PRESET )
1282             preset = optarg;
1283         if( c == OPT_TUNE )
1284             tune = optarg;
1285         else if( c == '?' )
1286             return -1;
1287     }
1288
1289     if( preset && !strcasecmp( preset, "placebo" ) )
1290         b_turbo = 0;
1291
1292     if( x264_param_default_preset( param, preset, tune ) < 0 )
1293         return -1;
1294
1295     /* Parse command line options */
1296     for( optind = 0;; )
1297     {
1298         int b_error = 0;
1299         int long_options_index = -1;
1300
1301         int c = getopt_long( argc, argv, short_options, long_options, &long_options_index );
1302
1303         if( c == -1 )
1304         {
1305             break;
1306         }
1307
1308         switch( c )
1309         {
1310             case 'h':
1311                 help( &defaults, 0 );
1312                 exit(0);
1313             case OPT_LONGHELP:
1314                 help( &defaults, 1 );
1315                 exit(0);
1316             case OPT_FULLHELP:
1317                 help( &defaults, 2 );
1318                 exit(0);
1319             case 'V':
1320                 print_version_info();
1321                 exit(0);
1322             case OPT_FRAMES:
1323                 param->i_frame_total = X264_MAX( atoi( optarg ), 0 );
1324                 break;
1325             case OPT_SEEK:
1326                 opt->i_seek = X264_MAX( atoi( optarg ), 0 );
1327                 break;
1328             case 'o':
1329                 output_filename = optarg;
1330                 break;
1331             case OPT_MUXER:
1332                 FAIL_IF_ERROR( parse_enum_name( optarg, muxer_names, &muxer ), "Unknown muxer `%s'\n", optarg )
1333                 break;
1334             case OPT_DEMUXER:
1335                 FAIL_IF_ERROR( parse_enum_name( optarg, demuxer_names, &demuxer ), "Unknown demuxer `%s'\n", optarg )
1336                 break;
1337             case OPT_INDEX:
1338                 input_opt.index_file = optarg;
1339                 break;
1340             case OPT_QPFILE:
1341                 opt->qpfile = fopen( optarg, "rb" );
1342                 FAIL_IF_ERROR( !opt->qpfile, "can't open qpfile `%s'\n", optarg )
1343                 if( !x264_is_regular_file( opt->qpfile ) )
1344                 {
1345                     x264_cli_log( "x264", X264_LOG_ERROR, "qpfile incompatible with non-regular file `%s'\n", optarg );
1346                     fclose( opt->qpfile );
1347                     return -1;
1348                 }
1349                 break;
1350             case OPT_THREAD_INPUT:
1351                 b_thread_input = 1;
1352                 break;
1353             case OPT_QUIET:
1354                 cli_log_level = param->i_log_level = X264_LOG_NONE;
1355                 break;
1356             case 'v':
1357                 cli_log_level = param->i_log_level = X264_LOG_DEBUG;
1358                 break;
1359             case OPT_LOG_LEVEL:
1360                 if( !parse_enum_value( optarg, log_level_names, &cli_log_level ) )
1361                     cli_log_level += X264_LOG_NONE;
1362                 else
1363                     cli_log_level = atoi( optarg );
1364                 param->i_log_level = cli_log_level;
1365                 break;
1366             case OPT_NOPROGRESS:
1367                 opt->b_progress = 0;
1368                 break;
1369             case OPT_VISUALIZE:
1370 #if HAVE_VISUALIZE
1371                 param->b_visualize = 1;
1372                 b_exit_on_ctrl_c = 1;
1373 #else
1374                 x264_cli_log( "x264", X264_LOG_WARNING, "not compiled with visualization support\n" );
1375 #endif
1376                 break;
1377             case OPT_TUNE:
1378             case OPT_PRESET:
1379                 break;
1380             case OPT_PROFILE:
1381                 profile = optarg;
1382                 break;
1383             case OPT_SLOWFIRSTPASS:
1384                 b_turbo = 0;
1385                 break;
1386             case 'r':
1387                 b_user_ref = 1;
1388                 goto generic_option;
1389             case OPT_FPS:
1390                 b_user_fps = 1;
1391                 param->b_vfr_input = 0;
1392                 goto generic_option;
1393             case OPT_INTERLACED:
1394                 b_user_interlaced = 1;
1395                 goto generic_option;
1396             case OPT_TCFILE_IN:
1397                 tcfile_name = optarg;
1398                 break;
1399             case OPT_TCFILE_OUT:
1400                 opt->tcfile_out = fopen( optarg, "wb" );
1401                 FAIL_IF_ERROR( !opt->tcfile_out, "can't open `%s'\n", optarg )
1402                 break;
1403             case OPT_TIMEBASE:
1404                 input_opt.timebase = optarg;
1405                 break;
1406             case OPT_PULLDOWN:
1407                 FAIL_IF_ERROR( parse_enum_value( optarg, pulldown_names, &opt->i_pulldown ), "Unknown pulldown `%s'\n", optarg )
1408                 break;
1409             case OPT_VIDEO_FILTER:
1410                 vid_filters = optarg;
1411                 break;
1412             case OPT_INPUT_FMT:
1413                 input_opt.format = optarg;
1414                 break;
1415             case OPT_INPUT_RES:
1416                 input_opt.resolution = optarg;
1417                 break;
1418             case OPT_INPUT_CSP:
1419                 input_opt.colorspace = optarg;
1420                 break;
1421             case OPT_INPUT_DEPTH:
1422                 input_opt.bit_depth = atoi( optarg );
1423                 break;
1424             case OPT_DTS_COMPRESSION:
1425                 output_opt.use_dts_compress = 1;
1426                 break;
1427             case OPT_OUTPUT_CSP:
1428                 FAIL_IF_ERROR( parse_enum_value( optarg, output_csp_names, &output_csp ), "Unknown output csp `%s'\n", optarg )
1429                 // correct the parsed value to the libx264 csp value
1430 #if X264_CHROMA_FORMAT
1431                 static const uint8_t output_csp_fix[] = { X264_CHROMA_FORMAT, X264_CSP_RGB };
1432 #else
1433                 static const uint8_t output_csp_fix[] = { X264_CSP_I420, X264_CSP_I422, X264_CSP_I444, X264_CSP_RGB };
1434 #endif
1435                 param->i_csp = output_csp = output_csp_fix[output_csp];
1436                 break;
1437             case OPT_INPUT_RANGE:
1438                 FAIL_IF_ERROR( parse_enum_value( optarg, range_names, &input_opt.input_range ), "Unknown input range `%s'\n", optarg )
1439                 input_opt.input_range += RANGE_AUTO;
1440                 break;
1441             case OPT_RANGE:
1442                 FAIL_IF_ERROR( parse_enum_value( optarg, range_names, &param->vui.b_fullrange ), "Unknown range `%s'\n", optarg );
1443                 input_opt.output_range = param->vui.b_fullrange += RANGE_AUTO;
1444                 break;
1445             default:
1446 generic_option:
1447             {
1448                 if( long_options_index < 0 )
1449                 {
1450                     for( int i = 0; long_options[i].name; i++ )
1451                         if( long_options[i].val == c )
1452                         {
1453                             long_options_index = i;
1454                             break;
1455                         }
1456                     if( long_options_index < 0 )
1457                     {
1458                         /* getopt_long already printed an error message */
1459                         return -1;
1460                     }
1461                 }
1462
1463                 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
1464             }
1465         }
1466
1467         if( b_error )
1468         {
1469             const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
1470             x264_cli_log( "x264", X264_LOG_ERROR, "invalid argument: %s = %s\n", name, optarg );
1471             return -1;
1472         }
1473     }
1474
1475     /* If first pass mode is used, apply faster settings. */
1476     if( b_turbo )
1477         x264_param_apply_fastfirstpass( param );
1478
1479     /* Apply profile restrictions. */
1480     if( x264_param_apply_profile( param, profile ) < 0 )
1481         return -1;
1482
1483     /* Get the file name */
1484     FAIL_IF_ERROR( optind > argc - 1 || !output_filename, "No %s file. Run x264 --help for a list of options.\n",
1485                    optind > argc - 1 ? "input" : "output" )
1486
1487     if( select_output( muxer, output_filename, param ) )
1488         return -1;
1489     FAIL_IF_ERROR( cli_output.open_file( output_filename, &opt->hout, &output_opt ), "could not open output file `%s'\n", output_filename )
1490
1491     input_filename = argv[optind++];
1492     video_info_t info = {0};
1493     char demuxername[5];
1494
1495     /* set info flags to be overwritten by demuxer as necessary. */
1496     info.csp        = param->i_csp;
1497     info.fps_num    = param->i_fps_num;
1498     info.fps_den    = param->i_fps_den;
1499     info.fullrange  = input_opt.input_range == RANGE_PC;
1500     info.interlaced = param->b_interlaced;
1501     info.sar_width  = param->vui.i_sar_width;
1502     info.sar_height = param->vui.i_sar_height;
1503     info.tff        = param->b_tff;
1504     info.vfr        = param->b_vfr_input;
1505
1506     input_opt.seek = opt->i_seek;
1507     input_opt.progress = opt->b_progress;
1508     input_opt.output_csp = output_csp;
1509
1510     if( select_input( demuxer, demuxername, input_filename, &opt->hin, &info, &input_opt ) )
1511         return -1;
1512
1513     FAIL_IF_ERROR( !opt->hin && cli_input.open_file( input_filename, &opt->hin, &info, &input_opt ),
1514                    "could not open input file `%s'\n", input_filename )
1515
1516     x264_reduce_fraction( &info.sar_width, &info.sar_height );
1517     x264_reduce_fraction( &info.fps_num, &info.fps_den );
1518     x264_cli_log( demuxername, X264_LOG_INFO, "%dx%d%c %u:%u @ %u/%u fps (%cfr)\n", info.width,
1519                   info.height, info.interlaced ? 'i' : 'p', info.sar_width, info.sar_height,
1520                   info.fps_num, info.fps_den, info.vfr ? 'v' : 'c' );
1521
1522     if( tcfile_name )
1523     {
1524         FAIL_IF_ERROR( b_user_fps, "--fps + --tcfile-in is incompatible.\n" )
1525         FAIL_IF_ERROR( timecode_input.open_file( tcfile_name, &opt->hin, &info, &input_opt ), "timecode input failed\n" )
1526         cli_input = timecode_input;
1527     }
1528     else FAIL_IF_ERROR( !info.vfr && input_opt.timebase, "--timebase is incompatible with cfr input\n" )
1529
1530     /* init threaded input while the information about the input video is unaltered by filtering */
1531 #if HAVE_THREAD
1532     if( info.thread_safe && (b_thread_input || param->i_threads > 1
1533         || (param->i_threads == X264_THREADS_AUTO && x264_cpu_num_processors() > 1)) )
1534     {
1535         if( thread_input.open_file( NULL, &opt->hin, &info, NULL ) )
1536         {
1537             fprintf( stderr, "x264 [error]: threaded input failed\n" );
1538             return -1;
1539         }
1540         cli_input = thread_input;
1541     }
1542 #endif
1543
1544     /* override detected values by those specified by the user */
1545     if( param->vui.i_sar_width && param->vui.i_sar_height )
1546     {
1547         info.sar_width  = param->vui.i_sar_width;
1548         info.sar_height = param->vui.i_sar_height;
1549     }
1550     if( b_user_fps )
1551     {
1552         info.fps_num = param->i_fps_num;
1553         info.fps_den = param->i_fps_den;
1554     }
1555     if( !info.vfr )
1556     {
1557         info.timebase_num = info.fps_den;
1558         info.timebase_den = info.fps_num;
1559     }
1560     if( !tcfile_name && input_opt.timebase )
1561     {
1562         uint64_t i_user_timebase_num;
1563         uint64_t i_user_timebase_den;
1564         int ret = sscanf( input_opt.timebase, "%"SCNu64"/%"SCNu64, &i_user_timebase_num, &i_user_timebase_den );
1565         FAIL_IF_ERROR( !ret, "invalid argument: timebase = %s\n", input_opt.timebase )
1566         else if( ret == 1 )
1567         {
1568             i_user_timebase_num = info.timebase_num;
1569             i_user_timebase_den = strtoul( input_opt.timebase, NULL, 10 );
1570         }
1571         FAIL_IF_ERROR( i_user_timebase_num > UINT32_MAX || i_user_timebase_den > UINT32_MAX,
1572                        "timebase you specified exceeds H.264 maximum\n" )
1573         opt->timebase_convert_multiplier = ((double)i_user_timebase_den / info.timebase_den)
1574                                          * ((double)info.timebase_num / i_user_timebase_num);
1575         info.timebase_num = i_user_timebase_num;
1576         info.timebase_den = i_user_timebase_den;
1577         info.vfr = 1;
1578     }
1579     if( b_user_interlaced )
1580     {
1581         info.interlaced = param->b_interlaced;
1582         info.tff = param->b_tff;
1583     }
1584     if( input_opt.input_range != RANGE_AUTO )
1585         info.fullrange = input_opt.input_range;
1586
1587     if( init_vid_filters( vid_filters, &opt->hin, &info, param, output_csp ) )
1588         return -1;
1589
1590     /* set param flags from the post-filtered video */
1591     param->b_vfr_input = info.vfr;
1592     param->i_fps_num = info.fps_num;
1593     param->i_fps_den = info.fps_den;
1594     param->i_timebase_num = info.timebase_num;
1595     param->i_timebase_den = info.timebase_den;
1596     param->vui.i_sar_width  = info.sar_width;
1597     param->vui.i_sar_height = info.sar_height;
1598
1599     info.num_frames = X264_MAX( info.num_frames - opt->i_seek, 0 );
1600     if( (!info.num_frames || param->i_frame_total < info.num_frames)
1601         && param->i_frame_total > 0 )
1602         info.num_frames = param->i_frame_total;
1603     param->i_frame_total = info.num_frames;
1604
1605     if( !b_user_interlaced && info.interlaced )
1606     {
1607 #if HAVE_INTERLACED
1608         x264_cli_log( "x264", X264_LOG_WARNING, "input appears to be interlaced, enabling %cff interlaced mode.\n"
1609                       "                If you want otherwise, use --no-interlaced or --%cff\n",
1610                       info.tff ? 't' : 'b', info.tff ? 'b' : 't' );
1611         param->b_interlaced = 1;
1612         param->b_tff = !!info.tff;
1613 #else
1614         x264_cli_log( "x264", X264_LOG_WARNING, "input appears to be interlaced, but not compiled with interlaced support\n" );
1615 #endif
1616     }
1617     /* if the user never specified the output range and the input is now rgb, default it to pc */
1618     int csp = param->i_csp & X264_CSP_MASK;
1619     if( csp >= X264_CSP_BGR && csp <= X264_CSP_RGB )
1620     {
1621         if( input_opt.output_range == RANGE_AUTO )
1622             param->vui.b_fullrange = RANGE_PC;
1623         /* otherwise fail if they specified tv */
1624         FAIL_IF_ERROR( !param->vui.b_fullrange, "RGB must be PC range" )
1625     }
1626
1627     /* Automatically reduce reference frame count to match the user's target level
1628      * if the user didn't explicitly set a reference frame count. */
1629     if( !b_user_ref )
1630     {
1631         int mbs = (((param->i_width)+15)>>4) * (((param->i_height)+15)>>4);
1632         for( int i = 0; x264_levels[i].level_idc != 0; i++ )
1633             if( param->i_level_idc == x264_levels[i].level_idc )
1634             {
1635                 while( mbs * param->i_frame_reference > x264_levels[i].dpb && param->i_frame_reference > 1 )
1636                     param->i_frame_reference--;
1637                 break;
1638             }
1639     }
1640
1641
1642     return 0;
1643 }
1644
1645 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
1646 {
1647     int num = -1, qp, ret;
1648     char type;
1649     uint64_t file_pos;
1650     while( num < i_frame )
1651     {
1652         file_pos = ftell( opt->qpfile );
1653         qp = -1;
1654         ret = fscanf( opt->qpfile, "%d %c%*[ \t]%d\n", &num, &type, &qp );
1655         pic->i_type = X264_TYPE_AUTO;
1656         pic->i_qpplus1 = X264_QP_AUTO;
1657         if( num > i_frame || ret == EOF )
1658         {
1659             fseek( opt->qpfile, file_pos, SEEK_SET );
1660             break;
1661         }
1662         if( num < i_frame && ret >= 2 )
1663             continue;
1664         if( ret == 3 && qp >= 0 )
1665             pic->i_qpplus1 = qp+1;
1666         if     ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
1667         else if( type == 'i' ) pic->i_type = X264_TYPE_I;
1668         else if( type == 'K' ) pic->i_type = X264_TYPE_KEYFRAME;
1669         else if( type == 'P' ) pic->i_type = X264_TYPE_P;
1670         else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
1671         else if( type == 'b' ) pic->i_type = X264_TYPE_B;
1672         else ret = 0;
1673         if( ret < 2 || qp < -1 || qp > QP_MAX )
1674         {
1675             x264_cli_log( "x264", X264_LOG_ERROR, "can't parse qpfile for frame %d\n", i_frame );
1676             fclose( opt->qpfile );
1677             opt->qpfile = NULL;
1678             break;
1679         }
1680     }
1681 }
1682
1683 static int encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic, int64_t *last_dts )
1684 {
1685     x264_picture_t pic_out;
1686     x264_nal_t *nal;
1687     int i_nal;
1688     int i_frame_size = 0;
1689
1690     i_frame_size = x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out );
1691
1692     FAIL_IF_ERROR( i_frame_size < 0, "x264_encoder_encode failed\n" );
1693
1694     if( i_frame_size )
1695     {
1696         i_frame_size = cli_output.write_frame( hout, nal[0].p_payload, i_frame_size, &pic_out );
1697         *last_dts = pic_out.i_dts;
1698     }
1699
1700     return i_frame_size;
1701 }
1702
1703 static int64_t print_status( int64_t i_start, int64_t i_previous, int i_frame, int i_frame_total, int64_t i_file, x264_param_t *param, int64_t last_ts )
1704 {
1705     char buf[200];
1706     int64_t i_time = x264_mdate();
1707     if( i_previous && i_time - i_previous < UPDATE_INTERVAL )
1708         return i_previous;
1709     int64_t i_elapsed = i_time - i_start;
1710     double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1711     double bitrate;
1712     if( last_ts )
1713         bitrate = (double) i_file * 8 / ( (double) last_ts * 1000 * param->i_timebase_num / param->i_timebase_den );
1714     else
1715         bitrate = (double) i_file * 8 / ( (double) 1000 * param->i_fps_den / param->i_fps_num );
1716     if( i_frame_total )
1717     {
1718         int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1719         sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
1720                  100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
1721                  eta/3600, (eta/60)%60, eta%60 );
1722     }
1723     else
1724     {
1725         sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
1726     }
1727     fprintf( stderr, "%s  \r", buf+5 );
1728     SetConsoleTitle( buf );
1729     fflush( stderr ); // needed in windows
1730     return i_time;
1731 }
1732
1733 static void convert_cli_to_lib_pic( x264_picture_t *lib, cli_pic_t *cli )
1734 {
1735     memcpy( lib->img.i_stride, cli->img.stride, sizeof(cli->img.stride) );
1736     memcpy( lib->img.plane, cli->img.plane, sizeof(cli->img.plane) );
1737     lib->img.i_plane = cli->img.planes;
1738     lib->img.i_csp = cli->img.csp;
1739     lib->i_pts = cli->pts;
1740 }
1741
1742 #define FAIL_IF_ERROR2( cond, ... )\
1743 if( cond )\
1744 {\
1745     x264_cli_log( "x264", X264_LOG_ERROR, __VA_ARGS__ );\
1746     retval = -1;\
1747     goto fail;\
1748 }
1749
1750 static int encode( x264_param_t *param, cli_opt_t *opt )
1751 {
1752     x264_t *h = NULL;
1753     x264_picture_t pic;
1754     cli_pic_t cli_pic;
1755     const cli_pulldown_t *pulldown = NULL; // shut up gcc
1756
1757     int     i_frame = 0;
1758     int     i_frame_output = 0;
1759     int64_t i_end, i_previous = 0, i_start = 0;
1760     int64_t i_file = 0;
1761     int     i_frame_size;
1762     int64_t last_dts = 0;
1763     int64_t prev_dts = 0;
1764     int64_t first_dts = 0;
1765 #   define  MAX_PTS_WARNING 3 /* arbitrary */
1766     int     pts_warning_cnt = 0;
1767     int64_t largest_pts = -1;
1768     int64_t second_largest_pts = -1;
1769     int64_t ticks_per_frame;
1770     double  duration;
1771     double  pulldown_pts = 0;
1772     int     retval = 0;
1773
1774     opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
1775
1776     /* set up pulldown */
1777     if( opt->i_pulldown && !param->b_vfr_input )
1778     {
1779         param->b_pulldown = 1;
1780         param->b_pic_struct = 1;
1781         pulldown = &pulldown_values[opt->i_pulldown];
1782         param->i_timebase_num = param->i_fps_den;
1783         FAIL_IF_ERROR2( fmod( param->i_fps_num * pulldown->fps_factor, 1 ),
1784                         "unsupported framerate for chosen pulldown\n" )
1785         param->i_timebase_den = param->i_fps_num * pulldown->fps_factor;
1786     }
1787
1788     h = x264_encoder_open( param );
1789     FAIL_IF_ERROR2( !h, "x264_encoder_open failed\n" );
1790
1791     x264_encoder_parameters( h, param );
1792
1793     FAIL_IF_ERROR2( cli_output.set_param( opt->hout, param ), "can't set outfile param\n" );
1794
1795     i_start = x264_mdate();
1796
1797     /* ticks/frame = ticks/second / frames/second */
1798     ticks_per_frame = (int64_t)param->i_timebase_den * param->i_fps_den / param->i_timebase_num / param->i_fps_num;
1799     FAIL_IF_ERROR2( ticks_per_frame < 1 && !param->b_vfr_input, "ticks_per_frame invalid: %"PRId64"\n", ticks_per_frame )
1800     ticks_per_frame = X264_MAX( ticks_per_frame, 1 );
1801
1802     if( !param->b_repeat_headers )
1803     {
1804         // Write SPS/PPS/SEI
1805         x264_nal_t *headers;
1806         int i_nal;
1807
1808         FAIL_IF_ERROR2( x264_encoder_headers( h, &headers, &i_nal ) < 0, "x264_encoder_headers failed\n" )
1809         FAIL_IF_ERROR2( (i_file = cli_output.write_headers( opt->hout, headers )) < 0, "error writing headers to output file\n" );
1810     }
1811
1812     if( opt->tcfile_out )
1813         fprintf( opt->tcfile_out, "# timecode format v2\n" );
1814
1815     /* Encode frames */
1816     for( ; !b_ctrl_c && (i_frame < param->i_frame_total || !param->i_frame_total); i_frame++ )
1817     {
1818         if( filter.get_frame( opt->hin, &cli_pic, i_frame + opt->i_seek ) )
1819             break;
1820         x264_picture_init( &pic );
1821         convert_cli_to_lib_pic( &pic, &cli_pic );
1822
1823         if( !param->b_vfr_input )
1824             pic.i_pts = i_frame;
1825
1826         if( opt->i_pulldown && !param->b_vfr_input )
1827         {
1828             pic.i_pic_struct = pulldown->pattern[ i_frame % pulldown->mod ];
1829             pic.i_pts = (int64_t)( pulldown_pts + 0.5 );
1830             pulldown_pts += pulldown_frame_duration[pic.i_pic_struct];
1831         }
1832         else if( opt->timebase_convert_multiplier )
1833             pic.i_pts = (int64_t)( pic.i_pts * opt->timebase_convert_multiplier + 0.5 );
1834
1835         if( pic.i_pts <= largest_pts )
1836         {
1837             if( cli_log_level >= X264_LOG_DEBUG || pts_warning_cnt < MAX_PTS_WARNING )
1838                 x264_cli_log( "x264", X264_LOG_WARNING, "non-strictly-monotonic pts at frame %d (%"PRId64" <= %"PRId64")\n",
1839                              i_frame, pic.i_pts, largest_pts );
1840             else if( pts_warning_cnt == MAX_PTS_WARNING )
1841                 x264_cli_log( "x264", X264_LOG_WARNING, "too many nonmonotonic pts warnings, suppressing further ones\n" );
1842             pts_warning_cnt++;
1843             pic.i_pts = largest_pts + ticks_per_frame;
1844         }
1845
1846         second_largest_pts = largest_pts;
1847         largest_pts = pic.i_pts;
1848         if( opt->tcfile_out )
1849             fprintf( opt->tcfile_out, "%.6f\n", pic.i_pts * ((double)param->i_timebase_num / param->i_timebase_den) * 1e3 );
1850
1851         if( opt->qpfile )
1852             parse_qpfile( opt, &pic, i_frame + opt->i_seek );
1853
1854         prev_dts = last_dts;
1855         i_frame_size = encode_frame( h, opt->hout, &pic, &last_dts );
1856         if( i_frame_size < 0 )
1857         {
1858             b_ctrl_c = 1; /* lie to exit the loop */
1859             retval = -1;
1860         }
1861         else if( i_frame_size )
1862         {
1863             i_file += i_frame_size;
1864             i_frame_output++;
1865             if( i_frame_output == 1 )
1866                 first_dts = prev_dts = last_dts;
1867         }
1868
1869         if( filter.release_frame( opt->hin, &cli_pic, i_frame + opt->i_seek ) )
1870             break;
1871
1872         /* update status line (up to 1000 times per input file) */
1873         if( opt->b_progress && i_frame_output )
1874             i_previous = print_status( i_start, i_previous, i_frame_output, param->i_frame_total, i_file, param, 2 * last_dts - prev_dts - first_dts );
1875     }
1876     /* Flush delayed frames */
1877     while( !b_ctrl_c && x264_encoder_delayed_frames( h ) )
1878     {
1879         prev_dts = last_dts;
1880         i_frame_size = encode_frame( h, opt->hout, NULL, &last_dts );
1881         if( i_frame_size < 0 )
1882         {
1883             b_ctrl_c = 1; /* lie to exit the loop */
1884             retval = -1;
1885         }
1886         else if( i_frame_size )
1887         {
1888             i_file += i_frame_size;
1889             i_frame_output++;
1890             if( i_frame_output == 1 )
1891                 first_dts = prev_dts = last_dts;
1892         }
1893         if( opt->b_progress && i_frame_output )
1894             i_previous = print_status( i_start, i_previous, i_frame_output, param->i_frame_total, i_file, param, 2 * last_dts - prev_dts - first_dts );
1895     }
1896 fail:
1897     if( pts_warning_cnt >= MAX_PTS_WARNING && cli_log_level < X264_LOG_DEBUG )
1898         x264_cli_log( "x264", X264_LOG_WARNING, "%d suppressed nonmonotonic pts warnings\n", pts_warning_cnt-MAX_PTS_WARNING );
1899
1900     /* duration algorithm fails when only 1 frame is output */
1901     if( i_frame_output == 1 )
1902         duration = (double)param->i_fps_den / param->i_fps_num;
1903     else if( b_ctrl_c )
1904         duration = (double)(2 * last_dts - prev_dts - first_dts) * param->i_timebase_num / param->i_timebase_den;
1905     else
1906         duration = (double)(2 * largest_pts - second_largest_pts) * param->i_timebase_num / param->i_timebase_den;
1907
1908     i_end = x264_mdate();
1909     /* Erase progress indicator before printing encoding stats. */
1910     if( opt->b_progress )
1911         fprintf( stderr, "                                                                               \r" );
1912     if( h )
1913         x264_encoder_close( h );
1914     fprintf( stderr, "\n" );
1915
1916     if( b_ctrl_c )
1917         fprintf( stderr, "aborted at input frame %d, output frame %d\n", opt->i_seek + i_frame, i_frame_output );
1918
1919     cli_output.close_file( opt->hout, largest_pts, second_largest_pts );
1920     opt->hout = NULL;
1921
1922     if( i_frame_output > 0 )
1923     {
1924         double fps = (double)i_frame_output * (double)1000000 /
1925                      (double)( i_end - i_start );
1926
1927         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame_output, fps,
1928                  (double) i_file * 8 / ( 1000 * duration ) );
1929     }
1930
1931     return retval;
1932 }