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