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