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