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