]> git.sesse.net Git - x264/blob - x264.c
f7786ce7b3b31cca68c949c07cfbea7025072d4d
[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 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 longhelp )
133 {
134 #define H0 printf
135 #define H1 if(longhelp>=1) printf
136 #define H2 if(longhelp==2) printf
137     H0( "x264 core:%d%s\n"
138         "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
139         "\n"
140         "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
141         "  or YUV4MPEG 4:2:0 (*.y4m),\n"
142         "  or AVI or Avisynth if compiled with AVIS support (%s).\n"
143         "Outfile type is selected by filename:\n"
144         " .264 -> Raw bytestream\n"
145         " .mkv -> Matroska\n"
146         " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
147         "\n"
148         "Options:\n"
149         "\n"
150         "  -h, --help                  List basic options\n"
151         "      --longhelp              List more options\n"
152         "      --fullhelp              List all options\n"
153         "\n",
154         X264_BUILD, X264_VERSION,
155 #ifdef AVIS_INPUT
156         "yes",
157 #else
158         "no",
159 #endif
160 #ifdef MP4_OUTPUT
161         "yes"
162 #else
163         "no"
164 #endif
165       );
166     H0( "Example usage:\n" );
167     H0( "\n" );
168     H0( "      Constant quality mode:\n" );
169     H0( "            x264 --crf 24 -o output input\n" );
170     H0( "\n" );
171     H0( "      Two-pass with a bitrate of 1000kbps:\n" );
172     H0( "            x264 --pass 1 --bitrate 1000 -o output input\n" );
173     H0( "            x264 --pass 2 --bitrate 1000 -o output input\n" );
174     H0( "\n" );
175     H0( "      Lossless:\n" );
176     H0( "            x264 --crf 0 -o output input\n" );
177     H0( "\n" );
178     H0( "      Maximum PSNR at the cost of speed and visual quality:\n" );
179     H0( "            x264 --preset placebo --tune psnr -o output input\n" );
180     H0( "\n" );
181     H0( "      Constant bitrate at 1000kbps with a 2 second-buffer:\n");
182     H0( "            x264 --vbv-bufsize 2000 --bitrate 1000 -o output input\n" );
183     H0( "\n" );
184     H0( "Presets:\n" );
185     H0( "\n" );
186     H0( "      --profile               Force H.264 profile [high]\n" );
187     H0( "                                  Overrides all settings\n");
188     H0( "                                  - baseline,main,high\n" );
189     H0( "      --preset                Use a preset to select encoding settings [medium]\n" );
190     H0( "                                  Overridden by user settings\n");
191     H0( "                                  - ultrafast,veryfast,faster,fast,medium\n"
192         "                                  - slow,slower,veryslow,placebo\n" );
193     H0( "      --tune                  Tune the settings for a particular type of source\n" );
194     H0( "                                  Overridden by user settings\n");
195     H2( "                                  - film,animation,grain,psnr,ssim\n"
196         "                                  - fastdecode,touhou\n");
197     else H0( "                                  - film,animation,grain,psnr,ssim,fastdecode\n");
198     H1( "      --slow-firstpass        Don't use faster settings with --pass 1\n" );
199     H0( "\n" );
200     H0( "Frame-type options:\n" );
201     H0( "\n" );
202     H0( "  -I, --keyint <integer>      Maximum GOP size [%d]\n", defaults->i_keyint_max );
203     H2( "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n", defaults->i_keyint_min );
204     H2( "      --no-scenecut           Disable adaptive I-frame decision\n" );
205     H2( "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
206     H1( "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n", defaults->i_bframe );
207     H1( "      --b-adapt               Adaptive B-frame decision method [%d]\n"
208         "                                  Higher values may lower threading efficiency.\n"
209         "                                  - 0: Disabled\n"
210         "                                  - 1: Fast\n"
211         "                                  - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
212     H2( "      --b-bias <integer>      Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
213     H1( "      --b-pyramid             Keep some B-frames as references\n" );
214     H1( "      --no-cabac              Disable CABAC\n" );
215     H1( "  -r, --ref <integer>         Number of reference frames [%d]\n", defaults->i_frame_reference );
216     H1( "      --no-deblock            Disable loop filter\n" );
217     H1( "  -f, --deblock <alpha:beta>  Loop filter parameters [%d:%d]\n",
218                                        defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
219     H2( "      --slices <integer>      Number of slices per frame; forces rectangular\n"
220         "                              slices and is overridden by other slicing options\n" );
221     else H1( "      --slices <integer>      Number of slices per frame\n" );
222     H2( "      --slice-max-size <integer> Limit the size of each slice in bytes\n");
223     H2( "      --slice-max-mbs <integer> Limit the size of each slice in macroblocks\n");
224     H0( "      --interlaced            Enable pure-interlaced mode\n" );
225     H0( "\n" );
226     H0( "Ratecontrol:\n" );
227     H0( "\n" );
228     H1( "  -q, --qp <integer>          Force constant QP (0-51, 0=lossless)\n" );
229     H0( "  -B, --bitrate <integer>     Set bitrate (kbit/s)\n" );
230     H0( "      --crf <float>           Quality-based VBR (0-51, 0=lossless) [%.1f]\n", defaults->rc.f_rf_constant );
231     H1( "      --rc-lookahead <integer> Number of frames for frametype lookahead [%d]\n", defaults->rc.i_lookahead );
232     H0( "      --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
233     H0( "      --vbv-bufsize <integer> Set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
234     H2( "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
235     H2( "      --qpmin <integer>       Set min QP [%d]\n", defaults->rc.i_qp_min );
236     H2( "      --qpmax <integer>       Set max QP [%d]\n", defaults->rc.i_qp_max );
237     H2( "      --qpstep <integer>      Set max QP step [%d]\n", defaults->rc.i_qp_step );
238     H2( "      --ratetol <float>       Allowed variance of average bitrate [%.1f]\n", defaults->rc.f_rate_tolerance );
239     H2( "      --ipratio <float>       QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
240     H2( "      --pbratio <float>       QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
241     H2( "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
242     H2( "      --aq-mode <integer>     AQ method [%d]\n"
243         "                                  - 0: Disabled\n"
244         "                                  - 1: Variance AQ (complexity mask)\n"
245         "                                  - 2: Auto-variance AQ (experimental)\n", defaults->rc.i_aq_mode );
246     H1( "      --aq-strength <float>   Reduces blocking and blurring in flat and\n"
247         "                              textured areas. [%.1f]\n", defaults->rc.f_aq_strength );
248     H1( "\n" );
249     H2( "  -p, --pass <1|2|3>          Enable multipass ratecontrol\n" );
250     else H0( "  -p, --pass <1|2>            Enable multipass ratecontrol\n" );
251     H0( "                                  - 1: First pass, creates stats file\n"
252         "                                  - 2: Last pass, does not overwrite stats file\n" );
253     H2( "                                  - 3: Nth pass, overwrites stats file\n" );
254     H1( "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
255     H2( "      --no-mbtree             Disable mb-tree ratecontrol.\n");
256     H2( "      --qcomp <float>         QP curve compression [%.2f]\n", defaults->rc.f_qcompress );
257     H2( "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
258     H2( "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
259     H2( "      --zones <zone0>/<zone1>/...  Tweak the bitrate of regions of the video\n" );
260     H2( "                              Each zone is of the form\n"
261         "                                  <start frame>,<end frame>,<option>\n"
262         "                                  where <option> is either\n"
263         "                                      q=<integer> (force QP)\n"
264         "                                  or  b=<float> (bitrate multiplier)\n" );
265     H2( "      --qpfile <string>       Force frametypes and QPs for some or all frames\n"
266         "                              Format of each line: framenumber frametype QP\n"
267         "                              QP of -1 lets x264 choose. Frametypes: I,i,P,B,b.\n"
268         "                              QPs are restricted by qpmin/qpmax.\n" );
269     H1( "\n" );
270     H1( "Analysis:\n" );
271     H1( "\n" );
272     H1( "  -A, --partitions <string>   Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
273         "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
274         "                                  - none, all\n"
275         "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
276     H1( "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
277         "                                  - none, spatial, temporal, auto\n",
278                                        strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
279     H2( "      --no-weightb            Disable weighted prediction for B-frames\n" );
280     H1( "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n",
281                                        strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
282     H2( "                                  - dia: diamond search, radius 1 (fast)\n"
283         "                                  - hex: hexagonal search, radius 2\n"
284         "                                  - umh: uneven multi-hexagon search\n"
285         "                                  - esa: exhaustive search\n"
286         "                                  - tesa: hadamard exhaustive search (slow)\n" );
287     else H1( "                                  - dia, hex, umh\n" );
288     H2( "      --merange <integer>     Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
289     H2( "      --mvrange <integer>     Maximum motion vector length [-1 (auto)]\n" );
290     H2( "      --mvrange-thread <int>  Minimum buffer between threads [-1 (auto)]\n" );
291     H1( "  -m, --subme <integer>       Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
292     H2( "                                  - 0: fullpel only (not recommended)\n"
293         "                                  - 1: SAD mode decision, one qpel iteration\n"
294         "                                  - 2: SATD mode decision\n"
295         "                                  - 3-5: Progressively more qpel\n"
296         "                                  - 6: RD mode decision for I/P-frames\n"
297         "                                  - 7: RD mode decision for all frames\n"
298         "                                  - 8: RD refinement for I/P-frames\n"
299         "                                  - 9: RD refinement for all frames\n"
300         "                                  - 10: QP-RD - requires trellis=2, aq-mode>0\n" );
301     else H1( "                                  decision quality: 1=fast, 10=best.\n"  );
302     H1( "      --psy-rd                Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
303         "                                  #1: RD (requires subme>=6)\n"
304         "                                  #2: Trellis (requires trellis, experimental)\n",
305                                        defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
306     H2( "      --no-psy                Disable all visual optimizations that worsen\n"
307         "                              both PSNR and SSIM.\n" );
308     H2( "      --no-mixed-refs         Don't decide references on a per partition basis\n" );
309     H2( "      --no-chroma-me          Ignore chroma in motion estimation\n" );
310     H1( "      --no-8x8dct             Disable adaptive spatial transform size\n" );
311     H1( "  -t, --trellis <integer>     Trellis RD quantization. Requires CABAC. [%d]\n"
312         "                                  - 0: disabled\n"
313         "                                  - 1: enabled only on the final encode of a MB\n"
314         "                                  - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
315     H2( "      --no-fast-pskip         Disables early SKIP detection on P-frames\n" );
316     H2( "      --no-dct-decimate       Disables coefficient thresholding on P-frames\n" );
317     H1( "      --nr <integer>          Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
318     H2( "\n" );
319     H2( "      --deadzone-inter <int>  Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
320     H2( "      --deadzone-intra <int>  Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
321     H2( "                                  Deadzones should be in the range 0 - 32.\n" );
322     H2( "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
323         "                                  - jvt, flat\n" );
324     H1( "      --cqmfile <string>      Read custom quant matrices from a JM-compatible file\n" );
325     H2( "                                  Overrides any other --cqm* options.\n" );
326     H2( "      --cqm4 <list>           Set all 4x4 quant matrices\n"
327         "                                  Takes a comma-separated list of 16 integers.\n" );
328     H2( "      --cqm8 <list>           Set all 8x8 quant matrices\n"
329         "                                  Takes a comma-separated list of 64 integers.\n" );
330     H2( "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
331         "                              Set both luma and chroma quant matrices\n" );
332     H2( "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
333         "                              Set individual quant matrices\n" );
334     H2( "\n" );
335     H2( "Video Usability Info (Annex E):\n" );
336     H2( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
337     H2( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
338     H2( "\n" );
339     H2( "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
340         "                                  - undef, show, crop\n",
341                                        strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
342     H2( "      --videoformat <string>  Specify video format [\"%s\"]\n"
343         "                                  - component, pal, ntsc, secam, mac, undef\n",
344                                        strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
345     H2( "      --fullrange <string>    Specify full range samples setting [\"%s\"]\n"
346         "                                  - off, on\n",
347                                        strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ) );
348     H2( "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
349         "                                  - undef, bt709, bt470m, bt470bg\n"
350         "                                    smpte170m, smpte240m, film\n",
351                                        strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
352     H2( "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
353         "                                  - undef, bt709, bt470m, bt470bg, linear,\n"
354         "                                    log100, log316, smpte170m, smpte240m\n",
355                                        strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
356     H2( "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
357         "                                  - undef, bt709, fcc, bt470bg\n"
358         "                                    smpte170m, smpte240m, GBR, YCgCo\n",
359                                        strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
360     H2( "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n",
361                                        defaults->vui.i_chroma_loc );
362     H0( "\n" );
363     H0( "Input/Output:\n" );
364     H0( "\n" );
365     H0( "  -o, --output                Specify output file\n" );
366     H0( "      --sar width:height      Specify Sample Aspect Ratio\n" );
367     H0( "      --fps <float|rational>  Specify framerate\n" );
368     H0( "      --seek <integer>        First frame to encode\n" );
369     H0( "      --frames <integer>      Maximum number of frames to encode\n" );
370     H0( "      --level <string>        Specify level (as defined by Annex A)\n" );
371     H1( "\n" );
372     H1( "  -v, --verbose               Print stats for each frame\n" );
373     H1( "      --no-progress           Don't show the progress indicator while encoding\n" );
374     H0( "      --quiet                 Quiet Mode\n" );
375     H1( "      --psnr                  Enable PSNR computation\n" );
376     H1( "      --ssim                  Enable SSIM computation\n" );
377     H1( "      --threads <integer>     Force a specific number of threads\n" );
378     H2( "      --thread-input          Run Avisynth in its own thread\n" );
379     H2( "      --sync-lookahead <integer> Number of buffer frames for threaded lookahead\n" );
380     H2( "      --non-deterministic     Slightly improve quality of SMP, at the cost of repeatability\n" );
381     H2( "      --asm <integer>         Override CPU detection\n" );
382     H2( "      --no-asm                Disable all CPU optimizations\n" );
383     H2( "      --visualize             Show MB types overlayed on the encoded video\n" );
384     H2( "      --dump-yuv <string>     Save reconstructed frames\n" );
385     H2( "      --sps-id <integer>      Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
386     H2( "      --aud                   Use access unit delimiters\n" );
387     H0( "\n" );
388 }
389
390 #define OPT_FRAMES 256
391 #define OPT_SEEK 257
392 #define OPT_QPFILE 258
393 #define OPT_THREAD_INPUT 259
394 #define OPT_QUIET 260
395 #define OPT_NOPROGRESS 261
396 #define OPT_VISUALIZE 262
397 #define OPT_LONGHELP 263
398 #define OPT_PROFILE 264
399 #define OPT_PRESET 265
400 #define OPT_TUNE 266
401 #define OPT_SLOWFIRSTPASS 267
402 #define OPT_FULLHELP 268
403 #define OPT_FPS 269
404
405 static char short_options[] = "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw";
406 static struct option long_options[] =
407 {
408     { "help",              no_argument, NULL, 'h' },
409     { "longhelp",          no_argument, NULL, OPT_LONGHELP },
410     { "fullhelp",          no_argument, NULL, OPT_FULLHELP },
411     { "version",           no_argument, NULL, 'V' },
412     { "profile",     required_argument, NULL, OPT_PROFILE },
413     { "preset",      required_argument, NULL, OPT_PRESET },
414     { "tune",        required_argument, NULL, OPT_TUNE },
415     { "slow-firstpass",    no_argument, NULL, OPT_SLOWFIRSTPASS },
416     { "bitrate",     required_argument, NULL, 'B' },
417     { "bframes",     required_argument, NULL, 'b' },
418     { "b-adapt",     required_argument, NULL, 0 },
419     { "no-b-adapt",        no_argument, NULL, 0 },
420     { "b-bias",      required_argument, NULL, 0 },
421     { "b-pyramid",         no_argument, NULL, 0 },
422     { "min-keyint",  required_argument, NULL, 'i' },
423     { "keyint",      required_argument, NULL, 'I' },
424     { "scenecut",    required_argument, NULL, 0 },
425     { "no-scenecut",       no_argument, NULL, 0 },
426     { "nf",                no_argument, NULL, 0 },
427     { "no-deblock",        no_argument, NULL, 0 },
428     { "filter",      required_argument, NULL, 0 },
429     { "deblock",     required_argument, NULL, 'f' },
430     { "interlaced",        no_argument, NULL, 0 },
431     { "cabac",             no_argument, NULL, 0 },
432     { "no-cabac",          no_argument, NULL, 0 },
433     { "qp",          required_argument, NULL, 'q' },
434     { "qpmin",       required_argument, NULL, 0 },
435     { "qpmax",       required_argument, NULL, 0 },
436     { "qpstep",      required_argument, NULL, 0 },
437     { "crf",         required_argument, NULL, 0 },
438     { "rc-lookahead",required_argument, NULL, 0 },
439     { "ref",         required_argument, NULL, 'r' },
440     { "asm",         required_argument, NULL, 0 },
441     { "no-asm",            no_argument, NULL, 0 },
442     { "sar",         required_argument, NULL, 0 },
443     { "fps",         required_argument, NULL, OPT_FPS },
444     { "frames",      required_argument, NULL, OPT_FRAMES },
445     { "seek",        required_argument, NULL, OPT_SEEK },
446     { "output",      required_argument, NULL, 'o' },
447     { "analyse",     required_argument, NULL, 0 },
448     { "partitions",  required_argument, NULL, 'A' },
449     { "direct",      required_argument, NULL, 0 },
450     { "weightb",           no_argument, NULL, 'w' },
451     { "no-weightb",        no_argument, NULL, 0 },
452     { "me",          required_argument, NULL, 0 },
453     { "merange",     required_argument, NULL, 0 },
454     { "mvrange",     required_argument, NULL, 0 },
455     { "mvrange-thread", required_argument, NULL, 0 },
456     { "subme",       required_argument, NULL, 'm' },
457     { "psy-rd",      required_argument, NULL, 0 },
458     { "no-psy",            no_argument, NULL, 0 },
459     { "psy",               no_argument, NULL, 0 },
460     { "mixed-refs",        no_argument, NULL, 0 },
461     { "no-mixed-refs",     no_argument, NULL, 0 },
462     { "no-chroma-me",      no_argument, NULL, 0 },
463     { "8x8dct",            no_argument, NULL, 0 },
464     { "no-8x8dct",         no_argument, NULL, 0 },
465     { "trellis",     required_argument, NULL, 't' },
466     { "fast-pskip",        no_argument, NULL, 0 },
467     { "no-fast-pskip",     no_argument, NULL, 0 },
468     { "no-dct-decimate",   no_argument, NULL, 0 },
469     { "aq-strength", required_argument, NULL, 0 },
470     { "aq-mode",     required_argument, NULL, 0 },
471     { "deadzone-inter", required_argument, NULL, '0' },
472     { "deadzone-intra", required_argument, NULL, '0' },
473     { "level",       required_argument, NULL, 0 },
474     { "ratetol",     required_argument, NULL, 0 },
475     { "vbv-maxrate", required_argument, NULL, 0 },
476     { "vbv-bufsize", required_argument, NULL, 0 },
477     { "vbv-init",    required_argument, NULL,  0 },
478     { "ipratio",     required_argument, NULL, 0 },
479     { "pbratio",     required_argument, NULL, 0 },
480     { "chroma-qp-offset", required_argument, NULL, 0 },
481     { "pass",        required_argument, NULL, 'p' },
482     { "stats",       required_argument, NULL, 0 },
483     { "qcomp",       required_argument, NULL, 0 },
484     { "mbtree",            no_argument, NULL, 0 },
485     { "no-mbtree",         no_argument, NULL, 0 },
486     { "qblur",       required_argument, NULL, 0 },
487     { "cplxblur",    required_argument, NULL, 0 },
488     { "zones",       required_argument, NULL, 0 },
489     { "qpfile",      required_argument, NULL, OPT_QPFILE },
490     { "threads",     required_argument, NULL, 0 },
491     { "slice-max-size",    required_argument, NULL, 0 },
492     { "slice-max-mbs",     required_argument, NULL, 0 },
493     { "slices",            required_argument, NULL, 0 },
494     { "thread-input",      no_argument, NULL, OPT_THREAD_INPUT },
495     { "sync-lookahead",    required_argument, NULL, 0 },
496     { "non-deterministic", no_argument, NULL, 0 },
497     { "psnr",              no_argument, NULL, 0 },
498     { "ssim",              no_argument, NULL, 0 },
499     { "quiet",             no_argument, NULL, OPT_QUIET },
500     { "verbose",           no_argument, NULL, 'v' },
501     { "no-progress",       no_argument, NULL, OPT_NOPROGRESS },
502     { "visualize",         no_argument, NULL, OPT_VISUALIZE },
503     { "dump-yuv",    required_argument, NULL, 0 },
504     { "sps-id",      required_argument, NULL, 0 },
505     { "aud",               no_argument, NULL, 0 },
506     { "nr",          required_argument, NULL, 0 },
507     { "cqm",         required_argument, NULL, 0 },
508     { "cqmfile",     required_argument, NULL, 0 },
509     { "cqm4",        required_argument, NULL, 0 },
510     { "cqm4i",       required_argument, NULL, 0 },
511     { "cqm4iy",      required_argument, NULL, 0 },
512     { "cqm4ic",      required_argument, NULL, 0 },
513     { "cqm4p",       required_argument, NULL, 0 },
514     { "cqm4py",      required_argument, NULL, 0 },
515     { "cqm4pc",      required_argument, NULL, 0 },
516     { "cqm8",        required_argument, NULL, 0 },
517     { "cqm8i",       required_argument, NULL, 0 },
518     { "cqm8p",       required_argument, NULL, 0 },
519     { "overscan",    required_argument, NULL, 0 },
520     { "videoformat", required_argument, NULL, 0 },
521     { "fullrange",   required_argument, NULL, 0 },
522     { "colorprim",   required_argument, NULL, 0 },
523     { "transfer",    required_argument, NULL, 0 },
524     { "colormatrix", required_argument, NULL, 0 },
525     { "chromaloc",   required_argument, NULL, 0 },
526     {0, 0, 0, 0}
527 };
528
529 /*****************************************************************************
530  * Parse:
531  *****************************************************************************/
532 static int  Parse( int argc, char **argv,
533                    x264_param_t *param, cli_opt_t *opt )
534 {
535     char *psz_filename = NULL;
536     x264_param_t defaults = *param;
537     char *psz;
538     char *profile = NULL;
539     int b_avis = 0;
540     int b_y4m = 0;
541     int b_thread_input = 0;
542     int b_turbo = 1;
543     int b_pass1 = 0;
544     int b_user_ref = 0;
545     int b_user_fps = 0;
546
547     memset( opt, 0, sizeof(cli_opt_t) );
548     opt->b_progress = 1;
549
550     /* Default input file driver */
551     p_open_infile = open_file_yuv;
552     p_get_frame_total = get_frame_total_yuv;
553     p_read_frame = read_frame_yuv;
554     p_close_infile = close_file_yuv;
555
556     /* Default output file driver */
557     p_open_outfile = open_file_bsf;
558     p_set_outfile_param = set_param_bsf;
559     p_write_nalu = write_nalu_bsf;
560     p_set_eop = set_eop_bsf;
561     p_close_outfile = close_file_bsf;
562
563     /* Presets are applied before all other options. */
564     for( optind = 0;; )
565     {
566         int c = getopt_long( argc, argv, short_options, long_options, NULL );
567         if( c == -1 )
568             break;
569
570         if( c == OPT_PRESET )
571         {
572             if( !strcasecmp( optarg, "ultrafast" ) )
573             {
574                 param->i_frame_reference = 1;
575                 param->i_scenecut_threshold = 0;
576                 param->b_deblocking_filter = 0;
577                 param->b_cabac = 0;
578                 param->i_bframe = 0;
579                 param->analyse.intra = 0;
580                 param->analyse.inter = 0;
581                 param->analyse.b_transform_8x8 = 0;
582                 param->analyse.i_me_method = X264_ME_DIA;
583                 param->analyse.i_subpel_refine = 0;
584                 param->rc.i_aq_mode = 0;
585                 param->analyse.b_mixed_references = 0;
586                 param->analyse.i_trellis = 0;
587                 param->i_bframe_adaptive = X264_B_ADAPT_NONE;
588                 param->rc.b_mb_tree = 0;
589             }
590             else if( !strcasecmp( optarg, "veryfast" ) )
591             {
592                 param->analyse.inter = X264_ANALYSE_I8x8|X264_ANALYSE_I4x4;
593                 param->analyse.i_me_method = X264_ME_DIA;
594                 param->analyse.i_subpel_refine = 1;
595                 param->i_frame_reference = 1;
596                 param->analyse.b_mixed_references = 0;
597                 param->analyse.i_trellis = 0;
598                 param->rc.b_mb_tree = 0;
599             }
600             else if( !strcasecmp( optarg, "faster" ) )
601             {
602                 param->analyse.b_mixed_references = 0;
603                 param->i_frame_reference = 2;
604                 param->analyse.i_subpel_refine = 4;
605                 param->rc.b_mb_tree = 0;
606             }
607             else if( !strcasecmp( optarg, "fast" ) )
608             {
609                 param->i_frame_reference = 2;
610                 param->analyse.i_subpel_refine = 6;
611                 param->rc.i_lookahead = 30;
612             }
613             else if( !strcasecmp( optarg, "medium" ) )
614             {
615                 /* Default is medium */
616             }
617             else if( !strcasecmp( optarg, "slow" ) )
618             {
619                 param->analyse.i_me_method = X264_ME_UMH;
620                 param->analyse.i_subpel_refine = 8;
621                 param->i_frame_reference = 5;
622                 param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;
623                 param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
624                 param->rc.i_lookahead = 50;
625             }
626             else if( !strcasecmp( optarg, "slower" ) )
627             {
628                 param->analyse.i_me_method = X264_ME_UMH;
629                 param->analyse.i_subpel_refine = 9;
630                 param->i_frame_reference = 8;
631                 param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;
632                 param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
633                 param->analyse.inter |= X264_ANALYSE_PSUB8x8;
634                 param->analyse.i_trellis = 2;
635                 param->rc.i_lookahead = 60;
636             }
637             else if( !strcasecmp( optarg, "veryslow" ) )
638             {
639                 param->analyse.i_me_method = X264_ME_UMH;
640                 param->analyse.i_subpel_refine = 10;
641                 param->analyse.i_me_range = 24;
642                 param->i_frame_reference = 16;
643                 param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;
644                 param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
645                 param->analyse.inter |= X264_ANALYSE_PSUB8x8;
646                 param->analyse.i_trellis = 2;
647                 param->i_bframe = 8;
648                 param->rc.i_lookahead = 60;
649             }
650             else if( !strcasecmp( optarg, "placebo" ) )
651             {
652                 param->analyse.i_me_method = X264_ME_TESA;
653                 param->analyse.i_subpel_refine = 10;
654                 param->analyse.i_me_range = 24;
655                 param->i_frame_reference = 16;
656                 param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;
657                 param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
658                 param->analyse.inter |= X264_ANALYSE_PSUB8x8;
659                 param->analyse.b_fast_pskip = 0;
660                 param->analyse.i_trellis = 2;
661                 param->i_bframe = 16;
662                 param->rc.i_lookahead = 60;
663             }
664             else
665             {
666                 fprintf( stderr, "x264 [error]: invalid preset: %s\n", optarg );
667                 return -1;
668             }
669         }
670         else if( c == '?' )
671             return -1;
672     }
673
674     /* Tunings are applied next. */
675     for( optind = 0;; )
676     {
677         int c = getopt_long( argc, argv, short_options, long_options, NULL );
678         if( c == -1 )
679             break;
680
681         if( c == OPT_TUNE )
682         {
683             if( !strcasecmp( optarg, "film" ) )
684             {
685                 param->i_deblocking_filter_alphac0 = -1;
686                 param->i_deblocking_filter_beta = -1;
687                 param->analyse.f_psy_trellis = 0.15;
688             }
689             else if( !strcasecmp( optarg, "animation" ) )
690             {
691                 param->i_frame_reference = param->i_frame_reference > 1 ? param->i_frame_reference*2 : 1;
692                 param->i_deblocking_filter_alphac0 = 1;
693                 param->i_deblocking_filter_beta = 1;
694                 param->analyse.f_psy_rd = 0.4;
695                 param->rc.f_aq_strength = 0.6;
696                 param->i_bframe += 2;
697             }
698             else if( !strcasecmp( optarg, "grain" ) )
699             {
700                 param->i_deblocking_filter_alphac0 = -2;
701                 param->i_deblocking_filter_beta = -2;
702                 param->analyse.f_psy_trellis = 0.25;
703                 param->analyse.b_dct_decimate = 0;
704                 param->rc.f_pb_factor = 1.1;
705                 param->rc.f_ip_factor = 1.1;
706                 param->rc.f_aq_strength = 0.5;
707                 param->analyse.i_luma_deadzone[0] = 6;
708                 param->analyse.i_luma_deadzone[1] = 6;
709                 param->rc.f_qcompress = 0.8;
710             }
711             else if( !strcasecmp( optarg, "psnr" ) )
712             {
713                 param->rc.i_aq_mode = X264_AQ_NONE;
714                 param->analyse.b_psy = 0;
715             }
716             else if( !strcasecmp( optarg, "ssim" ) )
717             {
718                 param->rc.i_aq_mode = X264_AQ_AUTOVARIANCE;
719                 param->analyse.b_psy = 0;
720             }
721             else if( !strcasecmp( optarg, "fastdecode" ) )
722             {
723                 param->b_deblocking_filter = 0;
724                 param->b_cabac = 0;
725                 param->analyse.b_weighted_bipred = 0;
726             }
727             else if( !strcasecmp( optarg, "touhou" ) )
728             {
729                 param->i_frame_reference = param->i_frame_reference > 1 ? param->i_frame_reference*2 : 1;
730                 param->i_deblocking_filter_alphac0 = -1;
731                 param->i_deblocking_filter_beta = -1;
732                 param->analyse.f_psy_trellis = 0.2;
733                 param->rc.f_aq_strength = 1.3;
734                 if( param->analyse.inter & X264_ANALYSE_PSUB16x16 )
735                     param->analyse.inter |= X264_ANALYSE_PSUB8x8;
736             }
737             else
738             {
739                 fprintf( stderr, "x264 [error]: invalid tune: %s\n", optarg );
740                 return -1;
741             }
742         }
743         else if( c == '?' )
744             return -1;
745     }
746
747     /* Parse command line options */
748     for( optind = 0;; )
749     {
750         int b_error = 0;
751         int long_options_index = -1;
752
753         int c = getopt_long( argc, argv, short_options, long_options, &long_options_index );
754
755         if( c == -1 )
756         {
757             break;
758         }
759
760         switch( c )
761         {
762             case 'h':
763                 Help( &defaults, 0 );
764                 exit(0);
765             case OPT_LONGHELP:
766                 Help( &defaults, 1 );
767                 exit(0);
768             case OPT_FULLHELP:
769                 Help( &defaults, 2 );
770                 exit(0);
771             case 'V':
772 #ifdef X264_POINTVER
773                 printf( "x264 "X264_POINTVER"\n" );
774 #else
775                 printf( "x264 0.%d.X\n", X264_BUILD );
776 #endif
777                 printf( "built on " __DATE__ ", " );
778 #ifdef __GNUC__
779                 printf( "gcc: " __VERSION__ "\n" );
780 #else
781                 printf( "using a non-gcc compiler\n" );
782 #endif
783                 exit(0);
784             case OPT_FRAMES:
785                 param->i_frame_total = atoi( optarg );
786                 break;
787             case OPT_SEEK:
788                 opt->i_seek = atoi( optarg );
789                 break;
790             case 'o':
791                 if( !strncasecmp(optarg + strlen(optarg) - 4, ".mp4", 4) )
792                 {
793 #ifdef MP4_OUTPUT
794                     p_open_outfile = open_file_mp4;
795                     p_write_nalu = write_nalu_mp4;
796                     p_set_outfile_param = set_param_mp4;
797                     p_set_eop = set_eop_mp4;
798                     p_close_outfile = close_file_mp4;
799 #else
800                     fprintf( stderr, "x264 [error]: not compiled with MP4 output support\n" );
801                     return -1;
802 #endif
803                 }
804                 else if( !strncasecmp(optarg + strlen(optarg) - 4, ".mkv", 4) )
805                 {
806                     p_open_outfile = open_file_mkv;
807                     p_write_nalu = write_nalu_mkv;
808                     p_set_outfile_param = set_param_mkv;
809                     p_set_eop = set_eop_mkv;
810                     p_close_outfile = close_file_mkv;
811                 }
812                 if( !strcmp(optarg, "-") )
813                     opt->hout = stdout;
814                 else if( p_open_outfile( optarg, &opt->hout ) )
815                 {
816                     fprintf( stderr, "x264 [error]: can't open output file `%s'\n", optarg );
817                     return -1;
818                 }
819                 break;
820             case OPT_QPFILE:
821                 opt->qpfile = fopen( optarg, "rb" );
822                 if( !opt->qpfile )
823                 {
824                     fprintf( stderr, "x264 [error]: can't open `%s'\n", optarg );
825                     return -1;
826                 }
827                 break;
828             case OPT_THREAD_INPUT:
829                 b_thread_input = 1;
830                 break;
831             case OPT_QUIET:
832                 param->i_log_level = X264_LOG_NONE;
833                 break;
834             case 'v':
835                 param->i_log_level = X264_LOG_DEBUG;
836                 break;
837             case OPT_NOPROGRESS:
838                 opt->b_progress = 0;
839                 break;
840             case OPT_VISUALIZE:
841 #ifdef VISUALIZE
842                 param->b_visualize = 1;
843                 b_exit_on_ctrl_c = 1;
844 #else
845                 fprintf( stderr, "x264 [warning]: not compiled with visualization support\n" );
846 #endif
847                 break;
848             case OPT_TUNE:
849             case OPT_PRESET:
850                 break;
851             case OPT_PROFILE:
852                 profile = optarg;
853                 break;
854             case OPT_SLOWFIRSTPASS:
855                 b_turbo = 0;
856                 break;
857             case 'r':
858                 b_user_ref = 1;
859                 goto generic_option;
860             case 'p':
861                 b_pass1 = atoi( optarg ) == 1;
862                 goto generic_option;
863             case OPT_FPS:
864                 b_user_fps = 1;
865                 goto generic_option;
866             default:
867 generic_option:
868             {
869                 int i;
870                 if( long_options_index < 0 )
871                 {
872                     for( i = 0; long_options[i].name; i++ )
873                         if( long_options[i].val == c )
874                         {
875                             long_options_index = i;
876                             break;
877                         }
878                     if( long_options_index < 0 )
879                     {
880                         /* getopt_long already printed an error message */
881                         return -1;
882                     }
883                 }
884
885                 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
886             }
887         }
888
889         if( b_error )
890         {
891             const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
892             fprintf( stderr, "x264 [error]: invalid argument: %s = %s\n", name, optarg );
893             return -1;
894         }
895     }
896
897     /* Set faster options in case of turbo firstpass. */
898     if( b_turbo && b_pass1 )
899     {
900         param->i_frame_reference = 1;
901         param->analyse.b_transform_8x8 = 0;
902         param->analyse.inter = 0;
903         param->analyse.i_me_method = X264_ME_DIA;
904         param->analyse.i_subpel_refine = X264_MIN( 2, param->analyse.i_subpel_refine );
905         param->analyse.i_trellis = 0;
906     }
907
908     /* Apply profile restrictions. */
909     if( profile )
910     {
911         if( !strcasecmp( profile, "baseline" ) )
912         {
913             param->analyse.b_transform_8x8 = 0;
914             param->b_cabac = 0;
915             param->i_cqm_preset = X264_CQM_FLAT;
916             param->i_bframe = 0;
917             if( param->b_interlaced )
918             {
919                 fprintf( stderr, "x264 [error]: baseline profile doesn't support interlacing\n" );
920                 return -1;
921             }
922         }
923         else if( !strcasecmp( profile, "main" ) )
924         {
925             param->analyse.b_transform_8x8 = 0;
926             param->i_cqm_preset = X264_CQM_FLAT;
927         }
928         else if( !strcasecmp( profile, "high" ) )
929         {
930             /* Default */
931         }
932         else
933         {
934             fprintf( stderr, "x264 [error]: invalid profile: %s\n", profile );
935             return -1;
936         }
937         if( (param->rc.i_rc_method == X264_RC_CQP && param->rc.i_qp_constant == 0) ||
938             (param->rc.i_rc_method == X264_RC_CRF && param->rc.f_rf_constant == 0) )
939         {
940             fprintf( stderr, "x264 [error]: %s profile doesn't support lossless\n", profile );
941             return -1;
942         }
943     }
944
945     /* Get the file name */
946     if( optind > argc - 1 || !opt->hout )
947     {
948         fprintf( stderr, "x264 [error]: No %s file. Run x264 --help for a list of options.\n",
949                  optind > argc - 1 ? "input" : "output" );
950         return -1;
951     }
952     psz_filename = argv[optind++];
953
954     /* check demuxer type */
955     psz = psz_filename + strlen(psz_filename) - 1;
956     while( psz > psz_filename && *psz != '.' )
957         psz--;
958     if( !strncasecmp( psz, ".avi", 4 ) || !strncasecmp( psz, ".avs", 4 ) )
959         b_avis = 1;
960     if( !strncasecmp( psz, ".y4m", 4 ) )
961         b_y4m = 1;
962
963     if( !(b_avis || b_y4m) ) // raw yuv
964     {
965         if( optind > argc - 1 )
966         {
967             /* try to parse the file name */
968             for( psz = psz_filename; *psz; psz++ )
969             {
970                 if( *psz >= '0' && *psz <= '9'
971                     && sscanf( psz, "%ux%u", &param->i_width, &param->i_height ) == 2 )
972                 {
973                     if( param->i_log_level >= X264_LOG_INFO )
974                         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);
975                     break;
976                 }
977             }
978         }
979         else
980         {
981             sscanf( argv[optind++], "%ux%u", &param->i_width, &param->i_height );
982             if( param->i_log_level >= X264_LOG_INFO )
983                 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);
984         }
985     }
986
987     if( !(b_avis || b_y4m) && ( !param->i_width || !param->i_height ) )
988     {
989         fprintf( stderr, "x264 [error]: Rawyuv input requires a resolution.\n" );
990         return -1;
991     }
992
993     /* open the input */
994     {
995         int i_fps_num = param->i_fps_num;
996         int i_fps_den = param->i_fps_den;
997         if( b_avis )
998         {
999 #ifdef AVIS_INPUT
1000             p_open_infile = open_file_avis;
1001             p_get_frame_total = get_frame_total_avis;
1002             p_read_frame = read_frame_avis;
1003             p_close_infile = close_file_avis;
1004 #else
1005             fprintf( stderr, "x264 [error]: not compiled with AVIS input support\n" );
1006             return -1;
1007 #endif
1008         }
1009         if( b_y4m )
1010         {
1011             p_open_infile = open_file_y4m;
1012             p_get_frame_total = get_frame_total_y4m;
1013             p_read_frame = read_frame_y4m;
1014             p_close_infile = close_file_y4m;
1015         }
1016
1017         if( p_open_infile( psz_filename, &opt->hin, param ) )
1018         {
1019             fprintf( stderr, "x264 [error]: could not open input file '%s'\n", psz_filename );
1020             return -1;
1021         }
1022         /* Restore the user's frame rate if fps has been explicitly set on the commandline. */
1023         if( b_user_fps )
1024         {
1025             param->i_fps_num = i_fps_num;
1026             param->i_fps_den = i_fps_den;
1027         }
1028     }
1029
1030 #ifdef HAVE_PTHREAD
1031     if( b_thread_input || param->i_threads > 1
1032         || (param->i_threads == X264_THREADS_AUTO && x264_cpu_num_processors() > 1) )
1033     {
1034         if( open_file_thread( NULL, &opt->hin, param ) )
1035         {
1036             fprintf( stderr, "x264 [error]: threaded input failed\n" );
1037             return -1;
1038         }
1039         else
1040         {
1041             p_open_infile = open_file_thread;
1042             p_get_frame_total = get_frame_total_thread;
1043             p_read_frame = read_frame_thread;
1044             p_close_infile = close_file_thread;
1045         }
1046     }
1047 #endif
1048
1049
1050     /* Automatically reduce reference frame count to match the user's target level
1051      * if the user didn't explicitly set a reference frame count. */
1052     if( !b_user_ref )
1053     {
1054         int mbs = (((param->i_width)+15)>>4) * (((param->i_height)+15)>>4);
1055         int i;
1056         for( i = 0; x264_levels[i].level_idc != 0; i++ )
1057             if( param->i_level_idc == x264_levels[i].level_idc )
1058             {
1059                 while( mbs * 384 * param->i_frame_reference > x264_levels[i].dpb
1060                        && param->i_frame_reference > 1 )
1061                 {
1062                     param->i_frame_reference--;
1063                 }
1064                 break;
1065             }
1066     }
1067
1068
1069     return 0;
1070 }
1071
1072 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
1073 {
1074     int num = -1, qp, ret;
1075     char type;
1076     uint64_t file_pos;
1077     while( num < i_frame )
1078     {
1079         file_pos = ftell( opt->qpfile );
1080         ret = fscanf( opt->qpfile, "%d %c %d\n", &num, &type, &qp );
1081         if( num > i_frame || ret == EOF )
1082         {
1083             pic->i_type = X264_TYPE_AUTO;
1084             pic->i_qpplus1 = 0;
1085             fseek( opt->qpfile , file_pos , SEEK_SET );
1086             break;
1087         }
1088         if( num < i_frame && ret == 3 )
1089             continue;
1090         pic->i_qpplus1 = qp+1;
1091         if     ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
1092         else if( type == 'i' ) pic->i_type = X264_TYPE_I;
1093         else if( type == 'P' ) pic->i_type = X264_TYPE_P;
1094         else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
1095         else if( type == 'b' ) pic->i_type = X264_TYPE_B;
1096         else ret = 0;
1097         if( ret != 3 || qp < -1 || qp > 51 )
1098         {
1099             fprintf( stderr, "x264 [error]: can't parse qpfile for frame %d\n", i_frame );
1100             fclose( opt->qpfile );
1101             opt->qpfile = NULL;
1102             pic->i_type = X264_TYPE_AUTO;
1103             pic->i_qpplus1 = 0;
1104             break;
1105         }
1106     }
1107 }
1108
1109 /*****************************************************************************
1110  * Encode:
1111  *****************************************************************************/
1112
1113 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
1114 {
1115     x264_picture_t pic_out;
1116     x264_nal_t *nal;
1117     int i_nal, i, i_nalu_size;
1118     int i_file = 0;
1119
1120     if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
1121     {
1122         fprintf( stderr, "x264 [error]: x264_encoder_encode failed\n" );
1123         return -1;
1124     }
1125
1126     for( i = 0; i < i_nal; i++ )
1127     {
1128         i_nalu_size = p_write_nalu( hout, nal[i].p_payload, nal[i].i_payload );
1129         if( i_nalu_size < 0 )
1130             return -1;
1131         i_file += i_nalu_size;
1132     }
1133     if (i_nal)
1134         p_set_eop( hout, &pic_out );
1135
1136     return i_file;
1137 }
1138
1139 static void Print_status( int64_t i_start, int i_frame, int i_frame_total, int64_t i_file, x264_param_t *param )
1140 {
1141     char    buf[200];
1142     int64_t i_elapsed = x264_mdate() - i_start;
1143     double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1144     double bitrate = (double) i_file * 8 * param->i_fps_num / ( (double) param->i_fps_den * i_frame * 1000 );
1145     if( i_frame_total )
1146     {
1147         int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1148         sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
1149                  100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
1150                  eta/3600, (eta/60)%60, eta%60 );
1151     }
1152     else
1153     {
1154         sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
1155     }
1156     fprintf( stderr, "%s  \r", buf+5 );
1157     SetConsoleTitle( buf );
1158     fflush( stderr ); // needed in windows
1159 }
1160
1161 static int  Encode( x264_param_t *param, cli_opt_t *opt )
1162 {
1163     x264_t *h;
1164     x264_picture_t pic;
1165
1166     int     i_frame, i_frame_total, i_frame_output;
1167     int64_t i_start, i_end;
1168     int64_t i_file;
1169     int     i_frame_size;
1170     int     i_update_interval;
1171
1172     opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
1173     i_frame_total = p_get_frame_total( opt->hin );
1174     i_frame_total -= opt->i_seek;
1175     if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
1176         && param->i_frame_total > 0 )
1177         i_frame_total = param->i_frame_total;
1178     param->i_frame_total = i_frame_total;
1179     i_update_interval = i_frame_total ? x264_clip3( i_frame_total / 1000, 1, 10 ) : 10;
1180
1181     if( ( h = x264_encoder_open( param ) ) == NULL )
1182     {
1183         fprintf( stderr, "x264 [error]: x264_encoder_open failed\n" );
1184         p_close_infile( opt->hin );
1185         return -1;
1186     }
1187
1188     if( p_set_outfile_param( opt->hout, param ) )
1189     {
1190         fprintf( stderr, "x264 [error]: can't set outfile param\n" );
1191         p_close_infile( opt->hin );
1192         p_close_outfile( opt->hout );
1193         return -1;
1194     }
1195
1196     /* Create a new pic */
1197     if( x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height ) < 0 )
1198     {
1199         fprintf( stderr, "x264 [error]: malloc failed\n" );
1200         return -1;
1201     }
1202
1203     i_start = x264_mdate();
1204
1205     /* Encode frames */
1206     for( i_frame = 0, i_file = 0, i_frame_output = 0; b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1207     {
1208         if( p_read_frame( &pic, opt->hin, i_frame + opt->i_seek ) )
1209             break;
1210
1211         pic.i_pts = (int64_t)i_frame * param->i_fps_den;
1212
1213         if( opt->qpfile )
1214             parse_qpfile( opt, &pic, i_frame + opt->i_seek );
1215         else
1216         {
1217             /* Do not force any parameters */
1218             pic.i_type = X264_TYPE_AUTO;
1219             pic.i_qpplus1 = 0;
1220         }
1221
1222         i_frame_size = Encode_frame( h, opt->hout, &pic );
1223         if( i_frame_size < 0 )
1224             return -1;
1225         i_file += i_frame_size;
1226         if( i_frame_size )
1227             i_frame_output++;
1228
1229         i_frame++;
1230
1231         /* update status line (up to 1000 times per input file) */
1232         if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1233             Print_status( i_start, i_frame_output, i_frame_total, i_file, param );
1234     }
1235     /* Flush delayed frames */
1236     while( !b_ctrl_c && x264_encoder_delayed_frames( h ) )
1237     {
1238         i_frame_size = Encode_frame( h, opt->hout, NULL );
1239         if( i_frame_size < 0 )
1240             return -1;
1241         i_file += i_frame_size;
1242         if( i_frame_size )
1243             i_frame_output++;
1244         if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1245             Print_status( i_start, i_frame_output, i_frame_total, i_file, param );
1246     }
1247
1248     i_end = x264_mdate();
1249     x264_picture_clean( &pic );
1250     /* Erase progress indicator before printing encoding stats. */
1251     if( opt->b_progress )
1252         fprintf( stderr, "                                                                               \r" );
1253     x264_encoder_close( h );
1254     x264_free( mux_buffer );
1255     fprintf( stderr, "\n" );
1256
1257     if( b_ctrl_c )
1258         fprintf( stderr, "aborted at input frame %d, output frame %d\n", opt->i_seek + i_frame, i_frame_output );
1259
1260     p_close_infile( opt->hin );
1261     p_close_outfile( opt->hout );
1262
1263     if( i_frame > 0 )
1264     {
1265         double fps = (double)i_frame * (double)1000000 /
1266                      (double)( i_end - i_start );
1267
1268         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame_output, fps,
1269                  (double) i_file * 8 * param->i_fps_num /
1270                  ( (double) param->i_fps_den * i_frame * 1000 ) );
1271     }
1272
1273     return 0;
1274 }