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