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