]> git.sesse.net Git - x264/blob - x264.c
e5aacd8fbb06a8e74168927255d34475a0fc5d22
[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 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27
28 #include <math.h>
29
30 #include <signal.h>
31 #define _GNU_SOURCE
32 #include <getopt.h>
33
34 #ifdef _MSC_VER
35 #include <io.h>     /* _setmode() */
36 #include <fcntl.h>  /* _O_BINARY */
37 #endif
38
39 #ifdef AVIS_INPUT
40 #include <windows.h>
41 #include <vfw.h>
42 #endif
43
44 #ifdef MP4_OUTPUT
45 #include <gpac/isomedia.h>
46 #endif
47
48
49 #include "common/common.h"
50 #include "x264.h"
51
52 #ifndef _MSC_VER
53 #include "config.h"
54 #endif
55
56 #include "matroska.h"
57
58 #define DATA_MAX 3000000
59 uint8_t data[DATA_MAX];
60
61 typedef void *hnd_t;
62
63 /* Ctrl-C handler */
64 static int     b_ctrl_c = 0;
65 static int     b_exit_on_ctrl_c = 0;
66 static void    SigIntHandler( int a )
67 {
68     if( b_exit_on_ctrl_c )
69         exit(0);
70     b_ctrl_c = 1;
71 }
72
73 typedef struct {
74     int b_decompress;
75     int b_progress;
76     int i_seek;
77     hnd_t hin;
78     hnd_t hout;
79 } cli_opt_t;
80
81 /* input file operation function pointers */
82 static int (*p_open_infile)( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
83 static int (*p_get_frame_total)( hnd_t handle, int i_width, int i_height );
84 static int (*p_read_frame)( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
85 static int (*p_close_infile)( hnd_t handle );
86
87 static int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
88 static int get_frame_total_yuv( hnd_t handle, int i_width, int i_height );
89 static int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
90 static int close_file_yuv( hnd_t handle );
91
92 #ifdef AVIS_INPUT
93 static int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
94 static int get_frame_total_avis( hnd_t handle, int i_width, int i_height );
95 static int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
96 static int close_file_avis( hnd_t handle );
97 #endif
98
99 /* output file operation function pointers */
100 static int (*p_open_outfile)( char *psz_filename, hnd_t *p_handle );
101 static int (*p_set_outfile_param)( hnd_t handle, x264_param_t *p_param );
102 static int (*p_write_nalu)( hnd_t handle, uint8_t *p_nal, int i_size );
103 static int (*p_set_eop)( hnd_t handle, x264_picture_t *p_picture );
104 static int (*p_close_outfile)( hnd_t handle );
105
106 static int open_file_bsf( char *psz_filename, hnd_t *p_handle );
107 static int set_param_bsf( hnd_t handle, x264_param_t *p_param );
108 static int write_nalu_bsf( hnd_t handle, uint8_t *p_nal, int i_size );
109 static int set_eop_bsf( hnd_t handle,  x264_picture_t *p_picture );
110 static int close_file_bsf( hnd_t handle );
111
112 #ifdef MP4_OUTPUT
113 static int open_file_mp4( char *psz_filename, hnd_t *p_handle );
114 static int set_param_mp4( hnd_t handle, x264_param_t *p_param );
115 static int write_nalu_mp4( hnd_t handle, uint8_t *p_nal, int i_size );
116 static int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture );
117 static int close_file_mp4( hnd_t handle );
118 #endif
119
120 static int open_file_mkv( char *psz_filename, hnd_t *p_handle );
121 static int set_param_mkv( hnd_t handle, x264_param_t *p_param );
122 static int write_nalu_mkv( hnd_t handle, uint8_t *p_nal, int i_size );
123 static int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture );
124 static int close_file_mkv( hnd_t handle );
125
126 static void Help( x264_param_t *defaults );
127 static int  Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
128 static int  Encode( x264_param_t *param, cli_opt_t *opt );
129
130
131 /****************************************************************************
132  * main:
133  ****************************************************************************/
134 int main( int argc, char **argv )
135 {
136     x264_param_t param;
137     cli_opt_t opt;
138
139 #ifdef _MSC_VER
140     _setmode(_fileno(stdin), _O_BINARY);    /* thanks to Marcos Morais <morais at dee.ufcg.edu.br> */
141     _setmode(_fileno(stdout), _O_BINARY);
142 #endif
143
144     x264_param_default( &param );
145
146     /* Parse command line */
147     if( Parse( argc, argv, &param, &opt ) < 0 )
148         return -1;
149
150     /* Control-C handler */
151     signal( SIGINT, SigIntHandler );
152
153     return Encode( &param, &opt );
154 }
155
156 static const char * const overscan_str[] = { "undef", "show", "crop", NULL };
157 static const char * const vidformat_str[] = { "component", "pal", "ntsc", "secam", "mac", "undef", NULL };
158 static const char * const fullrange_str[] = { "off", "on", NULL };
159 static const char * const colorprim_str[] = { "", "bt709", "undef", "", "bt470m", "bt470bg", "smpte170m", "smpte240m", "film", NULL };
160 static const char * const transfer_str[] = { "", "bt709", "undef", "", "bt470m", "bt470bg", "smpte170m", "smpte240m", "linear", "log100", "log316", NULL };
161 static const char * const colmatrix_str[] = { "GBR", "bt709", "undef", "", "fcc", "bt470bg", "smpte170m", "smpte240m", "YCgCo", NULL };
162
163 static char const *strtable_lookup( const char * const table[], int index )
164 {
165     int i = 0; while( table[i] ) i++;
166     return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
167 }
168
169 /*****************************************************************************
170  * Help:
171  *****************************************************************************/
172 static void Help( x264_param_t *defaults )
173 {
174     fprintf( stderr,
175              "x264 core:%d%s\n"
176              "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
177              "\n"
178              "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
179              "  or AVI or Avisynth if compiled with AVIS support (%s).\n"
180              "Outfile type is selected by filename:\n"
181              " .264 -> Raw bytestream\n"
182              " .mkv -> Matroska\n"
183              " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
184              "\n"
185              "Options:\n"
186              "\n"
187              "  -h, --help                  Print this help\n"
188              "\n"
189              "Frame-type options:\n"
190              "\n"
191              "  -I, --keyint <integer>      Maximum GOP size [%d]\n"
192              "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n"
193              "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n"
194              "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n"
195              "      --no-b-adapt            Disable adaptive B-frame decision\n"
196              "      --b-bias <integer>      Influences how often B-frames are used [%d]\n"
197              "      --b-pyramid             Keep some B-frames as references\n"
198              "\n"
199              "      --no-cabac              Disable CABAC\n"
200              "  -r, --ref <integer>         Number of reference frames [%d]\n"
201              "      --nf                    Disable loop filter\n"
202              "  -f, --filter <alpha:beta>   Loop filter AlphaC0 and Beta parameters [%d:%d]\n"
203              "\n"
204              "Ratecontrol:\n"
205              "\n"
206              "  -q, --qp <integer>          Set QP (0=lossless) [%d]\n"
207              "  -B, --bitrate <integer>     Set bitrate\n"
208              "      --crf <integer>         Quality-based VBR (nominal QP)\n"
209              "      --qpmin <integer>       Set min QP [%d]\n"
210              "      --qpmax <integer>       Set max QP [%d]\n"
211              "      --qpstep <integer>      Set max QP step [%d]\n"
212              "      --ratetol <float>       Allowed variance of average bitrate [%.1f]\n"
213              "      --vbv-maxrate <integer> Max local bitrate [%d]\n"
214              "      --vbv-bufsize <integer> Size of VBV buffer [%d]\n"
215              "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n"
216              "\n"
217              "      --ipratio <float>       QP factor between I and P [%.2f]\n"
218              "      --pbratio <float>       QP factor between P and B [%.2f]\n"
219              "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n"
220              "\n"
221              "  -p, --pass <1|2|3>          Enable multipass ratecontrol:\n"
222              "                                  - 1: First pass, creates stats file\n"
223              "                                  - 2: Last pass, does not overwrite stats file\n"
224              "                                  - 3: Nth pass, overwrites stats file\n"
225              "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n"
226              "      --rceq <string>         Ratecontrol equation [\"%s\"]\n"
227              "      --qcomp <float>         QP curve compression: 0.0 => CBR, 1.0 => CQP [%.2f]\n"
228              "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n"
229              "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n"
230              "\n"
231              "      --zones <zone0>/<zone1>/...\n"
232              "                              Tweak the bitrate of some regions of the video\n"
233              "                              Each zone is of the form\n"
234              "                                  <start frame>,<end frame>,<option>\n"
235              "                                  where <option> is either\n"
236              "                                      q=<integer> (force QP)\n"
237              "                                  or  b=<float> (bitrate multiplier)\n"
238              "\n"
239              "Analysis:\n"
240              "\n"
241              "  -A, --analyse <string>      Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
242              "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
243              "                                  - none, all\n"
244              "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n"
245              "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
246              "                                  - none, spatial, temporal\n"
247              "  -w, --weightb               Weighted prediction for B-frames\n"
248              "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n"
249              "                                  - dia: diamond search, radius 1 (fast)\n"
250              "                                  - hex: hexagonal search, radius 2\n"
251              "                                  - umh: uneven multi-hexagon search\n"
252              "                                  - esa: exhaustive search (slow)\n"
253              "      --merange <integer>     Maximum motion vector search range [%d]\n"
254              "  -m, --subme <integer>       Subpixel motion estimation and partition\n"
255              "                                  decision quality: 1=fast, 6=best. [%d]\n"
256              "      --mixed-refs            Decide references on a per partition basis\n"
257              "      --no-chroma-me          Ignore chroma in motion estimation\n"
258              "  -8, --8x8dct                Adaptive spatial transform size\n"
259              "\n"
260              "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
261              "                                  - jvt, flat\n"
262              "      --cqmfile <string>      Read quant matrices from a JM-compatible file\n"
263              "                                  Overrides any other --cqm* options.\n"
264              "      --cqm4 <list>           Set all 4x4 quant matrices\n"
265              "                                  Takes a comma-separated list of 16 integers.\n"
266              "      --cqm8 <list>           Set all 8x8 quant matrices\n"
267              "                                  Takes a comma-separated list of 64 integers.\n"
268              "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
269              "                              Set both luma and chroma quant matrices\n"
270              "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
271              "                              Set individual quant matrices\n"
272              "\n"
273              "Video Usability Info (Annex E):\n"
274              "The VUI settings are not used by the encoder but are merely suggestions to\n"
275              "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n"
276              "\n"
277              "      --sar width:height      Specify Sample Aspect Ratio\n"
278              "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
279              "                                  - undef, show, crop\n"
280              "      --videoformat <string>  Specify video format [\"%s\"]\n"
281              "                                  - component, pal, ntsc, secam, mac, undef\n"
282              "      --fullrange <string>    Specify full range samples setting [\"%s\"]\n"
283              "                                  - off, on\n"
284              "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
285              "                                  - undef, bt709, bt470m, bt470bg\n"
286              "                                    smpte170m, smpte240m, film\n"
287              "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
288              "                                  - undef, bt709, bt470m, bt470bg, linear,\n"
289              "                                    log100, log316, smpte170m, smpte240m\n"
290              "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
291              "                                  - undef, bt709, fcc, bt470bg\n"
292              "                                    smpte170m, smpte240m, GBR, YCgCo\n"
293              "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n"
294              "\n"
295              "Input/Output:\n"
296              "\n"
297              "      --level <integer>       Specify level (as defined by Annex A)\n"
298              "      --fps <float|rational>  Specify framerate\n"
299              "      --seek <integer>        First frame to encode\n"
300              "      --frames <integer>      Maximum number of frames to encode\n"
301              "  -o, --output                Specify output file\n"
302              "\n"
303              "      --threads <integer>     Parallel encoding (uses slices)\n"
304              "      --no-asm                Disable all CPU optimizations\n"
305              "      --no-psnr               Disable PSNR computation\n"
306              "      --quiet                 Quiet Mode\n"
307              "  -v, --verbose               Print stats for each frame\n"
308              "      --progress              Show a progress indicator while encoding\n"
309              "      --visualize             Show MB types overlayed on the encoded video\n"
310              "      --aud                   Use access unit delimiters\n"
311              "\n",
312             X264_BUILD, X264_VERSION,
313 #ifdef AVIS_INPUT
314             "yes",
315 #else
316             "no",
317 #endif
318 #ifdef MP4_OUTPUT
319             "yes",
320 #else
321             "no",
322 #endif
323             defaults->i_keyint_max,
324             defaults->i_keyint_min,
325             defaults->i_scenecut_threshold,
326             defaults->i_bframe,
327             defaults->i_bframe_bias,
328             defaults->i_frame_reference,
329             defaults->i_deblocking_filter_alphac0,
330             defaults->i_deblocking_filter_beta,
331             defaults->rc.i_qp_constant,
332             defaults->rc.i_qp_min,
333             defaults->rc.i_qp_max,
334             defaults->rc.i_qp_step,
335             defaults->rc.f_rate_tolerance,
336             defaults->rc.i_vbv_max_bitrate,
337             defaults->rc.i_vbv_buffer_size,
338             defaults->rc.f_vbv_buffer_init,
339             defaults->rc.f_ip_factor,
340             defaults->rc.f_pb_factor,
341             defaults->analyse.i_chroma_qp_offset,
342             defaults->rc.psz_stat_out,
343             defaults->rc.psz_rc_eq,
344             defaults->rc.f_qcompress,
345             defaults->rc.f_complexity_blur,
346             defaults->rc.f_qblur,
347             strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ),
348             strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ),
349             defaults->analyse.i_me_range,
350             defaults->analyse.i_subpel_refine,
351             strtable_lookup( overscan_str, defaults->vui.i_overscan ),
352             strtable_lookup( vidformat_str, defaults->vui.i_vidformat ),
353             strtable_lookup( fullrange_str, defaults->vui.b_fullrange ),
354             strtable_lookup( colorprim_str, defaults->vui.i_colorprim ),
355             strtable_lookup( transfer_str, defaults->vui.i_transfer ),
356             strtable_lookup( colmatrix_str, defaults->vui.i_colmatrix ),
357             defaults->vui.i_chroma_loc
358            );
359 }
360
361 static int parse_enum( const char *arg, const char * const *names, int *dst )
362 {
363     int i;
364     for( i = 0; names[i]; i++ )
365         if( !strcmp( arg, names[i] ) )
366         {
367             *dst = i;
368             return 0;
369         }
370     return -1;
371 }
372
373 static int parse_cqm( const char *str, uint8_t *cqm, int length )
374 {
375     int i = 0;
376     do {
377         int coef;
378         if( !sscanf( str, "%d", &coef ) || coef < 1 || coef > 255 )
379             return -1;
380         cqm[i++] = coef;
381     } while( i < length && (str = strchr( str, ',' )) && str++ );
382     return (i == length) ? 0 : -1;
383 }
384
385 /*****************************************************************************
386  * Parse:
387  *****************************************************************************/
388 static int  Parse( int argc, char **argv,
389                    x264_param_t *param, cli_opt_t *opt )
390 {
391     char *psz_filename = NULL;
392     x264_param_t defaults = *param;
393     char *psz;
394     char b_avis = 0;
395
396     memset( opt, 0, sizeof(cli_opt_t) );
397
398     /* Default input file driver */
399     p_open_infile = open_file_yuv;
400     p_get_frame_total = get_frame_total_yuv;
401     p_read_frame = read_frame_yuv;
402     p_close_infile = close_file_yuv;
403
404     /* Default output file driver */
405     p_open_outfile = open_file_bsf;
406     p_set_outfile_param = set_param_bsf;
407     p_write_nalu = write_nalu_bsf;
408     p_set_eop = set_eop_bsf;
409     p_close_outfile = close_file_bsf;
410
411     /* Parse command line options */
412     opterr = 0; // no error message
413     for( ;; )
414     {
415         int b_error = 0;
416         int long_options_index;
417 #define OPT_QPMIN 256
418 #define OPT_QPMAX 257
419 #define OPT_QPSTEP 258
420 #define OPT_IPRATIO 260
421 #define OPT_PBRATIO 261
422 #define OPT_RATETOL 262
423 #define OPT_RCSTATS 264
424 #define OPT_RCEQ 265
425 #define OPT_QCOMP 266
426 #define OPT_NOPSNR 267
427 #define OPT_QUIET 268
428 #define OPT_SCENECUT 270
429 #define OPT_QBLUR 271
430 #define OPT_CPLXBLUR 272
431 #define OPT_FRAMES 273
432 #define OPT_FPS 274
433 #define OPT_DIRECT 275
434 #define OPT_LEVEL 276
435 #define OPT_NOBADAPT 277
436 #define OPT_BBIAS 278
437 #define OPT_BPYRAMID 279
438 #define OPT_CHROMA_QP 280
439 #define OPT_NO_CHROMA_ME 281
440 #define OPT_NO_CABAC 282
441 #define OPT_AUD 283
442 #define OPT_PROGRESS 284
443 #define OPT_ME 285
444 #define OPT_MERANGE 286
445 #define OPT_VBVMAXRATE 287
446 #define OPT_VBVBUFSIZE 288
447 #define OPT_VBVINIT 289
448 #define OPT_VISUALIZE 290
449 #define OPT_SEEK 291
450 #define OPT_ZONES 292
451 #define OPT_THREADS 293
452 #define OPT_CQM 294
453 #define OPT_CQM4 295
454 #define OPT_CQM4I 296
455 #define OPT_CQM4IY 297
456 #define OPT_CQM4IC 298
457 #define OPT_CQM4P 299
458 #define OPT_CQM4PY 300
459 #define OPT_CQM4PC 301
460 #define OPT_CQM8 302
461 #define OPT_CQM8I 303
462 #define OPT_CQM8P 304
463 #define OPT_CQMFILE 305
464 #define OPT_SAR 306
465 #define OPT_OVERSCAN 307
466 #define OPT_VIDFORMAT 308
467 #define OPT_FULLRANGE 309
468 #define OPT_COLOURPRIM 310
469 #define OPT_TRANSFER 311
470 #define OPT_COLOURMATRIX 312
471 #define OPT_CHROMALOC 313
472 #define OPT_MIXED_REFS 314
473 #define OPT_CRF 315
474
475         static struct option long_options[] =
476         {
477             { "help",    no_argument,       NULL, 'h' },
478             { "bitrate", required_argument, NULL, 'B' },
479             { "bframes", required_argument, NULL, 'b' },
480             { "no-b-adapt", no_argument,    NULL, OPT_NOBADAPT },
481             { "b-bias",  required_argument, NULL, OPT_BBIAS },
482             { "b-pyramid", no_argument,     NULL, OPT_BPYRAMID },
483             { "min-keyint",required_argument,NULL,'i' },
484             { "keyint",  required_argument, NULL, 'I' },
485             { "scenecut",required_argument, NULL, OPT_SCENECUT },
486             { "nf",      no_argument,       NULL, 'n' },
487             { "filter",  required_argument, NULL, 'f' },
488             { "no-cabac",no_argument,       NULL, OPT_NO_CABAC },
489             { "qp",      required_argument, NULL, 'q' },
490             { "qpmin",   required_argument, NULL, OPT_QPMIN },
491             { "qpmax",   required_argument, NULL, OPT_QPMAX },
492             { "qpstep",  required_argument, NULL, OPT_QPSTEP },
493             { "crf",     required_argument, NULL, OPT_CRF },
494             { "ref",     required_argument, NULL, 'r' },
495             { "no-asm",  no_argument,       NULL, 'C' },
496             { "sar",     required_argument, NULL, OPT_SAR },
497             { "fps",     required_argument, NULL, OPT_FPS },
498             { "frames",  required_argument, NULL, OPT_FRAMES },
499             { "seek",    required_argument, NULL, OPT_SEEK },
500             { "output",  required_argument, NULL, 'o' },
501             { "analyse", required_argument, NULL, 'A' },
502             { "direct",  required_argument, NULL, OPT_DIRECT },
503             { "weightb", no_argument,       NULL, 'w' },
504             { "me",      required_argument, NULL, OPT_ME },
505             { "merange", required_argument, NULL, OPT_MERANGE },
506             { "subme",   required_argument, NULL, 'm' },
507             { "mixed-refs", no_argument,    NULL, OPT_MIXED_REFS },
508             { "no-chroma-me", no_argument,  NULL, OPT_NO_CHROMA_ME },
509             { "8x8dct",  no_argument,       NULL, '8' },
510             { "level",   required_argument, NULL, OPT_LEVEL },
511             { "ratetol", required_argument, NULL, OPT_RATETOL },
512             { "vbv-maxrate", required_argument, NULL, OPT_VBVMAXRATE },
513             { "vbv-bufsize", required_argument, NULL, OPT_VBVBUFSIZE },
514             { "vbv-init", required_argument,NULL,  OPT_VBVINIT },
515             { "ipratio", required_argument, NULL, OPT_IPRATIO },
516             { "pbratio", required_argument, NULL, OPT_PBRATIO },
517             { "chroma-qp-offset", required_argument, NULL, OPT_CHROMA_QP },
518             { "pass",    required_argument, NULL, 'p' },
519             { "stats",   required_argument, NULL, OPT_RCSTATS },
520             { "rceq",    required_argument, NULL, OPT_RCEQ },
521             { "qcomp",   required_argument, NULL, OPT_QCOMP },
522             { "qblur",   required_argument, NULL, OPT_QBLUR },
523             { "cplxblur",required_argument, NULL, OPT_CPLXBLUR },
524             { "zones",   required_argument, NULL, OPT_ZONES },
525             { "threads", required_argument, NULL, OPT_THREADS },
526             { "no-psnr", no_argument,       NULL, OPT_NOPSNR },
527             { "quiet",   no_argument,       NULL, OPT_QUIET },
528             { "verbose", no_argument,       NULL, 'v' },
529             { "progress",no_argument,       NULL, OPT_PROGRESS },
530             { "visualize",no_argument,      NULL, OPT_VISUALIZE },
531             { "aud",     no_argument,       NULL, OPT_AUD },
532             { "cqm",     required_argument, NULL, OPT_CQM },
533             { "cqmfile", required_argument, NULL, OPT_CQMFILE },
534             { "cqm4",    required_argument, NULL, OPT_CQM4 },
535             { "cqm4i",   required_argument, NULL, OPT_CQM4I },
536             { "cqm4iy",  required_argument, NULL, OPT_CQM4IY },
537             { "cqm4ic",  required_argument, NULL, OPT_CQM4IC },
538             { "cqm4p",   required_argument, NULL, OPT_CQM4P },
539             { "cqm4py",  required_argument, NULL, OPT_CQM4PY },
540             { "cqm4pc",  required_argument, NULL, OPT_CQM4PC },
541             { "cqm8",    required_argument, NULL, OPT_CQM8 },
542             { "cqm8i",   required_argument, NULL, OPT_CQM8I },
543             { "cqm8p",   required_argument, NULL, OPT_CQM8P },
544             { "overscan", required_argument, NULL, OPT_OVERSCAN },
545             { "videoformat", required_argument, NULL, OPT_VIDFORMAT },
546             { "fullrange", required_argument, NULL, OPT_FULLRANGE },
547             { "colorprim", required_argument, NULL, OPT_COLOURPRIM },
548             { "transfer", required_argument, NULL, OPT_TRANSFER },
549             { "colormatrix", required_argument, NULL, OPT_COLOURMATRIX },
550             { "chromaloc", required_argument, NULL, OPT_CHROMALOC },
551             {0, 0, 0, 0}
552         };
553
554         int c;
555
556         c = getopt_long( argc, argv, "hi:I:b:r:cxB:q:f:o:A:m:p:vw8",
557                          long_options, &long_options_index);
558
559         if( c == -1 )
560         {
561             break;
562         }
563
564         switch( c )
565         {
566             case 'h':
567                 Help( &defaults );
568                 return -1;
569
570             case 0:
571                 break;
572             case 'B':
573                 param->rc.i_bitrate = atol( optarg );
574                 param->rc.b_cbr = 1;
575                 break;
576             case OPT_CRF:
577                 param->rc.i_rf_constant = atol( optarg );
578                 break;
579             case 'b':
580                 param->i_bframe = atol( optarg );
581                 break;
582             case OPT_NOBADAPT:
583                 param->b_bframe_adaptive = 0;
584                 break;
585             case OPT_BBIAS:
586                 param->i_bframe_bias = atol( optarg );
587                 break;
588             case OPT_BPYRAMID:
589                 param->b_bframe_pyramid = 1;
590                 break;
591             case 'i':
592                 param->i_keyint_min = atol( optarg );
593                 if( param->i_keyint_max < param->i_keyint_min )
594                     param->i_keyint_max = param->i_keyint_min;
595                 break;
596             case 'I':
597                 param->i_keyint_max = atol( optarg );
598                 if( param->i_keyint_min > param->i_keyint_max )
599                     param->i_keyint_min = param->i_keyint_max;
600                 break;
601             case OPT_SCENECUT:
602                 param->i_scenecut_threshold = atol( optarg );
603                 break;
604             case 'n':
605                 param->b_deblocking_filter = 0;
606                 break;
607             case 'f':
608             {
609                 char *p = strchr( optarg, ':' );
610                 param->i_deblocking_filter_alphac0 = atoi( optarg );
611                 param->i_deblocking_filter_beta = p ? atoi( p+1 ) : param->i_deblocking_filter_alphac0;
612                 break;
613             }
614             case 'q':
615                 param->rc.i_qp_constant = atoi( optarg );
616                 break;
617             case OPT_QPMIN:
618                 param->rc.i_qp_min = atoi( optarg );
619                 break;
620             case OPT_QPMAX:
621                 param->rc.i_qp_max = atoi( optarg );
622                 break;
623             case OPT_QPSTEP:
624                 param->rc.i_qp_step = atoi( optarg );
625                 break;
626             case 'r':
627                 param->i_frame_reference = atoi( optarg );
628                 break;
629             case OPT_NO_CABAC:
630                 param->b_cabac = 0;
631                 break;
632             case 'x':
633                 opt->b_decompress = 1;
634                 break;
635             case 'C':
636                 param->cpu = 0;
637                 break;
638             case OPT_FRAMES:
639                 param->i_frame_total = atoi( optarg );
640                 break;
641             case OPT_SEEK:
642                 opt->i_seek = atoi( optarg );
643                 break;
644             case 'o':
645                 if( !strncasecmp(optarg + strlen(optarg) - 4, ".mp4", 4) )
646                 {
647 #ifdef MP4_OUTPUT
648                     p_open_outfile = open_file_mp4;
649                     p_write_nalu = write_nalu_mp4;
650                     p_set_outfile_param = set_param_mp4;
651                     p_set_eop = set_eop_mp4;
652                     p_close_outfile = close_file_mp4;
653 #else
654                     fprintf( stderr, "not compiled with MP4 output support\n" );
655                     return -1;
656 #endif
657                 }
658                 else if( !strncasecmp(optarg + strlen(optarg) - 4, ".mkv", 4) )
659                 {
660                     p_open_outfile = open_file_mkv;
661                     p_write_nalu = write_nalu_mkv;
662                     p_set_outfile_param = set_param_mkv;
663                     p_set_eop = set_eop_mkv;
664                     p_close_outfile = close_file_mkv;
665                 }
666                 if( !strcmp(optarg, "-") )
667                     opt->hout = stdout;
668                 else if( p_open_outfile( optarg, &opt->hout ) )
669                 {
670                     fprintf( stderr, "cannot open output file `%s'\n", optarg );
671                     return -1;
672                 }
673                 break;
674             case OPT_SAR:
675             {
676                 char *p = strchr( optarg, ':' );
677                 if( p )
678                 {
679                     param->vui.i_sar_width = atoi( optarg );
680                     param->vui.i_sar_height = atoi( p + 1 );
681                 }
682                 break;
683             }
684             case OPT_FPS:
685             {
686                 float fps;
687                 if( sscanf( optarg, "%d/%d", &param->i_fps_num, &param->i_fps_den ) == 2 )
688                     ;
689                 else if( sscanf( optarg, "%f", &fps ) )
690                 {
691                     param->i_fps_num = (int)(fps * 1000 + .5);
692                     param->i_fps_den = 1000;
693                 }
694                 else
695                 {
696                     fprintf( stderr, "bad fps `%s'\n", optarg );
697                     return -1;
698                 }
699                 break;
700             }
701             case 'A':
702                 param->analyse.inter = 0;
703                 if( strstr( optarg, "none" ) )  param->analyse.inter =  0;
704                 if( strstr( optarg, "all" ) )   param->analyse.inter = ~0;
705
706                 if( strstr( optarg, "i4x4" ) )  param->analyse.inter |= X264_ANALYSE_I4x4;
707                 if( strstr( optarg, "i8x8" ) )  param->analyse.inter |= X264_ANALYSE_I8x8;
708                 if( strstr( optarg, "p8x8" ) )  param->analyse.inter |= X264_ANALYSE_PSUB16x16;
709                 if( strstr( optarg, "p4x4" ) )  param->analyse.inter |= X264_ANALYSE_PSUB8x8;
710                 if( strstr( optarg, "b8x8" ) )  param->analyse.inter |= X264_ANALYSE_BSUB16x16;
711                 break;
712             case OPT_DIRECT:
713                 b_error |= parse_enum( optarg, x264_direct_pred_names, &param->analyse.i_direct_mv_pred );
714                 break;
715             case 'w':
716                 param->analyse.b_weighted_bipred = 1;
717                 break;
718             case OPT_ME:
719                 b_error |= parse_enum( optarg, x264_motion_est_names, &param->analyse.i_me_method );
720                 break;
721             case OPT_MERANGE:
722                 param->analyse.i_me_range = atoi(optarg);
723                 break;
724             case 'm':
725                 param->analyse.i_subpel_refine = atoi(optarg);
726                 break;
727             case OPT_MIXED_REFS:
728                 param->analyse.b_mixed_references = 1;
729                 break;
730             case OPT_NO_CHROMA_ME:
731                 param->analyse.b_chroma_me = 0;
732                 break;
733             case '8':
734                 param->analyse.b_transform_8x8 = 1;
735                 break;
736             case OPT_LEVEL:
737                 param->i_level_idc = atoi(optarg);
738                 break;
739             case OPT_RATETOL:
740                 param->rc.f_rate_tolerance = !strncmp("inf", optarg, 3) ? 1e9 : atof(optarg);
741                 break;
742             case OPT_VBVMAXRATE:
743                 param->rc.i_vbv_max_bitrate = atoi( optarg );
744                 break;
745             case OPT_VBVBUFSIZE:
746                 param->rc.i_vbv_buffer_size = atoi( optarg );
747                 break;
748             case OPT_VBVINIT:
749                 param->rc.f_vbv_buffer_init = atof(optarg);
750                 break;
751             case OPT_IPRATIO:
752                 param->rc.f_ip_factor = atof(optarg);
753                 break;
754             case OPT_PBRATIO:
755                 param->rc.f_pb_factor = atof(optarg);
756                 break;
757             case OPT_CHROMA_QP:
758                 param->analyse.i_chroma_qp_offset = atoi(optarg);
759                 break;
760             case 'p':
761             {
762                 int i_pass = atoi(optarg);
763                 if( i_pass == 1 )
764                     param->rc.b_stat_write = 1;
765                 else if( i_pass == 2 )
766                     param->rc.b_stat_read = 1;
767                 else if( i_pass > 2 )
768                     param->rc.b_stat_read =
769                     param->rc.b_stat_write = 1;
770                 break;
771             }
772             case OPT_RCSTATS:
773                 param->rc.psz_stat_in = optarg;
774                 param->rc.psz_stat_out = optarg;
775                 break;
776             case OPT_RCEQ:
777                 param->rc.psz_rc_eq = optarg;
778                break;
779             case OPT_QCOMP:
780                 param->rc.f_qcompress = atof(optarg);
781                 break;
782             case OPT_QBLUR:
783                 param->rc.f_qblur = atof(optarg);
784                 break;
785             case OPT_CPLXBLUR:
786                 param->rc.f_complexity_blur = atof(optarg);
787                 break;
788             case OPT_ZONES:
789                 param->rc.psz_zones = optarg;
790                 break;
791             case OPT_THREADS:
792                 param->i_threads = atoi(optarg);
793                 break;
794             case OPT_NOPSNR:
795                 param->analyse.b_psnr = 0;
796                 break;
797             case OPT_QUIET:
798                 param->i_log_level = X264_LOG_NONE;
799                 break;
800             case 'v':
801                 param->i_log_level = X264_LOG_DEBUG;
802                 break;
803             case OPT_AUD:
804                 param->b_aud = 1;
805                 break;
806             case OPT_PROGRESS:
807                 opt->b_progress = 1;
808                 break;
809             case OPT_VISUALIZE:
810 #ifdef VISUALIZE
811                 param->b_visualize = 1;
812                 b_exit_on_ctrl_c = 1;
813 #else
814                 fprintf( stderr, "not compiled with visualization support\n" );
815 #endif
816                 break;
817             case OPT_CQM:
818                 if( strstr( optarg, "flat" ) )
819                     param->i_cqm_preset = X264_CQM_FLAT;
820                 else if( strstr( optarg, "jvt" ) )
821                     param->i_cqm_preset = X264_CQM_JVT;
822                 else
823                 {
824                     fprintf( stderr, "bad CQM preset `%s'\n", optarg );
825                     return -1;
826                 }
827                 break;
828             case OPT_CQMFILE:
829                 param->psz_cqm_file = optarg;
830                 break;
831             case OPT_CQM4:
832                 param->i_cqm_preset = X264_CQM_CUSTOM;
833                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
834                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
835                 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
836                 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
837                 break;
838             case OPT_CQM8:
839                 param->i_cqm_preset = X264_CQM_CUSTOM;
840                 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
841                 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
842                 break;
843             case OPT_CQM4I:
844                 param->i_cqm_preset = X264_CQM_CUSTOM;
845                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
846                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
847                 break;
848             case OPT_CQM4P:
849                 param->i_cqm_preset = X264_CQM_CUSTOM;
850                 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
851                 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
852                 break;
853             case OPT_CQM4IY:
854                 param->i_cqm_preset = X264_CQM_CUSTOM;
855                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
856                 break;
857             case OPT_CQM4IC:
858                 param->i_cqm_preset = X264_CQM_CUSTOM;
859                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
860                 break;
861             case OPT_CQM4PY:
862                 param->i_cqm_preset = X264_CQM_CUSTOM;
863                 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
864                 break;
865             case OPT_CQM4PC:
866                 param->i_cqm_preset = X264_CQM_CUSTOM;
867                 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
868                 break;
869             case OPT_CQM8I:
870                 param->i_cqm_preset = X264_CQM_CUSTOM;
871                 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
872                 break;
873             case OPT_CQM8P:
874                 param->i_cqm_preset = X264_CQM_CUSTOM;
875                 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
876                 break;
877             case OPT_OVERSCAN:
878                 b_error |= parse_enum( optarg, overscan_str, &param->vui.i_overscan );
879                 break;
880             case OPT_VIDFORMAT:
881                 b_error |= parse_enum( optarg, vidformat_str, &param->vui.i_vidformat );
882                 break;
883             case OPT_FULLRANGE:
884                 b_error |= parse_enum( optarg, fullrange_str, &param->vui.b_fullrange );
885                 break;
886             case OPT_COLOURPRIM:
887                 b_error |= parse_enum( optarg, colorprim_str, &param->vui.i_colorprim );
888                 break;
889             case OPT_TRANSFER:
890                 b_error |= parse_enum( optarg, transfer_str, &param->vui.i_transfer );
891                 break;
892             case OPT_COLOURMATRIX:
893                 b_error |= parse_enum( optarg, colmatrix_str, &param->vui.i_colmatrix );
894                 break;
895             case OPT_CHROMALOC:
896                 param->vui.i_chroma_loc = atoi( optarg );
897                 b_error = ( param->vui.i_chroma_loc < 0 || param->vui.i_chroma_loc > 5 );
898                 break;
899             default:
900                 fprintf( stderr, "unknown option (%c)\n", optopt );
901                 return -1;
902         }
903
904         if( b_error )
905         {
906             fprintf( stderr, "bad argument: %s %s\n", argv[optind-2], optarg );
907             return -1;
908         }
909     }
910
911     /* Get the file name */
912     if( optind > argc - 1 || !opt->hout )
913     {
914         Help( &defaults );
915         return -1;
916     }
917     psz_filename = argv[optind++];
918
919     if( !opt->b_decompress )
920     {
921         if( optind > argc - 1 )
922         {
923             /* try to parse the file name */
924             for( psz = psz_filename; *psz; psz++ )
925             {
926                 if( *psz >= '0' && *psz <= '9'
927                     && sscanf( psz, "%ux%u", &param->i_width, &param->i_height ) == 2 )
928                 {
929                     if( param->i_log_level >= X264_LOG_INFO )
930                         fprintf( stderr, "x264 [info]: file name gives %dx%d\n", param->i_width, param->i_height );
931                     break;
932                 }
933             }
934         }
935         else
936         {
937             sscanf( argv[optind++], "%ux%u", &param->i_width, &param->i_height );
938         }
939         
940         /* check avis input */
941         psz = psz_filename + strlen(psz_filename) - 1;
942         while( psz > psz_filename && *psz != '.' )
943             psz--;
944
945         if( !strncasecmp( psz, ".avi", 4 ) || !strncasecmp( psz, ".avs", 4 ) )
946             b_avis = 1;
947
948         if( !b_avis && ( !param->i_width || !param->i_height ) )
949         {
950             Help( &defaults );
951             return -1;
952         }
953     }
954
955     /* open the input */
956     if( !strcmp( psz_filename, "-" ) )
957     {
958         opt->hin = stdin;
959         optind++;
960     }
961     else
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( p_open_infile( psz_filename, &opt->hin, param ) )
976         {
977             fprintf( stderr, "could not open input file '%s'\n", psz_filename );
978             return -1;
979         }
980     }
981
982     return 0;
983 }
984
985 /*****************************************************************************
986  * Decode:
987  *****************************************************************************/
988
989 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
990 {
991     x264_picture_t pic_out;
992     x264_nal_t *nal;
993     int i_nal, i;
994     int i_file = 0;
995
996     /* Do not force any parameters */
997     if( pic )
998     {
999         pic->i_type = X264_TYPE_AUTO;
1000         pic->i_qpplus1 = 0;
1001     }
1002     if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
1003     {
1004         fprintf( stderr, "x264_encoder_encode failed\n" );
1005     }
1006
1007     for( i = 0; i < i_nal; i++ )
1008     {
1009         int i_size;
1010         int i_data;
1011
1012         i_data = DATA_MAX;
1013         if( ( i_size = x264_nal_encode( data, &i_data, 1, &nal[i] ) ) > 0 )
1014         {
1015             i_file += p_write_nalu( hout, data, i_size );
1016         }
1017         else if( i_size < 0 )
1018         {
1019             fprintf( stderr, "need to increase buffer size (size=%d)\n", -i_size );
1020         }
1021     }
1022     if (i_nal)
1023         p_set_eop( hout, &pic_out );
1024
1025     return i_file;
1026 }
1027
1028 /*****************************************************************************
1029  * Encode:
1030  *****************************************************************************/
1031 static int  Encode( x264_param_t *param, cli_opt_t *opt )
1032 {
1033     x264_t *h;
1034     x264_picture_t pic;
1035
1036     int     i_frame, i_frame_total;
1037     int64_t i_start, i_end;
1038     int64_t i_file;
1039     int     i_frame_size;
1040     int     i_progress;
1041
1042     i_frame_total = p_get_frame_total( opt->hin, param->i_width, param->i_height );
1043     i_frame_total -= opt->i_seek;
1044     if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
1045         && param->i_frame_total > 0 )
1046         i_frame_total = param->i_frame_total;
1047     param->i_frame_total = i_frame_total;
1048
1049     if( ( h = x264_encoder_open( param ) ) == NULL )
1050     {
1051         fprintf( stderr, "x264_encoder_open failed\n" );
1052         p_close_infile( opt->hin );
1053         p_close_outfile( opt->hout );
1054         return -1;
1055     }
1056
1057     if( p_set_outfile_param( opt->hout, param ) )
1058     {
1059         fprintf( stderr, "can't set outfile param\n" );
1060         p_close_infile( opt->hin );
1061         p_close_outfile( opt->hout );
1062         return -1;
1063     }
1064
1065     /* Create a new pic */
1066     x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height );
1067
1068     i_start = x264_mdate();
1069
1070     /* Encode frames */
1071     for( i_frame = 0, i_file = 0, i_progress = 0;
1072          b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1073     {
1074         if( p_read_frame( &pic, opt->hin, i_frame + opt->i_seek, param->i_width, param->i_height ) )
1075             break;
1076
1077         pic.i_pts = (int64_t)i_frame * param->i_fps_den;
1078
1079         i_file += Encode_frame( h, opt->hout, &pic );
1080
1081         i_frame++;
1082
1083         /* update status line (up to 1000 times per input file) */
1084         if( opt->b_progress && param->i_log_level < X264_LOG_DEBUG && 
1085             ( i_frame_total ? i_frame * 1000 / i_frame_total > i_progress
1086                             : i_frame % 10 == 0 ) )
1087         {
1088             int64_t i_elapsed = x264_mdate() - i_start;
1089             double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1090             if( i_frame_total )
1091             {
1092                 i_progress = i_frame * 1000 / i_frame_total;
1093                 fprintf( stderr, "encoded frames: %d/%d (%.1f%%), %.2f fps   \r", i_frame,
1094                          i_frame_total, (float)i_progress / 10, fps );
1095             }
1096             else
1097                 fprintf( stderr, "encoded frames: %d, %.2f fps   \r", i_frame, fps );
1098             fflush( stderr ); // needed in windows
1099         }
1100     }
1101     /* Flush delayed B-frames */
1102     do {
1103         i_file +=
1104         i_frame_size = Encode_frame( h, opt->hout, NULL );
1105     } while( i_frame_size );
1106
1107     i_end = x264_mdate();
1108     x264_picture_clean( &pic );
1109     x264_encoder_close( h );
1110     fprintf( stderr, "\n" );
1111
1112     if( b_ctrl_c )
1113         fprintf( stderr, "aborted at input frame %d\n", opt->i_seek + i_frame );
1114
1115     p_close_infile( opt->hin );
1116     p_close_outfile( opt->hout );
1117
1118     if( i_frame > 0 )
1119     {
1120         double fps = (double)i_frame * (double)1000000 /
1121                      (double)( i_end - i_start );
1122
1123         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame, fps,
1124                  (double) i_file * 8 * param->i_fps_num / ( param->i_fps_den * i_frame * 1000 ) );
1125     }
1126
1127     return 0;
1128 }
1129
1130 /* raw 420 yuv file operation */
1131 static int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1132 {
1133     if ((*p_handle = fopen(psz_filename, "rb")) == NULL)
1134         return -1;
1135     return 0;
1136 }
1137
1138 static int get_frame_total_yuv( hnd_t handle, int i_width, int i_height )
1139 {
1140     FILE *f = (FILE *)handle;
1141     int i_frame_total = 0;
1142
1143     if( !fseek( f, 0, SEEK_END ) )
1144     {
1145         int64_t i_size = ftell( f );
1146         fseek( f, 0, SEEK_SET );
1147         i_frame_total = (int)(i_size / ( i_width * i_height * 3 / 2 ));
1148     }
1149
1150     return i_frame_total;
1151 }
1152
1153 static int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1154 {
1155     static int prev_frame = -1;
1156     FILE *f = (FILE *)handle;
1157
1158     if( i_frame != prev_frame+1 )
1159         if( fseek( f, i_frame * i_width * i_height * 3 / 2, SEEK_SET ) )
1160             return -1;
1161
1162     if( fread( p_pic->img.plane[0], 1, i_width * i_height, f ) <= 0
1163             || fread( p_pic->img.plane[1], 1, i_width * i_height / 4, f ) <= 0
1164             || fread( p_pic->img.plane[2], 1, i_width * i_height / 4, f ) <= 0 )
1165         return -1;
1166
1167     prev_frame = i_frame;
1168
1169     return 0;
1170 }
1171
1172 static int close_file_yuv(hnd_t handle)
1173 {
1174     if (handle == NULL)
1175         return 0;
1176     return fclose((FILE *)handle);
1177 }
1178
1179
1180 /* avs/avi input file support under cygwin */
1181
1182 #ifdef AVIS_INPUT
1183
1184 static int gcd(int a, int b)
1185 {
1186     int c;
1187
1188     while (1)
1189     {
1190         c = a % b;
1191         if (!c)
1192             return b;
1193         a = b;
1194         b = c;
1195     }
1196 }
1197
1198 static int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1199 {
1200     AVISTREAMINFO info;
1201     PAVISTREAM p_avi = NULL;
1202     int i;
1203
1204     *p_handle = NULL;
1205
1206     AVIFileInit();
1207     if( AVIStreamOpenFromFile( &p_avi, psz_filename, streamtypeVIDEO, 0, OF_READ, NULL ) )
1208     {
1209         AVIFileExit();
1210         return -1;
1211     }
1212
1213     if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1214     {
1215         AVIStreamRelease(p_avi);
1216         AVIFileExit();
1217         return -1;
1218     }
1219
1220     // check input format
1221     if (info.fccHandler != MAKEFOURCC('Y', 'V', '1', '2'))
1222     {
1223         fprintf( stderr, "avis [error]: unsupported input format (%c%c%c%c)\n",
1224             (char)(info.fccHandler & 0xff), (char)((info.fccHandler >> 8) & 0xff),
1225             (char)((info.fccHandler >> 16) & 0xff), (char)((info.fccHandler >> 24)) );
1226
1227         AVIStreamRelease(p_avi);
1228         AVIFileExit();
1229
1230         return -1;
1231     }
1232
1233     p_param->i_width = info.rcFrame.right - info.rcFrame.left;
1234     p_param->i_height = info.rcFrame.bottom - info.rcFrame.top;
1235     i = gcd(info.dwRate, info.dwScale);
1236     p_param->i_fps_den = info.dwScale / i;
1237     p_param->i_fps_num = info.dwRate / i;
1238
1239     fprintf( stderr, "avis [info]: %dx%d @ %.2f fps (%d frames)\n",  
1240         p_param->i_width, p_param->i_height,
1241         (double)p_param->i_fps_num / (double)p_param->i_fps_den,
1242         (int)info.dwLength );
1243
1244     *p_handle = (hnd_t)p_avi;
1245
1246     return 0;
1247 }
1248
1249 static int get_frame_total_avis( hnd_t handle, int i_width, int i_height )
1250 {
1251     PAVISTREAM p_avi = (PAVISTREAM)handle;
1252     AVISTREAMINFO info;
1253
1254     if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1255         return -1;
1256
1257     return info.dwLength;
1258 }
1259
1260 static int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1261 {
1262     PAVISTREAM p_avi = (PAVISTREAM)handle;
1263     
1264     p_pic->img.i_csp = X264_CSP_YV12;
1265     
1266     if( AVIStreamRead(p_avi, i_frame, 1, p_pic->img.plane[0], i_width * i_height * 3 / 2, NULL, NULL ) )
1267         return -1;
1268
1269     return 0;
1270 }
1271
1272 static int close_file_avis( hnd_t handle )
1273 {
1274     PAVISTREAM p_avi = (PAVISTREAM)handle;
1275
1276     AVIStreamRelease(p_avi);
1277     AVIFileExit();
1278
1279     return 0;
1280 }
1281
1282 #endif
1283
1284
1285 static int open_file_bsf( char *psz_filename, hnd_t *p_handle )
1286 {
1287     if ((*p_handle = fopen(psz_filename, "w+b")) == NULL)
1288         return -1;
1289
1290     return 0;
1291 }
1292
1293 static int set_param_bsf( hnd_t handle, x264_param_t *p_param )
1294 {
1295     return 0;
1296 }
1297
1298 static int write_nalu_bsf( hnd_t handle, uint8_t *p_nalu, int i_size )
1299 {
1300     if (fwrite(p_nalu, i_size, 1, (FILE *)handle) > 0)
1301         return i_size;
1302     return -1;
1303 }
1304
1305 static int set_eop_bsf( hnd_t handle,  x264_picture_t *p_picture )
1306 {
1307     return 0;
1308 }
1309
1310 static int close_file_bsf( hnd_t handle )
1311 {
1312     if ((handle == NULL) || (handle == stdout))
1313         return 0;
1314
1315     return fclose((FILE *)handle);
1316 }
1317
1318 /* -- mp4 muxing support ------------------------------------------------- */
1319 #ifdef MP4_OUTPUT
1320
1321 typedef struct
1322 {
1323     GF_ISOFile *p_file;
1324     GF_AVCConfig *p_config;
1325     GF_ISOSample *p_sample;
1326     int i_track;
1327     int i_descidx;
1328     int i_time_inc;
1329     int i_time_res;
1330     int i_numframe;
1331     int i_init_delay;
1332     uint8_t b_sps;
1333     uint8_t b_pps;
1334 } mp4_t;
1335
1336
1337 static void recompute_bitrate_mp4(GF_ISOFile *p_file, int i_track)
1338 {
1339     u32 i, count, di, timescale, time_wnd, rate;
1340     u64 offset;
1341     Double br;
1342     GF_ESD *esd;
1343
1344     esd = gf_isom_get_esd(p_file, i_track, 1);
1345     if (!esd) return;
1346
1347     esd->decoderConfig->avgBitrate = 0;
1348     esd->decoderConfig->maxBitrate = 0;
1349     rate = time_wnd = 0;
1350
1351     timescale = gf_isom_get_media_timescale(p_file, i_track);
1352     count = gf_isom_get_sample_count(p_file, i_track);
1353     for (i=0; i<count; i++) {
1354         GF_ISOSample *samp = gf_isom_get_sample_info(p_file, i_track, i+1, &di, &offset);
1355
1356         if (samp->dataLength>esd->decoderConfig->bufferSizeDB) esd->decoderConfig->bufferSizeDB = samp->dataLength;
1357
1358         if (esd->decoderConfig->bufferSizeDB < samp->dataLength) esd->decoderConfig->bufferSizeDB = samp->dataLength;
1359         esd->decoderConfig->avgBitrate += samp->dataLength;
1360         rate += samp->dataLength;
1361         if (samp->DTS > time_wnd + timescale) {
1362             if (rate > esd->decoderConfig->maxBitrate) esd->decoderConfig->maxBitrate = rate;
1363             time_wnd = samp->DTS;
1364             rate = 0;
1365         }
1366
1367         gf_isom_sample_del(&samp);
1368     }
1369
1370     br = (Double) (s64) gf_isom_get_media_duration(p_file, i_track);
1371     br /= timescale;
1372     esd->decoderConfig->avgBitrate = (u32) (esd->decoderConfig->avgBitrate / br);
1373     /*move to bps*/
1374     esd->decoderConfig->avgBitrate *= 8;
1375     esd->decoderConfig->maxBitrate *= 8;
1376
1377     gf_isom_change_mpeg4_description(p_file, i_track, 1, esd);
1378     gf_odf_desc_del((GF_Descriptor *) esd);
1379 }
1380
1381
1382 static int close_file_mp4( hnd_t handle )
1383 {
1384     mp4_t *p_mp4 = (mp4_t *)handle;
1385
1386     if (p_mp4 == NULL)
1387         return 0;
1388
1389     if (p_mp4->p_config)
1390         gf_odf_avc_cfg_del(p_mp4->p_config);
1391
1392     if (p_mp4->p_sample)
1393     {
1394         if (p_mp4->p_sample->data)
1395             free(p_mp4->p_sample->data);
1396
1397         gf_isom_sample_del(&p_mp4->p_sample);
1398     }
1399
1400     if (p_mp4->p_file)
1401     {
1402         recompute_bitrate_mp4(p_mp4->p_file, p_mp4->i_track);
1403         gf_isom_set_pl_indication(p_mp4->p_file, GF_ISOM_PL_VISUAL, 0x15);
1404         gf_isom_set_storage_mode(p_mp4->p_file, GF_ISOM_STORE_FLAT);
1405         gf_isom_close(p_mp4->p_file);
1406     }
1407
1408     free(p_mp4);
1409
1410     return 0;
1411 }
1412
1413 static int open_file_mp4( char *psz_filename, hnd_t *p_handle )
1414 {
1415     mp4_t *p_mp4;
1416
1417     *p_handle = NULL;
1418
1419     if ((p_mp4 = (mp4_t *)malloc(sizeof(mp4_t))) == NULL)
1420         return -1;
1421
1422     memset(p_mp4, 0, sizeof(mp4_t));
1423     p_mp4->p_file = gf_isom_open(psz_filename, GF_ISOM_OPEN_WRITE, NULL);
1424
1425     if ((p_mp4->p_sample = gf_isom_sample_new()) == NULL)
1426     {
1427         close_file_mp4( p_mp4 );
1428         return -1;
1429     }
1430
1431     gf_isom_set_brand_info(p_mp4->p_file, GF_ISOM_BRAND_AVC1, 0);
1432
1433     *p_handle = p_mp4;
1434
1435     return 0;
1436 }
1437
1438
1439 static int set_param_mp4( hnd_t handle, x264_param_t *p_param )
1440 {
1441     mp4_t *p_mp4 = (mp4_t *)handle;
1442
1443     p_mp4->i_track = gf_isom_new_track(p_mp4->p_file, 0, GF_ISOM_MEDIA_VISUAL, 
1444         p_param->i_fps_num);
1445
1446     p_mp4->p_config = gf_odf_avc_cfg_new();
1447     gf_isom_avc_config_new(p_mp4->p_file, p_mp4->i_track, p_mp4->p_config, 
1448         NULL, NULL, &p_mp4->i_descidx);
1449
1450     gf_isom_set_visual_info(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, 
1451         p_param->i_width, p_param->i_height);
1452
1453     p_mp4->p_sample->data = (char *)malloc(p_param->i_width * p_param->i_height * 3 / 2);
1454     if (p_mp4->p_sample->data == NULL)
1455         return -1;
1456
1457     p_mp4->i_time_res = p_param->i_fps_num;
1458     p_mp4->i_time_inc = p_param->i_fps_den;
1459     p_mp4->i_init_delay = p_param->i_bframe ? (p_param->b_bframe_pyramid ? 2 : 1) : 0;
1460     p_mp4->i_init_delay *= p_mp4->i_time_inc;
1461     fprintf(stderr, "mp4 [info]: initial delay %d (scale %d)\n", 
1462         p_mp4->i_init_delay, p_mp4->i_time_res);
1463
1464     return 0;
1465 }
1466
1467
1468 static int write_nalu_mp4( hnd_t handle, uint8_t *p_nalu, int i_size )
1469 {
1470     mp4_t *p_mp4 = (mp4_t *)handle;
1471     GF_AVCConfigSlot *p_slot;
1472     uint8_t type = p_nalu[4] & 0x1f;
1473     int psize;
1474
1475     switch(type)
1476     {
1477     // sps
1478     case 0x07:
1479         if (!p_mp4->b_sps)
1480         {
1481             p_mp4->p_config->configurationVersion = 1;
1482             p_mp4->p_config->AVCProfileIndication = p_nalu[5];
1483             p_mp4->p_config->profile_compatibility = p_nalu[6];
1484             p_mp4->p_config->AVCLevelIndication = p_nalu[7];
1485             p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
1486             p_slot->size = i_size - 4;
1487             p_slot->data = (char *)malloc(p_slot->size);
1488             memcpy(p_slot->data, p_nalu + 4, i_size - 4);
1489             gf_list_add(p_mp4->p_config->sequenceParameterSets, p_slot);
1490             p_slot = NULL;
1491             p_mp4->b_sps = 1;
1492         }
1493         break;
1494
1495     // pps      
1496     case 0x08:
1497         if (!p_mp4->b_pps)
1498         {
1499             p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
1500             p_slot->size = i_size - 4;
1501             p_slot->data = (char *)malloc(p_slot->size);
1502             memcpy(p_slot->data, p_nalu + 4, i_size - 4);
1503             gf_list_add(p_mp4->p_config->pictureParameterSets, p_slot);
1504             p_slot = NULL;
1505             p_mp4->b_pps = 1;
1506             if (p_mp4->b_sps)
1507                 gf_isom_avc_config_update(p_mp4->p_file, p_mp4->i_track, 1, p_mp4->p_config);
1508         }
1509         break;
1510
1511     // slice, sei
1512     case 0x1:
1513     case 0x5:
1514     case 0x6:
1515         psize = i_size - 4 ;
1516         memcpy(p_mp4->p_sample->data + p_mp4->p_sample->dataLength, p_nalu, i_size);
1517         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 0] = (psize >> 24) & 0xff;
1518         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 1] = (psize >> 16) & 0xff;
1519         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 2] = (psize >> 8) & 0xff;
1520         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 3] = (psize >> 0) & 0xff;
1521         p_mp4->p_sample->dataLength += i_size;
1522         break;
1523     }
1524
1525     return i_size;
1526 }
1527
1528 static int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture )
1529 {
1530     mp4_t *p_mp4 = (mp4_t *)handle;
1531     uint32_t dts = p_mp4->i_numframe * p_mp4->i_time_inc;
1532     uint32_t pts = p_picture->i_pts;
1533     int offset = p_mp4->i_init_delay + pts - dts;
1534
1535     p_mp4->p_sample->IsRAP = p_picture->i_type == X264_TYPE_IDR ? 1 : 0;
1536     p_mp4->p_sample->DTS = dts;
1537     p_mp4->p_sample->CTS_Offset = offset;
1538     gf_isom_add_sample(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, p_mp4->p_sample);
1539
1540     p_mp4->p_sample->dataLength = 0;
1541     p_mp4->i_numframe++;
1542
1543     return 0;
1544 }
1545
1546 #endif
1547
1548
1549 /* -- mkv muxing support ------------------------------------------------- */
1550 typedef struct
1551 {
1552     mk_Writer *w;
1553
1554     uint8_t   *sps, *pps;
1555     int       sps_len, pps_len;
1556
1557     int       width, height, d_width, d_height;
1558
1559     int64_t   frame_duration;
1560     int       fps_num;
1561
1562     int       b_header_written;
1563     char      b_writing_frame;
1564 } mkv_t;
1565
1566 static int write_header_mkv( mkv_t *p_mkv )
1567 {
1568     int       ret;
1569     uint8_t   *avcC;
1570     int  avcC_len;
1571
1572     if( p_mkv->sps == NULL || p_mkv->pps == NULL ||
1573         p_mkv->width == 0 || p_mkv->height == 0 ||
1574         p_mkv->d_width == 0 || p_mkv->d_height == 0)
1575         return -1;
1576
1577     avcC_len = 5 + 1 + 2 + p_mkv->sps_len + 1 + 2 + p_mkv->pps_len;
1578     avcC = malloc(avcC_len);
1579     if (avcC == NULL)
1580         return -1;
1581
1582     avcC[0] = 1;
1583     avcC[1] = p_mkv->sps[1];
1584     avcC[2] = p_mkv->sps[2];
1585     avcC[3] = p_mkv->sps[3];
1586     avcC[4] = 0xfe; // nalu size length is three bytes
1587     avcC[5] = 0xe1; // one sps
1588
1589     avcC[6] = p_mkv->sps_len >> 8;
1590     avcC[7] = p_mkv->sps_len;
1591
1592     memcpy(avcC+8, p_mkv->sps, p_mkv->sps_len);
1593
1594     avcC[8+p_mkv->sps_len] = 1; // one pps
1595     avcC[9+p_mkv->sps_len] = p_mkv->pps_len >> 8;
1596     avcC[10+p_mkv->sps_len] = p_mkv->pps_len;
1597
1598     memcpy( avcC+11+p_mkv->sps_len, p_mkv->pps, p_mkv->pps_len );
1599
1600     ret = mk_writeHeader( p_mkv->w, "x264", "V_MPEG4/ISO/AVC",
1601                           avcC, avcC_len, p_mkv->frame_duration, 50000,
1602                           p_mkv->width, p_mkv->height,
1603                           p_mkv->d_width, p_mkv->d_height );
1604
1605     free( avcC );
1606
1607     p_mkv->b_header_written = 1;
1608
1609     return ret;
1610 }
1611
1612 static int open_file_mkv( char *psz_filename, hnd_t *p_handle )
1613 {
1614     mkv_t *p_mkv;
1615
1616     *p_handle = NULL;
1617
1618     p_mkv  = malloc(sizeof(*p_mkv));
1619     if (p_mkv == NULL)
1620         return -1;
1621
1622     memset(p_mkv, 0, sizeof(*p_mkv));
1623
1624     p_mkv->w = mk_createWriter(psz_filename);
1625     if (p_mkv->w == NULL)
1626     {
1627         free(p_mkv);
1628         return -1;
1629     }
1630
1631     *p_handle = p_mkv;
1632
1633     return 0;
1634 }
1635
1636 static int set_param_mkv( hnd_t handle, x264_param_t *p_param )
1637 {
1638     mkv_t   *p_mkv = handle;
1639     int64_t dw, dh;
1640
1641     if( p_param->i_fps_num > 0 )
1642     {
1643         p_mkv->frame_duration = (int64_t)p_param->i_fps_den *
1644                                 (int64_t)1000000000 / p_param->i_fps_num;
1645         p_mkv->fps_num = p_param->i_fps_num;
1646     }
1647     else
1648     {
1649         p_mkv->frame_duration = 0;
1650         p_mkv->fps_num = 1;
1651     }
1652
1653     p_mkv->width = p_param->i_width;
1654     p_mkv->height = p_param->i_height;
1655
1656     if( p_param->vui.i_sar_width && p_param->vui.i_sar_height )
1657     {
1658         dw = (int64_t)p_param->i_width  * p_param->vui.i_sar_width;
1659         dh = (int64_t)p_param->i_height * p_param->vui.i_sar_height;
1660     }
1661     else
1662     {
1663         dw = p_param->i_width;
1664         dh = p_param->i_height;
1665     }
1666
1667     if( dw > 0 && dh > 0 )
1668     {
1669         int64_t a = dw, b = dh;
1670
1671         for (;;)
1672         {
1673             int64_t c = a % b;
1674             if( c == 0 )
1675               break;
1676             a = b;
1677             b = c;
1678         }
1679
1680         dw /= b;
1681         dh /= b;
1682     }
1683
1684     p_mkv->d_width = (int)dw;
1685     p_mkv->d_height = (int)dh;
1686
1687     return 0;
1688 }
1689
1690 static int write_nalu_mkv( hnd_t handle, uint8_t *p_nalu, int i_size )
1691 {
1692     mkv_t *p_mkv = handle;
1693     uint8_t type = p_nalu[4] & 0x1f;
1694     uint8_t dsize[3];
1695     int psize;
1696
1697     switch( type )
1698     {
1699     // sps
1700     case 0x07:
1701         if( !p_mkv->sps )
1702         {
1703             p_mkv->sps = malloc(i_size - 4);
1704             if (p_mkv->sps == NULL)
1705                 return -1;
1706             p_mkv->sps_len = i_size - 4;
1707             memcpy(p_mkv->sps, p_nalu + 4, i_size - 4);
1708         }
1709         break;
1710
1711     // pps
1712     case 0x08:
1713         if( !p_mkv->pps )
1714         {
1715             p_mkv->pps = malloc(i_size - 4);
1716             if (p_mkv->pps == NULL)
1717                 return -1;
1718             p_mkv->pps_len = i_size - 4;
1719             memcpy(p_mkv->pps, p_nalu + 4, i_size - 4);
1720         }
1721         break;
1722
1723     // slice, sei
1724     case 0x1:
1725     case 0x5:
1726     case 0x6:
1727         if( !p_mkv->b_writing_frame )
1728         {
1729             if( mk_startFrame(p_mkv->w) < 0 )
1730                 return -1;
1731             p_mkv->b_writing_frame = 1;
1732         }
1733         psize = i_size - 4 ;
1734         dsize[0] = psize >> 16;
1735         dsize[1] = psize >> 8;
1736         dsize[2] = psize;
1737         if( mk_addFrameData(p_mkv->w, dsize, 3) < 0 ||
1738             mk_addFrameData(p_mkv->w, p_nalu + 4, i_size - 4) < 0 )
1739             return -1;
1740         break;
1741
1742     default:
1743         break;
1744     }
1745
1746     if( !p_mkv->b_header_written && p_mkv->pps && p_mkv->sps &&
1747         write_header_mkv(p_mkv) < 0 )
1748         return -1;
1749
1750     return i_size;
1751 }
1752
1753 static int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture )
1754 {
1755     mkv_t *p_mkv = handle;
1756     int64_t i_stamp = (int64_t)(p_picture->i_pts * 1e9 / p_mkv->fps_num);
1757
1758     p_mkv->b_writing_frame = 0;
1759
1760     return mk_setFrameFlags( p_mkv->w, i_stamp,
1761                              p_picture->i_type == X264_TYPE_IDR );
1762 }
1763
1764 static int close_file_mkv( hnd_t handle )
1765 {
1766     mkv_t *p_mkv = handle;
1767     int   ret;
1768
1769     if( p_mkv->sps )
1770         free( p_mkv->sps );
1771     if( p_mkv->pps )
1772         free( p_mkv->pps );
1773
1774     ret = mk_close(p_mkv->w);
1775
1776     free( p_mkv );
1777
1778     return ret;
1779 }
1780