]> git.sesse.net Git - x264/blob - x264.c
Remove non-pre scenecut
[x264] / x264.c
1 /*****************************************************************************
2  * x264: h264 encoder testing program.
3  *****************************************************************************
4  * Copyright (C) 2003-2008 x264 project
5  *
6  * Authors: Loren Merritt <lorenm@u.washington.edu>
7  *          Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 #include <stdlib.h>
25 #include <math.h>
26
27 #include <signal.h>
28 #define _GNU_SOURCE
29 #include <getopt.h>
30
31 #include "common/common.h"
32 #include "common/cpu.h"
33 #include "x264.h"
34 #include "muxers.h"
35
36 #ifndef _MSC_VER
37 #include "config.h"
38 #endif
39
40 #ifdef _WIN32
41 #include <windows.h>
42 #else
43 #define SetConsoleTitle(t)
44 #endif
45
46 uint8_t *mux_buffer = NULL;
47 int mux_buffer_size = 0;
48
49 /* Ctrl-C handler */
50 static int     b_ctrl_c = 0;
51 static int     b_exit_on_ctrl_c = 0;
52 static void    SigIntHandler( int a )
53 {
54     if( b_exit_on_ctrl_c )
55         exit(0);
56     b_ctrl_c = 1;
57 }
58
59 typedef struct {
60     int b_progress;
61     int i_seek;
62     hnd_t hin;
63     hnd_t hout;
64     FILE *qpfile;
65 } cli_opt_t;
66
67 /* input file operation function pointers */
68 int (*p_open_infile)( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
69 int (*p_get_frame_total)( hnd_t handle );
70 int (*p_read_frame)( x264_picture_t *p_pic, hnd_t handle, int i_frame );
71 int (*p_close_infile)( hnd_t handle );
72
73 /* output file operation function pointers */
74 static int (*p_open_outfile)( char *psz_filename, hnd_t *p_handle );
75 static int (*p_set_outfile_param)( hnd_t handle, x264_param_t *p_param );
76 static int (*p_write_nalu)( hnd_t handle, uint8_t *p_nal, int i_size );
77 static int (*p_set_eop)( hnd_t handle, x264_picture_t *p_picture );
78 static int (*p_close_outfile)( hnd_t handle );
79
80 static void Help( x264_param_t *defaults, int b_longhelp );
81 static int  Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
82 static int  Encode( x264_param_t *param, cli_opt_t *opt );
83
84
85 /****************************************************************************
86  * main:
87  ****************************************************************************/
88 int main( int argc, char **argv )
89 {
90     x264_param_t param;
91     cli_opt_t opt;
92     int ret;
93
94 #ifdef PTW32_STATIC_LIB
95     pthread_win32_process_attach_np();
96     pthread_win32_thread_attach_np();
97 #endif
98
99 #ifdef _WIN32
100     _setmode(_fileno(stdin), _O_BINARY);
101     _setmode(_fileno(stdout), _O_BINARY);
102 #endif
103
104     x264_param_default( &param );
105
106     /* Parse command line */
107     if( Parse( argc, argv, &param, &opt ) < 0 )
108         return -1;
109
110     /* Control-C handler */
111     signal( SIGINT, SigIntHandler );
112
113     ret = Encode( &param, &opt );
114
115 #ifdef PTW32_STATIC_LIB
116     pthread_win32_thread_detach_np();
117     pthread_win32_process_detach_np();
118 #endif
119
120     return ret;
121 }
122
123 static char const *strtable_lookup( const char * const table[], int index )
124 {
125     int i = 0; while( table[i] ) i++;
126     return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
127 }
128
129 /*****************************************************************************
130  * Help:
131  *****************************************************************************/
132 static void Help( x264_param_t *defaults, int b_longhelp )
133 {
134 #define H0 printf
135 #define H1 if(b_longhelp) printf
136     H0( "x264 core:%d%s\n"
137         "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
138         "\n"
139         "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
140         "  or YUV4MPEG 4:2:0 (*.y4m),\n"
141         "  or AVI or Avisynth if compiled with AVIS support (%s).\n"
142         "Outfile type is selected by filename:\n"
143         " .264 -> Raw bytestream\n"
144         " .mkv -> Matroska\n"
145         " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
146         "\n"
147         "Options:\n"
148         "\n"
149         "  -h, --help                  List the more commonly used options\n"
150         "      --longhelp              List all options\n"
151         "\n",
152         X264_BUILD, X264_VERSION,
153 #ifdef AVIS_INPUT
154         "yes",
155 #else
156         "no",
157 #endif
158 #ifdef MP4_OUTPUT
159         "yes"
160 #else
161         "no"
162 #endif
163       );
164     H0( "Frame-type options:\n" );
165     H0( "\n" );
166     H0( "  -I, --keyint <integer>      Maximum GOP size [%d]\n", defaults->i_keyint_max );
167     H1( "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n", defaults->i_keyint_min );
168     H1( "      --no-scenecut           Disable adaptive I-frame decision\n" );
169     H1( "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
170     H0( "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n", defaults->i_bframe );
171     H1( "      --b-adapt               Adaptive B-frame decision method [%d]\n"
172         "                                  Higher values may lower threading efficiency.\n"
173         "                                  - 0: Disabled\n"
174         "                                  - 1: Fast\n"
175         "                                  - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
176     H1( "      --b-bias <integer>      Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
177     H0( "      --b-pyramid             Keep some B-frames as references\n" );
178     H0( "      --no-cabac              Disable CABAC\n" );
179     H0( "  -r, --ref <integer>         Number of reference frames [%d]\n", defaults->i_frame_reference );
180     H1( "      --no-deblock            Disable loop filter\n" );
181     H0( "  -f, --deblock <alpha:beta>  Loop filter AlphaC0 and Beta parameters [%d:%d]\n",
182                                        defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
183     H0( "      --interlaced            Enable pure-interlaced mode\n" );
184     H0( "\n" );
185     H0( "Ratecontrol:\n" );
186     H0( "\n" );
187     H0( "  -q, --qp <integer>          Set QP (0=lossless) [%d]\n", defaults->rc.i_qp_constant );
188     H0( "  -B, --bitrate <integer>     Set bitrate (kbit/s)\n" );
189     H0( "      --crf <float>           Quality-based VBR (nominal QP)\n" );
190     H1( "      --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
191     H0( "      --vbv-bufsize <integer> Enable CBR and set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
192     H1( "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
193     H1( "      --qpmin <integer>       Set min QP [%d]\n", defaults->rc.i_qp_min );
194     H1( "      --qpmax <integer>       Set max QP [%d]\n", defaults->rc.i_qp_max );
195     H1( "      --qpstep <integer>      Set max QP step [%d]\n", defaults->rc.i_qp_step );
196     H0( "      --ratetol <float>       Allowed variance of average bitrate [%.1f]\n", defaults->rc.f_rate_tolerance );
197     H0( "      --ipratio <float>       QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
198     H0( "      --pbratio <float>       QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
199     H1( "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
200     H1( "      --aq-mode <integer>     AQ method [%d]\n"
201         "                                  - 0: Disabled\n"
202         "                                  - 1: Variance AQ (complexity mask)\n", defaults->rc.i_aq_mode );
203     H0( "      --aq-strength <float>   Reduces blocking and blurring in flat and\n"
204         "                              textured areas. [%.1f]\n"
205         "                                  - 0.5: weak AQ\n"
206         "                                  - 1.5: strong AQ\n", defaults->rc.f_aq_strength );
207     H0( "\n" );
208     H0( "  -p, --pass <1|2|3>          Enable multipass ratecontrol\n"
209         "                                  - 1: First pass, creates stats file\n"
210         "                                  - 2: Last pass, does not overwrite stats file\n"
211         "                                  - 3: Nth pass, overwrites stats file\n" );
212     H0( "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
213     H0( "      --qcomp <float>         QP curve compression: 0.0 => CBR, 1.0 => CQP [%.2f]\n", defaults->rc.f_qcompress );
214     H1( "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
215     H1( "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
216     H0( "      --zones <zone0>/<zone1>/...  Tweak the bitrate of some regions of the video\n" );
217     H1( "                              Each zone is of the form\n"
218         "                                  <start frame>,<end frame>,<option>\n"
219         "                                  where <option> is either\n"
220         "                                      q=<integer> (force QP)\n"
221         "                                  or  b=<float> (bitrate multiplier)\n" );
222     H1( "      --qpfile <string>       Force frametypes and QPs for some or all frames\n"
223         "                              Format of each line: framenumber frametype QP\n"
224         "                              QP of -1 lets x264 choose. Frametypes: I,i,P,B,b.\n" );
225     H0( "\n" );
226     H0( "Analysis:\n" );
227     H0( "\n" );
228     H0( "  -A, --partitions <string>   Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
229         "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
230         "                                  - none, all\n"
231         "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
232     H0( "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
233         "                                  - none, spatial, temporal, auto\n",
234                                        strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
235     H0( "  -w, --weightb               Weighted prediction for B-frames\n" );
236     H0( "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n",
237                                        strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
238     H1( "                                  - dia: diamond search, radius 1 (fast)\n"
239         "                                  - hex: hexagonal search, radius 2\n"
240         "                                  - umh: uneven multi-hexagon search\n"
241         "                                  - esa: exhaustive search\n"
242         "                                  - tesa: hadamard exhaustive search (slow)\n" );
243     else H0( "                                  - dia, hex, umh\n" );
244     H0( "      --merange <integer>     Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
245     H1( "      --mvrange <integer>     Maximum motion vector length [-1 (auto)]\n" );
246     H1( "      --mvrange-thread <int>  Minimum buffer between threads [-1 (auto)]\n" );
247     H0( "  -m, --subme <integer>       Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
248     H1( "                                  - 0: fullpel only (not recommended)\n"
249         "                                  - 1: SAD mode decision, one qpel iteration\n"
250         "                                  - 2: SATD mode decision\n"
251         "                                  - 3-5: Progressively more qpel\n"
252         "                                  - 6: RD mode decision for I/P-frames\n"
253         "                                  - 7: RD mode decision for all frames\n"
254         "                                  - 8: RD refinement for I/P-frames\n"
255         "                                  - 9: RD refinement for all frames\n" );
256     else H0( "                                  decision quality: 1=fast, 9=best.\n"  );
257     H0( "      --psy-rd                Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
258         "                                  #1: RD (requires subme>=6)\n"
259         "                                  #2: Trellis (requires trellis, experimental)\n",
260                                        defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
261     H0( "      --mixed-refs            Decide references on a per partition basis\n" );
262     H1( "      --no-chroma-me          Ignore chroma in motion estimation\n" );
263     H0( "  -8, --8x8dct                Adaptive spatial transform size\n" );
264     H0( "  -t, --trellis <integer>     Trellis RD quantization. Requires CABAC. [%d]\n"
265         "                                  - 0: disabled\n"
266         "                                  - 1: enabled only on the final encode of a MB\n"
267         "                                  - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
268     H0( "      --no-fast-pskip         Disables early SKIP detection on P-frames\n" );
269     H0( "      --no-dct-decimate       Disables coefficient thresholding on P-frames\n" );
270     H0( "      --nr <integer>          Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
271     H1( "\n" );
272     H1( "      --deadzone-inter <int>  Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
273     H1( "      --deadzone-intra <int>  Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
274     H1( "                                  Deadzones should be in the range 0 - 32.\n" );
275     H1( "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
276         "                                  - jvt, flat\n" );
277     H0( "      --cqmfile <string>      Read custom quant matrices from a JM-compatible file\n" );
278     H1( "                                  Overrides any other --cqm* options.\n" );
279     H1( "      --cqm4 <list>           Set all 4x4 quant matrices\n"
280         "                                  Takes a comma-separated list of 16 integers.\n" );
281     H1( "      --cqm8 <list>           Set all 8x8 quant matrices\n"
282         "                                  Takes a comma-separated list of 64 integers.\n" );
283     H1( "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
284         "                              Set both luma and chroma quant matrices\n" );
285     H1( "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
286         "                              Set individual quant matrices\n" );
287     H1( "\n" );
288     H1( "Video Usability Info (Annex E):\n" );
289     H1( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
290     H1( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
291     H1( "\n" );
292     H1( "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
293         "                                  - undef, show, crop\n",
294                                        strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
295     H1( "      --videoformat <string>  Specify video format [\"%s\"]\n"
296         "                                  - component, pal, ntsc, secam, mac, undef\n",
297                                        strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
298     H1( "      --fullrange <string>    Specify full range samples setting [\"%s\"]\n"
299         "                                  - off, on\n",
300                                        strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ) );
301     H1( "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
302         "                                  - undef, bt709, bt470m, bt470bg\n"
303         "                                    smpte170m, smpte240m, film\n",
304                                        strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
305     H1( "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
306         "                                  - undef, bt709, bt470m, bt470bg, linear,\n"
307         "                                    log100, log316, smpte170m, smpte240m\n",
308                                        strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
309     H1( "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
310         "                                  - undef, bt709, fcc, bt470bg\n"
311         "                                    smpte170m, smpte240m, GBR, YCgCo\n",
312                                        strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
313     H1( "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n",
314                                        defaults->vui.i_chroma_loc );
315     H0( "\n" );
316     H0( "Input/Output:\n" );
317     H0( "\n" );
318     H0( "  -o, --output                Specify output file\n" );
319     H0( "      --sar width:height      Specify Sample Aspect Ratio\n" );
320     H0( "      --fps <float|rational>  Specify framerate\n" );
321     H0( "      --seek <integer>        First frame to encode\n" );
322     H0( "      --frames <integer>      Maximum number of frames to encode\n" );
323     H0( "      --level <string>        Specify level (as defined by Annex A)\n" );
324     H0( "\n" );
325     H0( "  -v, --verbose               Print stats for each frame\n" );
326     H0( "      --progress              Show a progress indicator while encoding\n" );
327     H0( "      --quiet                 Quiet Mode\n" );
328     H0( "      --no-psnr               Disable PSNR computation\n" );
329     H0( "      --no-ssim               Disable SSIM computation\n" );
330     H0( "      --threads <integer>     Parallel encoding\n" );
331     H0( "      --thread-input          Run Avisynth in its own thread\n" );
332     H1( "      --non-deterministic     Slightly improve quality of SMP, at the cost of repeatability\n" );
333     H1( "      --asm <integer>         Override CPU detection\n" );
334     H1( "      --no-asm                Disable all CPU optimizations\n" );
335     H1( "      --visualize             Show MB types overlayed on the encoded video\n" );
336     H1( "      --dump-yuv <string>     Save reconstructed frames\n" );
337     H1( "      --sps-id <integer>      Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
338     H1( "      --aud                   Use access unit delimiters\n" );
339     H0( "\n" );
340 }
341
342 /*****************************************************************************
343  * Parse:
344  *****************************************************************************/
345 static int  Parse( int argc, char **argv,
346                    x264_param_t *param, cli_opt_t *opt )
347 {
348     char *psz_filename = NULL;
349     x264_param_t defaults = *param;
350     char *psz;
351     int b_avis = 0;
352     int b_y4m = 0;
353     int b_thread_input = 0;
354
355     memset( opt, 0, sizeof(cli_opt_t) );
356
357     /* Default input file driver */
358     p_open_infile = open_file_yuv;
359     p_get_frame_total = get_frame_total_yuv;
360     p_read_frame = read_frame_yuv;
361     p_close_infile = close_file_yuv;
362
363     /* Default output file driver */
364     p_open_outfile = open_file_bsf;
365     p_set_outfile_param = set_param_bsf;
366     p_write_nalu = write_nalu_bsf;
367     p_set_eop = set_eop_bsf;
368     p_close_outfile = close_file_bsf;
369
370     /* Parse command line options */
371     for( ;; )
372     {
373         int b_error = 0;
374         int long_options_index = -1;
375
376 #define OPT_FRAMES 256
377 #define OPT_SEEK 257
378 #define OPT_QPFILE 258
379 #define OPT_THREAD_INPUT 259
380 #define OPT_QUIET 260
381 #define OPT_PROGRESS 261
382 #define OPT_VISUALIZE 262
383 #define OPT_LONGHELP 263
384
385         static struct option long_options[] =
386         {
387             { "help",    no_argument,       NULL, 'h' },
388             { "longhelp",no_argument,       NULL, OPT_LONGHELP },
389             { "version", no_argument,       NULL, 'V' },
390             { "bitrate", required_argument, NULL, 'B' },
391             { "bframes", required_argument, NULL, 'b' },
392             { "b-adapt", required_argument, NULL, 0 },
393             { "no-b-adapt", no_argument,    NULL, 0 },
394             { "b-bias",  required_argument, NULL, 0 },
395             { "b-pyramid", no_argument,     NULL, 0 },
396             { "min-keyint",required_argument,NULL,'i' },
397             { "keyint",  required_argument, NULL, 'I' },
398             { "scenecut",required_argument, NULL, 0 },
399             { "no-scenecut",no_argument,    NULL, 0 },
400             { "nf",      no_argument,       NULL, 0 },
401             { "no-deblock", no_argument,    NULL, 0 },
402             { "filter",  required_argument, NULL, 0 },
403             { "deblock", required_argument, NULL, 'f' },
404             { "interlaced", no_argument,    NULL, 0 },
405             { "no-cabac",no_argument,       NULL, 0 },
406             { "qp",      required_argument, NULL, 'q' },
407             { "qpmin",   required_argument, NULL, 0 },
408             { "qpmax",   required_argument, NULL, 0 },
409             { "qpstep",  required_argument, NULL, 0 },
410             { "crf",     required_argument, NULL, 0 },
411             { "ref",     required_argument, NULL, 'r' },
412             { "asm",     required_argument, NULL, 0 },
413             { "no-asm",  no_argument,       NULL, 0 },
414             { "sar",     required_argument, NULL, 0 },
415             { "fps",     required_argument, NULL, 0 },
416             { "frames",  required_argument, NULL, OPT_FRAMES },
417             { "seek",    required_argument, NULL, OPT_SEEK },
418             { "output",  required_argument, NULL, 'o' },
419             { "analyse", required_argument, NULL, 0 },
420             { "partitions", required_argument, NULL, 'A' },
421             { "direct",  required_argument, NULL, 0 },
422             { "weightb", no_argument,       NULL, 'w' },
423             { "me",      required_argument, NULL, 0 },
424             { "merange", required_argument, NULL, 0 },
425             { "mvrange", required_argument, NULL, 0 },
426             { "mvrange-thread", required_argument, NULL, 0 },
427             { "subme",   required_argument, NULL, 'm' },
428             { "psy-rd",  required_argument, NULL, 0 },
429             { "mixed-refs", no_argument,    NULL, 0 },
430             { "no-chroma-me", no_argument,  NULL, 0 },
431             { "8x8dct",  no_argument,       NULL, '8' },
432             { "trellis", required_argument, NULL, 't' },
433             { "no-fast-pskip", no_argument, NULL, 0 },
434             { "no-dct-decimate", no_argument, NULL, 0 },
435             { "aq-strength", required_argument, NULL, 0 },
436             { "aq-mode", required_argument, NULL, 0 },
437             { "deadzone-inter", required_argument, NULL, '0' },
438             { "deadzone-intra", required_argument, NULL, '0' },
439             { "level",   required_argument, NULL, 0 },
440             { "ratetol", required_argument, NULL, 0 },
441             { "vbv-maxrate", required_argument, NULL, 0 },
442             { "vbv-bufsize", required_argument, NULL, 0 },
443             { "vbv-init", required_argument,NULL,  0 },
444             { "ipratio", required_argument, NULL, 0 },
445             { "pbratio", required_argument, NULL, 0 },
446             { "chroma-qp-offset", required_argument, NULL, 0 },
447             { "pass",    required_argument, NULL, 'p' },
448             { "stats",   required_argument, NULL, 0 },
449             { "qcomp",   required_argument, NULL, 0 },
450             { "qblur",   required_argument, NULL, 0 },
451             { "cplxblur",required_argument, NULL, 0 },
452             { "zones",   required_argument, NULL, 0 },
453             { "qpfile",  required_argument, NULL, OPT_QPFILE },
454             { "threads", required_argument, NULL, 0 },
455             { "thread-input", no_argument,  NULL, OPT_THREAD_INPUT },
456             { "non-deterministic", no_argument, NULL, 0 },
457             { "no-psnr", no_argument,       NULL, 0 },
458             { "no-ssim", no_argument,       NULL, 0 },
459             { "quiet",   no_argument,       NULL, OPT_QUIET },
460             { "verbose", no_argument,       NULL, 'v' },
461             { "progress",no_argument,       NULL, OPT_PROGRESS },
462             { "visualize",no_argument,      NULL, OPT_VISUALIZE },
463             { "dump-yuv",required_argument, NULL, 0 },
464             { "sps-id",  required_argument, NULL, 0 },
465             { "aud",     no_argument,       NULL, 0 },
466             { "nr",      required_argument, NULL, 0 },
467             { "cqm",     required_argument, NULL, 0 },
468             { "cqmfile", required_argument, NULL, 0 },
469             { "cqm4",    required_argument, NULL, 0 },
470             { "cqm4i",   required_argument, NULL, 0 },
471             { "cqm4iy",  required_argument, NULL, 0 },
472             { "cqm4ic",  required_argument, NULL, 0 },
473             { "cqm4p",   required_argument, NULL, 0 },
474             { "cqm4py",  required_argument, NULL, 0 },
475             { "cqm4pc",  required_argument, NULL, 0 },
476             { "cqm8",    required_argument, NULL, 0 },
477             { "cqm8i",   required_argument, NULL, 0 },
478             { "cqm8p",   required_argument, NULL, 0 },
479             { "overscan", required_argument, NULL, 0 },
480             { "videoformat", required_argument, NULL, 0 },
481             { "fullrange", required_argument, NULL, 0 },
482             { "colorprim", required_argument, NULL, 0 },
483             { "transfer", required_argument, NULL, 0 },
484             { "colormatrix", required_argument, NULL, 0 },
485             { "chromaloc", required_argument, NULL, 0 },
486             {0, 0, 0, 0}
487         };
488
489         int c = getopt_long( argc, argv, "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw",
490                              long_options, &long_options_index);
491
492         if( c == -1 )
493         {
494             break;
495         }
496
497         switch( c )
498         {
499             case 'h':
500                 Help( &defaults, 0 );
501                 exit(0);
502             case OPT_LONGHELP:
503                 Help( &defaults, 1 );
504                 exit(0);
505             case 'V':
506 #ifdef X264_POINTVER
507                 printf( "x264 "X264_POINTVER"\n" );
508 #else
509                 printf( "x264 0.%d.X\n", X264_BUILD );
510 #endif
511                 printf( "built on " __DATE__ ", " );
512 #ifdef __GNUC__
513                 printf( "gcc: " __VERSION__ "\n" );
514 #else
515                 printf( "using a non-gcc compiler\n" );
516 #endif
517                 exit(0);
518             case OPT_FRAMES:
519                 param->i_frame_total = atoi( optarg );
520                 break;
521             case OPT_SEEK:
522                 opt->i_seek = atoi( optarg );
523                 break;
524             case 'o':
525                 if( !strncasecmp(optarg + strlen(optarg) - 4, ".mp4", 4) )
526                 {
527 #ifdef MP4_OUTPUT
528                     p_open_outfile = open_file_mp4;
529                     p_write_nalu = write_nalu_mp4;
530                     p_set_outfile_param = set_param_mp4;
531                     p_set_eop = set_eop_mp4;
532                     p_close_outfile = close_file_mp4;
533 #else
534                     fprintf( stderr, "x264 [error]: not compiled with MP4 output support\n" );
535                     return -1;
536 #endif
537                 }
538                 else if( !strncasecmp(optarg + strlen(optarg) - 4, ".mkv", 4) )
539                 {
540                     p_open_outfile = open_file_mkv;
541                     p_write_nalu = write_nalu_mkv;
542                     p_set_outfile_param = set_param_mkv;
543                     p_set_eop = set_eop_mkv;
544                     p_close_outfile = close_file_mkv;
545                 }
546                 if( !strcmp(optarg, "-") )
547                     opt->hout = stdout;
548                 else if( p_open_outfile( optarg, &opt->hout ) )
549                 {
550                     fprintf( stderr, "x264 [error]: can't open output file `%s'\n", optarg );
551                     return -1;
552                 }
553                 break;
554             case OPT_QPFILE:
555                 opt->qpfile = fopen( optarg, "r" );
556                 if( !opt->qpfile )
557                 {
558                     fprintf( stderr, "x264 [error]: can't open `%s'\n", optarg );
559                     return -1;
560                 }
561                 break;
562             case OPT_THREAD_INPUT:
563                 b_thread_input = 1;
564                 break;
565             case OPT_QUIET:
566                 param->i_log_level = X264_LOG_NONE;
567                 break;
568             case 'v':
569                 param->i_log_level = X264_LOG_DEBUG;
570                 break;
571             case OPT_PROGRESS:
572                 opt->b_progress = 1;
573                 break;
574             case OPT_VISUALIZE:
575 #ifdef VISUALIZE
576                 param->b_visualize = 1;
577                 b_exit_on_ctrl_c = 1;
578 #else
579                 fprintf( stderr, "x264 [warning]: not compiled with visualization support\n" );
580 #endif
581                 break;
582             default:
583             {
584                 int i;
585                 if( long_options_index < 0 )
586                 {
587                     for( i = 0; long_options[i].name; i++ )
588                         if( long_options[i].val == c )
589                         {
590                             long_options_index = i;
591                             break;
592                         }
593                     if( long_options_index < 0 )
594                     {
595                         /* getopt_long already printed an error message */
596                         return -1;
597                     }
598                 }
599
600                 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
601             }
602         }
603
604         if( b_error )
605         {
606             const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
607             fprintf( stderr, "x264 [error]: invalid argument: %s = %s\n", name, optarg );
608             return -1;
609         }
610     }
611
612     /* Get the file name */
613     if( optind > argc - 1 || !opt->hout )
614     {
615         fprintf( stderr, "x264 [error]: No %s file. Run x264 --help for a list of options.\n",
616                  optind > argc - 1 ? "input" : "output" );
617         return -1;
618     }
619     psz_filename = argv[optind++];
620
621     /* check demuxer type */
622     psz = psz_filename + strlen(psz_filename) - 1;
623     while( psz > psz_filename && *psz != '.' )
624         psz--;
625     if( !strncasecmp( psz, ".avi", 4 ) || !strncasecmp( psz, ".avs", 4 ) )
626         b_avis = 1;
627     if( !strncasecmp( psz, ".y4m", 4 ) )
628         b_y4m = 1;
629
630     if( !(b_avis || b_y4m) ) // raw yuv
631     {
632         if( optind > argc - 1 )
633         {
634             /* try to parse the file name */
635             for( psz = psz_filename; *psz; psz++ )
636             {
637                 if( *psz >= '0' && *psz <= '9'
638                     && sscanf( psz, "%ux%u", &param->i_width, &param->i_height ) == 2 )
639                 {
640                     if( param->i_log_level >= X264_LOG_INFO )
641                         fprintf( stderr, "x264 [info]: %dx%d (given by file name) @ %.2f fps\n", param->i_width, param->i_height, (double)param->i_fps_num / (double)param->i_fps_den);
642                     break;
643                 }
644             }
645         }
646         else
647         {
648             sscanf( argv[optind++], "%ux%u", &param->i_width, &param->i_height );
649             if( param->i_log_level >= X264_LOG_INFO )
650                 fprintf( stderr, "x264 [info]: %dx%d @ %.2f fps\n", param->i_width, param->i_height, (double)param->i_fps_num / (double)param->i_fps_den);
651         }
652     }
653
654     if( !(b_avis || b_y4m) && ( !param->i_width || !param->i_height ) )
655     {
656         fprintf( stderr, "x264 [error]: Rawyuv input requires a resolution.\n" );
657         return -1;
658     }
659
660     /* open the input */
661     {
662         if( b_avis )
663         {
664 #ifdef AVIS_INPUT
665             p_open_infile = open_file_avis;
666             p_get_frame_total = get_frame_total_avis;
667             p_read_frame = read_frame_avis;
668             p_close_infile = close_file_avis;
669 #else
670             fprintf( stderr, "x264 [error]: not compiled with AVIS input support\n" );
671             return -1;
672 #endif
673         }
674         if ( b_y4m )
675         {
676             p_open_infile = open_file_y4m;
677             p_get_frame_total = get_frame_total_y4m;
678             p_read_frame = read_frame_y4m;
679             p_close_infile = close_file_y4m;
680         }
681
682         if( p_open_infile( psz_filename, &opt->hin, param ) )
683         {
684             fprintf( stderr, "x264 [error]: could not open input file '%s'\n", psz_filename );
685             return -1;
686         }
687     }
688
689 #ifdef HAVE_PTHREAD
690     if( b_thread_input || param->i_threads > 1
691         || (param->i_threads == 0 && x264_cpu_num_processors() > 1) )
692     {
693         if( open_file_thread( NULL, &opt->hin, param ) )
694         {
695             fprintf( stderr, "x264 [warning]: threaded input failed\n" );
696         }
697         else
698         {
699             p_open_infile = open_file_thread;
700             p_get_frame_total = get_frame_total_thread;
701             p_read_frame = read_frame_thread;
702             p_close_infile = close_file_thread;
703         }
704     }
705 #endif
706
707     return 0;
708 }
709
710 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
711 {
712     int num = -1, qp, ret;
713     char type;
714     uint64_t file_pos;
715     while( num < i_frame )
716     {
717         file_pos = ftell( opt->qpfile );
718         ret = fscanf( opt->qpfile, "%d %c %d\n", &num, &type, &qp );
719                 if( num > i_frame || ret == EOF )
720                 {
721                         pic->i_type = X264_TYPE_AUTO;
722                         pic->i_qpplus1 = 0;
723                         fseek( opt->qpfile , file_pos , SEEK_SET );
724                         break;
725                 }
726         if( num < i_frame )
727             continue;
728         pic->i_qpplus1 = qp+1;
729         if     ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
730         else if( type == 'i' ) pic->i_type = X264_TYPE_I;
731         else if( type == 'P' ) pic->i_type = X264_TYPE_P;
732         else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
733         else if( type == 'b' ) pic->i_type = X264_TYPE_B;
734         else ret = 0;
735         if( ret != 3 || qp < -1 || qp > 51 )
736         {
737             fprintf( stderr, "x264 [error]: can't parse qpfile for frame %d\n", i_frame );
738             fclose( opt->qpfile );
739             opt->qpfile = NULL;
740             pic->i_type = X264_TYPE_AUTO;
741             pic->i_qpplus1 = 0;
742             break;
743         }
744     }
745 }
746
747 /*****************************************************************************
748  * Encode:
749  *****************************************************************************/
750
751 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
752 {
753     x264_picture_t pic_out;
754     x264_nal_t *nal;
755     int i_nal, i;
756     int i_file = 0;
757
758     if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
759     {
760         fprintf( stderr, "x264 [error]: x264_encoder_encode failed\n" );
761     }
762
763     for( i = 0; i < i_nal; i++ )
764     {
765         int i_size;
766
767         if( mux_buffer_size < nal[i].i_payload * 3/2 + 4 )
768         {
769             mux_buffer_size = nal[i].i_payload * 2 + 4;
770             x264_free( mux_buffer );
771             mux_buffer = x264_malloc( mux_buffer_size );
772         }
773
774         i_size = mux_buffer_size;
775         x264_nal_encode( mux_buffer, &i_size, 1, &nal[i] );
776         i_file += p_write_nalu( hout, mux_buffer, i_size );
777     }
778     if (i_nal)
779         p_set_eop( hout, &pic_out );
780
781     return i_file;
782 }
783
784 static int  Encode( x264_param_t *param, cli_opt_t *opt )
785 {
786     x264_t *h;
787     x264_picture_t pic;
788
789     int     i_frame, i_frame_total;
790     int64_t i_start, i_end;
791     int64_t i_file;
792     int     i_frame_size;
793     int     i_update_interval;
794     char    buf[200];
795
796     opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
797     i_frame_total = p_get_frame_total( opt->hin );
798     i_frame_total -= opt->i_seek;
799     if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
800         && param->i_frame_total > 0 )
801         i_frame_total = param->i_frame_total;
802     param->i_frame_total = i_frame_total;
803     i_update_interval = i_frame_total ? x264_clip3( i_frame_total / 1000, 1, 10 ) : 10;
804
805     if( ( h = x264_encoder_open( param ) ) == NULL )
806     {
807         fprintf( stderr, "x264 [error]: x264_encoder_open failed\n" );
808         p_close_infile( opt->hin );
809         return -1;
810     }
811
812     if( p_set_outfile_param( opt->hout, param ) )
813     {
814         fprintf( stderr, "x264 [error]: can't set outfile param\n" );
815         p_close_infile( opt->hin );
816         p_close_outfile( opt->hout );
817         return -1;
818     }
819
820     /* Create a new pic */
821     x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height );
822
823     i_start = x264_mdate();
824
825     /* Encode frames */
826     for( i_frame = 0, i_file = 0; b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
827     {
828         if( p_read_frame( &pic, opt->hin, i_frame + opt->i_seek ) )
829             break;
830
831         pic.i_pts = (int64_t)i_frame * param->i_fps_den;
832
833         if( opt->qpfile )
834             parse_qpfile( opt, &pic, i_frame + opt->i_seek );
835         else
836         {
837             /* Do not force any parameters */
838             pic.i_type = X264_TYPE_AUTO;
839             pic.i_qpplus1 = 0;
840         }
841
842         i_file += Encode_frame( h, opt->hout, &pic );
843
844         i_frame++;
845
846         /* update status line (up to 1000 times per input file) */
847         if( opt->b_progress && i_frame % i_update_interval == 0 )
848         {
849             int64_t i_elapsed = x264_mdate() - i_start;
850             double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
851             double bitrate = (double) i_file * 8 * param->i_fps_num / ( (double) param->i_fps_den * i_frame * 1000 );
852             if( i_frame_total )
853             {
854                 int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
855                 sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
856                          100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
857                          eta/3600, (eta/60)%60, eta%60 );
858             }
859             else
860             {
861                 sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
862             }
863             fprintf( stderr, "%s  \r", buf+5 );
864             SetConsoleTitle( buf );
865             fflush( stderr ); // needed in windows
866         }
867     }
868     /* Flush delayed B-frames */
869     do {
870         i_file +=
871         i_frame_size = Encode_frame( h, opt->hout, NULL );
872     } while( i_frame_size );
873
874     i_end = x264_mdate();
875     x264_picture_clean( &pic );
876     /* Erase progress indicator before printing encoding stats. */
877     if( opt->b_progress )
878         fprintf( stderr, "                                                                               \r" );
879     x264_encoder_close( h );
880     x264_free( mux_buffer );
881     fprintf( stderr, "\n" );
882
883     if( b_ctrl_c )
884         fprintf( stderr, "aborted at input frame %d\n", opt->i_seek + i_frame );
885
886     p_close_infile( opt->hin );
887     p_close_outfile( opt->hout );
888
889     if( i_frame > 0 )
890     {
891         double fps = (double)i_frame * (double)1000000 /
892                      (double)( i_end - i_start );
893
894         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame, fps,
895                  (double) i_file * 8 * param->i_fps_num /
896                  ( (double) param->i_fps_den * i_frame * 1000 ) );
897     }
898
899     return 0;
900 }