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