1 /*****************************************************************************
2 * x264: h264 encoder testing program.
3 *****************************************************************************
4 * Copyright (C) 2003-2008 x264 project
6 * Authors: Loren Merritt <lorenm@u.washington.edu>
7 * Laurent Aimar <fenrir@via.ecp.fr>
8 * Steven Walters <kemuri9@gmail.com>
9 * Kieran Kunhya <kieran@kunhya.com>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
24 *****************************************************************************/
33 #include "common/common.h"
35 #include "input/input.h"
36 #include "output/output.h"
38 #define FAIL_IF_ERROR( cond, ... ) FAIL_IF_ERR( cond, "x264", __VA_ARGS__ )
43 #define SetConsoleTitle(t)
47 static int b_ctrl_c = 0;
48 static int b_exit_on_ctrl_c = 0;
49 static void SigIntHandler( int a )
51 if( b_exit_on_ctrl_c )
63 double timebase_convert_multiplier;
67 /* i/o file operation function pointer structs */
69 static cli_output_t output;
71 static const char * const demuxer_names[] =
88 static const char * const muxer_names[] =
100 static const char * const pulldown_names[] = { "none", "22", "32", "64", "double", "triple", "euro", 0 };
101 static const char * const log_level_names[] = { "none", "error", "warning", "info", "debug", 0 };
111 X264_PULLDOWN_22 = 1,
114 X264_PULLDOWN_DOUBLE,
115 X264_PULLDOWN_TRIPLE,
119 #define TB PIC_STRUCT_TOP_BOTTOM
120 #define BT PIC_STRUCT_BOTTOM_TOP
121 #define TBT PIC_STRUCT_TOP_BOTTOM_TOP
122 #define BTB PIC_STRUCT_BOTTOM_TOP_BOTTOM
124 static const cli_pulldown_t pulldown_values[] =
126 [X264_PULLDOWN_22] = {1, {TB}, 1.0},
127 [X264_PULLDOWN_32] = {4, {TBT, BT, BTB, TB}, 1.25},
128 [X264_PULLDOWN_64] = {2, {PIC_STRUCT_DOUBLE, PIC_STRUCT_TRIPLE}, 1.0},
129 [X264_PULLDOWN_DOUBLE] = {1, {PIC_STRUCT_DOUBLE}, 2.0},
130 [X264_PULLDOWN_TRIPLE] = {1, {PIC_STRUCT_TRIPLE}, 3.0},
131 [X264_PULLDOWN_EURO] = {24, {TBT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT, BT,
132 BTB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB}, 25.0/24.0}
140 // indexed by pic_struct enum
141 static const float pulldown_frame_duration[10] = { 0.0, 1, 0.5, 0.5, 1, 1, 1.5, 1.5, 2, 3 };
143 static void Help( x264_param_t *defaults, int longhelp );
144 static int Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
145 static int Encode( x264_param_t *param, cli_opt_t *opt );
147 /* logging and printing for within the cli system */
148 static int cli_log_level;
149 void x264_cli_log( const char *name, int i_level, const char *fmt, ... )
151 if( i_level > cli_log_level )
159 case X264_LOG_WARNING:
172 fprintf( stderr, "%s [%s]: ", name, s_level );
174 va_start( arg, fmt );
175 vfprintf( stderr, fmt, arg );
179 void x264_cli_printf( int i_level, const char *fmt, ... )
181 if( i_level > cli_log_level )
184 va_start( arg, fmt );
185 vfprintf( stderr, fmt, arg );
189 /****************************************************************************
191 ****************************************************************************/
192 int main( int argc, char **argv )
199 pthread_win32_process_attach_np();
200 pthread_win32_thread_attach_np();
204 _setmode(_fileno(stdin), _O_BINARY);
205 _setmode(_fileno(stdout), _O_BINARY);
208 /* Parse command line */
209 if( Parse( argc, argv, ¶m, &opt ) < 0 )
212 /* Control-C handler */
213 signal( SIGINT, SigIntHandler );
215 ret = Encode( ¶m, &opt );
218 pthread_win32_thread_detach_np();
219 pthread_win32_process_detach_np();
225 static char const *strtable_lookup( const char * const table[], int idx )
227 int i = 0; while( table[i] ) i++;
228 return ( ( idx >= 0 && idx < i ) ? table[ idx ] : "???" );
231 static char *stringify_names( char *buf, const char * const names[] )
235 for( p[0] = 0; names[i]; i++ )
237 p += sprintf( p, "%s", names[i] );
239 p += sprintf( p, ", " );
244 /*****************************************************************************
246 *****************************************************************************/
247 static void Help( x264_param_t *defaults, int longhelp )
251 #define H1 if(longhelp>=1) printf
252 #define H2 if(longhelp==2) printf
253 H0( "x264 core:%d%s\n"
254 "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
256 "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
257 " or YUV4MPEG 4:2:0 (*.y4m),\n"
258 " or Avisynth if compiled with support (%s).\n"
259 " or libav* formats if compiled with lavf support (%s) or ffms support (%s).\n"
260 "Outfile type is selected by filename:\n"
261 " .264 -> Raw bytestream\n"
262 " .mkv -> Matroska\n"
263 " .flv -> Flash Video\n"
264 " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
268 " -h, --help List basic options\n"
269 " --longhelp List more options\n"
270 " --fullhelp List all options\n"
272 X264_BUILD, X264_VERSION,
294 H0( "Example usage:\n" );
296 H0( " Constant quality mode:\n" );
297 H0( " x264 --crf 24 -o <output> <input>\n" );
299 H0( " Two-pass with a bitrate of 1000kbps:\n" );
300 H0( " x264 --pass 1 --bitrate 1000 -o <output> <input>\n" );
301 H0( " x264 --pass 2 --bitrate 1000 -o <output> <input>\n" );
303 H0( " Lossless:\n" );
304 H0( " x264 --crf 0 -o <output> <input>\n" );
306 H0( " Maximum PSNR at the cost of speed and visual quality:\n" );
307 H0( " x264 --preset placebo --tune psnr -o <output> <input>\n" );
309 H0( " Constant bitrate at 1000kbps with a 2 second-buffer:\n");
310 H0( " x264 --vbv-bufsize 2000 --bitrate 1000 -o <output> <input>\n" );
314 H0( " --profile Force the limits of an H.264 profile [high]\n"
315 " Overrides all settings.\n" );
317 " --no-8x8dct --bframes 0 --no-cabac\n"
318 " --cqm flat --weightp 0\n"
322 " --no-8x8dct --cqm flat\n"
326 else H0( " - baseline,main,high\n" );
327 H0( " --preset Use a preset to select encoding settings [medium]\n"
328 " Overridden by user settings.\n" );
329 H2( " - ultrafast:\n"
330 " --no-8x8dct --aq-mode 0 --b-adapt 0\n"
331 " --bframes 0 --no-cabac --no-deblock\n"
332 " --no-mbtree --me dia --no-mixed-refs\n"
333 " --partitions none --rc-lookahead 0 --ref 1\n"
334 " --scenecut 0 --subme 0 --trellis 0\n"
335 " --no-weightb --weightp 0\n"
337 " --no-mbtree --me dia --no-mixed-refs\n"
338 " --partitions i8x8,i4x4 --rc-lookahead 0\n"
339 " --ref 1 --subme 1 --trellis 0 --weightp 0\n"
341 " --no-mixed-refs --rc-lookahead 10\n"
342 " --ref 1 --subme 2 --trellis 0 --weightp 0\n"
344 " --no-mixed-refs --rc-lookahead 20\n"
345 " --ref 2 --subme 4 --weightp 1\n"
347 " --rc-lookahead 30 --ref 2 --subme 6\n"
349 " Default settings apply.\n"
351 " --b-adapt 2 --direct auto --me umh\n"
352 " --rc-lookahead 50 --ref 5 --subme 8\n"
354 " --b-adapt 2 --direct auto --me umh\n"
355 " --partitions all --rc-lookahead 60\n"
356 " --ref 8 --subme 9 --trellis 2\n"
358 " --b-adapt 2 --bframes 8 --direct auto\n"
359 " --me umh --merange 24 --partitions all\n"
360 " --ref 16 --subme 10 --trellis 2\n"
361 " --rc-lookahead 60\n"
363 " --bframes 16 --b-adapt 2 --direct auto\n"
364 " --slow-firstpass --no-fast-pskip\n"
365 " --me tesa --merange 24 --partitions all\n"
366 " --rc-lookahead 60 --ref 16 --subme 10\n"
368 else H0( " - ultrafast,superfast,veryfast,faster,fast\n"
369 " - medium,slow,slower,veryslow,placebo\n" );
370 H0( " --tune Tune the settings for a particular type of source\n"
372 " Overridden by user settings.\n"
373 " Multiple tunings are separated by commas.\n"
374 " Only one psy tuning can be used at a time.\n" );
375 H2( " - film (psy tuning):\n"
376 " --deblock -1:-1 --psy-rd <unset>:0.15\n"
377 " - animation (psy tuning):\n"
378 " --bframes {+2} --deblock 1:1\n"
379 " --psy-rd 0.4:<unset> --aq-strength 0.6\n"
380 " --ref {Double if >1 else 1}\n"
381 " - grain (psy tuning):\n"
382 " --aq-strength 0.5 --no-dct-decimate\n"
383 " --deadzone-inter 6 --deadzone-intra 6\n"
384 " --deblock -2:-2 --ipratio 1.1 \n"
385 " --pbratio 1.1 --psy-rd <unset>:0.25\n"
387 " - stillimage (psy tuning):\n"
388 " --aq-strength 1.2 --deblock -3:-3\n"
389 " --psy-rd 2.0:0.7\n"
390 " - psnr (psy tuning):\n"
391 " --aq-mode 0 --no-psy\n"
392 " - ssim (psy tuning):\n"
393 " --aq-mode 2 --no-psy\n"
395 " --no-cabac --no-deblock --no-weightb\n"
398 " --bframes 0 --force-cfr --no-mbtree\n"
399 " --sync-lookahead 0 --sliced-threads\n"
400 " --rc-lookahead 0\n" );
401 else H0( " - psy tunings: film,animation,grain,\n"
402 " stillimage,psnr,ssim\n"
403 " - other tunings: fastdecode,zerolatency\n" );
404 H2( " --slow-firstpass Don't force these faster settings with --pass 1:\n"
405 " --no-8x8dct --me dia --partitions none\n"
406 " --ref 1 --subme {2 if >2 else unchanged}\n"
407 " --trellis 0 --fast-pskip\n" );
408 else H1( " --slow-firstpass Don't force faster settings with --pass 1\n" );
410 H0( "Frame-type options:\n" );
412 H0( " -I, --keyint <integer> Maximum GOP size [%d]\n", defaults->i_keyint_max );
413 H2( " -i, --min-keyint <integer> Minimum GOP size [auto]\n" );
414 H2( " --no-scenecut Disable adaptive I-frame decision\n" );
415 H2( " --scenecut <integer> How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
416 H2( " --intra-refresh Use Periodic Intra Refresh instead of IDR frames\n" );
417 H1( " -b, --bframes <integer> Number of B-frames between I and P [%d]\n", defaults->i_bframe );
418 H1( " --b-adapt <integer> Adaptive B-frame decision method [%d]\n"
419 " Higher values may lower threading efficiency.\n"
422 " - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
423 H2( " --b-bias <integer> Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
424 H1( " --b-pyramid <string> Keep some B-frames as references [%s]\n"
425 " - none: Disabled\n"
426 " - strict: Strictly hierarchical pyramid\n"
427 " - normal: Non-strict (not Blu-ray compatible)\n",
428 strtable_lookup( x264_b_pyramid_names, defaults->i_bframe_pyramid ) );
429 H1( " --open-gop <string> Use recovery points to close GOPs [none]\n"
430 " - none: closed GOPs only\n"
431 " - normal: standard open GOPs\n"
432 " (not Blu-ray compatible)\n"
433 " - bluray: Blu-ray-compatible open GOPs\n"
434 " Only available with b-frames\n" );
435 H1( " --no-cabac Disable CABAC\n" );
436 H1( " -r, --ref <integer> Number of reference frames [%d]\n", defaults->i_frame_reference );
437 H1( " --no-deblock Disable loop filter\n" );
438 H1( " -f, --deblock <alpha:beta> Loop filter parameters [%d:%d]\n",
439 defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
440 H2( " --slices <integer> Number of slices per frame; forces rectangular\n"
441 " slices and is overridden by other slicing options\n" );
442 else H1( " --slices <integer> Number of slices per frame\n" );
443 H2( " --slice-max-size <integer> Limit the size of each slice in bytes\n");
444 H2( " --slice-max-mbs <integer> Limit the size of each slice in macroblocks\n");
445 H0( " --tff Enable interlaced mode (top field first)\n" );
446 H0( " --bff Enable interlaced mode (bottom field first)\n" );
447 H2( " --constrained-intra Enable constrained intra prediction.\n" );
448 H0( " --pulldown <string> Use soft pulldown to change frame rate\n"
449 " - none, 22, 32, 64, double, triple, euro (requires cfr input)\n" );
450 H2( " --fake-interlaced Flag stream as interlaced but encode progressive.\n"
451 " Makes it possible to encode 25p and 30p Blu-Ray\n"
452 " streams. Ignored in interlaced mode.\n" );
454 H0( "Ratecontrol:\n" );
456 H1( " -q, --qp <integer> Force constant QP (0-51, 0=lossless)\n" );
457 H0( " -B, --bitrate <integer> Set bitrate (kbit/s)\n" );
458 H0( " --crf <float> Quality-based VBR (0-51, 0=lossless) [%.1f]\n", defaults->rc.f_rf_constant );
459 H1( " --rc-lookahead <integer> Number of frames for frametype lookahead [%d]\n", defaults->rc.i_lookahead );
460 H0( " --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
461 H0( " --vbv-bufsize <integer> Set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
462 H2( " --vbv-init <float> Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
463 H2( " --crf-max <float> With CRF+VBV, limit RF to this value\n"
464 " May cause VBV underflows!\n" );
465 H2( " --qpmin <integer> Set min QP [%d]\n", defaults->rc.i_qp_min );
466 H2( " --qpmax <integer> Set max QP [%d]\n", defaults->rc.i_qp_max );
467 H2( " --qpstep <integer> Set max QP step [%d]\n", defaults->rc.i_qp_step );
468 H2( " --ratetol <float> Tolerance of ABR ratecontrol and VBV [%.1f]\n", defaults->rc.f_rate_tolerance );
469 H2( " --ipratio <float> QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
470 H2( " --pbratio <float> QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
471 H2( " --chroma-qp-offset <integer> QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
472 H2( " --aq-mode <integer> AQ method [%d]\n"
474 " - 1: Variance AQ (complexity mask)\n"
475 " - 2: Auto-variance AQ (experimental)\n", defaults->rc.i_aq_mode );
476 H1( " --aq-strength <float> Reduces blocking and blurring in flat and\n"
477 " textured areas. [%.1f]\n", defaults->rc.f_aq_strength );
479 H0( " -p, --pass <integer> Enable multipass ratecontrol\n"
480 " - 1: First pass, creates stats file\n"
481 " - 2: Last pass, does not overwrite stats file\n" );
482 H2( " - 3: Nth pass, overwrites stats file\n" );
483 H1( " --stats <string> Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
484 H2( " --no-mbtree Disable mb-tree ratecontrol.\n");
485 H2( " --qcomp <float> QP curve compression [%.2f]\n", defaults->rc.f_qcompress );
486 H2( " --cplxblur <float> Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
487 H2( " --qblur <float> Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
488 H2( " --zones <zone0>/<zone1>/... Tweak the bitrate of regions of the video\n" );
489 H2( " Each zone is of the form\n"
490 " <start frame>,<end frame>,<option>\n"
491 " where <option> is either\n"
492 " q=<integer> (force QP)\n"
493 " or b=<float> (bitrate multiplier)\n" );
494 H2( " --qpfile <string> Force frametypes and QPs for some or all frames\n"
495 " Format of each line: framenumber frametype QP\n"
496 " QP of -1 lets x264 choose. Frametypes: I,i,K,P,B,b.\n"
497 " K=<I or i> depending on open-gop setting\n"
498 " QPs are restricted by qpmin/qpmax.\n" );
502 H1( " -A, --partitions <string> Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
503 " - p8x8, p4x4, b8x8, i8x8, i4x4\n"
505 " (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
506 H1( " --direct <string> Direct MV prediction mode [\"%s\"]\n"
507 " - none, spatial, temporal, auto\n",
508 strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
509 H2( " --no-weightb Disable weighted prediction for B-frames\n" );
510 H1( " --weightp <integer> Weighted prediction for P-frames [%d]\n"
512 " - 1: Blind offset\n"
513 " - 2: Smart analysis\n", defaults->analyse.i_weighted_pred );
514 H1( " --me <string> Integer pixel motion estimation method [\"%s\"]\n",
515 strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
516 H2( " - dia: diamond search, radius 1 (fast)\n"
517 " - hex: hexagonal search, radius 2\n"
518 " - umh: uneven multi-hexagon search\n"
519 " - esa: exhaustive search\n"
520 " - tesa: hadamard exhaustive search (slow)\n" );
521 else H1( " - dia, hex, umh\n" );
522 H2( " --merange <integer> Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
523 H2( " --mvrange <integer> Maximum motion vector length [-1 (auto)]\n" );
524 H2( " --mvrange-thread <int> Minimum buffer between threads [-1 (auto)]\n" );
525 H1( " -m, --subme <integer> Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
526 H2( " - 0: fullpel only (not recommended)\n"
527 " - 1: SAD mode decision, one qpel iteration\n"
528 " - 2: SATD mode decision\n"
529 " - 3-5: Progressively more qpel\n"
530 " - 6: RD mode decision for I/P-frames\n"
531 " - 7: RD mode decision for all frames\n"
532 " - 8: RD refinement for I/P-frames\n"
533 " - 9: RD refinement for all frames\n"
534 " - 10: QP-RD - requires trellis=2, aq-mode>0\n" );
535 else H1( " decision quality: 1=fast, 10=best.\n" );
536 H1( " --psy-rd Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
537 " #1: RD (requires subme>=6)\n"
538 " #2: Trellis (requires trellis, experimental)\n",
539 defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
540 H2( " --no-psy Disable all visual optimizations that worsen\n"
541 " both PSNR and SSIM.\n" );
542 H2( " --no-mixed-refs Don't decide references on a per partition basis\n" );
543 H2( " --no-chroma-me Ignore chroma in motion estimation\n" );
544 H1( " --no-8x8dct Disable adaptive spatial transform size\n" );
545 H1( " -t, --trellis <integer> Trellis RD quantization. Requires CABAC. [%d]\n"
547 " - 1: enabled only on the final encode of a MB\n"
548 " - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
549 H2( " --no-fast-pskip Disables early SKIP detection on P-frames\n" );
550 H2( " --no-dct-decimate Disables coefficient thresholding on P-frames\n" );
551 H1( " --nr <integer> Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
553 H2( " --deadzone-inter <int> Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
554 H2( " --deadzone-intra <int> Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
555 H2( " Deadzones should be in the range 0 - 32.\n" );
556 H2( " --cqm <string> Preset quant matrices [\"flat\"]\n"
558 H1( " --cqmfile <string> Read custom quant matrices from a JM-compatible file\n" );
559 H2( " Overrides any other --cqm* options.\n" );
560 H2( " --cqm4 <list> Set all 4x4 quant matrices\n"
561 " Takes a comma-separated list of 16 integers.\n" );
562 H2( " --cqm8 <list> Set all 8x8 quant matrices\n"
563 " Takes a comma-separated list of 64 integers.\n" );
564 H2( " --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
565 " Set both luma and chroma quant matrices\n" );
566 H2( " --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
567 " Set individual quant matrices\n" );
569 H2( "Video Usability Info (Annex E):\n" );
570 H2( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
571 H2( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
573 H2( " --overscan <string> Specify crop overscan setting [\"%s\"]\n"
574 " - undef, show, crop\n",
575 strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
576 H2( " --videoformat <string> Specify video format [\"%s\"]\n"
577 " - component, pal, ntsc, secam, mac, undef\n",
578 strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
579 H2( " --fullrange <string> Specify full range samples setting [\"%s\"]\n"
581 strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ) );
582 H2( " --colorprim <string> Specify color primaries [\"%s\"]\n"
583 " - undef, bt709, bt470m, bt470bg\n"
584 " smpte170m, smpte240m, film\n",
585 strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
586 H2( " --transfer <string> Specify transfer characteristics [\"%s\"]\n"
587 " - undef, bt709, bt470m, bt470bg, linear,\n"
588 " log100, log316, smpte170m, smpte240m\n",
589 strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
590 H2( " --colormatrix <string> Specify color matrix setting [\"%s\"]\n"
591 " - undef, bt709, fcc, bt470bg\n"
592 " smpte170m, smpte240m, GBR, YCgCo\n",
593 strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
594 H2( " --chromaloc <integer> Specify chroma sample location (0 to 5) [%d]\n",
595 defaults->vui.i_chroma_loc );
597 H2( " --nal-hrd <string> Signal HRD information (requires vbv-bufsize)\n"
598 " - none, vbr, cbr (cbr not allowed in .mp4)\n" );
599 H2( " --pic-struct Force pic_struct in Picture Timing SEI\n" );
602 H0( "Input/Output:\n" );
604 H0( " -o, --output Specify output file\n" );
605 H1( " --muxer <string> Specify output container format [\"%s\"]\n"
606 " - %s\n", muxer_names[0], stringify_names( buf, muxer_names ) );
607 H1( " --demuxer <string> Specify input container format [\"%s\"]\n"
608 " - %s\n", demuxer_names[0], stringify_names( buf, demuxer_names ) );
609 H1( " --index <string> Filename for input index file\n" );
610 H0( " --sar width:height Specify Sample Aspect Ratio\n" );
611 H0( " --fps <float|rational> Specify framerate\n" );
612 H0( " --seek <integer> First frame to encode\n" );
613 H0( " --frames <integer> Maximum number of frames to encode\n" );
614 H0( " --level <string> Specify level (as defined by Annex A)\n" );
616 H1( " -v, --verbose Print stats for each frame\n" );
617 H1( " --no-progress Don't show the progress indicator while encoding\n" );
618 H0( " --quiet Quiet Mode\n" );
619 H1( " --log-level <string> Specify the maximum level of logging [\"%s\"]\n"
620 " - %s\n", strtable_lookup( log_level_names, cli_log_level - X264_LOG_NONE ),
621 stringify_names( buf, log_level_names ) );
622 H1( " --psnr Enable PSNR computation\n" );
623 H1( " --ssim Enable SSIM computation\n" );
624 H1( " --threads <integer> Force a specific number of threads\n" );
625 H2( " --sliced-threads Low-latency but lower-efficiency threading\n" );
626 H2( " --thread-input Run Avisynth in its own thread\n" );
627 H2( " --sync-lookahead <integer> Number of buffer frames for threaded lookahead\n" );
628 H2( " --non-deterministic Slightly improve quality of SMP, at the cost of repeatability\n" );
629 H2( " --asm <integer> Override CPU detection\n" );
630 H2( " --no-asm Disable all CPU optimizations\n" );
631 H2( " --visualize Show MB types overlayed on the encoded video\n" );
632 H2( " --dump-yuv <string> Save reconstructed frames\n" );
633 H2( " --sps-id <integer> Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
634 H2( " --aud Use access unit delimiters\n" );
635 H2( " --force-cfr Force constant framerate timestamp generation\n" );
636 H2( " --tcfile-in <string> Force timestamp generation with timecode file\n" );
637 H2( " --tcfile-out <string> Output timecode v2 file from input timestamps\n" );
638 H2( " --timebase <int/int> Specify timebase numerator and denominator\n"
639 " <integer> Specify timebase numerator for input timecode file\n"
640 " or specify timebase denominator for other input\n" );
670 static char short_options[] = "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw";
671 static struct option long_options[] =
673 { "help", no_argument, NULL, 'h' },
674 { "longhelp", no_argument, NULL, OPT_LONGHELP },
675 { "fullhelp", no_argument, NULL, OPT_FULLHELP },
676 { "version", no_argument, NULL, 'V' },
677 { "profile", required_argument, NULL, OPT_PROFILE },
678 { "preset", required_argument, NULL, OPT_PRESET },
679 { "tune", required_argument, NULL, OPT_TUNE },
680 { "slow-firstpass", no_argument, NULL, OPT_SLOWFIRSTPASS },
681 { "bitrate", required_argument, NULL, 'B' },
682 { "bframes", required_argument, NULL, 'b' },
683 { "b-adapt", required_argument, NULL, 0 },
684 { "no-b-adapt", no_argument, NULL, 0 },
685 { "b-bias", required_argument, NULL, 0 },
686 { "b-pyramid", required_argument, NULL, 0 },
687 { "open-gop", required_argument, NULL, 0 },
688 { "min-keyint", required_argument, NULL, 'i' },
689 { "keyint", required_argument, NULL, 'I' },
690 { "intra-refresh", no_argument, NULL, 0 },
691 { "scenecut", required_argument, NULL, 0 },
692 { "no-scenecut", no_argument, NULL, 0 },
693 { "nf", no_argument, NULL, 0 },
694 { "no-deblock", no_argument, NULL, 0 },
695 { "filter", required_argument, NULL, 0 },
696 { "deblock", required_argument, NULL, 'f' },
697 { "interlaced", no_argument, NULL, OPT_INTERLACED },
698 { "tff", no_argument, NULL, OPT_INTERLACED },
699 { "bff", no_argument, NULL, OPT_INTERLACED },
700 { "no-interlaced", no_argument, NULL, OPT_INTERLACED },
701 { "constrained-intra", no_argument, NULL, 0 },
702 { "cabac", no_argument, NULL, 0 },
703 { "no-cabac", no_argument, NULL, 0 },
704 { "qp", required_argument, NULL, 'q' },
705 { "qpmin", required_argument, NULL, 0 },
706 { "qpmax", required_argument, NULL, 0 },
707 { "qpstep", required_argument, NULL, 0 },
708 { "crf", required_argument, NULL, 0 },
709 { "rc-lookahead",required_argument, NULL, 0 },
710 { "ref", required_argument, NULL, 'r' },
711 { "asm", required_argument, NULL, 0 },
712 { "no-asm", no_argument, NULL, 0 },
713 { "sar", required_argument, NULL, 0 },
714 { "fps", required_argument, NULL, OPT_FPS },
715 { "frames", required_argument, NULL, OPT_FRAMES },
716 { "seek", required_argument, NULL, OPT_SEEK },
717 { "output", required_argument, NULL, 'o' },
718 { "muxer", required_argument, NULL, OPT_MUXER },
719 { "demuxer", required_argument, NULL, OPT_DEMUXER },
720 { "stdout", required_argument, NULL, OPT_MUXER },
721 { "stdin", required_argument, NULL, OPT_DEMUXER },
722 { "index", required_argument, NULL, OPT_INDEX },
723 { "analyse", required_argument, NULL, 0 },
724 { "partitions", required_argument, NULL, 'A' },
725 { "direct", required_argument, NULL, 0 },
726 { "weightb", no_argument, NULL, 'w' },
727 { "no-weightb", no_argument, NULL, 0 },
728 { "weightp", required_argument, NULL, 0 },
729 { "me", required_argument, NULL, 0 },
730 { "merange", required_argument, NULL, 0 },
731 { "mvrange", required_argument, NULL, 0 },
732 { "mvrange-thread", required_argument, NULL, 0 },
733 { "subme", required_argument, NULL, 'm' },
734 { "psy-rd", required_argument, NULL, 0 },
735 { "no-psy", no_argument, NULL, 0 },
736 { "psy", no_argument, NULL, 0 },
737 { "mixed-refs", no_argument, NULL, 0 },
738 { "no-mixed-refs", no_argument, NULL, 0 },
739 { "no-chroma-me", no_argument, NULL, 0 },
740 { "8x8dct", no_argument, NULL, 0 },
741 { "no-8x8dct", no_argument, NULL, 0 },
742 { "trellis", required_argument, NULL, 't' },
743 { "fast-pskip", no_argument, NULL, 0 },
744 { "no-fast-pskip", no_argument, NULL, 0 },
745 { "no-dct-decimate", no_argument, NULL, 0 },
746 { "aq-strength", required_argument, NULL, 0 },
747 { "aq-mode", required_argument, NULL, 0 },
748 { "deadzone-inter", required_argument, NULL, '0' },
749 { "deadzone-intra", required_argument, NULL, '0' },
750 { "level", required_argument, NULL, 0 },
751 { "ratetol", required_argument, NULL, 0 },
752 { "vbv-maxrate", required_argument, NULL, 0 },
753 { "vbv-bufsize", required_argument, NULL, 0 },
754 { "vbv-init", required_argument, NULL, 0 },
755 { "crf-max", required_argument, NULL, 0 },
756 { "ipratio", required_argument, NULL, 0 },
757 { "pbratio", required_argument, NULL, 0 },
758 { "chroma-qp-offset", required_argument, NULL, 0 },
759 { "pass", required_argument, NULL, 'p' },
760 { "stats", required_argument, NULL, 0 },
761 { "qcomp", required_argument, NULL, 0 },
762 { "mbtree", no_argument, NULL, 0 },
763 { "no-mbtree", no_argument, NULL, 0 },
764 { "qblur", required_argument, NULL, 0 },
765 { "cplxblur", required_argument, NULL, 0 },
766 { "zones", required_argument, NULL, 0 },
767 { "qpfile", required_argument, NULL, OPT_QPFILE },
768 { "threads", required_argument, NULL, 0 },
769 { "sliced-threads", no_argument, NULL, 0 },
770 { "no-sliced-threads", no_argument, NULL, 0 },
771 { "slice-max-size", required_argument, NULL, 0 },
772 { "slice-max-mbs", required_argument, NULL, 0 },
773 { "slices", required_argument, NULL, 0 },
774 { "thread-input", no_argument, NULL, OPT_THREAD_INPUT },
775 { "sync-lookahead", required_argument, NULL, 0 },
776 { "non-deterministic", no_argument, NULL, 0 },
777 { "psnr", no_argument, NULL, 0 },
778 { "ssim", no_argument, NULL, 0 },
779 { "quiet", no_argument, NULL, OPT_QUIET },
780 { "verbose", no_argument, NULL, 'v' },
781 { "log-level", required_argument, NULL, OPT_LOG_LEVEL },
782 { "no-progress", no_argument, NULL, OPT_NOPROGRESS },
783 { "visualize", no_argument, NULL, OPT_VISUALIZE },
784 { "dump-yuv", required_argument, NULL, 0 },
785 { "sps-id", required_argument, NULL, 0 },
786 { "aud", no_argument, NULL, 0 },
787 { "nr", required_argument, NULL, 0 },
788 { "cqm", required_argument, NULL, 0 },
789 { "cqmfile", required_argument, NULL, 0 },
790 { "cqm4", required_argument, NULL, 0 },
791 { "cqm4i", required_argument, NULL, 0 },
792 { "cqm4iy", required_argument, NULL, 0 },
793 { "cqm4ic", required_argument, NULL, 0 },
794 { "cqm4p", required_argument, NULL, 0 },
795 { "cqm4py", required_argument, NULL, 0 },
796 { "cqm4pc", required_argument, NULL, 0 },
797 { "cqm8", required_argument, NULL, 0 },
798 { "cqm8i", required_argument, NULL, 0 },
799 { "cqm8p", required_argument, NULL, 0 },
800 { "overscan", required_argument, NULL, 0 },
801 { "videoformat", required_argument, NULL, 0 },
802 { "fullrange", required_argument, NULL, 0 },
803 { "colorprim", required_argument, NULL, 0 },
804 { "transfer", required_argument, NULL, 0 },
805 { "colormatrix", required_argument, NULL, 0 },
806 { "chromaloc", required_argument, NULL, 0 },
807 { "force-cfr", no_argument, NULL, 0 },
808 { "tcfile-in", required_argument, NULL, OPT_TCFILE_IN },
809 { "tcfile-out", required_argument, NULL, OPT_TCFILE_OUT },
810 { "timebase", required_argument, NULL, OPT_TIMEBASE },
811 { "pic-struct", no_argument, NULL, 0 },
812 { "nal-hrd", required_argument, NULL, 0 },
813 { "pulldown", required_argument, NULL, OPT_PULLDOWN },
814 { "fake-interlaced", no_argument, NULL, 0 },
818 static int select_output( const char *muxer, char *filename, x264_param_t *param )
820 const char *ext = get_filename_extension( filename );
821 if( !strcmp( filename, "-" ) || strcasecmp( muxer, "auto" ) )
824 if( !strcasecmp( ext, "mp4" ) )
829 param->b_dts_compress = 0;
830 param->b_repeat_headers = 0;
831 if( param->i_nal_hrd == X264_NAL_HRD_CBR )
833 x264_cli_log( "x264", X264_LOG_WARNING, "cbr nal-hrd is not compatible with mp4\n" );
834 param->i_nal_hrd = X264_NAL_HRD_VBR;
837 x264_cli_log( "x264", X264_LOG_ERROR, "not compiled with MP4 output support\n" );
841 else if( !strcasecmp( ext, "mkv" ) )
845 param->b_dts_compress = 0;
846 param->b_repeat_headers = 0;
848 else if( !strcasecmp( ext, "flv" ) )
852 param->b_dts_compress = 1;
853 param->b_repeat_headers = 0;
860 static int select_input( const char *demuxer, char *used_demuxer, char *filename,
861 hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
863 const char *ext = get_filename_extension( filename );
864 int b_regular = strcmp( filename, "-" );
865 int b_auto = !strcasecmp( demuxer, "auto" );
866 if( !b_regular && b_auto )
868 b_regular = b_regular && x264_is_regular_file_path( filename );
871 FILE *f = fopen( filename, "r" );
874 b_regular = x264_is_regular_file( f );
878 const char *module = b_auto ? ext : demuxer;
880 if( !strcasecmp( module, "avs" ) || !strcasecmp( ext, "d2v" ) || !strcasecmp( ext, "dga" ) )
886 x264_cli_log( "x264", X264_LOG_ERROR, "not compiled with AVS input support\n" );
890 else if( !strcasecmp( module, "y4m" ) )
892 else if( !strcasecmp( module, "yuv" ) )
897 if( b_regular && (b_auto || !strcasecmp( demuxer, "ffms" )) &&
898 !ffms_input.open_file( filename, p_handle, info, opt ) )
906 if( (b_auto || !strcasecmp( demuxer, "lavf" )) &&
907 !lavf_input.open_file( filename, p_handle, info, opt ) )
915 if( b_regular && (b_auto || !strcasecmp( demuxer, "avs" )) &&
916 !avs_input.open_file( filename, p_handle, info, opt ) )
923 if( b_auto && !yuv_input.open_file( filename, p_handle, info, opt ) )
930 FAIL_IF_ERROR( !(*p_handle), "could not open input file `%s' via any method!\n", filename )
932 strcpy( used_demuxer, module );
937 static int parse_enum_name( const char *arg, const char * const *names, const char **dst )
939 for( int i = 0; names[i]; i++ )
940 if( !strcasecmp( arg, names[i] ) )
948 static int parse_enum_value( const char *arg, const char * const *names, int *dst )
950 for( int i = 0; names[i]; i++ )
951 if( !strcasecmp( arg, names[i] ) )
959 /*****************************************************************************
961 *****************************************************************************/
962 static int Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt )
964 char *input_filename = NULL;
965 const char *demuxer = demuxer_names[0];
966 char *output_filename = NULL;
967 const char *muxer = muxer_names[0];
968 char *tcfile_name = NULL;
969 x264_param_t defaults;
970 char *profile = NULL;
971 int b_thread_input = 0;
975 int b_user_interlaced = 0;
976 cli_input_opt_t input_opt;
980 x264_param_default( &defaults );
981 cli_log_level = defaults.i_log_level;
983 memset( opt, 0, sizeof(cli_opt_t) );
984 memset( &input_opt, 0, sizeof(cli_input_opt_t) );
987 /* Presets are applied before all other options. */
990 int c = getopt_long( argc, argv, short_options, long_options, NULL );
993 if( c == OPT_PRESET )
1001 if( preset && !strcasecmp( preset, "placebo" ) )
1004 if( x264_param_default_preset( param, preset, tune ) < 0 )
1007 /* Parse command line options */
1011 int long_options_index = -1;
1013 int c = getopt_long( argc, argv, short_options, long_options, &long_options_index );
1023 Help( &defaults, 0 );
1026 Help( &defaults, 1 );
1029 Help( &defaults, 2 );
1032 #ifdef X264_POINTVER
1033 printf( "x264 "X264_POINTVER"\n" );
1035 printf( "x264 0.%d.X\n", X264_BUILD );
1037 printf( "built on " __DATE__ ", " );
1039 printf( "gcc: " __VERSION__ "\n" );
1041 printf( "using a non-gcc compiler\n" );
1045 param->i_frame_total = X264_MAX( atoi( optarg ), 0 );
1048 opt->i_seek = input_opt.seek = X264_MAX( atoi( optarg ), 0 );
1051 output_filename = optarg;
1054 FAIL_IF_ERROR( parse_enum_name( optarg, muxer_names, &muxer ), "Unknown muxer `%s'\n", optarg )
1057 FAIL_IF_ERROR( parse_enum_name( optarg, demuxer_names, &demuxer ), "Unknown demuxer `%s'\n", optarg )
1060 input_opt.index_file = optarg;
1063 opt->qpfile = fopen( optarg, "rb" );
1064 FAIL_IF_ERROR( !opt->qpfile, "can't open qpfile `%s'\n", optarg )
1065 if( !x264_is_regular_file( opt->qpfile ) )
1067 x264_cli_log( "x264", X264_LOG_ERROR, "qpfile incompatible with non-regular file `%s'\n", optarg );
1068 fclose( opt->qpfile );
1072 case OPT_THREAD_INPUT:
1076 cli_log_level = param->i_log_level = X264_LOG_NONE;
1079 cli_log_level = param->i_log_level = X264_LOG_DEBUG;
1082 if( !parse_enum_value( optarg, log_level_names, &cli_log_level ) )
1083 cli_log_level += X264_LOG_NONE;
1085 cli_log_level = atoi( optarg );
1086 param->i_log_level = cli_log_level;
1087 case OPT_NOPROGRESS:
1088 opt->b_progress = 0;
1092 param->b_visualize = 1;
1093 b_exit_on_ctrl_c = 1;
1095 x264_cli_log( "x264", X264_LOG_WARNING, "not compiled with visualization support\n" );
1104 case OPT_SLOWFIRSTPASS:
1109 goto generic_option;
1112 param->b_vfr_input = 0;
1113 goto generic_option;
1114 case OPT_INTERLACED:
1115 b_user_interlaced = 1;
1116 goto generic_option;
1118 tcfile_name = optarg;
1120 case OPT_TCFILE_OUT:
1121 opt->tcfile_out = fopen( optarg, "wb" );
1122 FAIL_IF_ERROR( !opt->tcfile_out, "can't open `%s'\n", optarg )
1125 input_opt.timebase = optarg;
1128 FAIL_IF_ERROR( parse_enum_value( optarg, pulldown_names, &opt->i_pulldown ), "Unknown pulldown `%s'\n", optarg )
1133 if( long_options_index < 0 )
1135 for( int i = 0; long_options[i].name; i++ )
1136 if( long_options[i].val == c )
1138 long_options_index = i;
1141 if( long_options_index < 0 )
1143 /* getopt_long already printed an error message */
1148 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
1154 const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
1155 x264_cli_log( "x264", X264_LOG_ERROR, "invalid argument: %s = %s\n", name, optarg );
1160 /* If first pass mode is used, apply faster settings. */
1162 x264_param_apply_fastfirstpass( param );
1164 /* Apply profile restrictions. */
1165 if( x264_param_apply_profile( param, profile ) < 0 )
1168 /* Get the file name */
1169 FAIL_IF_ERROR( optind > argc - 1 || !output_filename, "No %s file. Run x264 --help for a list of options.\n",
1170 optind > argc - 1 ? "input" : "output" )
1172 if( select_output( muxer, output_filename, param ) )
1174 FAIL_IF_ERROR( output.open_file( output_filename, &opt->hout ), "could not open output file `%s'\n", output_filename )
1176 input_filename = argv[optind++];
1177 input_opt.resolution = optind < argc ? argv[optind++] : NULL;
1178 video_info_t info = {0};
1179 char demuxername[5];
1181 /* set info flags to param flags to be overwritten by demuxer as necessary. */
1182 info.csp = param->i_csp;
1183 info.fps_num = param->i_fps_num;
1184 info.fps_den = param->i_fps_den;
1185 info.interlaced = param->b_interlaced;
1186 info.sar_width = param->vui.i_sar_width;
1187 info.sar_height = param->vui.i_sar_height;
1188 info.tff = param->b_tff;
1189 info.vfr = param->b_vfr_input;
1191 if( select_input( demuxer, demuxername, input_filename, &opt->hin, &info, &input_opt ) )
1194 FAIL_IF_ERROR( !opt->hin && input.open_file( input_filename, &opt->hin, &info, &input_opt ),
1195 "could not open input file `%s'\n", input_filename )
1197 x264_reduce_fraction( &info.sar_width, &info.sar_height );
1198 x264_reduce_fraction( &info.fps_num, &info.fps_den );
1199 x264_cli_log( demuxername, X264_LOG_INFO, "%dx%d%c %d:%d @ %d/%d fps (%cfr)\n", info.width,
1200 info.height, info.interlaced ? 'i' : 'p', info.sar_width, info.sar_height,
1201 info.fps_num, info.fps_den, info.vfr ? 'v' : 'c' );
1205 FAIL_IF_ERROR( b_user_fps, "--fps + --tcfile-in is incompatible.\n" )
1206 FAIL_IF_ERROR( timecode_input.open_file( tcfile_name, &opt->hin, &info, &input_opt ), "timecode input failed\n" )
1207 input = timecode_input;
1209 else FAIL_IF_ERROR( !info.vfr && input_opt.timebase, "--timebase is incompatible with cfr input\n" )
1211 /* set param flags from the info flags as necessary */
1212 param->i_csp = info.csp;
1213 param->i_height = info.height;
1214 param->b_vfr_input = info.vfr;
1215 param->i_width = info.width;
1216 if( !b_user_interlaced && info.interlaced )
1218 x264_cli_log( "x264", X264_LOG_WARNING, "input appears to be interlaced, enabling %cff interlaced mode.\n"
1219 " If you want otherwise, use --no-interlaced or --%cff\n",
1220 info.tff ? 't' : 'b', info.tff ? 'b' : 't' );
1221 param->b_interlaced = 1;
1222 param->b_tff = !!info.tff;
1226 param->i_fps_num = info.fps_num;
1227 param->i_fps_den = info.fps_den;
1229 if( param->b_vfr_input )
1231 param->i_timebase_num = info.timebase_num;
1232 param->i_timebase_den = info.timebase_den;
1236 param->i_timebase_num = param->i_fps_den;
1237 param->i_timebase_den = param->i_fps_num;
1239 if( !tcfile_name && input_opt.timebase )
1241 uint64_t i_user_timebase_num;
1242 uint64_t i_user_timebase_den;
1243 int ret = sscanf( input_opt.timebase, "%"SCNu64"/%"SCNu64, &i_user_timebase_num, &i_user_timebase_den );
1244 FAIL_IF_ERROR( !ret, "invalid argument: timebase = %s\n", input_opt.timebase )
1247 i_user_timebase_num = param->i_timebase_num;
1248 i_user_timebase_den = strtoul( input_opt.timebase, NULL, 10 );
1250 FAIL_IF_ERROR( i_user_timebase_num > UINT32_MAX || i_user_timebase_den > UINT32_MAX,
1251 "timebase you specified exceeds H.264 maximum\n" )
1252 opt->timebase_convert_multiplier = ((double)i_user_timebase_den / param->i_timebase_den)
1253 * ((double)param->i_timebase_num / i_user_timebase_num);
1254 param->i_timebase_num = i_user_timebase_num;
1255 param->i_timebase_den = i_user_timebase_den;
1256 param->b_vfr_input = 1;
1258 if( !param->vui.i_sar_width || !param->vui.i_sar_height )
1260 param->vui.i_sar_width = info.sar_width;
1261 param->vui.i_sar_height = info.sar_height;
1265 if( b_thread_input || param->i_threads > 1
1266 || (param->i_threads == X264_THREADS_AUTO && x264_cpu_num_processors() > 1) )
1268 FAIL_IF_ERROR( thread_input.open_file( NULL, &opt->hin, &info, NULL ), "threaded input failed\n" )
1269 input = thread_input;
1274 /* Automatically reduce reference frame count to match the user's target level
1275 * if the user didn't explicitly set a reference frame count. */
1278 int mbs = (((param->i_width)+15)>>4) * (((param->i_height)+15)>>4);
1279 for( int i = 0; x264_levels[i].level_idc != 0; i++ )
1280 if( param->i_level_idc == x264_levels[i].level_idc )
1282 while( mbs * 384 * param->i_frame_reference > x264_levels[i].dpb &&
1283 param->i_frame_reference > 1 )
1285 param->i_frame_reference--;
1295 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
1297 int num = -1, qp, ret;
1300 while( num < i_frame )
1302 file_pos = ftell( opt->qpfile );
1303 ret = fscanf( opt->qpfile, "%d %c %d\n", &num, &type, &qp );
1304 if( num > i_frame || ret == EOF )
1306 pic->i_type = X264_TYPE_AUTO;
1308 fseek( opt->qpfile, file_pos, SEEK_SET );
1311 if( num < i_frame && ret == 3 )
1313 pic->i_qpplus1 = qp+1;
1314 if ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
1315 else if( type == 'i' ) pic->i_type = X264_TYPE_I;
1316 else if( type == 'K' ) pic->i_type = X264_TYPE_KEYFRAME;
1317 else if( type == 'P' ) pic->i_type = X264_TYPE_P;
1318 else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
1319 else if( type == 'b' ) pic->i_type = X264_TYPE_B;
1321 if( ret != 3 || qp < -1 || qp > 51 )
1323 x264_cli_log( "x264", X264_LOG_ERROR, "can't parse qpfile for frame %d\n", i_frame );
1324 fclose( opt->qpfile );
1326 pic->i_type = X264_TYPE_AUTO;
1333 /*****************************************************************************
1335 *****************************************************************************/
1337 static int Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic, int64_t *last_dts )
1339 x264_picture_t pic_out;
1342 int i_frame_size = 0;
1344 i_frame_size = x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out );
1346 FAIL_IF_ERROR( i_frame_size < 0, "x264_encoder_encode failed\n" );
1350 i_frame_size = output.write_frame( hout, nal[0].p_payload, i_frame_size, &pic_out );
1351 *last_dts = pic_out.i_dts;
1354 return i_frame_size;
1357 static void Print_status( int64_t i_start, int i_frame, int i_frame_total, int64_t i_file, x264_param_t *param, int64_t last_ts )
1360 int64_t i_elapsed = x264_mdate() - i_start;
1361 double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1364 bitrate = (double) i_file * 8 / ( (double) last_ts * 1000 * param->i_timebase_num / param->i_timebase_den );
1366 bitrate = (double) i_file * 8 / ( (double) 1000 * param->i_fps_den / param->i_fps_num );
1369 int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1370 sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
1371 100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
1372 eta/3600, (eta/60)%60, eta%60 );
1376 sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
1378 fprintf( stderr, "%s \r", buf+5 );
1379 SetConsoleTitle( buf );
1380 fflush( stderr ); // needed in windows
1383 static int Encode( x264_param_t *param, cli_opt_t *opt )
1387 const cli_pulldown_t *pulldown = NULL; // shut up gcc
1389 int i_frame, i_frame_total, i_frame_output;
1390 int64_t i_start, i_end;
1393 int i_update_interval;
1394 int64_t last_dts = 0;
1395 int64_t prev_dts = 0;
1396 int64_t first_dts = 0;
1397 # define MAX_PTS_WARNING 3 /* arbitrary */
1398 int pts_warning_cnt = 0;
1399 int64_t largest_pts = -1;
1400 int64_t second_largest_pts = -1;
1401 int64_t ticks_per_frame;
1403 int prev_timebase_den = param->i_timebase_den / gcd( param->i_timebase_num, param->i_timebase_den );
1404 int dts_compress_multiplier;
1405 double pulldown_pts = 0;
1407 opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
1408 i_frame_total = input.get_frame_total( opt->hin );
1409 i_frame_total = X264_MAX( i_frame_total - opt->i_seek, 0 );
1410 if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
1411 && param->i_frame_total > 0 )
1412 i_frame_total = param->i_frame_total;
1413 param->i_frame_total = i_frame_total;
1414 i_update_interval = i_frame_total ? x264_clip3( i_frame_total / 1000, 1, 10 ) : 10;
1416 /* set up pulldown */
1417 if( opt->i_pulldown && !param->b_vfr_input )
1419 param->b_pic_struct = 1;
1420 pulldown = &pulldown_values[opt->i_pulldown];
1421 param->i_timebase_num = param->i_fps_den;
1422 FAIL_IF_ERROR( fmod( param->i_fps_num * pulldown->fps_factor, 1 ),
1423 "unsupported framerate for chosen pulldown\n" )
1424 param->i_timebase_den = param->i_fps_num * pulldown->fps_factor;
1427 if( ( h = x264_encoder_open( param ) ) == NULL )
1429 x264_cli_log( "x264", X264_LOG_ERROR, "x264_encoder_open failed\n" );
1430 input.close_file( opt->hin );
1434 x264_encoder_parameters( h, param );
1436 dts_compress_multiplier = param->i_timebase_den / prev_timebase_den;
1438 if( output.set_param( opt->hout, param ) )
1440 x264_cli_log( "x264", X264_LOG_ERROR, "can't set outfile param\n" );
1441 input.close_file( opt->hin );
1442 output.close_file( opt->hout, largest_pts, second_largest_pts );
1446 /* Create a new pic */
1447 FAIL_IF_ERROR( input.picture_alloc( &pic, param->i_csp, param->i_width, param->i_height ), "malloc failed\n" )
1449 i_start = x264_mdate();
1450 /* ticks/frame = ticks/second / frames/second */
1451 ticks_per_frame = (int64_t)param->i_timebase_den * param->i_fps_den / param->i_timebase_num / param->i_fps_num;
1452 FAIL_IF_ERROR( ticks_per_frame < 1, "ticks_per_frame invalid: %"PRId64"\n", ticks_per_frame )
1454 if( !param->b_repeat_headers )
1456 // Write SPS/PPS/SEI
1457 x264_nal_t *headers;
1460 FAIL_IF_ERROR( x264_encoder_headers( h, &headers, &i_nal ) < 0, "x264_encoder_headers failed\n" )
1461 if( (i_file = output.write_headers( opt->hout, headers )) < 0 )
1465 if( opt->tcfile_out )
1466 fprintf( opt->tcfile_out, "# timecode format v2\n" );
1469 for( i_frame = 0, i_frame_output = 0; b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1471 if( input.read_frame( &pic, opt->hin, i_frame + opt->i_seek ) )
1474 if( !param->b_vfr_input )
1475 pic.i_pts = i_frame;
1477 if( opt->i_pulldown && !param->b_vfr_input )
1479 pic.i_pic_struct = pulldown->pattern[ i_frame % pulldown->mod ];
1480 pic.i_pts = (int64_t)( pulldown_pts + 0.5 );
1481 pulldown_pts += pulldown_frame_duration[pic.i_pic_struct];
1483 else if( opt->timebase_convert_multiplier )
1484 pic.i_pts = (int64_t)( pic.i_pts * opt->timebase_convert_multiplier + 0.5 );
1486 int64_t output_pts = pic.i_pts * dts_compress_multiplier; /* pts libx264 returns */
1488 if( pic.i_pts <= largest_pts )
1490 if( cli_log_level >= X264_LOG_DEBUG || pts_warning_cnt < MAX_PTS_WARNING )
1491 x264_cli_log( "x264", X264_LOG_WARNING, "non-strictly-monotonic pts at frame %d (%"PRId64" <= %"PRId64")\n",
1492 i_frame, output_pts, largest_pts * dts_compress_multiplier );
1493 else if( pts_warning_cnt == MAX_PTS_WARNING )
1494 x264_cli_log( "x264", X264_LOG_WARNING, "too many nonmonotonic pts warnings, suppressing further ones\n" );
1496 pic.i_pts = largest_pts + ticks_per_frame;
1497 output_pts = pic.i_pts * dts_compress_multiplier;
1500 second_largest_pts = largest_pts;
1501 largest_pts = pic.i_pts;
1502 if( opt->tcfile_out )
1503 fprintf( opt->tcfile_out, "%.6f\n", output_pts * ((double)param->i_timebase_num / param->i_timebase_den) * 1e3 );
1506 parse_qpfile( opt, &pic, i_frame + opt->i_seek );
1509 /* Do not force any parameters */
1510 pic.i_type = X264_TYPE_AUTO;
1514 prev_dts = last_dts;
1515 i_frame_size = Encode_frame( h, opt->hout, &pic, &last_dts );
1516 if( i_frame_size < 0 )
1518 i_file += i_frame_size;
1522 if( i_frame_output == 1 )
1523 first_dts = prev_dts = last_dts;
1528 if( input.release_frame && input.release_frame( &pic, opt->hin ) )
1531 /* update status line (up to 1000 times per input file) */
1532 if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1533 Print_status( i_start, i_frame_output, i_frame_total, i_file, param, 2 * last_dts - prev_dts - first_dts );
1535 /* Flush delayed frames */
1536 while( !b_ctrl_c && x264_encoder_delayed_frames( h ) )
1538 prev_dts = last_dts;
1539 i_frame_size = Encode_frame( h, opt->hout, NULL, &last_dts );
1540 if( i_frame_size < 0 )
1542 i_file += i_frame_size;
1546 if( i_frame_output == 1 )
1547 first_dts = prev_dts = last_dts;
1549 if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1550 Print_status( i_start, i_frame_output, i_frame_total, i_file, param, 2 * last_dts - prev_dts - first_dts );
1552 if( pts_warning_cnt >= MAX_PTS_WARNING && cli_log_level < X264_LOG_DEBUG )
1553 x264_cli_log( "x264", X264_LOG_WARNING, "%d suppressed nonmonotonic pts warnings\n", pts_warning_cnt-MAX_PTS_WARNING );
1555 /* duration algorithm fails when only 1 frame is output */
1556 if( i_frame_output == 1 )
1557 duration = (double)param->i_fps_den / param->i_fps_num;
1559 duration = (double)(2 * last_dts - prev_dts - first_dts) * param->i_timebase_num / param->i_timebase_den;
1561 duration = (double)(2 * largest_pts - second_largest_pts) * param->i_timebase_num / param->i_timebase_den;
1562 if( !(opt->i_pulldown && !param->b_vfr_input) )
1563 duration *= dts_compress_multiplier;
1565 i_end = x264_mdate();
1566 input.picture_clean( &pic );
1567 /* Erase progress indicator before printing encoding stats. */
1568 if( opt->b_progress )
1569 fprintf( stderr, " \r" );
1570 x264_encoder_close( h );
1571 fprintf( stderr, "\n" );
1574 fprintf( stderr, "aborted at input frame %d, output frame %d\n", opt->i_seek + i_frame, i_frame_output );
1576 if( opt->tcfile_out )
1578 fclose( opt->tcfile_out );
1579 opt->tcfile_out = NULL;
1582 input.close_file( opt->hin );
1583 output.close_file( opt->hout, largest_pts, second_largest_pts );
1585 if( i_frame_output > 0 )
1587 double fps = (double)i_frame_output * (double)1000000 /
1588 (double)( i_end - i_start );
1590 fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame_output, fps,
1591 (double) i_file * 8 / ( 1000 * duration ) );