1 /*****************************************************************************
2 * x264: top-level x264cli functions
3 *****************************************************************************
4 * Copyright (C) 2003-2010 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 *****************************************************************************/
37 #include "common/common.h"
39 #include "input/input.h"
40 #include "output/output.h"
41 #include "filters/filters.h"
43 #define FAIL_IF_ERROR( cond, ... ) FAIL_IF_ERR( cond, "x264", __VA_ARGS__ )
48 #define SetConsoleTitle(t)
52 #undef DECLARE_ALIGNED
53 #include <libavformat/avformat.h>
54 #include <libavutil/pixfmt.h>
55 #include <libavutil/pixdesc.h>
59 #include <libswscale/swscale.h>
67 static volatile int b_ctrl_c = 0;
68 static int b_exit_on_ctrl_c = 0;
69 static void sigint_handler( int a )
71 if( b_exit_on_ctrl_c )
83 double timebase_convert_multiplier;
87 /* file i/o operation structs */
89 static cli_output_t output;
91 /* video filter operation struct */
92 static cli_vid_filter_t filter;
94 static const char * const demuxer_names[] =
111 static const char * const muxer_names[] =
123 static const char * const pulldown_names[] = { "none", "22", "32", "64", "double", "triple", "euro", 0 };
124 static const char * const log_level_names[] = { "none", "error", "warning", "info", "debug", 0 };
134 X264_PULLDOWN_22 = 1,
137 X264_PULLDOWN_DOUBLE,
138 X264_PULLDOWN_TRIPLE,
142 #define TB PIC_STRUCT_TOP_BOTTOM
143 #define BT PIC_STRUCT_BOTTOM_TOP
144 #define TBT PIC_STRUCT_TOP_BOTTOM_TOP
145 #define BTB PIC_STRUCT_BOTTOM_TOP_BOTTOM
147 static const cli_pulldown_t pulldown_values[] =
149 [X264_PULLDOWN_22] = {1, {TB}, 1.0},
150 [X264_PULLDOWN_32] = {4, {TBT, BT, BTB, TB}, 1.25},
151 [X264_PULLDOWN_64] = {2, {PIC_STRUCT_DOUBLE, PIC_STRUCT_TRIPLE}, 1.0},
152 [X264_PULLDOWN_DOUBLE] = {1, {PIC_STRUCT_DOUBLE}, 2.0},
153 [X264_PULLDOWN_TRIPLE] = {1, {PIC_STRUCT_TRIPLE}, 3.0},
154 [X264_PULLDOWN_EURO] = {24, {TBT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT,
155 BTB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB}, 25.0/24.0}
163 // indexed by pic_struct enum
164 static const float pulldown_frame_duration[10] = { 0.0, 1, 0.5, 0.5, 1, 1, 1.5, 1.5, 2, 3 };
166 static void help( x264_param_t *defaults, int longhelp );
167 static int parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
168 static int encode( x264_param_t *param, cli_opt_t *opt );
170 /* logging and printing for within the cli system */
171 static int cli_log_level;
172 void x264_cli_log( const char *name, int i_level, const char *fmt, ... )
174 if( i_level > cli_log_level )
182 case X264_LOG_WARNING:
195 fprintf( stderr, "%s [%s]: ", name, s_level );
197 va_start( arg, fmt );
198 vfprintf( stderr, fmt, arg );
202 void x264_cli_printf( int i_level, const char *fmt, ... )
204 if( i_level > cli_log_level )
207 va_start( arg, fmt );
208 vfprintf( stderr, fmt, arg );
212 static void print_version_info()
215 printf( "x264 "X264_POINTVER"\n" );
217 printf( "x264 0.%d.X\n", X264_BUILD );
220 printf( "(libswscale %d.%d.%d)\n", LIBSWSCALE_VERSION_MAJOR, LIBSWSCALE_VERSION_MINOR, LIBSWSCALE_VERSION_MICRO );
223 printf( "(libavformat %d.%d.%d)\n", LIBAVFORMAT_VERSION_MAJOR, LIBAVFORMAT_VERSION_MINOR, LIBAVFORMAT_VERSION_MICRO );
226 printf( "(ffmpegsource %d.%d.%d.%d)\n", FFMS_VERSION >> 24, (FFMS_VERSION & 0xff0000) >> 16, (FFMS_VERSION & 0xff00) >> 8, FFMS_VERSION & 0xff );
228 printf( "built on " __DATE__ ", " );
230 printf( "gcc: " __VERSION__ "\n" );
232 printf( "using a non-gcc compiler\n" );
234 printf( "configuration: --bit-depth=%d\n", x264_bit_depth );
235 printf( "x264 license: " );
237 printf( "GPL version 2 or later\n" );
239 printf( "Non-GPL commercial\n" );
242 const char *license = swscale_license();
243 printf( "libswscale%s%s license: %s\n", HAVE_LAVF ? "/libavformat" : "", HAVE_FFMS ? "/ffmpegsource" : "" , license );
244 if( !strcmp( license, "nonfree and unredistributable" ) ||
245 (!HAVE_GPL && (!strcmp( license, "GPL version 2 or later" )
246 || !strcmp( license, "GPL version 3 or later" ))))
247 printf( "WARNING: This binary is unredistributable!\n" );
251 int main( int argc, char **argv )
258 pthread_win32_process_attach_np();
259 pthread_win32_thread_attach_np();
263 _setmode(_fileno(stdin), _O_BINARY);
264 _setmode(_fileno(stdout), _O_BINARY);
267 /* Parse command line */
268 if( parse( argc, argv, ¶m, &opt ) < 0 )
271 /* Control-C handler */
272 signal( SIGINT, sigint_handler );
274 ret = encode( ¶m, &opt );
277 pthread_win32_thread_detach_np();
278 pthread_win32_process_detach_np();
284 static char const *strtable_lookup( const char * const table[], int idx )
286 int i = 0; while( table[i] ) i++;
287 return ( ( idx >= 0 && idx < i ) ? table[ idx ] : "???" );
290 static char *stringify_names( char *buf, const char * const names[] )
294 for( p[0] = 0; names[i]; i++ )
296 p += sprintf( p, "%s", names[i] );
298 p += sprintf( p, ", " );
303 static void print_csp_names( int longhelp )
308 printf( " - valid csps for `raw' demuxer:\n" );
310 for( int i = X264_CSP_NONE+1; i < X264_CSP_CLI_MAX; i++ )
312 printf( "%s", x264_cli_csps[i].name );
313 if( i+1 < X264_CSP_CLI_MAX )
318 printf( " - valid csps for `lavf' demuxer:\n" );
320 int line_len = strlen( INDENT );
321 for( enum PixelFormat i = PIX_FMT_NONE+1; i < PIX_FMT_NB; i++ )
323 const char *pfname = av_pix_fmt_descriptors[i].name;
324 int name_len = strlen( pfname );
325 if( line_len + name_len > (80 - strlen( ", " )) )
327 printf( "\n" INDENT );
328 line_len = strlen( INDENT );
330 printf( "%s", pfname );
331 line_len += name_len;
332 if( i+1 < PIX_FMT_NB )
342 static void help( x264_param_t *defaults, int longhelp )
346 #define H1 if(longhelp>=1) printf
347 #define H2 if(longhelp==2) printf
348 H0( "x264 core:%d%s\n"
349 "Syntax: x264 [options] -o outfile infile\n"
351 "Infile can be raw (in which case resolution is required),\n"
352 " or YUV4MPEG (*.y4m),\n"
353 " or Avisynth if compiled with support (%s).\n"
354 " or libav* formats if compiled with lavf support (%s) or ffms support (%s).\n"
355 "Outfile type is selected by filename:\n"
356 " .264 -> Raw bytestream\n"
357 " .mkv -> Matroska\n"
358 " .flv -> Flash Video\n"
359 " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
360 "Output bit depth: %d (configured at compile time)\n"
364 " -h, --help List basic options\n"
365 " --longhelp List more options\n"
366 " --fullhelp List all options\n"
368 X264_BUILD, X264_VERSION,
391 H0( "Example usage:\n" );
393 H0( " Constant quality mode:\n" );
394 H0( " x264 --crf 24 -o <output> <input>\n" );
396 H0( " Two-pass with a bitrate of 1000kbps:\n" );
397 H0( " x264 --pass 1 --bitrate 1000 -o <output> <input>\n" );
398 H0( " x264 --pass 2 --bitrate 1000 -o <output> <input>\n" );
400 H0( " Lossless:\n" );
401 H0( " x264 --qp 0 -o <output> <input>\n" );
403 H0( " Maximum PSNR at the cost of speed and visual quality:\n" );
404 H0( " x264 --preset placebo --tune psnr -o <output> <input>\n" );
406 H0( " Constant bitrate at 1000kbps with a 2 second-buffer:\n");
407 H0( " x264 --vbv-bufsize 2000 --bitrate 1000 -o <output> <input>\n" );
411 H0( " --profile Force the limits of an H.264 profile\n"
412 " Overrides all settings.\n" );
414 " --no-8x8dct --bframes 0 --no-cabac\n"
415 " --cqm flat --weightp 0\n"
419 " --no-8x8dct --cqm flat\n"
425 " Support for bit depth 8-10.\n" );
426 else H0( " - baseline,main,high,high10\n" );
427 H0( " --preset Use a preset to select encoding settings [medium]\n"
428 " Overridden by user settings.\n" );
429 H2( " - ultrafast:\n"
430 " --no-8x8dct --aq-mode 0 --b-adapt 0\n"
431 " --bframes 0 --no-cabac --no-deblock\n"
432 " --no-mbtree --me dia --no-mixed-refs\n"
433 " --partitions none --rc-lookahead 0 --ref 1\n"
434 " --scenecut 0 --subme 0 --trellis 0\n"
435 " --no-weightb --weightp 0\n"
437 " --no-mbtree --me dia --no-mixed-refs\n"
438 " --partitions i8x8,i4x4 --rc-lookahead 0\n"
439 " --ref 1 --subme 1 --trellis 0 --weightp 1\n"
441 " --no-mixed-refs --rc-lookahead 10\n"
442 " --ref 1 --subme 2 --trellis 0 --weightp 1\n"
444 " --no-mixed-refs --rc-lookahead 20\n"
445 " --ref 2 --subme 4 --weightp 1\n"
447 " --rc-lookahead 30 --ref 2 --subme 6\n"
450 " Default settings apply.\n"
452 " --b-adapt 2 --direct auto --me umh\n"
453 " --rc-lookahead 50 --ref 5 --subme 8\n"
455 " --b-adapt 2 --direct auto --me umh\n"
456 " --partitions all --rc-lookahead 60\n"
457 " --ref 8 --subme 9 --trellis 2\n"
459 " --b-adapt 2 --bframes 8 --direct auto\n"
460 " --me umh --merange 24 --partitions all\n"
461 " --ref 16 --subme 10 --trellis 2\n"
462 " --rc-lookahead 60\n"
464 " --bframes 16 --b-adapt 2 --direct auto\n"
465 " --slow-firstpass --no-fast-pskip\n"
466 " --me tesa --merange 24 --partitions all\n"
467 " --rc-lookahead 60 --ref 16 --subme 10\n"
469 else H0( " - ultrafast,superfast,veryfast,faster,fast\n"
470 " - medium,slow,slower,veryslow,placebo\n" );
471 H0( " --tune Tune the settings for a particular type of source\n"
473 " Overridden by user settings.\n"
474 " Multiple tunings are separated by commas.\n"
475 " Only one psy tuning can be used at a time.\n" );
476 H2( " - film (psy tuning):\n"
477 " --deblock -1:-1 --psy-rd <unset>:0.15\n"
478 " - animation (psy tuning):\n"
479 " --bframes {+2} --deblock 1:1\n"
480 " --psy-rd 0.4:<unset> --aq-strength 0.6\n"
481 " --ref {Double if >1 else 1}\n"
482 " - grain (psy tuning):\n"
483 " --aq-strength 0.5 --no-dct-decimate\n"
484 " --deadzone-inter 6 --deadzone-intra 6\n"
485 " --deblock -2:-2 --ipratio 1.1 \n"
486 " --pbratio 1.1 --psy-rd <unset>:0.25\n"
488 " - stillimage (psy tuning):\n"
489 " --aq-strength 1.2 --deblock -3:-3\n"
490 " --psy-rd 2.0:0.7\n"
491 " - psnr (psy tuning):\n"
492 " --aq-mode 0 --no-psy\n"
493 " - ssim (psy tuning):\n"
494 " --aq-mode 2 --no-psy\n"
496 " --no-cabac --no-deblock --no-weightb\n"
499 " --bframes 0 --force-cfr --no-mbtree\n"
500 " --sync-lookahead 0 --sliced-threads\n"
501 " --rc-lookahead 0\n" );
502 else H0( " - psy tunings: film,animation,grain,\n"
503 " stillimage,psnr,ssim\n"
504 " - other tunings: fastdecode,zerolatency\n" );
505 H2( " --slow-firstpass Don't force these faster settings with --pass 1:\n"
506 " --no-8x8dct --me dia --partitions none\n"
507 " --ref 1 --subme {2 if >2 else unchanged}\n"
508 " --trellis 0 --fast-pskip\n" );
509 else H1( " --slow-firstpass Don't force faster settings with --pass 1\n" );
511 H0( "Frame-type options:\n" );
513 H0( " -I, --keyint <integer or \"infinite\"> Maximum GOP size [%d]\n", defaults->i_keyint_max );
514 H2( " -i, --min-keyint <integer> Minimum GOP size [auto]\n" );
515 H2( " --no-scenecut Disable adaptive I-frame decision\n" );
516 H2( " --scenecut <integer> How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
517 H2( " --intra-refresh Use Periodic Intra Refresh instead of IDR frames\n" );
518 H1( " -b, --bframes <integer> Number of B-frames between I and P [%d]\n", defaults->i_bframe );
519 H1( " --b-adapt <integer> Adaptive B-frame decision method [%d]\n"
520 " Higher values may lower threading efficiency.\n"
523 " - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
524 H2( " --b-bias <integer> Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
525 H1( " --b-pyramid <string> Keep some B-frames as references [%s]\n"
526 " - none: Disabled\n"
527 " - strict: Strictly hierarchical pyramid\n"
528 " - normal: Non-strict (not Blu-ray compatible)\n",
529 strtable_lookup( x264_b_pyramid_names, defaults->i_bframe_pyramid ) );
530 H1( " --open-gop <string> Use recovery points to close GOPs [none]\n"
531 " - none: closed GOPs only\n"
532 " - normal: standard open GOPs\n"
533 " (not Blu-ray compatible)\n"
534 " - bluray: Blu-ray-compatible open GOPs\n"
535 " Only available with b-frames\n" );
536 H1( " --no-cabac Disable CABAC\n" );
537 H1( " -r, --ref <integer> Number of reference frames [%d]\n", defaults->i_frame_reference );
538 H1( " --no-deblock Disable loop filter\n" );
539 H1( " -f, --deblock <alpha:beta> Loop filter parameters [%d:%d]\n",
540 defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
541 H2( " --slices <integer> Number of slices per frame; forces rectangular\n"
542 " slices and is overridden by other slicing options\n" );
543 else H1( " --slices <integer> Number of slices per frame\n" );
544 H2( " --slice-max-size <integer> Limit the size of each slice in bytes\n");
545 H2( " --slice-max-mbs <integer> Limit the size of each slice in macroblocks\n");
546 H0( " --tff Enable interlaced mode (top field first)\n" );
547 H0( " --bff Enable interlaced mode (bottom field first)\n" );
548 H2( " --constrained-intra Enable constrained intra prediction.\n" );
549 H0( " --pulldown <string> Use soft pulldown to change frame rate\n"
550 " - none, 22, 32, 64, double, triple, euro (requires cfr input)\n" );
551 H2( " --fake-interlaced Flag stream as interlaced but encode progressive.\n"
552 " Makes it possible to encode 25p and 30p Blu-Ray\n"
553 " streams. Ignored in interlaced mode.\n" );
554 H2( " --frame-packing <integer> For stereoscopic videos define frame arrangement\n"
555 " - 0: checkerboard - pixels are alternatively from L and R\n"
556 " - 1: column alternation - L and R are interlaced by column\n"
557 " - 2: row alternation - L and R are interlaced by row\n"
558 " - 3: side by side - L is on the left, R on the right\n"
559 " - 4: top bottom - L is on top, R on bottom\n"
560 " - 5: frame alternation - one view per frame\n" );
562 H0( "Ratecontrol:\n" );
564 H1( " -q, --qp <integer> Force constant QP (0-%d, 0=lossless)\n", QP_MAX );
565 H0( " -B, --bitrate <integer> Set bitrate (kbit/s)\n" );
566 H0( " --crf <float> Quality-based VBR (%d-51) [%.1f]\n", 51 - QP_MAX, defaults->rc.f_rf_constant );
567 H1( " --rc-lookahead <integer> Number of frames for frametype lookahead [%d]\n", defaults->rc.i_lookahead );
568 H0( " --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
569 H0( " --vbv-bufsize <integer> Set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
570 H2( " --vbv-init <float> Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
571 H2( " --crf-max <float> With CRF+VBV, limit RF to this value\n"
572 " May cause VBV underflows!\n" );
573 H2( " --qpmin <integer> Set min QP [%d]\n", defaults->rc.i_qp_min );
574 H2( " --qpmax <integer> Set max QP [%d]\n", defaults->rc.i_qp_max );
575 H2( " --qpstep <integer> Set max QP step [%d]\n", defaults->rc.i_qp_step );
576 H2( " --ratetol <float> Tolerance of ABR ratecontrol and VBV [%.1f]\n", defaults->rc.f_rate_tolerance );
577 H2( " --ipratio <float> QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
578 H2( " --pbratio <float> QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
579 H2( " --chroma-qp-offset <integer> QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
580 H2( " --aq-mode <integer> AQ method [%d]\n"
582 " - 1: Variance AQ (complexity mask)\n"
583 " - 2: Auto-variance AQ (experimental)\n", defaults->rc.i_aq_mode );
584 H1( " --aq-strength <float> Reduces blocking and blurring in flat and\n"
585 " textured areas. [%.1f]\n", defaults->rc.f_aq_strength );
587 H0( " -p, --pass <integer> Enable multipass ratecontrol\n"
588 " - 1: First pass, creates stats file\n"
589 " - 2: Last pass, does not overwrite stats file\n" );
590 H2( " - 3: Nth pass, overwrites stats file\n" );
591 H1( " --stats <string> Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
592 H2( " --no-mbtree Disable mb-tree ratecontrol.\n");
593 H2( " --qcomp <float> QP curve compression [%.2f]\n", defaults->rc.f_qcompress );
594 H2( " --cplxblur <float> Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
595 H2( " --qblur <float> Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
596 H2( " --zones <zone0>/<zone1>/... Tweak the bitrate of regions of the video\n" );
597 H2( " Each zone is of the form\n"
598 " <start frame>,<end frame>,<option>\n"
599 " where <option> is either\n"
600 " q=<integer> (force QP)\n"
601 " or b=<float> (bitrate multiplier)\n" );
602 H2( " --qpfile <string> Force frametypes and QPs for some or all frames\n"
603 " Format of each line: framenumber frametype QP\n"
604 " QP is optional (none lets x264 choose). Frametypes: I,i,K,P,B,b.\n"
605 " K=<I or i> depending on open-gop setting\n"
606 " QPs are restricted by qpmin/qpmax.\n" );
610 H1( " -A, --partitions <string> Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
611 " - p8x8, p4x4, b8x8, i8x8, i4x4\n"
613 " (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
614 H1( " --direct <string> Direct MV prediction mode [\"%s\"]\n"
615 " - none, spatial, temporal, auto\n",
616 strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
617 H2( " --no-weightb Disable weighted prediction for B-frames\n" );
618 H1( " --weightp <integer> Weighted prediction for P-frames [%d]\n"
620 " - 1: Weighted refs\n"
621 " - 2: Weighted refs + Duplicates\n", defaults->analyse.i_weighted_pred );
622 H1( " --me <string> Integer pixel motion estimation method [\"%s\"]\n",
623 strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
624 H2( " - dia: diamond search, radius 1 (fast)\n"
625 " - hex: hexagonal search, radius 2\n"
626 " - umh: uneven multi-hexagon search\n"
627 " - esa: exhaustive search\n"
628 " - tesa: hadamard exhaustive search (slow)\n" );
629 else H1( " - dia, hex, umh\n" );
630 H2( " --merange <integer> Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
631 H2( " --mvrange <integer> Maximum motion vector length [-1 (auto)]\n" );
632 H2( " --mvrange-thread <int> Minimum buffer between threads [-1 (auto)]\n" );
633 H1( " -m, --subme <integer> Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
634 H2( " - 0: fullpel only (not recommended)\n"
635 " - 1: SAD mode decision, one qpel iteration\n"
636 " - 2: SATD mode decision\n"
637 " - 3-5: Progressively more qpel\n"
638 " - 6: RD mode decision for I/P-frames\n"
639 " - 7: RD mode decision for all frames\n"
640 " - 8: RD refinement for I/P-frames\n"
641 " - 9: RD refinement for all frames\n"
642 " - 10: QP-RD - requires trellis=2, aq-mode>0\n" );
643 else H1( " decision quality: 1=fast, 10=best.\n" );
644 H1( " --psy-rd Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
645 " #1: RD (requires subme>=6)\n"
646 " #2: Trellis (requires trellis, experimental)\n",
647 defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
648 H2( " --no-psy Disable all visual optimizations that worsen\n"
649 " both PSNR and SSIM.\n" );
650 H2( " --no-mixed-refs Don't decide references on a per partition basis\n" );
651 H2( " --no-chroma-me Ignore chroma in motion estimation\n" );
652 H1( " --no-8x8dct Disable adaptive spatial transform size\n" );
653 H1( " -t, --trellis <integer> Trellis RD quantization. [%d]\n"
655 " - 1: enabled only on the final encode of a MB\n"
656 " - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
657 H2( " --no-fast-pskip Disables early SKIP detection on P-frames\n" );
658 H2( " --no-dct-decimate Disables coefficient thresholding on P-frames\n" );
659 H1( " --nr <integer> Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
661 H2( " --deadzone-inter <int> Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
662 H2( " --deadzone-intra <int> Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
663 H2( " Deadzones should be in the range 0 - 32.\n" );
664 H2( " --cqm <string> Preset quant matrices [\"flat\"]\n"
666 H1( " --cqmfile <string> Read custom quant matrices from a JM-compatible file\n" );
667 H2( " Overrides any other --cqm* options.\n" );
668 H2( " --cqm4 <list> Set all 4x4 quant matrices\n"
669 " Takes a comma-separated list of 16 integers.\n" );
670 H2( " --cqm8 <list> Set all 8x8 quant matrices\n"
671 " Takes a comma-separated list of 64 integers.\n" );
672 H2( " --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
673 " Set both luma and chroma quant matrices\n" );
674 H2( " --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
675 " Set individual quant matrices\n" );
677 H2( "Video Usability Info (Annex E):\n" );
678 H2( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
679 H2( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
681 H2( " --overscan <string> Specify crop overscan setting [\"%s\"]\n"
682 " - undef, show, crop\n",
683 strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
684 H2( " --videoformat <string> Specify video format [\"%s\"]\n"
685 " - component, pal, ntsc, secam, mac, undef\n",
686 strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
687 H2( " --fullrange <string> Specify full range samples setting [\"%s\"]\n"
689 strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ) );
690 H2( " --colorprim <string> Specify color primaries [\"%s\"]\n"
691 " - undef, bt709, bt470m, bt470bg\n"
692 " smpte170m, smpte240m, film\n",
693 strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
694 H2( " --transfer <string> Specify transfer characteristics [\"%s\"]\n"
695 " - undef, bt709, bt470m, bt470bg, linear,\n"
696 " log100, log316, smpte170m, smpte240m\n",
697 strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
698 H2( " --colormatrix <string> Specify color matrix setting [\"%s\"]\n"
699 " - undef, bt709, fcc, bt470bg\n"
700 " smpte170m, smpte240m, GBR, YCgCo\n",
701 strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
702 H2( " --chromaloc <integer> Specify chroma sample location (0 to 5) [%d]\n",
703 defaults->vui.i_chroma_loc );
705 H2( " --nal-hrd <string> Signal HRD information (requires vbv-bufsize)\n"
706 " - none, vbr, cbr (cbr not allowed in .mp4)\n" );
707 H2( " --pic-struct Force pic_struct in Picture Timing SEI\n" );
708 H2( " --crop-rect <string> Add 'left,top,right,bottom' to the bitstream-level\n"
709 " cropping rectangle\n" );
712 H0( "Input/Output:\n" );
714 H0( " -o, --output Specify output file\n" );
715 H1( " --muxer <string> Specify output container format [\"%s\"]\n"
716 " - %s\n", muxer_names[0], stringify_names( buf, muxer_names ) );
717 H1( " --demuxer <string> Specify input container format [\"%s\"]\n"
718 " - %s\n", demuxer_names[0], stringify_names( buf, demuxer_names ) );
719 H1( " --input-csp <string> Specify input colorspace format for raw input\n" );
720 print_csp_names( longhelp );
721 H1( " --input-depth <integer> Specify input bit depth for raw input\n" );
722 H1( " --input-res <intxint> Specify input resolution (width x height)\n" );
723 H1( " --index <string> Filename for input index file\n" );
724 H0( " --sar width:height Specify Sample Aspect Ratio\n" );
725 H0( " --fps <float|rational> Specify framerate\n" );
726 H0( " --seek <integer> First frame to encode\n" );
727 H0( " --frames <integer> Maximum number of frames to encode\n" );
728 H0( " --level <string> Specify level (as defined by Annex A)\n" );
730 H1( " -v, --verbose Print stats for each frame\n" );
731 H1( " --no-progress Don't show the progress indicator while encoding\n" );
732 H0( " --quiet Quiet Mode\n" );
733 H1( " --log-level <string> Specify the maximum level of logging [\"%s\"]\n"
734 " - %s\n", strtable_lookup( log_level_names, cli_log_level - X264_LOG_NONE ),
735 stringify_names( buf, log_level_names ) );
736 H1( " --psnr Enable PSNR computation\n" );
737 H1( " --ssim Enable SSIM computation\n" );
738 H1( " --threads <integer> Force a specific number of threads\n" );
739 H2( " --sliced-threads Low-latency but lower-efficiency threading\n" );
740 H2( " --thread-input Run Avisynth in its own thread\n" );
741 H2( " --sync-lookahead <integer> Number of buffer frames for threaded lookahead\n" );
742 H2( " --non-deterministic Slightly improve quality of SMP, at the cost of repeatability\n" );
743 H2( " --asm <integer> Override CPU detection\n" );
744 H2( " --no-asm Disable all CPU optimizations\n" );
745 H2( " --visualize Show MB types overlayed on the encoded video\n" );
746 H2( " --dump-yuv <string> Save reconstructed frames\n" );
747 H2( " --sps-id <integer> Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
748 H2( " --aud Use access unit delimiters\n" );
749 H2( " --force-cfr Force constant framerate timestamp generation\n" );
750 H2( " --tcfile-in <string> Force timestamp generation with timecode file\n" );
751 H2( " --tcfile-out <string> Output timecode v2 file from input timestamps\n" );
752 H2( " --timebase <int/int> Specify timebase numerator and denominator\n"
753 " <integer> Specify timebase numerator for input timecode file\n"
754 " or specify timebase denominator for other input\n" );
755 H2( " --dts-compress Eliminate initial delay with container DTS hack\n" );
757 H0( "Filtering:\n" );
759 H0( " --vf, --video-filter <filter0>/<filter1>/... Apply video filtering to the input file\n" );
761 H0( " Filter options may be specified in <filter>:<option>=<value> format.\n" );
763 H0( " Available filters:\n" );
764 x264_register_vid_filters();
765 x264_vid_filter_help( longhelp );
801 static char short_options[] = "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw";
802 static struct option long_options[] =
804 { "help", no_argument, NULL, 'h' },
805 { "longhelp", no_argument, NULL, OPT_LONGHELP },
806 { "fullhelp", no_argument, NULL, OPT_FULLHELP },
807 { "version", no_argument, NULL, 'V' },
808 { "profile", required_argument, NULL, OPT_PROFILE },
809 { "preset", required_argument, NULL, OPT_PRESET },
810 { "tune", required_argument, NULL, OPT_TUNE },
811 { "slow-firstpass", no_argument, NULL, OPT_SLOWFIRSTPASS },
812 { "bitrate", required_argument, NULL, 'B' },
813 { "bframes", required_argument, NULL, 'b' },
814 { "b-adapt", required_argument, NULL, 0 },
815 { "no-b-adapt", no_argument, NULL, 0 },
816 { "b-bias", required_argument, NULL, 0 },
817 { "b-pyramid", required_argument, NULL, 0 },
818 { "open-gop", required_argument, NULL, 0 },
819 { "min-keyint", required_argument, NULL, 'i' },
820 { "keyint", required_argument, NULL, 'I' },
821 { "intra-refresh", no_argument, NULL, 0 },
822 { "scenecut", required_argument, NULL, 0 },
823 { "no-scenecut", no_argument, NULL, 0 },
824 { "nf", no_argument, NULL, 0 },
825 { "no-deblock", no_argument, NULL, 0 },
826 { "filter", required_argument, NULL, 0 },
827 { "deblock", required_argument, NULL, 'f' },
828 { "interlaced", no_argument, NULL, OPT_INTERLACED },
829 { "tff", no_argument, NULL, OPT_INTERLACED },
830 { "bff", no_argument, NULL, OPT_INTERLACED },
831 { "no-interlaced", no_argument, NULL, OPT_INTERLACED },
832 { "constrained-intra", no_argument, NULL, 0 },
833 { "cabac", no_argument, NULL, 0 },
834 { "no-cabac", no_argument, NULL, 0 },
835 { "qp", required_argument, NULL, 'q' },
836 { "qpmin", required_argument, NULL, 0 },
837 { "qpmax", required_argument, NULL, 0 },
838 { "qpstep", required_argument, NULL, 0 },
839 { "crf", required_argument, NULL, 0 },
840 { "rc-lookahead",required_argument, NULL, 0 },
841 { "ref", required_argument, NULL, 'r' },
842 { "asm", required_argument, NULL, 0 },
843 { "no-asm", no_argument, NULL, 0 },
844 { "sar", required_argument, NULL, 0 },
845 { "fps", required_argument, NULL, OPT_FPS },
846 { "frames", required_argument, NULL, OPT_FRAMES },
847 { "seek", required_argument, NULL, OPT_SEEK },
848 { "output", required_argument, NULL, 'o' },
849 { "muxer", required_argument, NULL, OPT_MUXER },
850 { "demuxer", required_argument, NULL, OPT_DEMUXER },
851 { "stdout", required_argument, NULL, OPT_MUXER },
852 { "stdin", required_argument, NULL, OPT_DEMUXER },
853 { "index", required_argument, NULL, OPT_INDEX },
854 { "analyse", required_argument, NULL, 0 },
855 { "partitions", required_argument, NULL, 'A' },
856 { "direct", required_argument, NULL, 0 },
857 { "weightb", no_argument, NULL, 'w' },
858 { "no-weightb", no_argument, NULL, 0 },
859 { "weightp", required_argument, NULL, 0 },
860 { "me", required_argument, NULL, 0 },
861 { "merange", required_argument, NULL, 0 },
862 { "mvrange", required_argument, NULL, 0 },
863 { "mvrange-thread", required_argument, NULL, 0 },
864 { "subme", required_argument, NULL, 'm' },
865 { "psy-rd", required_argument, NULL, 0 },
866 { "no-psy", no_argument, NULL, 0 },
867 { "psy", no_argument, NULL, 0 },
868 { "mixed-refs", no_argument, NULL, 0 },
869 { "no-mixed-refs", no_argument, NULL, 0 },
870 { "no-chroma-me", no_argument, NULL, 0 },
871 { "8x8dct", no_argument, NULL, '8' },
872 { "no-8x8dct", no_argument, NULL, 0 },
873 { "trellis", required_argument, NULL, 't' },
874 { "fast-pskip", no_argument, NULL, 0 },
875 { "no-fast-pskip", no_argument, NULL, 0 },
876 { "no-dct-decimate", no_argument, NULL, 0 },
877 { "aq-strength", required_argument, NULL, 0 },
878 { "aq-mode", required_argument, NULL, 0 },
879 { "deadzone-inter", required_argument, NULL, 0 },
880 { "deadzone-intra", required_argument, NULL, 0 },
881 { "level", required_argument, NULL, 0 },
882 { "ratetol", required_argument, NULL, 0 },
883 { "vbv-maxrate", required_argument, NULL, 0 },
884 { "vbv-bufsize", required_argument, NULL, 0 },
885 { "vbv-init", required_argument, NULL, 0 },
886 { "crf-max", required_argument, NULL, 0 },
887 { "ipratio", required_argument, NULL, 0 },
888 { "pbratio", required_argument, NULL, 0 },
889 { "chroma-qp-offset", required_argument, NULL, 0 },
890 { "pass", required_argument, NULL, 'p' },
891 { "stats", required_argument, NULL, 0 },
892 { "qcomp", required_argument, NULL, 0 },
893 { "mbtree", no_argument, NULL, 0 },
894 { "no-mbtree", no_argument, NULL, 0 },
895 { "qblur", required_argument, NULL, 0 },
896 { "cplxblur", required_argument, NULL, 0 },
897 { "zones", required_argument, NULL, 0 },
898 { "qpfile", required_argument, NULL, OPT_QPFILE },
899 { "threads", required_argument, NULL, 0 },
900 { "sliced-threads", no_argument, NULL, 0 },
901 { "no-sliced-threads", no_argument, NULL, 0 },
902 { "slice-max-size", required_argument, NULL, 0 },
903 { "slice-max-mbs", required_argument, NULL, 0 },
904 { "slices", required_argument, NULL, 0 },
905 { "thread-input", no_argument, NULL, OPT_THREAD_INPUT },
906 { "sync-lookahead", required_argument, NULL, 0 },
907 { "non-deterministic", no_argument, NULL, 0 },
908 { "psnr", no_argument, NULL, 0 },
909 { "ssim", no_argument, NULL, 0 },
910 { "quiet", no_argument, NULL, OPT_QUIET },
911 { "verbose", no_argument, NULL, 'v' },
912 { "log-level", required_argument, NULL, OPT_LOG_LEVEL },
913 { "no-progress", no_argument, NULL, OPT_NOPROGRESS },
914 { "visualize", no_argument, NULL, OPT_VISUALIZE },
915 { "dump-yuv", required_argument, NULL, 0 },
916 { "sps-id", required_argument, NULL, 0 },
917 { "aud", no_argument, NULL, 0 },
918 { "nr", required_argument, NULL, 0 },
919 { "cqm", required_argument, NULL, 0 },
920 { "cqmfile", required_argument, NULL, 0 },
921 { "cqm4", required_argument, NULL, 0 },
922 { "cqm4i", required_argument, NULL, 0 },
923 { "cqm4iy", required_argument, NULL, 0 },
924 { "cqm4ic", required_argument, NULL, 0 },
925 { "cqm4p", required_argument, NULL, 0 },
926 { "cqm4py", required_argument, NULL, 0 },
927 { "cqm4pc", required_argument, NULL, 0 },
928 { "cqm8", required_argument, NULL, 0 },
929 { "cqm8i", required_argument, NULL, 0 },
930 { "cqm8p", required_argument, NULL, 0 },
931 { "overscan", required_argument, NULL, 0 },
932 { "videoformat", required_argument, NULL, 0 },
933 { "fullrange", required_argument, NULL, 0 },
934 { "colorprim", required_argument, NULL, 0 },
935 { "transfer", required_argument, NULL, 0 },
936 { "colormatrix", required_argument, NULL, 0 },
937 { "chromaloc", required_argument, NULL, 0 },
938 { "force-cfr", no_argument, NULL, 0 },
939 { "tcfile-in", required_argument, NULL, OPT_TCFILE_IN },
940 { "tcfile-out", required_argument, NULL, OPT_TCFILE_OUT },
941 { "timebase", required_argument, NULL, OPT_TIMEBASE },
942 { "pic-struct", no_argument, NULL, 0 },
943 { "crop-rect", required_argument, NULL, 0 },
944 { "nal-hrd", required_argument, NULL, 0 },
945 { "pulldown", required_argument, NULL, OPT_PULLDOWN },
946 { "fake-interlaced", no_argument, NULL, 0 },
947 { "frame-packing", required_argument, NULL, 0 },
948 { "vf", required_argument, NULL, OPT_VIDEO_FILTER },
949 { "video-filter", required_argument, NULL, OPT_VIDEO_FILTER },
950 { "input-res", required_argument, NULL, OPT_INPUT_RES },
951 { "input-csp", required_argument, NULL, OPT_INPUT_CSP },
952 { "input-depth", required_argument, NULL, OPT_INPUT_DEPTH },
953 { "dts-compress", no_argument, NULL, OPT_DTS_COMPRESSION },
957 static int select_output( const char *muxer, char *filename, x264_param_t *param )
959 const char *ext = get_filename_extension( filename );
960 if( !strcmp( filename, "-" ) || strcasecmp( muxer, "auto" ) )
963 if( !strcasecmp( ext, "mp4" ) )
968 param->b_repeat_headers = 0;
969 if( param->i_nal_hrd == X264_NAL_HRD_CBR )
971 x264_cli_log( "x264", X264_LOG_WARNING, "cbr nal-hrd is not compatible with mp4\n" );
972 param->i_nal_hrd = X264_NAL_HRD_VBR;
975 x264_cli_log( "x264", X264_LOG_ERROR, "not compiled with MP4 output support\n" );
979 else if( !strcasecmp( ext, "mkv" ) )
983 param->b_repeat_headers = 0;
985 else if( !strcasecmp( ext, "flv" ) )
989 param->b_repeat_headers = 0;
996 static int select_input( const char *demuxer, char *used_demuxer, char *filename,
997 hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
999 int b_auto = !strcasecmp( demuxer, "auto" );
1000 const char *ext = b_auto ? get_filename_extension( filename ) : "";
1001 int b_regular = strcmp( filename, "-" );
1002 if( !b_regular && b_auto )
1004 b_regular = b_regular && x264_is_regular_file_path( filename );
1007 FILE *f = fopen( filename, "r" );
1010 b_regular = x264_is_regular_file( f );
1014 const char *module = b_auto ? ext : demuxer;
1016 if( !strcasecmp( module, "avs" ) || !strcasecmp( ext, "d2v" ) || !strcasecmp( ext, "dga" ) )
1022 x264_cli_log( "x264", X264_LOG_ERROR, "not compiled with AVS input support\n" );
1026 else if( !strcasecmp( module, "y4m" ) )
1028 else if( !strcasecmp( module, "raw" ) || !strcasecmp( ext, "yuv" ) )
1033 if( b_regular && (b_auto || !strcasecmp( demuxer, "ffms" )) &&
1034 !ffms_input.open_file( filename, p_handle, info, opt ) )
1042 if( (b_auto || !strcasecmp( demuxer, "lavf" )) &&
1043 !lavf_input.open_file( filename, p_handle, info, opt ) )
1051 if( b_regular && (b_auto || !strcasecmp( demuxer, "avs" )) &&
1052 !avs_input.open_file( filename, p_handle, info, opt ) )
1059 if( b_auto && !raw_input.open_file( filename, p_handle, info, opt ) )
1066 FAIL_IF_ERROR( !(*p_handle), "could not open input file `%s' via any method!\n", filename )
1068 strcpy( used_demuxer, module );
1073 static int init_vid_filters( char *sequence, hnd_t *handle, video_info_t *info, x264_param_t *param )
1075 x264_register_vid_filters();
1077 /* intialize baseline filters */
1078 if( x264_init_vid_filter( "source", handle, &filter, info, param, NULL ) ) /* wrap demuxer into a filter */
1080 if( x264_init_vid_filter( "resize", handle, &filter, info, param, "normcsp" ) ) /* normalize csps to be of a known/supported format */
1082 if( x264_init_vid_filter( "fix_vfr_pts", handle, &filter, info, param, NULL ) ) /* fix vfr pts */
1085 /* parse filter chain */
1086 for( char *p = sequence; p && *p; )
1088 int tok_len = strcspn( p, "/" );
1089 int p_len = strlen( p );
1091 int name_len = strcspn( p, ":" );
1093 name_len += name_len != tok_len;
1094 if( x264_init_vid_filter( p, handle, &filter, info, param, p + name_len ) )
1096 p += X264_MIN( tok_len+1, p_len );
1099 /* force end result resolution */
1100 if( !param->i_width && !param->i_height )
1102 param->i_height = info->height;
1103 param->i_width = info->width;
1105 /* if the current csp is supported by libx264, have libx264 use this csp.
1106 * otherwise change the csp to I420 and have libx264 use this.
1107 * when more colorspaces are supported, this decision will need to be updated. */
1108 int csp = info->csp & X264_CSP_MASK;
1109 if( csp > X264_CSP_NONE && csp < X264_CSP_MAX )
1110 param->i_csp = info->csp;
1112 param->i_csp = X264_CSP_I420 | ( info->csp & X264_CSP_HIGH_DEPTH );
1113 if( x264_init_vid_filter( "resize", handle, &filter, info, param, NULL ) )
1117 sprintf( args, "bit_depth=%d", x264_bit_depth );
1119 if( x264_init_vid_filter( "depth", handle, &filter, info, param, args ) )
1125 static int parse_enum_name( const char *arg, const char * const *names, const char **dst )
1127 for( int i = 0; names[i]; i++ )
1128 if( !strcasecmp( arg, names[i] ) )
1136 static int parse_enum_value( const char *arg, const char * const *names, int *dst )
1138 for( int i = 0; names[i]; i++ )
1139 if( !strcasecmp( arg, names[i] ) )
1147 static int parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt )
1149 char *input_filename = NULL;
1150 const char *demuxer = demuxer_names[0];
1151 char *output_filename = NULL;
1152 const char *muxer = muxer_names[0];
1153 char *tcfile_name = NULL;
1154 x264_param_t defaults;
1155 char *profile = NULL;
1156 char *vid_filters = NULL;
1157 int b_thread_input = 0;
1161 int b_user_interlaced = 0;
1162 cli_input_opt_t input_opt;
1163 cli_output_opt_t output_opt;
1164 char *preset = NULL;
1167 x264_param_default( &defaults );
1168 cli_log_level = defaults.i_log_level;
1170 memset( opt, 0, sizeof(cli_opt_t) );
1171 memset( &input_opt, 0, sizeof(cli_input_opt_t) );
1172 memset( &output_opt, 0, sizeof(cli_output_opt_t) );
1173 input_opt.bit_depth = 8;
1174 opt->b_progress = 1;
1176 /* Presets are applied before all other options. */
1179 int c = getopt_long( argc, argv, short_options, long_options, NULL );
1182 if( c == OPT_PRESET )
1190 if( preset && !strcasecmp( preset, "placebo" ) )
1193 if( x264_param_default_preset( param, preset, tune ) < 0 )
1196 /* Parse command line options */
1200 int long_options_index = -1;
1202 int c = getopt_long( argc, argv, short_options, long_options, &long_options_index );
1212 help( &defaults, 0 );
1215 help( &defaults, 1 );
1218 help( &defaults, 2 );
1221 print_version_info();
1224 param->i_frame_total = X264_MAX( atoi( optarg ), 0 );
1227 opt->i_seek = input_opt.seek = X264_MAX( atoi( optarg ), 0 );
1230 output_filename = optarg;
1233 FAIL_IF_ERROR( parse_enum_name( optarg, muxer_names, &muxer ), "Unknown muxer `%s'\n", optarg )
1236 FAIL_IF_ERROR( parse_enum_name( optarg, demuxer_names, &demuxer ), "Unknown demuxer `%s'\n", optarg )
1239 input_opt.index_file = optarg;
1242 opt->qpfile = fopen( optarg, "rb" );
1243 FAIL_IF_ERROR( !opt->qpfile, "can't open qpfile `%s'\n", optarg )
1244 if( !x264_is_regular_file( opt->qpfile ) )
1246 x264_cli_log( "x264", X264_LOG_ERROR, "qpfile incompatible with non-regular file `%s'\n", optarg );
1247 fclose( opt->qpfile );
1251 case OPT_THREAD_INPUT:
1255 cli_log_level = param->i_log_level = X264_LOG_NONE;
1258 cli_log_level = param->i_log_level = X264_LOG_DEBUG;
1261 if( !parse_enum_value( optarg, log_level_names, &cli_log_level ) )
1262 cli_log_level += X264_LOG_NONE;
1264 cli_log_level = atoi( optarg );
1265 param->i_log_level = cli_log_level;
1267 case OPT_NOPROGRESS:
1268 opt->b_progress = 0;
1272 param->b_visualize = 1;
1273 b_exit_on_ctrl_c = 1;
1275 x264_cli_log( "x264", X264_LOG_WARNING, "not compiled with visualization support\n" );
1284 case OPT_SLOWFIRSTPASS:
1289 goto generic_option;
1292 param->b_vfr_input = 0;
1293 goto generic_option;
1294 case OPT_INTERLACED:
1295 b_user_interlaced = 1;
1296 goto generic_option;
1298 tcfile_name = optarg;
1300 case OPT_TCFILE_OUT:
1301 opt->tcfile_out = fopen( optarg, "wb" );
1302 FAIL_IF_ERROR( !opt->tcfile_out, "can't open `%s'\n", optarg )
1305 input_opt.timebase = optarg;
1308 FAIL_IF_ERROR( parse_enum_value( optarg, pulldown_names, &opt->i_pulldown ), "Unknown pulldown `%s'\n", optarg )
1310 case OPT_VIDEO_FILTER:
1311 vid_filters = optarg;
1314 input_opt.resolution = optarg;
1317 input_opt.colorspace = optarg;
1319 case OPT_INPUT_DEPTH:
1320 input_opt.bit_depth = atoi( optarg );
1322 case OPT_DTS_COMPRESSION:
1323 output_opt.use_dts_compress = 1;
1328 if( long_options_index < 0 )
1330 for( int i = 0; long_options[i].name; i++ )
1331 if( long_options[i].val == c )
1333 long_options_index = i;
1336 if( long_options_index < 0 )
1338 /* getopt_long already printed an error message */
1343 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
1349 const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
1350 x264_cli_log( "x264", X264_LOG_ERROR, "invalid argument: %s = %s\n", name, optarg );
1355 /* If first pass mode is used, apply faster settings. */
1357 x264_param_apply_fastfirstpass( param );
1359 /* Apply profile restrictions. */
1360 if( x264_param_apply_profile( param, profile ) < 0 )
1363 /* Get the file name */
1364 FAIL_IF_ERROR( optind > argc - 1 || !output_filename, "No %s file. Run x264 --help for a list of options.\n",
1365 optind > argc - 1 ? "input" : "output" )
1367 if( select_output( muxer, output_filename, param ) )
1369 FAIL_IF_ERROR( output.open_file( output_filename, &opt->hout, &output_opt ), "could not open output file `%s'\n", output_filename )
1371 input_filename = argv[optind++];
1372 video_info_t info = {0};
1373 char demuxername[5];
1375 /* set info flags to param flags to be overwritten by demuxer as necessary. */
1376 info.csp = param->i_csp;
1377 info.fps_num = param->i_fps_num;
1378 info.fps_den = param->i_fps_den;
1379 info.interlaced = param->b_interlaced;
1380 info.sar_width = param->vui.i_sar_width;
1381 info.sar_height = param->vui.i_sar_height;
1382 info.tff = param->b_tff;
1383 info.vfr = param->b_vfr_input;
1385 if( select_input( demuxer, demuxername, input_filename, &opt->hin, &info, &input_opt ) )
1388 FAIL_IF_ERROR( !opt->hin && input.open_file( input_filename, &opt->hin, &info, &input_opt ),
1389 "could not open input file `%s'\n", input_filename )
1391 x264_reduce_fraction( &info.sar_width, &info.sar_height );
1392 x264_reduce_fraction( &info.fps_num, &info.fps_den );
1393 x264_cli_log( demuxername, X264_LOG_INFO, "%dx%d%c %d:%d @ %d/%d fps (%cfr)\n", info.width,
1394 info.height, info.interlaced ? 'i' : 'p', info.sar_width, info.sar_height,
1395 info.fps_num, info.fps_den, info.vfr ? 'v' : 'c' );
1399 FAIL_IF_ERROR( b_user_fps, "--fps + --tcfile-in is incompatible.\n" )
1400 FAIL_IF_ERROR( timecode_input.open_file( tcfile_name, &opt->hin, &info, &input_opt ), "timecode input failed\n" )
1401 input = timecode_input;
1403 else FAIL_IF_ERROR( !info.vfr && input_opt.timebase, "--timebase is incompatible with cfr input\n" )
1405 /* init threaded input while the information about the input video is unaltered by filtering */
1407 if( info.thread_safe && (b_thread_input || param->i_threads > 1
1408 || (param->i_threads == X264_THREADS_AUTO && x264_cpu_num_processors() > 1)) )
1410 if( thread_input.open_file( NULL, &opt->hin, &info, NULL ) )
1412 fprintf( stderr, "x264 [error]: threaded input failed\n" );
1415 input = thread_input;
1419 /* override detected values by those specified by the user */
1420 if( param->vui.i_sar_width && param->vui.i_sar_height )
1422 info.sar_width = param->vui.i_sar_width;
1423 info.sar_height = param->vui.i_sar_height;
1427 info.fps_num = param->i_fps_num;
1428 info.fps_den = param->i_fps_den;
1432 info.timebase_num = info.fps_den;
1433 info.timebase_den = info.fps_num;
1435 if( !tcfile_name && input_opt.timebase )
1437 uint64_t i_user_timebase_num;
1438 uint64_t i_user_timebase_den;
1439 int ret = sscanf( input_opt.timebase, "%"SCNu64"/%"SCNu64, &i_user_timebase_num, &i_user_timebase_den );
1440 FAIL_IF_ERROR( !ret, "invalid argument: timebase = %s\n", input_opt.timebase )
1443 i_user_timebase_num = info.timebase_num;
1444 i_user_timebase_den = strtoul( input_opt.timebase, NULL, 10 );
1446 FAIL_IF_ERROR( i_user_timebase_num > UINT32_MAX || i_user_timebase_den > UINT32_MAX,
1447 "timebase you specified exceeds H.264 maximum\n" )
1448 opt->timebase_convert_multiplier = ((double)i_user_timebase_den / info.timebase_den)
1449 * ((double)info.timebase_num / i_user_timebase_num);
1450 info.timebase_num = i_user_timebase_num;
1451 info.timebase_den = i_user_timebase_den;
1454 if( b_user_interlaced )
1456 info.interlaced = param->b_interlaced;
1457 info.tff = param->b_tff;
1460 if( init_vid_filters( vid_filters, &opt->hin, &info, param ) )
1463 /* set param flags from the post-filtered video */
1464 param->b_vfr_input = info.vfr;
1465 param->i_fps_num = info.fps_num;
1466 param->i_fps_den = info.fps_den;
1467 param->i_timebase_num = info.timebase_num;
1468 param->i_timebase_den = info.timebase_den;
1469 param->vui.i_sar_width = info.sar_width;
1470 param->vui.i_sar_height = info.sar_height;
1472 info.num_frames = X264_MAX( info.num_frames - opt->i_seek, 0 );
1473 if( (!info.num_frames || param->i_frame_total < info.num_frames)
1474 && param->i_frame_total > 0 )
1475 info.num_frames = param->i_frame_total;
1476 param->i_frame_total = info.num_frames;
1478 if( !b_user_interlaced && info.interlaced )
1480 x264_cli_log( "x264", X264_LOG_WARNING, "input appears to be interlaced, enabling %cff interlaced mode.\n"
1481 " If you want otherwise, use --no-interlaced or --%cff\n",
1482 info.tff ? 't' : 'b', info.tff ? 'b' : 't' );
1483 param->b_interlaced = 1;
1484 param->b_tff = !!info.tff;
1487 /* Automatically reduce reference frame count to match the user's target level
1488 * if the user didn't explicitly set a reference frame count. */
1491 int mbs = (((param->i_width)+15)>>4) * (((param->i_height)+15)>>4);
1492 for( int i = 0; x264_levels[i].level_idc != 0; i++ )
1493 if( param->i_level_idc == x264_levels[i].level_idc )
1495 while( mbs * 384 * param->i_frame_reference > x264_levels[i].dpb &&
1496 param->i_frame_reference > 1 )
1498 param->i_frame_reference--;
1508 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
1510 int num = -1, qp, ret;
1513 while( num < i_frame )
1515 file_pos = ftell( opt->qpfile );
1517 ret = fscanf( opt->qpfile, "%d %c%*[ \t]%d\n", &num, &type, &qp );
1518 pic->i_type = X264_TYPE_AUTO;
1519 pic->i_qpplus1 = X264_QP_AUTO;
1520 if( num > i_frame || ret == EOF )
1522 fseek( opt->qpfile, file_pos, SEEK_SET );
1525 if( num < i_frame && ret >= 2 )
1527 if( ret == 3 && qp >= 0 )
1528 pic->i_qpplus1 = qp+1;
1529 if ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
1530 else if( type == 'i' ) pic->i_type = X264_TYPE_I;
1531 else if( type == 'K' ) pic->i_type = X264_TYPE_KEYFRAME;
1532 else if( type == 'P' ) pic->i_type = X264_TYPE_P;
1533 else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
1534 else if( type == 'b' ) pic->i_type = X264_TYPE_B;
1536 if( ret < 2 || qp < -1 || qp > QP_MAX )
1538 x264_cli_log( "x264", X264_LOG_ERROR, "can't parse qpfile for frame %d\n", i_frame );
1539 fclose( opt->qpfile );
1546 static int encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic, int64_t *last_dts )
1548 x264_picture_t pic_out;
1551 int i_frame_size = 0;
1553 i_frame_size = x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out );
1555 FAIL_IF_ERROR( i_frame_size < 0, "x264_encoder_encode failed\n" );
1559 i_frame_size = output.write_frame( hout, nal[0].p_payload, i_frame_size, &pic_out );
1560 *last_dts = pic_out.i_dts;
1563 return i_frame_size;
1566 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 )
1569 int64_t i_elapsed = x264_mdate() - i_start;
1570 double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1573 bitrate = (double) i_file * 8 / ( (double) last_ts * 1000 * param->i_timebase_num / param->i_timebase_den );
1575 bitrate = (double) i_file * 8 / ( (double) 1000 * param->i_fps_den / param->i_fps_num );
1578 int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1579 sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
1580 100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
1581 eta/3600, (eta/60)%60, eta%60 );
1585 sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
1587 fprintf( stderr, "%s \r", buf+5 );
1588 SetConsoleTitle( buf );
1589 fflush( stderr ); // needed in windows
1592 static void convert_cli_to_lib_pic( x264_picture_t *lib, cli_pic_t *cli )
1594 memcpy( lib->img.i_stride, cli->img.stride, sizeof(cli->img.stride) );
1595 memcpy( lib->img.plane, cli->img.plane, sizeof(cli->img.plane) );
1596 lib->img.i_plane = cli->img.planes;
1597 lib->img.i_csp = cli->img.csp;
1598 lib->i_pts = cli->pts;
1601 static int encode( x264_param_t *param, cli_opt_t *opt )
1606 const cli_pulldown_t *pulldown = NULL; // shut up gcc
1608 int i_frame, i_frame_output;
1609 int64_t i_start, i_end;
1612 int i_update_interval;
1613 int64_t last_dts = 0;
1614 int64_t prev_dts = 0;
1615 int64_t first_dts = 0;
1616 # define MAX_PTS_WARNING 3 /* arbitrary */
1617 int pts_warning_cnt = 0;
1618 int64_t largest_pts = -1;
1619 int64_t second_largest_pts = -1;
1620 int64_t ticks_per_frame;
1622 double pulldown_pts = 0;
1624 opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
1625 i_update_interval = param->i_frame_total ? x264_clip3( param->i_frame_total / 1000, 1, 10 ) : 10;
1627 /* set up pulldown */
1628 if( opt->i_pulldown && !param->b_vfr_input )
1630 param->b_pulldown = 1;
1631 param->b_pic_struct = 1;
1632 pulldown = &pulldown_values[opt->i_pulldown];
1633 param->i_timebase_num = param->i_fps_den;
1634 FAIL_IF_ERROR( fmod( param->i_fps_num * pulldown->fps_factor, 1 ),
1635 "unsupported framerate for chosen pulldown\n" )
1636 param->i_timebase_den = param->i_fps_num * pulldown->fps_factor;
1639 if( ( h = x264_encoder_open( param ) ) == NULL )
1641 x264_cli_log( "x264", X264_LOG_ERROR, "x264_encoder_open failed\n" );
1642 filter.free( opt->hin );
1646 x264_encoder_parameters( h, param );
1648 if( output.set_param( opt->hout, param ) )
1650 x264_cli_log( "x264", X264_LOG_ERROR, "can't set outfile param\n" );
1651 filter.free( opt->hin );
1652 output.close_file( opt->hout, largest_pts, second_largest_pts );
1656 i_start = x264_mdate();
1657 /* ticks/frame = ticks/second / frames/second */
1658 ticks_per_frame = (int64_t)param->i_timebase_den * param->i_fps_den / param->i_timebase_num / param->i_fps_num;
1659 FAIL_IF_ERROR( ticks_per_frame < 1 && !param->b_vfr_input, "ticks_per_frame invalid: %"PRId64"\n", ticks_per_frame )
1660 ticks_per_frame = X264_MAX( ticks_per_frame, 1 );
1662 if( !param->b_repeat_headers )
1664 // Write SPS/PPS/SEI
1665 x264_nal_t *headers;
1668 FAIL_IF_ERROR( x264_encoder_headers( h, &headers, &i_nal ) < 0, "x264_encoder_headers failed\n" )
1669 if( (i_file = output.write_headers( opt->hout, headers )) < 0 )
1673 if( opt->tcfile_out )
1674 fprintf( opt->tcfile_out, "# timecode format v2\n" );
1677 for( i_frame = 0, i_frame_output = 0; !b_ctrl_c && (i_frame < param->i_frame_total || !param->i_frame_total); i_frame++ )
1679 if( filter.get_frame( opt->hin, &cli_pic, i_frame + opt->i_seek ) )
1681 x264_picture_init( &pic );
1682 convert_cli_to_lib_pic( &pic, &cli_pic );
1684 if( !param->b_vfr_input )
1685 pic.i_pts = i_frame;
1687 if( opt->i_pulldown && !param->b_vfr_input )
1689 pic.i_pic_struct = pulldown->pattern[ i_frame % pulldown->mod ];
1690 pic.i_pts = (int64_t)( pulldown_pts + 0.5 );
1691 pulldown_pts += pulldown_frame_duration[pic.i_pic_struct];
1693 else if( opt->timebase_convert_multiplier )
1694 pic.i_pts = (int64_t)( pic.i_pts * opt->timebase_convert_multiplier + 0.5 );
1696 if( pic.i_pts <= largest_pts )
1698 if( cli_log_level >= X264_LOG_DEBUG || pts_warning_cnt < MAX_PTS_WARNING )
1699 x264_cli_log( "x264", X264_LOG_WARNING, "non-strictly-monotonic pts at frame %d (%"PRId64" <= %"PRId64")\n",
1700 i_frame, pic.i_pts, largest_pts );
1701 else if( pts_warning_cnt == MAX_PTS_WARNING )
1702 x264_cli_log( "x264", X264_LOG_WARNING, "too many nonmonotonic pts warnings, suppressing further ones\n" );
1704 pic.i_pts = largest_pts + ticks_per_frame;
1707 second_largest_pts = largest_pts;
1708 largest_pts = pic.i_pts;
1709 if( opt->tcfile_out )
1710 fprintf( opt->tcfile_out, "%.6f\n", pic.i_pts * ((double)param->i_timebase_num / param->i_timebase_den) * 1e3 );
1713 parse_qpfile( opt, &pic, i_frame + opt->i_seek );
1715 prev_dts = last_dts;
1716 i_frame_size = encode_frame( h, opt->hout, &pic, &last_dts );
1717 if( i_frame_size < 0 )
1719 i_file += i_frame_size;
1723 if( i_frame_output == 1 )
1724 first_dts = prev_dts = last_dts;
1727 if( filter.release_frame( opt->hin, &cli_pic, i_frame + opt->i_seek ) )
1730 /* update status line (up to 1000 times per input file) */
1731 if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1732 print_status( i_start, i_frame_output, param->i_frame_total, i_file, param, 2 * last_dts - prev_dts - first_dts );
1734 /* Flush delayed frames */
1735 while( !b_ctrl_c && x264_encoder_delayed_frames( h ) )
1737 prev_dts = last_dts;
1738 i_frame_size = encode_frame( h, opt->hout, NULL, &last_dts );
1739 if( i_frame_size < 0 )
1741 i_file += i_frame_size;
1745 if( i_frame_output == 1 )
1746 first_dts = prev_dts = last_dts;
1748 if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1749 print_status( i_start, i_frame_output, param->i_frame_total, i_file, param, 2 * last_dts - prev_dts - first_dts );
1751 if( pts_warning_cnt >= MAX_PTS_WARNING && cli_log_level < X264_LOG_DEBUG )
1752 x264_cli_log( "x264", X264_LOG_WARNING, "%d suppressed nonmonotonic pts warnings\n", pts_warning_cnt-MAX_PTS_WARNING );
1754 /* duration algorithm fails when only 1 frame is output */
1755 if( i_frame_output == 1 )
1756 duration = (double)param->i_fps_den / param->i_fps_num;
1758 duration = (double)(2 * last_dts - prev_dts - first_dts) * param->i_timebase_num / param->i_timebase_den;
1760 duration = (double)(2 * largest_pts - second_largest_pts) * param->i_timebase_num / param->i_timebase_den;
1762 i_end = x264_mdate();
1763 /* Erase progress indicator before printing encoding stats. */
1764 if( opt->b_progress )
1765 fprintf( stderr, " \r" );
1766 x264_encoder_close( h );
1767 fprintf( stderr, "\n" );
1770 fprintf( stderr, "aborted at input frame %d, output frame %d\n", opt->i_seek + i_frame, i_frame_output );
1772 if( opt->tcfile_out )
1774 fclose( opt->tcfile_out );
1775 opt->tcfile_out = NULL;
1778 filter.free( opt->hin );
1779 output.close_file( opt->hout, largest_pts, second_largest_pts );
1781 if( i_frame_output > 0 )
1783 double fps = (double)i_frame_output * (double)1000000 /
1784 (double)( i_end - i_start );
1786 fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame_output, fps,
1787 (double) i_file * 8 / ( 1000 * duration ) );