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