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