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