]> git.sesse.net Git - x264/blob - x264.c
cli: support yuv4mpeg input.
[x264] / x264.c
1 /*****************************************************************************
2  * x264: h264 encoder/decoder 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 #define _LARGEFILE_SOURCE
25 #define _FILE_OFFSET_BITS 64
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <math.h>
31
32 #include <signal.h>
33 #define _GNU_SOURCE
34 #include <getopt.h>
35
36 #ifdef _MSC_VER
37 #include <io.h>     /* _setmode() */
38 #include <fcntl.h>  /* _O_BINARY */
39 #endif
40
41 #ifndef _MSC_VER
42 #include "config.h"
43 #endif
44
45 #include "common/common.h"
46 #include "x264.h"
47 #include "muxers.h"
48
49 #define DATA_MAX 3000000
50 uint8_t data[DATA_MAX];
51
52 /* Ctrl-C handler */
53 static int     b_ctrl_c = 0;
54 static int     b_exit_on_ctrl_c = 0;
55 static void    SigIntHandler( int a )
56 {
57     if( b_exit_on_ctrl_c )
58         exit(0);
59     b_ctrl_c = 1;
60 }
61
62 typedef struct {
63     int b_decompress;
64     int b_progress;
65     int i_seek;
66     hnd_t hin;
67     hnd_t hout;
68 } cli_opt_t;
69
70 /* input file operation function pointers */
71 int (*p_open_infile)( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
72 int (*p_get_frame_total)( hnd_t handle );
73 int (*p_read_frame)( x264_picture_t *p_pic, hnd_t handle, int i_frame );
74 int (*p_close_infile)( hnd_t handle );
75
76 /* output file operation function pointers */
77 static int (*p_open_outfile)( char *psz_filename, hnd_t *p_handle );
78 static int (*p_set_outfile_param)( hnd_t handle, x264_param_t *p_param );
79 static int (*p_write_nalu)( hnd_t handle, uint8_t *p_nal, int i_size );
80 static int (*p_set_eop)( hnd_t handle, x264_picture_t *p_picture );
81 static int (*p_close_outfile)( hnd_t handle );
82
83 static void Help( x264_param_t *defaults );
84 static int  Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
85 static int  Encode( x264_param_t *param, cli_opt_t *opt );
86
87
88 /****************************************************************************
89  * main:
90  ****************************************************************************/
91 int main( int argc, char **argv )
92 {
93     x264_param_t param;
94     cli_opt_t opt;
95
96 #ifdef _MSC_VER
97     _setmode(_fileno(stdin), _O_BINARY);
98     _setmode(_fileno(stdout), _O_BINARY);
99 #endif
100
101     x264_param_default( &param );
102
103     /* Parse command line */
104     if( Parse( argc, argv, &param, &opt ) < 0 )
105         return -1;
106
107     /* Control-C handler */
108     signal( SIGINT, SigIntHandler );
109
110     return Encode( &param, &opt );
111 }
112
113 static const char * const overscan_str[] = { "undef", "show", "crop", NULL };
114 static const char * const vidformat_str[] = { "component", "pal", "ntsc", "secam", "mac", "undef", NULL };
115 static const char * const fullrange_str[] = { "off", "on", NULL };
116 static const char * const colorprim_str[] = { "", "bt709", "undef", "", "bt470m", "bt470bg", "smpte170m", "smpte240m", "film", NULL };
117 static const char * const transfer_str[] = { "", "bt709", "undef", "", "bt470m", "bt470bg", "smpte170m", "smpte240m", "linear", "log100", "log316", NULL };
118 static const char * const colmatrix_str[] = { "GBR", "bt709", "undef", "", "fcc", "bt470bg", "smpte170m", "smpte240m", "YCgCo", NULL };
119
120 static char const *strtable_lookup( const char * const table[], int index )
121 {
122     int i = 0; while( table[i] ) i++;
123     return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
124 }
125
126 /*****************************************************************************
127  * Help:
128  *****************************************************************************/
129 static void Help( x264_param_t *defaults )
130 {
131     fprintf( stderr,
132              "x264 core:%d%s\n"
133              "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
134              "\n"
135              "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
136              "  or YUV4MPEG 4:2:0 (*.y4m),\n"
137              "  or AVI or Avisynth if compiled with AVIS support (%s).\n"
138              "Outfile type is selected by filename:\n"
139              " .264 -> Raw bytestream\n"
140              " .mkv -> Matroska\n"
141              " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
142              "\n"
143              "Options:\n"
144              "\n"
145              "  -h, --help                  Print this help\n"
146              "\n"
147              "Frame-type options:\n"
148              "\n"
149              "  -I, --keyint <integer>      Maximum GOP size [%d]\n"
150              "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n"
151              "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n"
152              "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n"
153              "      --no-b-adapt            Disable adaptive B-frame decision\n"
154              "      --b-bias <integer>      Influences how often B-frames are used [%d]\n"
155              "      --b-pyramid             Keep some B-frames as references\n"
156              "\n"
157              "      --no-cabac              Disable CABAC\n"
158              "  -r, --ref <integer>         Number of reference frames [%d]\n"
159              "      --nf                    Disable loop filter\n"
160              "  -f, --filter <alpha:beta>   Loop filter AlphaC0 and Beta parameters [%d:%d]\n"
161              "\n"
162              "Ratecontrol:\n"
163              "\n"
164              "  -q, --qp <integer>          Set QP (0=lossless) [%d]\n"
165              "  -B, --bitrate <integer>     Set bitrate\n"
166              "      --crf <integer>         Quality-based VBR (nominal QP)\n"
167              "      --qpmin <integer>       Set min QP [%d]\n"
168              "      --qpmax <integer>       Set max QP [%d]\n"
169              "      --qpstep <integer>      Set max QP step [%d]\n"
170              "      --ratetol <float>       Allowed variance of average bitrate [%.1f]\n"
171              "      --vbv-maxrate <integer> Max local bitrate [%d]\n"
172              "      --vbv-bufsize <integer> Size of VBV buffer [%d]\n"
173              "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n"
174              "\n"
175              "      --ipratio <float>       QP factor between I and P [%.2f]\n"
176              "      --pbratio <float>       QP factor between P and B [%.2f]\n"
177              "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n"
178              "\n"
179              "  -p, --pass <1|2|3>          Enable multipass ratecontrol:\n"
180              "                                  - 1: First pass, creates stats file\n"
181              "                                  - 2: Last pass, does not overwrite stats file\n"
182              "                                  - 3: Nth pass, overwrites stats file\n"
183              "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n"
184              "      --rceq <string>         Ratecontrol equation [\"%s\"]\n"
185              "      --qcomp <float>         QP curve compression: 0.0 => CBR, 1.0 => CQP [%.2f]\n"
186              "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n"
187              "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n"
188              "\n"
189              "      --zones <zone0>/<zone1>/...\n"
190              "                              Tweak the bitrate of some regions of the video\n"
191              "                              Each zone is of the form\n"
192              "                                  <start frame>,<end frame>,<option>\n"
193              "                                  where <option> is either\n"
194              "                                      q=<integer> (force QP)\n"
195              "                                  or  b=<float> (bitrate multiplier)\n"
196              "\n"
197              "Analysis:\n"
198              "\n"
199              "  -A, --analyse <string>      Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
200              "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
201              "                                  - none, all\n"
202              "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n"
203              "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
204              "                                  - none, spatial, temporal, auto\n"
205              "  -w, --weightb               Weighted prediction for B-frames\n"
206              "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n"
207              "                                  - dia: diamond search, radius 1 (fast)\n"
208              "                                  - hex: hexagonal search, radius 2\n"
209              "                                  - umh: uneven multi-hexagon search\n"
210              "                                  - esa: exhaustive search (slow)\n"
211              "      --merange <integer>     Maximum motion vector search range [%d]\n"
212              "  -m, --subme <integer>       Subpixel motion estimation and partition\n"
213              "                                  decision quality: 1=fast, 7=best. [%d]\n"
214              "      --b-rdo                 RD based mode decision for B-frames. Requires subme 6.\n"
215              "      --mixed-refs            Decide references on a per partition basis\n"
216              "      --no-chroma-me          Ignore chroma in motion estimation\n"
217              "      --bime                  Jointly optimize both MVs in B-frames\n"
218              "  -8, --8x8dct                Adaptive spatial transform size\n"
219              "  -t, --trellis <integer>     Trellis RD quantization. Requires CABAC. [%d]\n"
220              "                                  - 0: disabled\n"
221              "                                  - 1: enabled only on the final encode of a MB\n"
222              "                                  - 2: enabled on all mode decisions\n"
223              "      --no-fast-pskip         Disables early SKIP detection on P-frames\n"
224              "      --nr <integer>          Noise reduction [%d]\n"
225              "\n"
226              "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
227              "                                  - jvt, flat\n"
228              "      --cqmfile <string>      Read quant matrices from a JM-compatible file\n"
229              "                                  Overrides any other --cqm* options.\n"
230              "      --cqm4 <list>           Set all 4x4 quant matrices\n"
231              "                                  Takes a comma-separated list of 16 integers.\n"
232              "      --cqm8 <list>           Set all 8x8 quant matrices\n"
233              "                                  Takes a comma-separated list of 64 integers.\n"
234              "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
235              "                              Set both luma and chroma quant matrices\n"
236              "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
237              "                              Set individual quant matrices\n"
238              "\n"
239              "Video Usability Info (Annex E):\n"
240              "The VUI settings are not used by the encoder but are merely suggestions to\n"
241              "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n"
242              "\n"
243              "      --sar width:height      Specify Sample Aspect Ratio\n"
244              "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
245              "                                  - undef, show, crop\n"
246              "      --videoformat <string>  Specify video format [\"%s\"]\n"
247              "                                  - component, pal, ntsc, secam, mac, undef\n"
248              "      --fullrange <string>    Specify full range samples setting [\"%s\"]\n"
249              "                                  - off, on\n"
250              "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
251              "                                  - undef, bt709, bt470m, bt470bg\n"
252              "                                    smpte170m, smpte240m, film\n"
253              "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
254              "                                  - undef, bt709, bt470m, bt470bg, linear,\n"
255              "                                    log100, log316, smpte170m, smpte240m\n"
256              "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
257              "                                  - undef, bt709, fcc, bt470bg\n"
258              "                                    smpte170m, smpte240m, GBR, YCgCo\n"
259              "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n"
260              "\n"
261              "Input/Output:\n"
262              "\n"
263              "      --level <string>        Specify level (as defined by Annex A)\n"
264              "      --fps <float|rational>  Specify framerate\n"
265              "      --seek <integer>        First frame to encode\n"
266              "      --frames <integer>      Maximum number of frames to encode\n"
267              "  -o, --output                Specify output file\n"
268              "\n"
269              "      --threads <integer>     Parallel encoding (uses slices)\n"
270              "      --thread-input          Run Avisynth in its own thread\n"
271              "      --no-asm                Disable all CPU optimizations\n"
272              "      --no-psnr               Disable PSNR computation\n"
273              "      --quiet                 Quiet Mode\n"
274              "  -v, --verbose               Print stats for each frame\n"
275              "      --progress              Show a progress indicator while encoding\n"
276              "      --visualize             Show MB types overlayed on the encoded video\n"
277              "      --aud                   Use access unit delimiters\n"
278              "\n",
279             X264_BUILD, X264_VERSION,
280 #ifdef AVIS_INPUT
281             "yes",
282 #else
283             "no",
284 #endif
285 #ifdef MP4_OUTPUT
286             "yes",
287 #else
288             "no",
289 #endif
290             defaults->i_keyint_max,
291             defaults->i_keyint_min,
292             defaults->i_scenecut_threshold,
293             defaults->i_bframe,
294             defaults->i_bframe_bias,
295             defaults->i_frame_reference,
296             defaults->i_deblocking_filter_alphac0,
297             defaults->i_deblocking_filter_beta,
298             defaults->rc.i_qp_constant,
299             defaults->rc.i_qp_min,
300             defaults->rc.i_qp_max,
301             defaults->rc.i_qp_step,
302             defaults->rc.f_rate_tolerance,
303             defaults->rc.i_vbv_max_bitrate,
304             defaults->rc.i_vbv_buffer_size,
305             defaults->rc.f_vbv_buffer_init,
306             defaults->rc.f_ip_factor,
307             defaults->rc.f_pb_factor,
308             defaults->analyse.i_chroma_qp_offset,
309             defaults->rc.psz_stat_out,
310             defaults->rc.psz_rc_eq,
311             defaults->rc.f_qcompress,
312             defaults->rc.f_complexity_blur,
313             defaults->rc.f_qblur,
314             strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ),
315             strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ),
316             defaults->analyse.i_me_range,
317             defaults->analyse.i_subpel_refine,
318             defaults->analyse.i_trellis,
319             defaults->analyse.i_noise_reduction,
320             strtable_lookup( overscan_str, defaults->vui.i_overscan ),
321             strtable_lookup( vidformat_str, defaults->vui.i_vidformat ),
322             strtable_lookup( fullrange_str, defaults->vui.b_fullrange ),
323             strtable_lookup( colorprim_str, defaults->vui.i_colorprim ),
324             strtable_lookup( transfer_str, defaults->vui.i_transfer ),
325             strtable_lookup( colmatrix_str, defaults->vui.i_colmatrix ),
326             defaults->vui.i_chroma_loc
327            );
328 }
329
330 static int parse_enum( const char *arg, const char * const *names, int *dst )
331 {
332     int i;
333     for( i = 0; names[i]; i++ )
334         if( !strcmp( arg, names[i] ) )
335         {
336             *dst = i;
337             return 0;
338         }
339     return -1;
340 }
341
342 static int parse_cqm( const char *str, uint8_t *cqm, int length )
343 {
344     int i = 0;
345     do {
346         int coef;
347         if( !sscanf( str, "%d", &coef ) || coef < 1 || coef > 255 )
348             return -1;
349         cqm[i++] = coef;
350     } while( i < length && (str = strchr( str, ',' )) && str++ );
351     return (i == length) ? 0 : -1;
352 }
353
354 /*****************************************************************************
355  * Parse:
356  *****************************************************************************/
357 static int  Parse( int argc, char **argv,
358                    x264_param_t *param, cli_opt_t *opt )
359 {
360     char *psz_filename = NULL;
361     x264_param_t defaults = *param;
362     char *psz;
363     int b_avis = 0;
364     int b_y4m = 0;
365     int b_thread_input = 0;
366
367     memset( opt, 0, sizeof(cli_opt_t) );
368
369     /* Default input file driver */
370     p_open_infile = open_file_yuv;
371     p_get_frame_total = get_frame_total_yuv;
372     p_read_frame = read_frame_yuv;
373     p_close_infile = close_file_yuv;
374
375     /* Default output file driver */
376     p_open_outfile = open_file_bsf;
377     p_set_outfile_param = set_param_bsf;
378     p_write_nalu = write_nalu_bsf;
379     p_set_eop = set_eop_bsf;
380     p_close_outfile = close_file_bsf;
381
382     /* Parse command line options */
383     opterr = 0; // no error message
384     for( ;; )
385     {
386         int b_error = 0;
387         int long_options_index;
388 #define OPT_QPMIN 256
389 #define OPT_QPMAX 257
390 #define OPT_QPSTEP 258
391 #define OPT_IPRATIO 260
392 #define OPT_PBRATIO 261
393 #define OPT_RATETOL 262
394 #define OPT_RCSTATS 264
395 #define OPT_RCEQ 265
396 #define OPT_QCOMP 266
397 #define OPT_NOPSNR 267
398 #define OPT_QUIET 268
399 #define OPT_SCENECUT 270
400 #define OPT_QBLUR 271
401 #define OPT_CPLXBLUR 272
402 #define OPT_FRAMES 273
403 #define OPT_FPS 274
404 #define OPT_DIRECT 275
405 #define OPT_LEVEL 276
406 #define OPT_NOBADAPT 277
407 #define OPT_BBIAS 278
408 #define OPT_BPYRAMID 279
409 #define OPT_CHROMA_QP 280
410 #define OPT_NO_CHROMA_ME 281
411 #define OPT_NO_CABAC 282
412 #define OPT_AUD 283
413 #define OPT_PROGRESS 284
414 #define OPT_ME 285
415 #define OPT_MERANGE 286
416 #define OPT_VBVMAXRATE 287
417 #define OPT_VBVBUFSIZE 288
418 #define OPT_VBVINIT 289
419 #define OPT_VISUALIZE 290
420 #define OPT_SEEK 291
421 #define OPT_ZONES 292
422 #define OPT_THREADS 293
423 #define OPT_CQM 294
424 #define OPT_CQM4 295
425 #define OPT_CQM4I 296
426 #define OPT_CQM4IY 297
427 #define OPT_CQM4IC 298
428 #define OPT_CQM4P 299
429 #define OPT_CQM4PY 300
430 #define OPT_CQM4PC 301
431 #define OPT_CQM8 302
432 #define OPT_CQM8I 303
433 #define OPT_CQM8P 304
434 #define OPT_CQMFILE 305
435 #define OPT_SAR 306
436 #define OPT_OVERSCAN 307
437 #define OPT_VIDFORMAT 308
438 #define OPT_FULLRANGE 309
439 #define OPT_COLOURPRIM 310
440 #define OPT_TRANSFER 311
441 #define OPT_COLOURMATRIX 312
442 #define OPT_CHROMALOC 313
443 #define OPT_MIXED_REFS 314
444 #define OPT_CRF 315
445 #define OPT_B_RDO 316
446 #define OPT_NO_FAST_PSKIP 317
447 #define OPT_BIME 318
448 #define OPT_NR 319
449 #define OPT_THREAD_INPUT 320
450
451         static struct option long_options[] =
452         {
453             { "help",    no_argument,       NULL, 'h' },
454             { "bitrate", required_argument, NULL, 'B' },
455             { "bframes", required_argument, NULL, 'b' },
456             { "no-b-adapt", no_argument,    NULL, OPT_NOBADAPT },
457             { "b-bias",  required_argument, NULL, OPT_BBIAS },
458             { "b-pyramid", no_argument,     NULL, OPT_BPYRAMID },
459             { "min-keyint",required_argument,NULL,'i' },
460             { "keyint",  required_argument, NULL, 'I' },
461             { "scenecut",required_argument, NULL, OPT_SCENECUT },
462             { "nf",      no_argument,       NULL, 'n' },
463             { "filter",  required_argument, NULL, 'f' },
464             { "no-cabac",no_argument,       NULL, OPT_NO_CABAC },
465             { "qp",      required_argument, NULL, 'q' },
466             { "qpmin",   required_argument, NULL, OPT_QPMIN },
467             { "qpmax",   required_argument, NULL, OPT_QPMAX },
468             { "qpstep",  required_argument, NULL, OPT_QPSTEP },
469             { "crf",     required_argument, NULL, OPT_CRF },
470             { "ref",     required_argument, NULL, 'r' },
471             { "no-asm",  no_argument,       NULL, 'C' },
472             { "sar",     required_argument, NULL, OPT_SAR },
473             { "fps",     required_argument, NULL, OPT_FPS },
474             { "frames",  required_argument, NULL, OPT_FRAMES },
475             { "seek",    required_argument, NULL, OPT_SEEK },
476             { "output",  required_argument, NULL, 'o' },
477             { "analyse", required_argument, NULL, 'A' },
478             { "direct",  required_argument, NULL, OPT_DIRECT },
479             { "weightb", no_argument,       NULL, 'w' },
480             { "me",      required_argument, NULL, OPT_ME },
481             { "merange", required_argument, NULL, OPT_MERANGE },
482             { "subme",   required_argument, NULL, 'm' },
483             { "b-rdo",   no_argument,       NULL, OPT_B_RDO },
484             { "mixed-refs", no_argument,    NULL, OPT_MIXED_REFS },
485             { "no-chroma-me", no_argument,  NULL, OPT_NO_CHROMA_ME },
486             { "bime",    no_argument,       NULL, OPT_BIME },
487             { "8x8dct",  no_argument,       NULL, '8' },
488             { "trellis", required_argument, NULL, 't' },
489             { "no-fast-pskip", no_argument, NULL, OPT_NO_FAST_PSKIP },
490             { "level",   required_argument, NULL, OPT_LEVEL },
491             { "ratetol", required_argument, NULL, OPT_RATETOL },
492             { "vbv-maxrate", required_argument, NULL, OPT_VBVMAXRATE },
493             { "vbv-bufsize", required_argument, NULL, OPT_VBVBUFSIZE },
494             { "vbv-init", required_argument,NULL,  OPT_VBVINIT },
495             { "ipratio", required_argument, NULL, OPT_IPRATIO },
496             { "pbratio", required_argument, NULL, OPT_PBRATIO },
497             { "chroma-qp-offset", required_argument, NULL, OPT_CHROMA_QP },
498             { "pass",    required_argument, NULL, 'p' },
499             { "stats",   required_argument, NULL, OPT_RCSTATS },
500             { "rceq",    required_argument, NULL, OPT_RCEQ },
501             { "qcomp",   required_argument, NULL, OPT_QCOMP },
502             { "qblur",   required_argument, NULL, OPT_QBLUR },
503             { "cplxblur",required_argument, NULL, OPT_CPLXBLUR },
504             { "zones",   required_argument, NULL, OPT_ZONES },
505             { "threads", required_argument, NULL, OPT_THREADS },
506             { "thread-input", no_argument,  NULL, OPT_THREAD_INPUT },
507             { "no-psnr", no_argument,       NULL, OPT_NOPSNR },
508             { "quiet",   no_argument,       NULL, OPT_QUIET },
509             { "verbose", no_argument,       NULL, 'v' },
510             { "progress",no_argument,       NULL, OPT_PROGRESS },
511             { "visualize",no_argument,      NULL, OPT_VISUALIZE },
512             { "aud",     no_argument,       NULL, OPT_AUD },
513             { "nr",      required_argument, NULL, OPT_NR },
514             { "cqm",     required_argument, NULL, OPT_CQM },
515             { "cqmfile", required_argument, NULL, OPT_CQMFILE },
516             { "cqm4",    required_argument, NULL, OPT_CQM4 },
517             { "cqm4i",   required_argument, NULL, OPT_CQM4I },
518             { "cqm4iy",  required_argument, NULL, OPT_CQM4IY },
519             { "cqm4ic",  required_argument, NULL, OPT_CQM4IC },
520             { "cqm4p",   required_argument, NULL, OPT_CQM4P },
521             { "cqm4py",  required_argument, NULL, OPT_CQM4PY },
522             { "cqm4pc",  required_argument, NULL, OPT_CQM4PC },
523             { "cqm8",    required_argument, NULL, OPT_CQM8 },
524             { "cqm8i",   required_argument, NULL, OPT_CQM8I },
525             { "cqm8p",   required_argument, NULL, OPT_CQM8P },
526             { "overscan", required_argument, NULL, OPT_OVERSCAN },
527             { "videoformat", required_argument, NULL, OPT_VIDFORMAT },
528             { "fullrange", required_argument, NULL, OPT_FULLRANGE },
529             { "colorprim", required_argument, NULL, OPT_COLOURPRIM },
530             { "transfer", required_argument, NULL, OPT_TRANSFER },
531             { "colormatrix", required_argument, NULL, OPT_COLOURMATRIX },
532             { "chromaloc", required_argument, NULL, OPT_CHROMALOC },
533             {0, 0, 0, 0}
534         };
535
536         int c;
537
538         c = getopt_long( argc, argv, "hi:I:b:r:cxB:q:f:o:A:m:p:t:vw8",
539                          long_options, &long_options_index);
540
541         if( c == -1 )
542         {
543             break;
544         }
545
546         switch( c )
547         {
548             case 'h':
549                 Help( &defaults );
550                 return -1;
551
552             case 0:
553                 break;
554             case 'B':
555                 param->rc.i_bitrate = atol( optarg );
556                 param->rc.b_cbr = 1;
557                 break;
558             case OPT_CRF:
559                 param->rc.i_rf_constant = atol( optarg );
560                 break;
561             case 'b':
562                 param->i_bframe = atol( optarg );
563                 break;
564             case OPT_NOBADAPT:
565                 param->b_bframe_adaptive = 0;
566                 break;
567             case OPT_BBIAS:
568                 param->i_bframe_bias = atol( optarg );
569                 break;
570             case OPT_BPYRAMID:
571                 param->b_bframe_pyramid = 1;
572                 break;
573             case 'i':
574                 param->i_keyint_min = atol( optarg );
575                 if( param->i_keyint_max < param->i_keyint_min )
576                     param->i_keyint_max = param->i_keyint_min;
577                 break;
578             case 'I':
579                 param->i_keyint_max = atol( optarg );
580                 if( param->i_keyint_min > param->i_keyint_max )
581                     param->i_keyint_min = param->i_keyint_max;
582                 break;
583             case OPT_SCENECUT:
584                 param->i_scenecut_threshold = atol( optarg );
585                 break;
586             case 'n':
587                 param->b_deblocking_filter = 0;
588                 break;
589             case 'f':
590             {
591                 char *p = strchr( optarg, ':' );
592                 if( !p ) p = strchr( optarg, ',' );
593                 param->i_deblocking_filter_alphac0 = atoi( optarg );
594                 param->i_deblocking_filter_beta = p ? atoi( p+1 ) : param->i_deblocking_filter_alphac0;
595                 break;
596             }
597             case 'q':
598                 param->rc.i_qp_constant = atoi( optarg );
599                 break;
600             case OPT_QPMIN:
601                 param->rc.i_qp_min = atoi( optarg );
602                 break;
603             case OPT_QPMAX:
604                 param->rc.i_qp_max = atoi( optarg );
605                 break;
606             case OPT_QPSTEP:
607                 param->rc.i_qp_step = atoi( optarg );
608                 break;
609             case 'r':
610                 param->i_frame_reference = atoi( optarg );
611                 break;
612             case OPT_NO_CABAC:
613                 param->b_cabac = 0;
614                 break;
615             case 'x':
616                 opt->b_decompress = 1;
617                 break;
618             case 'C':
619                 param->cpu = 0;
620                 break;
621             case OPT_FRAMES:
622                 param->i_frame_total = atoi( optarg );
623                 break;
624             case OPT_SEEK:
625                 opt->i_seek = atoi( optarg );
626                 break;
627             case 'o':
628                 if( !strncasecmp(optarg + strlen(optarg) - 4, ".mp4", 4) )
629                 {
630 #ifdef MP4_OUTPUT
631                     p_open_outfile = open_file_mp4;
632                     p_write_nalu = write_nalu_mp4;
633                     p_set_outfile_param = set_param_mp4;
634                     p_set_eop = set_eop_mp4;
635                     p_close_outfile = close_file_mp4;
636 #else
637                     fprintf( stderr, "not compiled with MP4 output support\n" );
638                     return -1;
639 #endif
640                 }
641                 else if( !strncasecmp(optarg + strlen(optarg) - 4, ".mkv", 4) )
642                 {
643                     p_open_outfile = open_file_mkv;
644                     p_write_nalu = write_nalu_mkv;
645                     p_set_outfile_param = set_param_mkv;
646                     p_set_eop = set_eop_mkv;
647                     p_close_outfile = close_file_mkv;
648                 }
649                 if( !strcmp(optarg, "-") )
650                     opt->hout = stdout;
651                 else if( p_open_outfile( optarg, &opt->hout ) )
652                 {
653                     fprintf( stderr, "cannot open output file `%s'\n", optarg );
654                     return -1;
655                 }
656                 break;
657             case OPT_SAR:
658             {
659                 char *p = strchr( optarg, ':' );
660                 if( !p ) p = strchr( optarg, '/' );
661                 if( p )
662                 {
663                     param->vui.i_sar_width = atoi( optarg );
664                     param->vui.i_sar_height = atoi( p + 1 );
665                 }
666                 break;
667             }
668             case OPT_FPS:
669             {
670                 float fps;
671                 if( sscanf( optarg, "%d/%d", &param->i_fps_num, &param->i_fps_den ) == 2 )
672                     ;
673                 else if( sscanf( optarg, "%f", &fps ) )
674                 {
675                     param->i_fps_num = (int)(fps * 1000 + .5);
676                     param->i_fps_den = 1000;
677                 }
678                 else
679                 {
680                     fprintf( stderr, "bad fps `%s'\n", optarg );
681                     return -1;
682                 }
683                 break;
684             }
685             case 'A':
686                 param->analyse.inter = 0;
687                 if( strstr( optarg, "none" ) )  param->analyse.inter =  0;
688                 if( strstr( optarg, "all" ) )   param->analyse.inter = ~0;
689
690                 if( strstr( optarg, "i4x4" ) )  param->analyse.inter |= X264_ANALYSE_I4x4;
691                 if( strstr( optarg, "i8x8" ) )  param->analyse.inter |= X264_ANALYSE_I8x8;
692                 if( strstr( optarg, "p8x8" ) )  param->analyse.inter |= X264_ANALYSE_PSUB16x16;
693                 if( strstr( optarg, "p4x4" ) )  param->analyse.inter |= X264_ANALYSE_PSUB8x8;
694                 if( strstr( optarg, "b8x8" ) )  param->analyse.inter |= X264_ANALYSE_BSUB16x16;
695                 break;
696             case OPT_DIRECT:
697                 b_error |= parse_enum( optarg, x264_direct_pred_names, &param->analyse.i_direct_mv_pred );
698                 break;
699             case 'w':
700                 param->analyse.b_weighted_bipred = 1;
701                 break;
702             case OPT_ME:
703                 b_error |= parse_enum( optarg, x264_motion_est_names, &param->analyse.i_me_method );
704                 break;
705             case OPT_MERANGE:
706                 param->analyse.i_me_range = atoi(optarg);
707                 break;
708             case 'm':
709                 param->analyse.i_subpel_refine = atoi(optarg);
710                 break;
711             case OPT_B_RDO:
712                 param->analyse.b_bframe_rdo = 1;
713                 break;
714             case OPT_MIXED_REFS:
715                 param->analyse.b_mixed_references = 1;
716                 break;
717             case OPT_NO_CHROMA_ME:
718                 param->analyse.b_chroma_me = 0;
719                 break;
720             case OPT_BIME:
721                 param->analyse.b_bidir_me = 1;
722                 break;
723             case '8':
724                 param->analyse.b_transform_8x8 = 1;
725                 break;
726             case 't':
727                 param->analyse.i_trellis = atoi(optarg);
728                 break;
729             case OPT_NO_FAST_PSKIP:
730                 param->analyse.b_fast_pskip = 0;
731                 break;
732             case OPT_LEVEL:
733                 if( atof(optarg) < 6 )
734                     param->i_level_idc = (int)(10*atof(optarg)+.5);
735                 else
736                     param->i_level_idc = atoi(optarg);
737                 break;
738             case OPT_RATETOL:
739                 param->rc.f_rate_tolerance = !strncmp("inf", optarg, 3) ? 1e9 : atof(optarg);
740                 break;
741             case OPT_VBVMAXRATE:
742                 param->rc.i_vbv_max_bitrate = atoi( optarg );
743                 break;
744             case OPT_VBVBUFSIZE:
745                 param->rc.i_vbv_buffer_size = atoi( optarg );
746                 break;
747             case OPT_VBVINIT:
748                 param->rc.f_vbv_buffer_init = atof(optarg);
749                 break;
750             case OPT_IPRATIO:
751                 param->rc.f_ip_factor = atof(optarg);
752                 break;
753             case OPT_PBRATIO:
754                 param->rc.f_pb_factor = atof(optarg);
755                 break;
756             case OPT_CHROMA_QP:
757                 param->analyse.i_chroma_qp_offset = atoi(optarg);
758                 break;
759             case 'p':
760             {
761                 int i_pass = atoi(optarg);
762                 if( i_pass == 1 )
763                     param->rc.b_stat_write = 1;
764                 else if( i_pass == 2 )
765                     param->rc.b_stat_read = 1;
766                 else if( i_pass > 2 )
767                     param->rc.b_stat_read =
768                     param->rc.b_stat_write = 1;
769                 break;
770             }
771             case OPT_RCSTATS:
772                 param->rc.psz_stat_in = optarg;
773                 param->rc.psz_stat_out = optarg;
774                 break;
775             case OPT_RCEQ:
776                 param->rc.psz_rc_eq = optarg;
777                break;
778             case OPT_QCOMP:
779                 param->rc.f_qcompress = atof(optarg);
780                 break;
781             case OPT_QBLUR:
782                 param->rc.f_qblur = atof(optarg);
783                 break;
784             case OPT_CPLXBLUR:
785                 param->rc.f_complexity_blur = atof(optarg);
786                 break;
787             case OPT_ZONES:
788                 param->rc.psz_zones = optarg;
789                 break;
790             case OPT_THREADS:
791                 param->i_threads = atoi(optarg);
792                 break;
793             case OPT_THREAD_INPUT:
794                 b_thread_input = 1;
795                 break;
796             case OPT_NOPSNR:
797                 param->analyse.b_psnr = 0;
798                 break;
799             case OPT_QUIET:
800                 param->i_log_level = X264_LOG_NONE;
801                 break;
802             case 'v':
803                 param->i_log_level = X264_LOG_DEBUG;
804                 break;
805             case OPT_AUD:
806                 param->b_aud = 1;
807                 break;
808             case OPT_PROGRESS:
809                 opt->b_progress = 1;
810                 break;
811             case OPT_VISUALIZE:
812 #ifdef VISUALIZE
813                 param->b_visualize = 1;
814                 b_exit_on_ctrl_c = 1;
815 #else
816                 fprintf( stderr, "not compiled with visualization support\n" );
817 #endif
818                 break;
819             case OPT_NR:
820                 param->analyse.i_noise_reduction = atoi(optarg);
821                 break;
822             case OPT_CQM:
823                 if( strstr( optarg, "flat" ) )
824                     param->i_cqm_preset = X264_CQM_FLAT;
825                 else if( strstr( optarg, "jvt" ) )
826                     param->i_cqm_preset = X264_CQM_JVT;
827                 else
828                 {
829                     fprintf( stderr, "bad CQM preset `%s'\n", optarg );
830                     return -1;
831                 }
832                 break;
833             case OPT_CQMFILE:
834                 param->psz_cqm_file = optarg;
835                 break;
836             case OPT_CQM4:
837                 param->i_cqm_preset = X264_CQM_CUSTOM;
838                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
839                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
840                 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
841                 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
842                 break;
843             case OPT_CQM8:
844                 param->i_cqm_preset = X264_CQM_CUSTOM;
845                 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
846                 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
847                 break;
848             case OPT_CQM4I:
849                 param->i_cqm_preset = X264_CQM_CUSTOM;
850                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
851                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
852                 break;
853             case OPT_CQM4P:
854                 param->i_cqm_preset = X264_CQM_CUSTOM;
855                 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
856                 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
857                 break;
858             case OPT_CQM4IY:
859                 param->i_cqm_preset = X264_CQM_CUSTOM;
860                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
861                 break;
862             case OPT_CQM4IC:
863                 param->i_cqm_preset = X264_CQM_CUSTOM;
864                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
865                 break;
866             case OPT_CQM4PY:
867                 param->i_cqm_preset = X264_CQM_CUSTOM;
868                 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
869                 break;
870             case OPT_CQM4PC:
871                 param->i_cqm_preset = X264_CQM_CUSTOM;
872                 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
873                 break;
874             case OPT_CQM8I:
875                 param->i_cqm_preset = X264_CQM_CUSTOM;
876                 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
877                 break;
878             case OPT_CQM8P:
879                 param->i_cqm_preset = X264_CQM_CUSTOM;
880                 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
881                 break;
882             case OPT_OVERSCAN:
883                 b_error |= parse_enum( optarg, overscan_str, &param->vui.i_overscan );
884                 break;
885             case OPT_VIDFORMAT:
886                 b_error |= parse_enum( optarg, vidformat_str, &param->vui.i_vidformat );
887                 break;
888             case OPT_FULLRANGE:
889                 b_error |= parse_enum( optarg, fullrange_str, &param->vui.b_fullrange );
890                 break;
891             case OPT_COLOURPRIM:
892                 b_error |= parse_enum( optarg, colorprim_str, &param->vui.i_colorprim );
893                 break;
894             case OPT_TRANSFER:
895                 b_error |= parse_enum( optarg, transfer_str, &param->vui.i_transfer );
896                 break;
897             case OPT_COLOURMATRIX:
898                 b_error |= parse_enum( optarg, colmatrix_str, &param->vui.i_colmatrix );
899                 break;
900             case OPT_CHROMALOC:
901                 param->vui.i_chroma_loc = atoi( optarg );
902                 b_error = ( param->vui.i_chroma_loc < 0 || param->vui.i_chroma_loc > 5 );
903                 break;
904             default:
905                 fprintf( stderr, "unknown option (%c)\n", optopt );
906                 return -1;
907         }
908
909         if( b_error )
910         {
911             fprintf( stderr, "bad argument: %s %s\n", argv[optind-2], optarg );
912             return -1;
913         }
914     }
915
916     /* Get the file name */
917     if( optind > argc - 1 || !opt->hout )
918     {
919         Help( &defaults );
920         return -1;
921     }
922     psz_filename = argv[optind++];
923
924     if( !opt->b_decompress )
925     {
926         if( optind > argc - 1 )
927         {
928             /* try to parse the file name */
929             for( psz = psz_filename; *psz; psz++ )
930             {
931                 if( *psz >= '0' && *psz <= '9'
932                     && sscanf( psz, "%ux%u", &param->i_width, &param->i_height ) == 2 )
933                 {
934                     if( param->i_log_level >= X264_LOG_INFO )
935                         fprintf( stderr, "x264 [info]: file name gives %dx%d\n", param->i_width, param->i_height );
936                     break;
937                 }
938             }
939         }
940         else
941         {
942             sscanf( argv[optind++], "%ux%u", &param->i_width, &param->i_height );
943         }
944         
945         /* check avis input */
946         psz = psz_filename + strlen(psz_filename) - 1;
947         while( psz > psz_filename && *psz != '.' )
948             psz--;
949
950         if( !strncasecmp( psz, ".avi", 4 ) || !strncasecmp( psz, ".avs", 4 ) )
951             b_avis = 1;
952         if( !strncasecmp( psz, ".y4m", 4 ) )
953             b_y4m = 1;
954         if( !(b_avis || b_y4m) && ( !param->i_width || !param->i_height ) )
955         {
956             Help( &defaults );
957             return -1;
958         }
959     }
960
961     /* open the input */
962     {
963         if( b_avis )
964         {
965 #ifdef AVIS_INPUT
966             p_open_infile = open_file_avis;
967             p_get_frame_total = get_frame_total_avis;
968             p_read_frame = read_frame_avis;
969             p_close_infile = close_file_avis;
970 #else
971             fprintf( stderr, "not compiled with AVIS input support\n" );
972             return -1;
973 #endif
974         }
975         if ( b_y4m )
976         {
977             p_open_infile = open_file_y4m;
978             p_get_frame_total = get_frame_total_y4m;
979             p_read_frame = read_frame_y4m;
980             p_close_infile = close_file_y4m;
981         }
982
983         if( p_open_infile( psz_filename, &opt->hin, param ) )
984         {
985             fprintf( stderr, "could not open input file '%s'\n", psz_filename );
986             return -1;
987         }
988     }
989
990 #ifdef HAVE_PTHREAD
991     if( b_thread_input || param->i_threads > 1 )
992     {
993         if( open_file_thread( NULL, &opt->hin, param ) )
994         {
995             fprintf( stderr, "threaded input failed\n" );
996         }
997         else
998         {
999             p_open_infile = open_file_thread;
1000             p_get_frame_total = get_frame_total_thread;
1001             p_read_frame = read_frame_thread;
1002             p_close_infile = close_file_thread;
1003         }
1004     }
1005 #endif
1006
1007     return 0;
1008 }
1009
1010 /*****************************************************************************
1011  * Decode:
1012  *****************************************************************************/
1013
1014 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
1015 {
1016     x264_picture_t pic_out;
1017     x264_nal_t *nal;
1018     int i_nal, i;
1019     int i_file = 0;
1020
1021     /* Do not force any parameters */
1022     if( pic )
1023     {
1024         pic->i_type = X264_TYPE_AUTO;
1025         pic->i_qpplus1 = 0;
1026     }
1027     if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
1028     {
1029         fprintf( stderr, "x264_encoder_encode failed\n" );
1030     }
1031
1032     for( i = 0; i < i_nal; i++ )
1033     {
1034         int i_size;
1035         int i_data;
1036
1037         i_data = DATA_MAX;
1038         if( ( i_size = x264_nal_encode( data, &i_data, 1, &nal[i] ) ) > 0 )
1039         {
1040             i_file += p_write_nalu( hout, data, i_size );
1041         }
1042         else if( i_size < 0 )
1043         {
1044             fprintf( stderr, "need to increase buffer size (size=%d)\n", -i_size );
1045         }
1046     }
1047     if (i_nal)
1048         p_set_eop( hout, &pic_out );
1049
1050     return i_file;
1051 }
1052
1053 /*****************************************************************************
1054  * Encode:
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_progress;
1066
1067     i_frame_total = p_get_frame_total( opt->hin );
1068     i_frame_total -= opt->i_seek;
1069     if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
1070         && param->i_frame_total > 0 )
1071         i_frame_total = param->i_frame_total;
1072     param->i_frame_total = i_frame_total;
1073
1074     if( ( h = x264_encoder_open( param ) ) == NULL )
1075     {
1076         fprintf( stderr, "x264_encoder_open failed\n" );
1077         p_close_infile( opt->hin );
1078         p_close_outfile( opt->hout );
1079         return -1;
1080     }
1081
1082     if( p_set_outfile_param( opt->hout, param ) )
1083     {
1084         fprintf( stderr, "can't set outfile param\n" );
1085         p_close_infile( opt->hin );
1086         p_close_outfile( opt->hout );
1087         return -1;
1088     }
1089
1090     /* Create a new pic */
1091     x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height );
1092
1093     i_start = x264_mdate();
1094
1095     /* Encode frames */
1096     for( i_frame = 0, i_file = 0, i_progress = 0;
1097          b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1098     {
1099         if( p_read_frame( &pic, opt->hin, i_frame + opt->i_seek ) )
1100             break;
1101
1102         pic.i_pts = (int64_t)i_frame * param->i_fps_den;
1103
1104         i_file += Encode_frame( h, opt->hout, &pic );
1105
1106         i_frame++;
1107
1108         /* update status line (up to 1000 times per input file) */
1109         if( opt->b_progress && param->i_log_level < X264_LOG_DEBUG && 
1110             ( i_frame_total ? i_frame * 1000 / i_frame_total > i_progress
1111                             : i_frame % 10 == 0 ) )
1112         {
1113             int64_t i_elapsed = x264_mdate() - i_start;
1114             double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1115             if( i_frame_total )
1116             {
1117                 int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1118                 i_progress = i_frame * 1000 / i_frame_total;
1119                 fprintf( stderr, "encoded frames: %d/%d (%.1f%%), %.2f fps, eta %d:%02d:%02d  \r",
1120                          i_frame, i_frame_total, (float)i_progress / 10, fps,
1121                          eta/3600, (eta/60)%60, eta%60 );
1122             }
1123             else
1124                 fprintf( stderr, "encoded frames: %d, %.2f fps   \r", i_frame, fps );
1125             fflush( stderr ); // needed in windows
1126         }
1127     }
1128     /* Flush delayed B-frames */
1129     do {
1130         i_file +=
1131         i_frame_size = Encode_frame( h, opt->hout, NULL );
1132     } while( i_frame_size );
1133
1134     i_end = x264_mdate();
1135     x264_picture_clean( &pic );
1136     x264_encoder_close( h );
1137     fprintf( stderr, "\n" );
1138
1139     if( b_ctrl_c )
1140         fprintf( stderr, "aborted at input frame %d\n", opt->i_seek + i_frame );
1141
1142     p_close_infile( opt->hin );
1143     p_close_outfile( opt->hout );
1144
1145     if( i_frame > 0 )
1146     {
1147         double fps = (double)i_frame * (double)1000000 /
1148                      (double)( i_end - i_start );
1149
1150         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame, fps,
1151                  (double) i_file * 8 * param->i_fps_num /
1152                  ( (double) param->i_fps_den * i_frame * 1000 ) );
1153     }
1154
1155     return 0;
1156 }