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