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