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