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