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