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