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