1 /*****************************************************************************
2 * x264: top-level x264cli functions
3 *****************************************************************************
4 * Copyright (C) 2003-2011 x264 project
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>
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.
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.
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.
26 * This program is also available under a commercial proprietary license.
27 * For more information, contact us at licensing@x264.com.
28 *****************************************************************************/
33 #include "common/common.h"
35 #include "input/input.h"
36 #include "output/output.h"
37 #include "filters/filters.h"
39 #define FAIL_IF_ERROR( cond, ... ) FAIL_IF_ERR( cond, "x264", __VA_ARGS__ )
44 #define GetConsoleTitle(t,n)
45 #define SetConsoleTitle(t)
49 #undef DECLARE_ALIGNED
50 #include <libavformat/avformat.h>
51 #include <libavutil/pixfmt.h>
52 #include <libavutil/pixdesc.h>
56 #include <libswscale/swscale.h>
64 static volatile int b_ctrl_c = 0;
65 static int b_exit_on_ctrl_c = 0;
66 static void sigint_handler( int a )
68 if( b_exit_on_ctrl_c )
73 static char UNUSED originalCTitle[200] = "";
82 double timebase_convert_multiplier;
86 /* file i/o operation structs */
87 cli_input_t cli_input;
88 static cli_output_t cli_output;
90 /* video filter operation struct */
91 static cli_vid_filter_t filter;
93 static const char * const demuxer_names[] =
110 static const char * const muxer_names[] =
122 static const char * const pulldown_names[] = { "none", "22", "32", "64", "double", "triple", "euro", 0 };
123 static const char * const log_level_names[] = { "none", "error", "warning", "info", "debug", 0 };
124 static const char * const output_csp_names[] = { "i420", "i422", "i444", "rgb", 0 };
135 X264_PULLDOWN_22 = 1,
138 X264_PULLDOWN_DOUBLE,
139 X264_PULLDOWN_TRIPLE,
143 #define TB PIC_STRUCT_TOP_BOTTOM
144 #define BT PIC_STRUCT_BOTTOM_TOP
145 #define TBT PIC_STRUCT_TOP_BOTTOM_TOP
146 #define BTB PIC_STRUCT_BOTTOM_TOP_BOTTOM
148 static const cli_pulldown_t pulldown_values[] =
150 [X264_PULLDOWN_22] = {1, {TB}, 1.0},
151 [X264_PULLDOWN_32] = {4, {TBT, BT, BTB, TB}, 1.25},
152 [X264_PULLDOWN_64] = {2, {PIC_STRUCT_DOUBLE, PIC_STRUCT_TRIPLE}, 1.0},
153 [X264_PULLDOWN_DOUBLE] = {1, {PIC_STRUCT_DOUBLE}, 2.0},
154 [X264_PULLDOWN_TRIPLE] = {1, {PIC_STRUCT_TRIPLE}, 3.0},
155 [X264_PULLDOWN_EURO] = {24, {TBT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT,
156 BTB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB}, 25.0/24.0}
164 // indexed by pic_struct enum
165 static const float pulldown_frame_duration[10] = { 0.0, 1, 0.5, 0.5, 1, 1, 1.5, 1.5, 2, 3 };
167 static void help( x264_param_t *defaults, int longhelp );
168 static int parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
169 static int encode( x264_param_t *param, cli_opt_t *opt );
171 /* logging and printing for within the cli system */
172 static int cli_log_level;
173 void x264_cli_log( const char *name, int i_level, const char *fmt, ... )
175 if( i_level > cli_log_level )
183 case X264_LOG_WARNING:
196 fprintf( stderr, "%s [%s]: ", name, s_level );
198 va_start( arg, fmt );
199 vfprintf( stderr, fmt, arg );
203 void x264_cli_printf( int i_level, const char *fmt, ... )
205 if( i_level > cli_log_level )
208 va_start( arg, fmt );
209 vfprintf( stderr, fmt, arg );
213 static void print_version_info()
216 printf( "x264 "X264_POINTVER"\n" );
218 printf( "x264 0.%d.X\n", X264_BUILD );
221 printf( "(libswscale %d.%d.%d)\n", LIBSWSCALE_VERSION_MAJOR, LIBSWSCALE_VERSION_MINOR, LIBSWSCALE_VERSION_MICRO );
224 printf( "(libavformat %d.%d.%d)\n", LIBAVFORMAT_VERSION_MAJOR, LIBAVFORMAT_VERSION_MINOR, LIBAVFORMAT_VERSION_MICRO );
227 printf( "(ffmpegsource %d.%d.%d.%d)\n", FFMS_VERSION >> 24, (FFMS_VERSION & 0xff0000) >> 16, (FFMS_VERSION & 0xff00) >> 8, FFMS_VERSION & 0xff );
229 printf( "built on " __DATE__ ", " );
230 #ifdef __INTEL_COMPILER
231 printf( "intel: %.2f (%d)\n", __INTEL_COMPILER / 100.f, __INTEL_COMPILER_BUILD_DATE );
232 #elif defined(__GNUC__)
233 printf( "gcc: " __VERSION__ "\n" );
235 printf( "using an unknown compiler\n" );
237 printf( "configuration: --bit-depth=%d\n", x264_bit_depth );
238 printf( "x264 license: " );
240 printf( "GPL version 2 or later\n" );
242 printf( "Non-GPL commercial\n" );
245 const char *license = swscale_license();
246 printf( "libswscale%s%s license: %s\n", HAVE_LAVF ? "/libavformat" : "", HAVE_FFMS ? "/ffmpegsource" : "" , license );
247 if( !strcmp( license, "nonfree and unredistributable" ) ||
248 (!HAVE_GPL && (!strcmp( license, "GPL version 2 or later" )
249 || !strcmp( license, "GPL version 3 or later" ))))
250 printf( "WARNING: This binary is unredistributable!\n" );
254 int main( int argc, char **argv )
260 FAIL_IF_ERROR( x264_threading_init(), "unable to initialize threading\n" )
263 _setmode(_fileno(stdin), _O_BINARY);
264 _setmode(_fileno(stdout), _O_BINARY);
267 GetConsoleTitle( originalCTitle, sizeof(originalCTitle) );
269 /* Parse command line */
270 if( parse( argc, argv, ¶m, &opt ) < 0 )
273 /* Restore title; it can be changed by input modules */
274 SetConsoleTitle( originalCTitle );
276 /* Control-C handler */
277 signal( SIGINT, sigint_handler );
280 ret = encode( ¶m, &opt );
282 /* clean up handles */
284 filter.free( opt.hin );
286 cli_input.close_file( opt.hin );
288 cli_output.close_file( opt.hout, 0, 0 );
290 fclose( opt.tcfile_out );
292 fclose( opt.qpfile );
294 SetConsoleTitle( originalCTitle );
299 static char const *strtable_lookup( const char * const table[], int idx )
301 int i = 0; while( table[i] ) i++;
302 return ( ( idx >= 0 && idx < i ) ? table[ idx ] : "???" );
305 static char *stringify_names( char *buf, const char * const names[] )
309 for( p[0] = 0; names[i]; i++ )
311 p += sprintf( p, "%s", names[i] );
313 p += sprintf( p, ", " );
318 static void print_csp_names( int longhelp )
323 printf( " - valid csps for `raw' demuxer:\n" );
325 for( int i = X264_CSP_NONE+1; i < X264_CSP_CLI_MAX; i++ )
327 printf( "%s", x264_cli_csps[i].name );
328 if( i+1 < X264_CSP_CLI_MAX )
333 printf( " - valid csps for `lavf' demuxer:\n" );
335 size_t line_len = strlen( INDENT );
336 for( enum PixelFormat i = PIX_FMT_NONE+1; i < PIX_FMT_NB; i++ )
338 const char *pfname = av_pix_fmt_descriptors[i].name;
339 size_t name_len = strlen( pfname );
340 if( line_len + name_len > (80 - strlen( ", " )) )
342 printf( "\n" INDENT );
343 line_len = strlen( INDENT );
345 printf( "%s", pfname );
346 line_len += name_len;
347 if( i+1 < PIX_FMT_NB )
357 static void help( x264_param_t *defaults, int longhelp )
361 #define H1 if(longhelp>=1) printf
362 #define H2 if(longhelp==2) printf
363 H0( "x264 core:%d%s\n"
364 "Syntax: x264 [options] -o outfile infile\n"
366 "Infile can be raw (in which case resolution is required),\n"
367 " or YUV4MPEG (*.y4m),\n"
368 " or Avisynth if compiled with support (%s).\n"
369 " or libav* formats if compiled with lavf support (%s) or ffms support (%s).\n"
370 "Outfile type is selected by filename:\n"
371 " .264 -> Raw bytestream\n"
372 " .mkv -> Matroska\n"
373 " .flv -> Flash Video\n"
374 " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
375 "Output bit depth: %d (configured at compile time)\n"
379 " -h, --help List basic options\n"
380 " --longhelp List more options\n"
381 " --fullhelp List all options\n"
383 X264_BUILD, X264_VERSION,
406 H0( "Example usage:\n" );
408 H0( " Constant quality mode:\n" );
409 H0( " x264 --crf 24 -o <output> <input>\n" );
411 H0( " Two-pass with a bitrate of 1000kbps:\n" );
412 H0( " x264 --pass 1 --bitrate 1000 -o <output> <input>\n" );
413 H0( " x264 --pass 2 --bitrate 1000 -o <output> <input>\n" );
415 H0( " Lossless:\n" );
416 H0( " x264 --qp 0 -o <output> <input>\n" );
418 H0( " Maximum PSNR at the cost of speed and visual quality:\n" );
419 H0( " x264 --preset placebo --tune psnr -o <output> <input>\n" );
421 H0( " Constant bitrate at 1000kbps with a 2 second-buffer:\n");
422 H0( " x264 --vbv-bufsize 2000 --bitrate 1000 -o <output> <input>\n" );
426 H0( " --profile <string> Force the limits of an H.264 profile\n"
427 " Overrides all settings.\n" );
429 " --no-8x8dct --bframes 0 --no-cabac\n"
430 " --cqm flat --weightp 0\n"
434 " --no-8x8dct --cqm flat\n"
440 " Support for bit depth 8-10.\n" );
441 else H0( " - baseline,main,high,high10\n" );
442 H0( " --preset <string> Use a preset to select encoding settings [medium]\n"
443 " Overridden by user settings.\n" );
444 H2( " - ultrafast:\n"
445 " --no-8x8dct --aq-mode 0 --b-adapt 0\n"
446 " --bframes 0 --no-cabac --no-deblock\n"
447 " --no-mbtree --me dia --no-mixed-refs\n"
448 " --partitions none --rc-lookahead 0 --ref 1\n"
449 " --scenecut 0 --subme 0 --trellis 0\n"
450 " --no-weightb --weightp 0\n"
452 " --no-mbtree --me dia --no-mixed-refs\n"
453 " --partitions i8x8,i4x4 --rc-lookahead 0\n"
454 " --ref 1 --subme 1 --trellis 0 --weightp 1\n"
456 " --no-mixed-refs --rc-lookahead 10\n"
457 " --ref 1 --subme 2 --trellis 0 --weightp 1\n"
459 " --no-mixed-refs --rc-lookahead 20\n"
460 " --ref 2 --subme 4 --weightp 1\n"
462 " --rc-lookahead 30 --ref 2 --subme 6\n"
465 " Default settings apply.\n"
467 " --b-adapt 2 --direct auto --me umh\n"
468 " --rc-lookahead 50 --ref 5 --subme 8\n"
470 " --b-adapt 2 --direct auto --me umh\n"
471 " --partitions all --rc-lookahead 60\n"
472 " --ref 8 --subme 9 --trellis 2\n"
474 " --b-adapt 2 --bframes 8 --direct auto\n"
475 " --me umh --merange 24 --partitions all\n"
476 " --ref 16 --subme 10 --trellis 2\n"
477 " --rc-lookahead 60\n"
479 " --bframes 16 --b-adapt 2 --direct auto\n"
480 " --slow-firstpass --no-fast-pskip\n"
481 " --me tesa --merange 24 --partitions all\n"
482 " --rc-lookahead 60 --ref 16 --subme 11\n"
484 else H0( " - ultrafast,superfast,veryfast,faster,fast\n"
485 " - medium,slow,slower,veryslow,placebo\n" );
486 H0( " --tune <string> Tune the settings for a particular type of source\n"
488 " Overridden by user settings.\n"
489 " Multiple tunings are separated by commas.\n"
490 " Only one psy tuning can be used at a time.\n" );
491 H2( " - film (psy tuning):\n"
492 " --deblock -1:-1 --psy-rd <unset>:0.15\n"
493 " - animation (psy tuning):\n"
494 " --bframes {+2} --deblock 1:1\n"
495 " --psy-rd 0.4:<unset> --aq-strength 0.6\n"
496 " --ref {Double if >1 else 1}\n"
497 " - grain (psy tuning):\n"
498 " --aq-strength 0.5 --no-dct-decimate\n"
499 " --deadzone-inter 6 --deadzone-intra 6\n"
500 " --deblock -2:-2 --ipratio 1.1 \n"
501 " --pbratio 1.1 --psy-rd <unset>:0.25\n"
503 " - stillimage (psy tuning):\n"
504 " --aq-strength 1.2 --deblock -3:-3\n"
505 " --psy-rd 2.0:0.7\n"
506 " - psnr (psy tuning):\n"
507 " --aq-mode 0 --no-psy\n"
508 " - ssim (psy tuning):\n"
509 " --aq-mode 2 --no-psy\n"
511 " --no-cabac --no-deblock --no-weightb\n"
514 " --bframes 0 --force-cfr --no-mbtree\n"
515 " --sync-lookahead 0 --sliced-threads\n"
516 " --rc-lookahead 0\n" );
517 else H0( " - psy tunings: film,animation,grain,\n"
518 " stillimage,psnr,ssim\n"
519 " - other tunings: fastdecode,zerolatency\n" );
520 H2( " --slow-firstpass Don't force these faster settings with --pass 1:\n"
521 " --no-8x8dct --me dia --partitions none\n"
522 " --ref 1 --subme {2 if >2 else unchanged}\n"
523 " --trellis 0 --fast-pskip\n" );
524 else H1( " --slow-firstpass Don't force faster settings with --pass 1\n" );
526 H0( "Frame-type options:\n" );
528 H0( " -I, --keyint <integer or \"infinite\"> Maximum GOP size [%d]\n", defaults->i_keyint_max );
529 H2( " -i, --min-keyint <integer> Minimum GOP size [auto]\n" );
530 H2( " --no-scenecut Disable adaptive I-frame decision\n" );
531 H2( " --scenecut <integer> How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
532 H2( " --intra-refresh Use Periodic Intra Refresh instead of IDR frames\n" );
533 H1( " -b, --bframes <integer> Number of B-frames between I and P [%d]\n", defaults->i_bframe );
534 H1( " --b-adapt <integer> Adaptive B-frame decision method [%d]\n"
535 " Higher values may lower threading efficiency.\n"
538 " - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
539 H2( " --b-bias <integer> Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
540 H1( " --b-pyramid <string> Keep some B-frames as references [%s]\n"
541 " - none: Disabled\n"
542 " - strict: Strictly hierarchical pyramid\n"
543 " - normal: Non-strict (not Blu-ray compatible)\n",
544 strtable_lookup( x264_b_pyramid_names, defaults->i_bframe_pyramid ) );
545 H1( " --open-gop Use recovery points to close GOPs\n"
546 " Only available with b-frames\n" );
547 H1( " --no-cabac Disable CABAC\n" );
548 H1( " -r, --ref <integer> Number of reference frames [%d]\n", defaults->i_frame_reference );
549 H1( " --no-deblock Disable loop filter\n" );
550 H1( " -f, --deblock <alpha:beta> Loop filter parameters [%d:%d]\n",
551 defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
552 H2( " --slices <integer> Number of slices per frame; forces rectangular\n"
553 " slices and is overridden by other slicing options\n" );
554 else H1( " --slices <integer> Number of slices per frame\n" );
555 H2( " --slice-max-size <integer> Limit the size of each slice in bytes\n");
556 H2( " --slice-max-mbs <integer> Limit the size of each slice in macroblocks\n");
557 H0( " --tff Enable interlaced mode (top field first)\n" );
558 H0( " --bff Enable interlaced mode (bottom field first)\n" );
559 H2( " --constrained-intra Enable constrained intra prediction.\n" );
560 H0( " --pulldown <string> Use soft pulldown to change frame rate\n"
561 " - none, 22, 32, 64, double, triple, euro (requires cfr input)\n" );
562 H2( " --fake-interlaced Flag stream as interlaced but encode progressive.\n"
563 " Makes it possible to encode 25p and 30p Blu-Ray\n"
564 " streams. Ignored in interlaced mode.\n" );
565 H2( " --frame-packing <integer> For stereoscopic videos define frame arrangement\n"
566 " - 0: checkerboard - pixels are alternatively from L and R\n"
567 " - 1: column alternation - L and R are interlaced by column\n"
568 " - 2: row alternation - L and R are interlaced by row\n"
569 " - 3: side by side - L is on the left, R on the right\n"
570 " - 4: top bottom - L is on top, R on bottom\n"
571 " - 5: frame alternation - one view per frame\n" );
573 H0( "Ratecontrol:\n" );
575 H1( " -q, --qp <integer> Force constant QP (0-%d, 0=lossless)\n", QP_MAX );
576 H0( " -B, --bitrate <integer> Set bitrate (kbit/s)\n" );
577 H0( " --crf <float> Quality-based VBR (%d-51) [%.1f]\n", 51 - QP_MAX_SPEC, defaults->rc.f_rf_constant );
578 H1( " --rc-lookahead <integer> Number of frames for frametype lookahead [%d]\n", defaults->rc.i_lookahead );
579 H0( " --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
580 H0( " --vbv-bufsize <integer> Set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
581 H2( " --vbv-init <float> Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
582 H2( " --crf-max <float> With CRF+VBV, limit RF to this value\n"
583 " May cause VBV underflows!\n" );
584 H2( " --qpmin <integer> Set min QP [%d]\n", defaults->rc.i_qp_min );
585 H2( " --qpmax <integer> Set max QP [%d]\n", defaults->rc.i_qp_max );
586 H2( " --qpstep <integer> Set max QP step [%d]\n", defaults->rc.i_qp_step );
587 H2( " --ratetol <float> Tolerance of ABR ratecontrol and VBV [%.1f]\n", defaults->rc.f_rate_tolerance );
588 H2( " --ipratio <float> QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
589 H2( " --pbratio <float> QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
590 H2( " --chroma-qp-offset <integer> QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
591 H2( " --aq-mode <integer> AQ method [%d]\n"
593 " - 1: Variance AQ (complexity mask)\n"
594 " - 2: Auto-variance AQ (experimental)\n", defaults->rc.i_aq_mode );
595 H1( " --aq-strength <float> Reduces blocking and blurring in flat and\n"
596 " textured areas. [%.1f]\n", defaults->rc.f_aq_strength );
598 H0( " -p, --pass <integer> Enable multipass ratecontrol\n"
599 " - 1: First pass, creates stats file\n"
600 " - 2: Last pass, does not overwrite stats file\n" );
601 H2( " - 3: Nth pass, overwrites stats file\n" );
602 H1( " --stats <string> Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
603 H2( " --no-mbtree Disable mb-tree ratecontrol.\n");
604 H2( " --qcomp <float> QP curve compression [%.2f]\n", defaults->rc.f_qcompress );
605 H2( " --cplxblur <float> Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
606 H2( " --qblur <float> Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
607 H2( " --zones <zone0>/<zone1>/... Tweak the bitrate of regions of the video\n" );
608 H2( " Each zone is of the form\n"
609 " <start frame>,<end frame>,<option>\n"
610 " where <option> is either\n"
611 " q=<integer> (force QP)\n"
612 " or b=<float> (bitrate multiplier)\n" );
613 H2( " --qpfile <string> Force frametypes and QPs for some or all frames\n"
614 " Format of each line: framenumber frametype QP\n"
615 " QP is optional (none lets x264 choose). Frametypes: I,i,K,P,B,b.\n"
616 " K=<I or i> depending on open-gop setting\n"
617 " QPs are restricted by qpmin/qpmax.\n" );
621 H1( " -A, --partitions <string> Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
622 " - p8x8, p4x4, b8x8, i8x8, i4x4\n"
624 " (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
625 H1( " --direct <string> Direct MV prediction mode [\"%s\"]\n"
626 " - none, spatial, temporal, auto\n",
627 strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
628 H2( " --no-weightb Disable weighted prediction for B-frames\n" );
629 H1( " --weightp <integer> Weighted prediction for P-frames [%d]\n"
631 " - 1: Weighted refs\n"
632 " - 2: Weighted refs + Duplicates\n", defaults->analyse.i_weighted_pred );
633 H1( " --me <string> Integer pixel motion estimation method [\"%s\"]\n",
634 strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
635 H2( " - dia: diamond search, radius 1 (fast)\n"
636 " - hex: hexagonal search, radius 2\n"
637 " - umh: uneven multi-hexagon search\n"
638 " - esa: exhaustive search\n"
639 " - tesa: hadamard exhaustive search (slow)\n" );
640 else H1( " - dia, hex, umh\n" );
641 H2( " --merange <integer> Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
642 H2( " --mvrange <integer> Maximum motion vector length [-1 (auto)]\n" );
643 H2( " --mvrange-thread <int> Minimum buffer between threads [-1 (auto)]\n" );
644 H1( " -m, --subme <integer> Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
645 H2( " - 0: fullpel only (not recommended)\n"
646 " - 1: SAD mode decision, one qpel iteration\n"
647 " - 2: SATD mode decision\n"
648 " - 3-5: Progressively more qpel\n"
649 " - 6: RD mode decision for I/P-frames\n"
650 " - 7: RD mode decision for all frames\n"
651 " - 8: RD refinement for I/P-frames\n"
652 " - 9: RD refinement for all frames\n"
653 " - 10: QP-RD - requires trellis=2, aq-mode>0\n"
654 " - 11: Full RD: disable all early terminations\n" );
655 else H1( " decision quality: 1=fast, 11=best\n" );
656 H1( " --psy-rd <float:float> Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
657 " #1: RD (requires subme>=6)\n"
658 " #2: Trellis (requires trellis, experimental)\n",
659 defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
660 H2( " --no-psy Disable all visual optimizations that worsen\n"
661 " both PSNR and SSIM.\n" );
662 H2( " --no-mixed-refs Don't decide references on a per partition basis\n" );
663 H2( " --no-chroma-me Ignore chroma in motion estimation\n" );
664 H1( " --no-8x8dct Disable adaptive spatial transform size\n" );
665 H1( " -t, --trellis <integer> Trellis RD quantization. [%d]\n"
667 " - 1: enabled only on the final encode of a MB\n"
668 " - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
669 H2( " --no-fast-pskip Disables early SKIP detection on P-frames\n" );
670 H2( " --no-dct-decimate Disables coefficient thresholding on P-frames\n" );
671 H1( " --nr <integer> Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
673 H2( " --deadzone-inter <int> Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
674 H2( " --deadzone-intra <int> Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
675 H2( " Deadzones should be in the range 0 - 32.\n" );
676 H2( " --cqm <string> Preset quant matrices [\"flat\"]\n"
678 H1( " --cqmfile <string> Read custom quant matrices from a JM-compatible file\n" );
679 H2( " Overrides any other --cqm* options.\n" );
680 H2( " --cqm4 <list> Set all 4x4 quant matrices\n"
681 " Takes a comma-separated list of 16 integers.\n" );
682 H2( " --cqm8 <list> Set all 8x8 quant matrices\n"
683 " Takes a comma-separated list of 64 integers.\n" );
684 H2( " --cqm4i, --cqm4p, --cqm8i, --cqm8p <list>\n"
685 " Set both luma and chroma quant matrices\n" );
686 H2( " --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc <list>\n"
687 " Set individual quant matrices\n" );
689 H2( "Video Usability Info (Annex E):\n" );
690 H2( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
691 H2( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
693 H2( " --overscan <string> Specify crop overscan setting [\"%s\"]\n"
694 " - undef, show, crop\n",
695 strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
696 H2( " --videoformat <string> Specify video format [\"%s\"]\n"
697 " - component, pal, ntsc, secam, mac, undef\n",
698 strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
699 H2( " --fullrange <string> Specify full range samples setting [\"%s\"]\n"
701 strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ) );
702 H2( " --colorprim <string> Specify color primaries [\"%s\"]\n"
703 " - undef, bt709, bt470m, bt470bg\n"
704 " smpte170m, smpte240m, film\n",
705 strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
706 H2( " --transfer <string> Specify transfer characteristics [\"%s\"]\n"
707 " - undef, bt709, bt470m, bt470bg, linear,\n"
708 " log100, log316, smpte170m, smpte240m\n",
709 strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
710 H2( " --colormatrix <string> Specify color matrix setting [\"%s\"]\n"
711 " - undef, bt709, fcc, bt470bg\n"
712 " smpte170m, smpte240m, GBR, YCgCo\n",
713 strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
714 H2( " --chromaloc <integer> Specify chroma sample location (0 to 5) [%d]\n",
715 defaults->vui.i_chroma_loc );
717 H2( " --nal-hrd <string> Signal HRD information (requires vbv-bufsize)\n"
718 " - none, vbr, cbr (cbr not allowed in .mp4)\n" );
719 H2( " --pic-struct Force pic_struct in Picture Timing SEI\n" );
720 H2( " --crop-rect <string> Add 'left,top,right,bottom' to the bitstream-level\n"
721 " cropping rectangle\n" );
724 H0( "Input/Output:\n" );
726 H0( " -o, --output <string> Specify output file\n" );
727 H1( " --muxer <string> Specify output container format [\"%s\"]\n"
728 " - %s\n", muxer_names[0], stringify_names( buf, muxer_names ) );
729 H1( " --demuxer <string> Specify input container format [\"%s\"]\n"
730 " - %s\n", demuxer_names[0], stringify_names( buf, demuxer_names ) );
731 H1( " --input-fmt <string> Specify input file format (requires lavf support)\n" );
732 H1( " --input-csp <string> Specify input colorspace format for raw input\n" );
733 print_csp_names( longhelp );
734 H1( " --output-csp <string> Specify output colorspace [\"%s\"]\n"
735 " - %s\n", output_csp_names[0], stringify_names( buf, output_csp_names ) );
736 H1( " --input-depth <integer> Specify input bit depth for raw input\n" );
737 H1( " --input-res <intxint> Specify input resolution (width x height)\n" );
738 H1( " --index <string> Filename for input index file\n" );
739 H0( " --sar width:height Specify Sample Aspect Ratio\n" );
740 H0( " --fps <float|rational> Specify framerate\n" );
741 H0( " --seek <integer> First frame to encode\n" );
742 H0( " --frames <integer> Maximum number of frames to encode\n" );
743 H0( " --level <string> Specify level (as defined by Annex A)\n" );
744 H1( " --bluray-compat Enable compatibility hacks for Blu-ray support\n" );
746 H1( " -v, --verbose Print stats for each frame\n" );
747 H1( " --no-progress Don't show the progress indicator while encoding\n" );
748 H0( " --quiet Quiet Mode\n" );
749 H1( " --log-level <string> Specify the maximum level of logging [\"%s\"]\n"
750 " - %s\n", strtable_lookup( log_level_names, cli_log_level - X264_LOG_NONE ),
751 stringify_names( buf, log_level_names ) );
752 H1( " --psnr Enable PSNR computation\n" );
753 H1( " --ssim Enable SSIM computation\n" );
754 H1( " --threads <integer> Force a specific number of threads\n" );
755 H2( " --sliced-threads Low-latency but lower-efficiency threading\n" );
756 H2( " --thread-input Run Avisynth in its own thread\n" );
757 H2( " --sync-lookahead <integer> Number of buffer frames for threaded lookahead\n" );
758 H2( " --non-deterministic Slightly improve quality of SMP, at the cost of repeatability\n" );
759 H2( " --cpu-independent Ensure exact reproducibility across different cpus,\n"
760 " as opposed to letting them select different algorithms\n" );
761 H2( " --asm <integer> Override CPU detection\n" );
762 H2( " --no-asm Disable all CPU optimizations\n" );
763 H2( " --visualize Show MB types overlayed on the encoded video\n" );
764 H2( " --dump-yuv <string> Save reconstructed frames\n" );
765 H2( " --sps-id <integer> Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
766 H2( " --aud Use access unit delimiters\n" );
767 H2( " --force-cfr Force constant framerate timestamp generation\n" );
768 H2( " --tcfile-in <string> Force timestamp generation with timecode file\n" );
769 H2( " --tcfile-out <string> Output timecode v2 file from input timestamps\n" );
770 H2( " --timebase <int/int> Specify timebase numerator and denominator\n"
771 " <integer> Specify timebase numerator for input timecode file\n"
772 " or specify timebase denominator for other input\n" );
773 H2( " --dts-compress Eliminate initial delay with container DTS hack\n" );
775 H0( "Filtering:\n" );
777 H0( " --vf, --video-filter <filter0>/<filter1>/... Apply video filtering to the input file\n" );
779 H0( " Filter options may be specified in <filter>:<option>=<value> format.\n" );
781 H0( " Available filters:\n" );
782 x264_register_vid_filters();
783 x264_vid_filter_help( longhelp );
821 static char short_options[] = "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw";
822 static struct option long_options[] =
824 { "help", no_argument, NULL, 'h' },
825 { "longhelp", no_argument, NULL, OPT_LONGHELP },
826 { "fullhelp", no_argument, NULL, OPT_FULLHELP },
827 { "version", no_argument, NULL, 'V' },
828 { "profile", required_argument, NULL, OPT_PROFILE },
829 { "preset", required_argument, NULL, OPT_PRESET },
830 { "tune", required_argument, NULL, OPT_TUNE },
831 { "slow-firstpass", no_argument, NULL, OPT_SLOWFIRSTPASS },
832 { "bitrate", required_argument, NULL, 'B' },
833 { "bframes", required_argument, NULL, 'b' },
834 { "b-adapt", required_argument, NULL, 0 },
835 { "no-b-adapt", no_argument, NULL, 0 },
836 { "b-bias", required_argument, NULL, 0 },
837 { "b-pyramid", required_argument, NULL, 0 },
838 { "open-gop", no_argument, NULL, 0 },
839 { "bluray-compat", no_argument, NULL, 0 },
840 { "min-keyint", required_argument, NULL, 'i' },
841 { "keyint", required_argument, NULL, 'I' },
842 { "intra-refresh", no_argument, NULL, 0 },
843 { "scenecut", required_argument, NULL, 0 },
844 { "no-scenecut", no_argument, NULL, 0 },
845 { "nf", no_argument, NULL, 0 },
846 { "no-deblock", no_argument, NULL, 0 },
847 { "filter", required_argument, NULL, 0 },
848 { "deblock", required_argument, NULL, 'f' },
849 { "interlaced", no_argument, NULL, OPT_INTERLACED },
850 { "tff", no_argument, NULL, OPT_INTERLACED },
851 { "bff", no_argument, NULL, OPT_INTERLACED },
852 { "no-interlaced", no_argument, NULL, OPT_INTERLACED },
853 { "constrained-intra", no_argument, NULL, 0 },
854 { "cabac", no_argument, NULL, 0 },
855 { "no-cabac", no_argument, NULL, 0 },
856 { "qp", required_argument, NULL, 'q' },
857 { "qpmin", required_argument, NULL, 0 },
858 { "qpmax", required_argument, NULL, 0 },
859 { "qpstep", required_argument, NULL, 0 },
860 { "crf", required_argument, NULL, 0 },
861 { "rc-lookahead",required_argument, NULL, 0 },
862 { "ref", required_argument, NULL, 'r' },
863 { "asm", required_argument, NULL, 0 },
864 { "no-asm", no_argument, NULL, 0 },
865 { "sar", required_argument, NULL, 0 },
866 { "fps", required_argument, NULL, OPT_FPS },
867 { "frames", required_argument, NULL, OPT_FRAMES },
868 { "seek", required_argument, NULL, OPT_SEEK },
869 { "output", required_argument, NULL, 'o' },
870 { "muxer", required_argument, NULL, OPT_MUXER },
871 { "demuxer", required_argument, NULL, OPT_DEMUXER },
872 { "stdout", required_argument, NULL, OPT_MUXER },
873 { "stdin", required_argument, NULL, OPT_DEMUXER },
874 { "index", required_argument, NULL, OPT_INDEX },
875 { "analyse", required_argument, NULL, 0 },
876 { "partitions", required_argument, NULL, 'A' },
877 { "direct", required_argument, NULL, 0 },
878 { "weightb", no_argument, NULL, 'w' },
879 { "no-weightb", no_argument, NULL, 0 },
880 { "weightp", required_argument, NULL, 0 },
881 { "me", required_argument, NULL, 0 },
882 { "merange", required_argument, NULL, 0 },
883 { "mvrange", required_argument, NULL, 0 },
884 { "mvrange-thread", required_argument, NULL, 0 },
885 { "subme", required_argument, NULL, 'm' },
886 { "psy-rd", required_argument, NULL, 0 },
887 { "no-psy", no_argument, NULL, 0 },
888 { "psy", no_argument, NULL, 0 },
889 { "mixed-refs", no_argument, NULL, 0 },
890 { "no-mixed-refs", no_argument, NULL, 0 },
891 { "no-chroma-me", no_argument, NULL, 0 },
892 { "8x8dct", no_argument, NULL, '8' },
893 { "no-8x8dct", no_argument, NULL, 0 },
894 { "trellis", required_argument, NULL, 't' },
895 { "fast-pskip", no_argument, NULL, 0 },
896 { "no-fast-pskip", no_argument, NULL, 0 },
897 { "no-dct-decimate", no_argument, NULL, 0 },
898 { "aq-strength", required_argument, NULL, 0 },
899 { "aq-mode", required_argument, NULL, 0 },
900 { "deadzone-inter", required_argument, NULL, 0 },
901 { "deadzone-intra", required_argument, NULL, 0 },
902 { "level", required_argument, NULL, 0 },
903 { "ratetol", required_argument, NULL, 0 },
904 { "vbv-maxrate", required_argument, NULL, 0 },
905 { "vbv-bufsize", required_argument, NULL, 0 },
906 { "vbv-init", required_argument, NULL, 0 },
907 { "crf-max", required_argument, NULL, 0 },
908 { "ipratio", required_argument, NULL, 0 },
909 { "pbratio", required_argument, NULL, 0 },
910 { "chroma-qp-offset", required_argument, NULL, 0 },
911 { "pass", required_argument, NULL, 'p' },
912 { "stats", required_argument, NULL, 0 },
913 { "qcomp", required_argument, NULL, 0 },
914 { "mbtree", no_argument, NULL, 0 },
915 { "no-mbtree", no_argument, NULL, 0 },
916 { "qblur", required_argument, NULL, 0 },
917 { "cplxblur", required_argument, NULL, 0 },
918 { "zones", required_argument, NULL, 0 },
919 { "qpfile", required_argument, NULL, OPT_QPFILE },
920 { "threads", required_argument, NULL, 0 },
921 { "sliced-threads", no_argument, NULL, 0 },
922 { "no-sliced-threads", no_argument, NULL, 0 },
923 { "slice-max-size", required_argument, NULL, 0 },
924 { "slice-max-mbs", required_argument, NULL, 0 },
925 { "slices", required_argument, NULL, 0 },
926 { "thread-input", no_argument, NULL, OPT_THREAD_INPUT },
927 { "sync-lookahead", required_argument, NULL, 0 },
928 { "non-deterministic", no_argument, NULL, 0 },
929 { "cpu-independent", no_argument, NULL, 0 },
930 { "psnr", no_argument, NULL, 0 },
931 { "ssim", no_argument, NULL, 0 },
932 { "quiet", no_argument, NULL, OPT_QUIET },
933 { "verbose", no_argument, NULL, 'v' },
934 { "log-level", required_argument, NULL, OPT_LOG_LEVEL },
935 { "no-progress", no_argument, NULL, OPT_NOPROGRESS },
936 { "visualize", no_argument, NULL, OPT_VISUALIZE },
937 { "dump-yuv", required_argument, NULL, 0 },
938 { "sps-id", required_argument, NULL, 0 },
939 { "aud", no_argument, NULL, 0 },
940 { "nr", required_argument, NULL, 0 },
941 { "cqm", required_argument, NULL, 0 },
942 { "cqmfile", required_argument, NULL, 0 },
943 { "cqm4", required_argument, NULL, 0 },
944 { "cqm4i", required_argument, NULL, 0 },
945 { "cqm4iy", required_argument, NULL, 0 },
946 { "cqm4ic", required_argument, NULL, 0 },
947 { "cqm4p", required_argument, NULL, 0 },
948 { "cqm4py", required_argument, NULL, 0 },
949 { "cqm4pc", required_argument, NULL, 0 },
950 { "cqm8", required_argument, NULL, 0 },
951 { "cqm8i", required_argument, NULL, 0 },
952 { "cqm8p", required_argument, NULL, 0 },
953 { "overscan", required_argument, NULL, 0 },
954 { "videoformat", required_argument, NULL, 0 },
955 { "fullrange", required_argument, NULL, 0 },
956 { "colorprim", required_argument, NULL, 0 },
957 { "transfer", required_argument, NULL, 0 },
958 { "colormatrix", required_argument, NULL, 0 },
959 { "chromaloc", required_argument, NULL, 0 },
960 { "force-cfr", no_argument, NULL, 0 },
961 { "tcfile-in", required_argument, NULL, OPT_TCFILE_IN },
962 { "tcfile-out", required_argument, NULL, OPT_TCFILE_OUT },
963 { "timebase", required_argument, NULL, OPT_TIMEBASE },
964 { "pic-struct", no_argument, NULL, 0 },
965 { "crop-rect", required_argument, NULL, 0 },
966 { "nal-hrd", required_argument, NULL, 0 },
967 { "pulldown", required_argument, NULL, OPT_PULLDOWN },
968 { "fake-interlaced", no_argument, NULL, 0 },
969 { "frame-packing", required_argument, NULL, 0 },
970 { "vf", required_argument, NULL, OPT_VIDEO_FILTER },
971 { "video-filter", required_argument, NULL, OPT_VIDEO_FILTER },
972 { "input-fmt", required_argument, NULL, OPT_INPUT_FMT },
973 { "input-res", required_argument, NULL, OPT_INPUT_RES },
974 { "input-csp", required_argument, NULL, OPT_INPUT_CSP },
975 { "input-depth", required_argument, NULL, OPT_INPUT_DEPTH },
976 { "dts-compress", no_argument, NULL, OPT_DTS_COMPRESSION },
977 { "output-csp", required_argument, NULL, OPT_OUTPUT_CSP },
981 static int select_output( const char *muxer, char *filename, x264_param_t *param )
983 const char *ext = get_filename_extension( filename );
984 if( !strcmp( filename, "-" ) || strcasecmp( muxer, "auto" ) )
987 if( !strcasecmp( ext, "mp4" ) )
990 cli_output = mp4_output;
992 param->b_repeat_headers = 0;
993 if( param->i_nal_hrd == X264_NAL_HRD_CBR )
995 x264_cli_log( "x264", X264_LOG_WARNING, "cbr nal-hrd is not compatible with mp4\n" );
996 param->i_nal_hrd = X264_NAL_HRD_VBR;
999 x264_cli_log( "x264", X264_LOG_ERROR, "not compiled with MP4 output support\n" );
1003 else if( !strcasecmp( ext, "mkv" ) )
1005 cli_output = mkv_output;
1006 param->b_annexb = 0;
1007 param->b_repeat_headers = 0;
1009 else if( !strcasecmp( ext, "flv" ) )
1011 cli_output = flv_output;
1012 param->b_annexb = 0;
1013 param->b_repeat_headers = 0;
1016 cli_output = raw_output;
1020 static int select_input( const char *demuxer, char *used_demuxer, char *filename,
1021 hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
1023 int b_auto = !strcasecmp( demuxer, "auto" );
1024 const char *ext = b_auto ? get_filename_extension( filename ) : "";
1025 int b_regular = strcmp( filename, "-" );
1026 if( !b_regular && b_auto )
1028 b_regular = b_regular && x264_is_regular_file_path( filename );
1031 FILE *f = fopen( filename, "r" );
1034 b_regular = x264_is_regular_file( f );
1038 const char *module = b_auto ? ext : demuxer;
1040 if( !strcasecmp( module, "avs" ) || !strcasecmp( ext, "d2v" ) || !strcasecmp( ext, "dga" ) )
1043 cli_input = avs_input;
1046 x264_cli_log( "x264", X264_LOG_ERROR, "not compiled with AVS input support\n" );
1050 else if( !strcasecmp( module, "y4m" ) )
1051 cli_input = y4m_input;
1052 else if( !strcasecmp( module, "raw" ) || !strcasecmp( ext, "yuv" ) )
1053 cli_input = raw_input;
1057 if( b_regular && (b_auto || !strcasecmp( demuxer, "ffms" )) &&
1058 !ffms_input.open_file( filename, p_handle, info, opt ) )
1062 cli_input = ffms_input;
1066 if( (b_auto || !strcasecmp( demuxer, "lavf" )) &&
1067 !lavf_input.open_file( filename, p_handle, info, opt ) )
1071 cli_input = lavf_input;
1075 if( b_regular && (b_auto || !strcasecmp( demuxer, "avs" )) &&
1076 !avs_input.open_file( filename, p_handle, info, opt ) )
1080 cli_input = avs_input;
1083 if( b_auto && !raw_input.open_file( filename, p_handle, info, opt ) )
1087 cli_input = raw_input;
1090 FAIL_IF_ERROR( !(*p_handle), "could not open input file `%s' via any method!\n", filename )
1092 strcpy( used_demuxer, module );
1097 static int init_vid_filters( char *sequence, hnd_t *handle, video_info_t *info, x264_param_t *param, int output_csp )
1099 x264_register_vid_filters();
1101 /* intialize baseline filters */
1102 if( x264_init_vid_filter( "source", handle, &filter, info, param, NULL ) ) /* wrap demuxer into a filter */
1104 if( x264_init_vid_filter( "resize", handle, &filter, info, param, "normcsp" ) ) /* normalize csps to be of a known/supported format */
1106 if( x264_init_vid_filter( "fix_vfr_pts", handle, &filter, info, param, NULL ) ) /* fix vfr pts */
1109 /* parse filter chain */
1110 for( char *p = sequence; p && *p; )
1112 int tok_len = strcspn( p, "/" );
1113 int p_len = strlen( p );
1115 int name_len = strcspn( p, ":" );
1117 name_len += name_len != tok_len;
1118 if( x264_init_vid_filter( p, handle, &filter, info, param, p + name_len ) )
1120 p += X264_MIN( tok_len+1, p_len );
1123 /* force end result resolution */
1124 if( !param->i_width && !param->i_height )
1126 param->i_height = info->height;
1127 param->i_width = info->width;
1129 /* force the output csp to what the user specified (or the default) */
1130 param->i_csp = info->csp;
1131 int csp = info->csp & X264_CSP_MASK;
1132 if( output_csp == X264_CSP_I420 && (csp < X264_CSP_I420 || csp > X264_CSP_NV12) )
1133 param->i_csp = X264_CSP_I420;
1134 else if( output_csp == X264_CSP_I422 && (csp < X264_CSP_I422 || csp > X264_CSP_NV16) )
1135 param->i_csp = X264_CSP_I422;
1136 else if( output_csp == X264_CSP_I444 && (csp < X264_CSP_I444 || csp > X264_CSP_YV24) )
1137 param->i_csp = X264_CSP_I444;
1138 else if( output_csp == X264_CSP_RGB && (csp < X264_CSP_BGR || csp > X264_CSP_RGB) )
1139 param->i_csp = X264_CSP_RGB;
1140 param->i_csp |= info->csp & X264_CSP_HIGH_DEPTH;
1142 if( x264_init_vid_filter( "resize", handle, &filter, info, param, NULL ) )
1146 sprintf( args, "bit_depth=%d", x264_bit_depth );
1148 if( x264_init_vid_filter( "depth", handle, &filter, info, param, args ) )
1154 static int parse_enum_name( const char *arg, const char * const *names, const char **dst )
1156 for( int i = 0; names[i]; i++ )
1157 if( !strcasecmp( arg, names[i] ) )
1165 static int parse_enum_value( const char *arg, const char * const *names, int *dst )
1167 for( int i = 0; names[i]; i++ )
1168 if( !strcasecmp( arg, names[i] ) )
1176 static int parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt )
1178 char *input_filename = NULL;
1179 const char *demuxer = demuxer_names[0];
1180 char *output_filename = NULL;
1181 const char *muxer = muxer_names[0];
1182 char *tcfile_name = NULL;
1183 x264_param_t defaults;
1184 char *profile = NULL;
1185 char *vid_filters = NULL;
1186 int b_thread_input = 0;
1190 int b_user_interlaced = 0;
1191 cli_input_opt_t input_opt;
1192 cli_output_opt_t output_opt;
1193 char *preset = NULL;
1196 x264_param_default( &defaults );
1197 cli_log_level = defaults.i_log_level;
1199 memset( &input_opt, 0, sizeof(cli_input_opt_t) );
1200 memset( &output_opt, 0, sizeof(cli_output_opt_t) );
1201 input_opt.bit_depth = 8;
1202 int output_csp = defaults.i_csp;
1203 opt->b_progress = 1;
1205 /* Presets are applied before all other options. */
1208 int c = getopt_long( argc, argv, short_options, long_options, NULL );
1211 if( c == OPT_PRESET )
1219 if( preset && !strcasecmp( preset, "placebo" ) )
1222 if( x264_param_default_preset( param, preset, tune ) < 0 )
1225 /* Parse command line options */
1229 int long_options_index = -1;
1231 int c = getopt_long( argc, argv, short_options, long_options, &long_options_index );
1241 help( &defaults, 0 );
1244 help( &defaults, 1 );
1247 help( &defaults, 2 );
1250 print_version_info();
1253 param->i_frame_total = X264_MAX( atoi( optarg ), 0 );
1256 opt->i_seek = X264_MAX( atoi( optarg ), 0 );
1259 output_filename = optarg;
1262 FAIL_IF_ERROR( parse_enum_name( optarg, muxer_names, &muxer ), "Unknown muxer `%s'\n", optarg )
1265 FAIL_IF_ERROR( parse_enum_name( optarg, demuxer_names, &demuxer ), "Unknown demuxer `%s'\n", optarg )
1268 input_opt.index_file = optarg;
1271 opt->qpfile = fopen( optarg, "rb" );
1272 FAIL_IF_ERROR( !opt->qpfile, "can't open qpfile `%s'\n", optarg )
1273 if( !x264_is_regular_file( opt->qpfile ) )
1275 x264_cli_log( "x264", X264_LOG_ERROR, "qpfile incompatible with non-regular file `%s'\n", optarg );
1276 fclose( opt->qpfile );
1280 case OPT_THREAD_INPUT:
1284 cli_log_level = param->i_log_level = X264_LOG_NONE;
1287 cli_log_level = param->i_log_level = X264_LOG_DEBUG;
1290 if( !parse_enum_value( optarg, log_level_names, &cli_log_level ) )
1291 cli_log_level += X264_LOG_NONE;
1293 cli_log_level = atoi( optarg );
1294 param->i_log_level = cli_log_level;
1296 case OPT_NOPROGRESS:
1297 opt->b_progress = 0;
1301 param->b_visualize = 1;
1302 b_exit_on_ctrl_c = 1;
1304 x264_cli_log( "x264", X264_LOG_WARNING, "not compiled with visualization support\n" );
1313 case OPT_SLOWFIRSTPASS:
1318 goto generic_option;
1321 param->b_vfr_input = 0;
1322 goto generic_option;
1323 case OPT_INTERLACED:
1324 b_user_interlaced = 1;
1325 goto generic_option;
1327 tcfile_name = optarg;
1329 case OPT_TCFILE_OUT:
1330 opt->tcfile_out = fopen( optarg, "wb" );
1331 FAIL_IF_ERROR( !opt->tcfile_out, "can't open `%s'\n", optarg )
1334 input_opt.timebase = optarg;
1337 FAIL_IF_ERROR( parse_enum_value( optarg, pulldown_names, &opt->i_pulldown ), "Unknown pulldown `%s'\n", optarg )
1339 case OPT_VIDEO_FILTER:
1340 vid_filters = optarg;
1343 input_opt.format = optarg;
1346 input_opt.resolution = optarg;
1349 input_opt.colorspace = optarg;
1351 case OPT_INPUT_DEPTH:
1352 input_opt.bit_depth = atoi( optarg );
1354 case OPT_DTS_COMPRESSION:
1355 output_opt.use_dts_compress = 1;
1357 case OPT_OUTPUT_CSP:
1358 FAIL_IF_ERROR( parse_enum_value( optarg, output_csp_names, &output_csp ), "Unknown output csp `%s'\n", optarg )
1359 // correct the parsed value to the libx264 csp value
1360 static const uint8_t output_csp_fix[] = { X264_CSP_I420, X264_CSP_I422, X264_CSP_I444, X264_CSP_RGB };
1361 param->i_csp = output_csp = output_csp_fix[output_csp];
1366 if( long_options_index < 0 )
1368 for( int i = 0; long_options[i].name; i++ )
1369 if( long_options[i].val == c )
1371 long_options_index = i;
1374 if( long_options_index < 0 )
1376 /* getopt_long already printed an error message */
1381 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
1387 const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
1388 x264_cli_log( "x264", X264_LOG_ERROR, "invalid argument: %s = %s\n", name, optarg );
1393 /* If first pass mode is used, apply faster settings. */
1395 x264_param_apply_fastfirstpass( param );
1397 /* Apply profile restrictions. */
1398 if( x264_param_apply_profile( param, profile ) < 0 )
1401 /* Get the file name */
1402 FAIL_IF_ERROR( optind > argc - 1 || !output_filename, "No %s file. Run x264 --help for a list of options.\n",
1403 optind > argc - 1 ? "input" : "output" )
1405 if( select_output( muxer, output_filename, param ) )
1407 FAIL_IF_ERROR( cli_output.open_file( output_filename, &opt->hout, &output_opt ), "could not open output file `%s'\n", output_filename )
1409 input_filename = argv[optind++];
1410 video_info_t info = {0};
1411 char demuxername[5];
1413 /* set info flags to param flags to be overwritten by demuxer as necessary. */
1414 info.csp = param->i_csp;
1415 info.fps_num = param->i_fps_num;
1416 info.fps_den = param->i_fps_den;
1417 info.interlaced = param->b_interlaced;
1418 info.sar_width = param->vui.i_sar_width;
1419 info.sar_height = param->vui.i_sar_height;
1420 info.tff = param->b_tff;
1421 info.vfr = param->b_vfr_input;
1423 input_opt.seek = opt->i_seek;
1424 input_opt.progress = opt->b_progress;
1425 input_opt.output_csp = output_csp;
1427 if( select_input( demuxer, demuxername, input_filename, &opt->hin, &info, &input_opt ) )
1430 FAIL_IF_ERROR( !opt->hin && cli_input.open_file( input_filename, &opt->hin, &info, &input_opt ),
1431 "could not open input file `%s'\n", input_filename )
1433 x264_reduce_fraction( &info.sar_width, &info.sar_height );
1434 x264_reduce_fraction( &info.fps_num, &info.fps_den );
1435 x264_cli_log( demuxername, X264_LOG_INFO, "%dx%d%c %d:%d @ %d/%d fps (%cfr)\n", info.width,
1436 info.height, info.interlaced ? 'i' : 'p', info.sar_width, info.sar_height,
1437 info.fps_num, info.fps_den, info.vfr ? 'v' : 'c' );
1441 FAIL_IF_ERROR( b_user_fps, "--fps + --tcfile-in is incompatible.\n" )
1442 FAIL_IF_ERROR( timecode_input.open_file( tcfile_name, &opt->hin, &info, &input_opt ), "timecode input failed\n" )
1443 cli_input = timecode_input;
1445 else FAIL_IF_ERROR( !info.vfr && input_opt.timebase, "--timebase is incompatible with cfr input\n" )
1447 /* init threaded input while the information about the input video is unaltered by filtering */
1449 if( info.thread_safe && (b_thread_input || param->i_threads > 1
1450 || (param->i_threads == X264_THREADS_AUTO && x264_cpu_num_processors() > 1)) )
1452 if( thread_input.open_file( NULL, &opt->hin, &info, NULL ) )
1454 fprintf( stderr, "x264 [error]: threaded input failed\n" );
1457 cli_input = thread_input;
1461 /* override detected values by those specified by the user */
1462 if( param->vui.i_sar_width && param->vui.i_sar_height )
1464 info.sar_width = param->vui.i_sar_width;
1465 info.sar_height = param->vui.i_sar_height;
1469 info.fps_num = param->i_fps_num;
1470 info.fps_den = param->i_fps_den;
1474 info.timebase_num = info.fps_den;
1475 info.timebase_den = info.fps_num;
1477 if( !tcfile_name && input_opt.timebase )
1479 uint64_t i_user_timebase_num;
1480 uint64_t i_user_timebase_den;
1481 int ret = sscanf( input_opt.timebase, "%"SCNu64"/%"SCNu64, &i_user_timebase_num, &i_user_timebase_den );
1482 FAIL_IF_ERROR( !ret, "invalid argument: timebase = %s\n", input_opt.timebase )
1485 i_user_timebase_num = info.timebase_num;
1486 i_user_timebase_den = strtoul( input_opt.timebase, NULL, 10 );
1488 FAIL_IF_ERROR( i_user_timebase_num > UINT32_MAX || i_user_timebase_den > UINT32_MAX,
1489 "timebase you specified exceeds H.264 maximum\n" )
1490 opt->timebase_convert_multiplier = ((double)i_user_timebase_den / info.timebase_den)
1491 * ((double)info.timebase_num / i_user_timebase_num);
1492 info.timebase_num = i_user_timebase_num;
1493 info.timebase_den = i_user_timebase_den;
1496 if( b_user_interlaced )
1498 info.interlaced = param->b_interlaced;
1499 info.tff = param->b_tff;
1502 if( init_vid_filters( vid_filters, &opt->hin, &info, param, output_csp ) )
1505 /* set param flags from the post-filtered video */
1506 param->b_vfr_input = info.vfr;
1507 param->i_fps_num = info.fps_num;
1508 param->i_fps_den = info.fps_den;
1509 param->i_timebase_num = info.timebase_num;
1510 param->i_timebase_den = info.timebase_den;
1511 param->vui.i_sar_width = info.sar_width;
1512 param->vui.i_sar_height = info.sar_height;
1514 info.num_frames = X264_MAX( info.num_frames - opt->i_seek, 0 );
1515 if( (!info.num_frames || param->i_frame_total < info.num_frames)
1516 && param->i_frame_total > 0 )
1517 info.num_frames = param->i_frame_total;
1518 param->i_frame_total = info.num_frames;
1520 if( !b_user_interlaced && info.interlaced )
1523 x264_cli_log( "x264", X264_LOG_WARNING, "input appears to be interlaced, enabling %cff interlaced mode.\n"
1524 " If you want otherwise, use --no-interlaced or --%cff\n",
1525 info.tff ? 't' : 'b', info.tff ? 'b' : 't' );
1526 param->b_interlaced = 1;
1527 param->b_tff = !!info.tff;
1529 x264_cli_log( "x264", X264_LOG_WARNING, "input appears to be interlaced, but not compiled with interlaced support\n" );
1533 /* Automatically reduce reference frame count to match the user's target level
1534 * if the user didn't explicitly set a reference frame count. */
1537 int mbs = (((param->i_width)+15)>>4) * (((param->i_height)+15)>>4);
1538 for( int i = 0; x264_levels[i].level_idc != 0; i++ )
1539 if( param->i_level_idc == x264_levels[i].level_idc )
1541 while( mbs * 384 * param->i_frame_reference > x264_levels[i].dpb &&
1542 param->i_frame_reference > 1 )
1544 param->i_frame_reference--;
1554 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
1556 int num = -1, qp, ret;
1559 while( num < i_frame )
1561 file_pos = ftell( opt->qpfile );
1563 ret = fscanf( opt->qpfile, "%d %c%*[ \t]%d\n", &num, &type, &qp );
1564 pic->i_type = X264_TYPE_AUTO;
1565 pic->i_qpplus1 = X264_QP_AUTO;
1566 if( num > i_frame || ret == EOF )
1568 fseek( opt->qpfile, file_pos, SEEK_SET );
1571 if( num < i_frame && ret >= 2 )
1573 if( ret == 3 && qp >= 0 )
1574 pic->i_qpplus1 = qp+1;
1575 if ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
1576 else if( type == 'i' ) pic->i_type = X264_TYPE_I;
1577 else if( type == 'K' ) pic->i_type = X264_TYPE_KEYFRAME;
1578 else if( type == 'P' ) pic->i_type = X264_TYPE_P;
1579 else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
1580 else if( type == 'b' ) pic->i_type = X264_TYPE_B;
1582 if( ret < 2 || qp < -1 || qp > QP_MAX )
1584 x264_cli_log( "x264", X264_LOG_ERROR, "can't parse qpfile for frame %d\n", i_frame );
1585 fclose( opt->qpfile );
1592 static int encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic, int64_t *last_dts )
1594 x264_picture_t pic_out;
1597 int i_frame_size = 0;
1599 i_frame_size = x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out );
1601 FAIL_IF_ERROR( i_frame_size < 0, "x264_encoder_encode failed\n" );
1605 i_frame_size = cli_output.write_frame( hout, nal[0].p_payload, i_frame_size, &pic_out );
1606 *last_dts = pic_out.i_dts;
1609 return i_frame_size;
1612 static int64_t print_status( int64_t i_start, int64_t i_previous, int i_frame, int i_frame_total, int64_t i_file, x264_param_t *param, int64_t last_ts )
1615 int64_t i_time = x264_mdate();
1616 if( i_previous && i_time - i_previous < UPDATE_INTERVAL )
1618 int64_t i_elapsed = i_time - i_start;
1619 double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1622 bitrate = (double) i_file * 8 / ( (double) last_ts * 1000 * param->i_timebase_num / param->i_timebase_den );
1624 bitrate = (double) i_file * 8 / ( (double) 1000 * param->i_fps_den / param->i_fps_num );
1627 int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1628 sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
1629 100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
1630 eta/3600, (eta/60)%60, eta%60 );
1634 sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
1636 fprintf( stderr, "%s \r", buf+5 );
1637 SetConsoleTitle( buf );
1638 fflush( stderr ); // needed in windows
1642 static void convert_cli_to_lib_pic( x264_picture_t *lib, cli_pic_t *cli )
1644 memcpy( lib->img.i_stride, cli->img.stride, sizeof(cli->img.stride) );
1645 memcpy( lib->img.plane, cli->img.plane, sizeof(cli->img.plane) );
1646 lib->img.i_plane = cli->img.planes;
1647 lib->img.i_csp = cli->img.csp;
1648 lib->i_pts = cli->pts;
1651 #define FAIL_IF_ERROR2( cond, ... )\
1654 x264_cli_log( "x264", X264_LOG_ERROR, __VA_ARGS__ );\
1659 static int encode( x264_param_t *param, cli_opt_t *opt )
1664 const cli_pulldown_t *pulldown = NULL; // shut up gcc
1667 int i_frame_output = 0;
1668 int64_t i_end, i_previous = 0, i_start = 0;
1671 int64_t last_dts = 0;
1672 int64_t prev_dts = 0;
1673 int64_t first_dts = 0;
1674 # define MAX_PTS_WARNING 3 /* arbitrary */
1675 int pts_warning_cnt = 0;
1676 int64_t largest_pts = -1;
1677 int64_t second_largest_pts = -1;
1678 int64_t ticks_per_frame;
1680 double pulldown_pts = 0;
1683 opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
1685 /* set up pulldown */
1686 if( opt->i_pulldown && !param->b_vfr_input )
1688 param->b_pulldown = 1;
1689 param->b_pic_struct = 1;
1690 pulldown = &pulldown_values[opt->i_pulldown];
1691 param->i_timebase_num = param->i_fps_den;
1692 FAIL_IF_ERROR2( fmod( param->i_fps_num * pulldown->fps_factor, 1 ),
1693 "unsupported framerate for chosen pulldown\n" )
1694 param->i_timebase_den = param->i_fps_num * pulldown->fps_factor;
1697 h = x264_encoder_open( param );
1698 FAIL_IF_ERROR2( !h, "x264_encoder_open failed\n" );
1700 x264_encoder_parameters( h, param );
1702 FAIL_IF_ERROR2( cli_output.set_param( opt->hout, param ), "can't set outfile param\n" );
1704 i_start = x264_mdate();
1706 /* ticks/frame = ticks/second / frames/second */
1707 ticks_per_frame = (int64_t)param->i_timebase_den * param->i_fps_den / param->i_timebase_num / param->i_fps_num;
1708 FAIL_IF_ERROR2( ticks_per_frame < 1 && !param->b_vfr_input, "ticks_per_frame invalid: %"PRId64"\n", ticks_per_frame )
1709 ticks_per_frame = X264_MAX( ticks_per_frame, 1 );
1711 if( !param->b_repeat_headers )
1713 // Write SPS/PPS/SEI
1714 x264_nal_t *headers;
1717 FAIL_IF_ERROR2( x264_encoder_headers( h, &headers, &i_nal ) < 0, "x264_encoder_headers failed\n" )
1718 FAIL_IF_ERROR2( (i_file = cli_output.write_headers( opt->hout, headers )) < 0, "error writing headers to output file\n" );
1721 if( opt->tcfile_out )
1722 fprintf( opt->tcfile_out, "# timecode format v2\n" );
1725 for( ; !b_ctrl_c && (i_frame < param->i_frame_total || !param->i_frame_total); i_frame++ )
1727 if( filter.get_frame( opt->hin, &cli_pic, i_frame + opt->i_seek ) )
1729 x264_picture_init( &pic );
1730 convert_cli_to_lib_pic( &pic, &cli_pic );
1732 if( !param->b_vfr_input )
1733 pic.i_pts = i_frame;
1735 if( opt->i_pulldown && !param->b_vfr_input )
1737 pic.i_pic_struct = pulldown->pattern[ i_frame % pulldown->mod ];
1738 pic.i_pts = (int64_t)( pulldown_pts + 0.5 );
1739 pulldown_pts += pulldown_frame_duration[pic.i_pic_struct];
1741 else if( opt->timebase_convert_multiplier )
1742 pic.i_pts = (int64_t)( pic.i_pts * opt->timebase_convert_multiplier + 0.5 );
1744 if( pic.i_pts <= largest_pts )
1746 if( cli_log_level >= X264_LOG_DEBUG || pts_warning_cnt < MAX_PTS_WARNING )
1747 x264_cli_log( "x264", X264_LOG_WARNING, "non-strictly-monotonic pts at frame %d (%"PRId64" <= %"PRId64")\n",
1748 i_frame, pic.i_pts, largest_pts );
1749 else if( pts_warning_cnt == MAX_PTS_WARNING )
1750 x264_cli_log( "x264", X264_LOG_WARNING, "too many nonmonotonic pts warnings, suppressing further ones\n" );
1752 pic.i_pts = largest_pts + ticks_per_frame;
1755 second_largest_pts = largest_pts;
1756 largest_pts = pic.i_pts;
1757 if( opt->tcfile_out )
1758 fprintf( opt->tcfile_out, "%.6f\n", pic.i_pts * ((double)param->i_timebase_num / param->i_timebase_den) * 1e3 );
1761 parse_qpfile( opt, &pic, i_frame + opt->i_seek );
1763 prev_dts = last_dts;
1764 i_frame_size = encode_frame( h, opt->hout, &pic, &last_dts );
1765 if( i_frame_size < 0 )
1767 b_ctrl_c = 1; /* lie to exit the loop */
1770 else if( i_frame_size )
1772 i_file += i_frame_size;
1774 if( i_frame_output == 1 )
1775 first_dts = prev_dts = last_dts;
1778 if( filter.release_frame( opt->hin, &cli_pic, i_frame + opt->i_seek ) )
1781 /* update status line (up to 1000 times per input file) */
1782 if( opt->b_progress && i_frame_output )
1783 i_previous = print_status( i_start, i_previous, i_frame_output, param->i_frame_total, i_file, param, 2 * last_dts - prev_dts - first_dts );
1785 /* Flush delayed frames */
1786 while( !b_ctrl_c && x264_encoder_delayed_frames( h ) )
1788 prev_dts = last_dts;
1789 i_frame_size = encode_frame( h, opt->hout, NULL, &last_dts );
1790 if( i_frame_size < 0 )
1792 b_ctrl_c = 1; /* lie to exit the loop */
1795 else if( i_frame_size )
1797 i_file += i_frame_size;
1799 if( i_frame_output == 1 )
1800 first_dts = prev_dts = last_dts;
1802 if( opt->b_progress && i_frame_output )
1803 i_previous = print_status( i_start, i_previous, i_frame_output, param->i_frame_total, i_file, param, 2 * last_dts - prev_dts - first_dts );
1806 if( pts_warning_cnt >= MAX_PTS_WARNING && cli_log_level < X264_LOG_DEBUG )
1807 x264_cli_log( "x264", X264_LOG_WARNING, "%d suppressed nonmonotonic pts warnings\n", pts_warning_cnt-MAX_PTS_WARNING );
1809 /* duration algorithm fails when only 1 frame is output */
1810 if( i_frame_output == 1 )
1811 duration = (double)param->i_fps_den / param->i_fps_num;
1813 duration = (double)(2 * last_dts - prev_dts - first_dts) * param->i_timebase_num / param->i_timebase_den;
1815 duration = (double)(2 * largest_pts - second_largest_pts) * param->i_timebase_num / param->i_timebase_den;
1817 i_end = x264_mdate();
1818 /* Erase progress indicator before printing encoding stats. */
1819 if( opt->b_progress )
1820 fprintf( stderr, " \r" );
1822 x264_encoder_close( h );
1823 fprintf( stderr, "\n" );
1826 fprintf( stderr, "aborted at input frame %d, output frame %d\n", opt->i_seek + i_frame, i_frame_output );
1828 cli_output.close_file( opt->hout, largest_pts, second_largest_pts );
1831 if( i_frame_output > 0 )
1833 double fps = (double)i_frame_output * (double)1000000 /
1834 (double)( i_end - i_start );
1836 fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame_output, fps,
1837 (double) i_file * 8 / ( 1000 * duration ) );