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