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