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