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