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