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