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