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