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 $
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
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.
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.
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 *****************************************************************************/
35 #include <io.h> /* _setmode() */
36 #include <fcntl.h> /* _O_BINARY */
45 #include <gpac/isomedia.h>
49 #include "common/common.h"
58 #define DATA_MAX 3000000
59 uint8_t data[DATA_MAX];
64 static int b_ctrl_c = 0;
65 static int b_exit_on_ctrl_c = 0;
66 static void SigIntHandler( int a )
68 if( b_exit_on_ctrl_c )
81 /* input file operation function pointers */
82 static int (*p_open_infile)( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
83 static int (*p_get_frame_total)( hnd_t handle, int i_width, int i_height );
84 static int (*p_read_frame)( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
85 static int (*p_close_infile)( hnd_t handle );
87 static int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
88 static int get_frame_total_yuv( hnd_t handle, int i_width, int i_height );
89 static int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
90 static int close_file_yuv( hnd_t handle );
93 static int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param );
94 static int get_frame_total_avis( hnd_t handle, int i_width, int i_height );
95 static int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height );
96 static int close_file_avis( hnd_t handle );
99 /* output file operation function pointers */
100 static int (*p_open_outfile)( char *psz_filename, hnd_t *p_handle );
101 static int (*p_set_outfile_param)( hnd_t handle, x264_param_t *p_param );
102 static int (*p_write_nalu)( hnd_t handle, uint8_t *p_nal, int i_size );
103 static int (*p_set_eop)( hnd_t handle, x264_picture_t *p_picture );
104 static int (*p_close_outfile)( hnd_t handle );
106 static int open_file_bsf( char *psz_filename, hnd_t *p_handle );
107 static int set_param_bsf( hnd_t handle, x264_param_t *p_param );
108 static int write_nalu_bsf( hnd_t handle, uint8_t *p_nal, int i_size );
109 static int set_eop_bsf( hnd_t handle, x264_picture_t *p_picture );
110 static int close_file_bsf( hnd_t handle );
113 static int open_file_mp4( char *psz_filename, hnd_t *p_handle );
114 static int set_param_mp4( hnd_t handle, x264_param_t *p_param );
115 static int write_nalu_mp4( hnd_t handle, uint8_t *p_nal, int i_size );
116 static int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture );
117 static int close_file_mp4( hnd_t handle );
120 static int open_file_mkv( char *psz_filename, hnd_t *p_handle );
121 static int set_param_mkv( hnd_t handle, x264_param_t *p_param );
122 static int write_nalu_mkv( hnd_t handle, uint8_t *p_nal, int i_size );
123 static int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture );
124 static int close_file_mkv( hnd_t handle );
126 static void Help( x264_param_t *defaults );
127 static int Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
128 static int Encode( x264_param_t *param, cli_opt_t *opt );
131 /****************************************************************************
133 ****************************************************************************/
134 int main( int argc, char **argv )
140 _setmode(_fileno(stdin), _O_BINARY); /* thanks to Marcos Morais <morais at dee.ufcg.edu.br> */
141 _setmode(_fileno(stdout), _O_BINARY);
144 x264_param_default( ¶m );
146 /* Parse command line */
147 if( Parse( argc, argv, ¶m, &opt ) < 0 )
150 /* Control-C handler */
151 signal( SIGINT, SigIntHandler );
153 return Encode( ¶m, &opt );
156 static const char * const overscan_str[] = { "undef", "show", "crop", NULL };
157 static const char * const vidformat_str[] = { "component", "pal", "ntsc", "secam", "mac", "undef", NULL };
158 static const char * const fullrange_str[] = { "off", "on", NULL };
159 static const char * const colorprim_str[] = { "", "bt709", "undef", "", "bt470m", "bt470bg", "smpte170m", "smpte240m", "film", NULL };
160 static const char * const transfer_str[] = { "", "bt709", "undef", "", "bt470m", "bt470bg", "smpte170m", "smpte240m", "linear", "log100", "log316", NULL };
161 static const char * const colmatrix_str[] = { "GBR", "bt709", "undef", "", "fcc", "bt470bg", "smpte170m", "smpte240m", "YCgCo", NULL };
163 static char const *strtable_lookup( const char * const table[], int index )
165 int i = 0; while( table[i] ) i++;
166 return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
169 /*****************************************************************************
171 *****************************************************************************/
172 static void Help( x264_param_t *defaults )
176 "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
178 "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
179 " or AVI or Avisynth if compiled with AVIS support (%s).\n"
180 "Outfile type is selected by filename:\n"
181 " .264 -> Raw bytestream\n"
182 " .mkv -> Matroska\n"
183 " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
187 " -h, --help Print this help\n"
189 "Frame-type options:\n"
191 " -I, --keyint <integer> Maximum GOP size [%d]\n"
192 " -i, --min-keyint <integer> Minimum GOP size [%d]\n"
193 " --scenecut <integer> How aggressively to insert extra I-frames [%d]\n"
194 " -b, --bframes <integer> Number of B-frames between I and P [%d]\n"
195 " --no-b-adapt Disable adaptive B-frame decision\n"
196 " --b-bias <integer> Influences how often B-frames are used [%d]\n"
197 " --b-pyramid Keep some B-frames as references\n"
199 " --no-cabac Disable CABAC\n"
200 " -r, --ref <integer> Number of reference frames [%d]\n"
201 " --nf Disable loop filter\n"
202 " -f, --filter <alpha:beta> Loop filter AlphaC0 and Beta parameters [%d:%d]\n"
206 " -q, --qp <integer> Set QP (0=lossless) [%d]\n"
207 " -B, --bitrate <integer> Set bitrate\n"
208 " --crf <integer> Quality-based VBR (nominal QP)\n"
209 " --qpmin <integer> Set min QP [%d]\n"
210 " --qpmax <integer> Set max QP [%d]\n"
211 " --qpstep <integer> Set max QP step [%d]\n"
212 " --ratetol <float> Allowed variance of average bitrate [%.1f]\n"
213 " --vbv-maxrate <integer> Max local bitrate [%d]\n"
214 " --vbv-bufsize <integer> Size of VBV buffer [%d]\n"
215 " --vbv-init <float> Initial VBV buffer occupancy [%.1f]\n"
217 " --ipratio <float> QP factor between I and P [%.2f]\n"
218 " --pbratio <float> QP factor between P and B [%.2f]\n"
219 " --chroma-qp-offset <integer> QP difference between chroma and luma [%d]\n"
221 " -p, --pass <1|2|3> Enable multipass ratecontrol:\n"
222 " - 1: First pass, creates stats file\n"
223 " - 2: Last pass, does not overwrite stats file\n"
224 " - 3: Nth pass, overwrites stats file\n"
225 " --stats <string> Filename for 2 pass stats [\"%s\"]\n"
226 " --rceq <string> Ratecontrol equation [\"%s\"]\n"
227 " --qcomp <float> QP curve compression: 0.0 => CBR, 1.0 => CQP [%.2f]\n"
228 " --cplxblur <float> Reduce fluctuations in QP (before curve compression) [%.1f]\n"
229 " --qblur <float> Reduce fluctuations in QP (after curve compression) [%.1f]\n"
231 " --zones <zone0>/<zone1>/...\n"
232 " Tweak the bitrate of some regions of the video\n"
233 " Each zone is of the form\n"
234 " <start frame>,<end frame>,<option>\n"
235 " where <option> is either\n"
236 " q=<integer> (force QP)\n"
237 " or b=<float> (bitrate multiplier)\n"
241 " -A, --analyse <string> Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
242 " - p8x8, p4x4, b8x8, i8x8, i4x4\n"
244 " (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n"
245 " --direct <string> Direct MV prediction mode [\"%s\"]\n"
246 " - none, spatial, temporal\n"
247 " -w, --weightb Weighted prediction for B-frames\n"
248 " --me <string> Integer pixel motion estimation method [\"%s\"]\n"
249 " - dia: diamond search, radius 1 (fast)\n"
250 " - hex: hexagonal search, radius 2\n"
251 " - umh: uneven multi-hexagon search\n"
252 " - esa: exhaustive search (slow)\n"
253 " --merange <integer> Maximum motion vector search range [%d]\n"
254 " -m, --subme <integer> Subpixel motion estimation and partition\n"
255 " decision quality: 1=fast, 6=best. [%d]\n"
256 " --mixed-refs Decide references on a per partition basis\n"
257 " --no-chroma-me Ignore chroma in motion estimation\n"
258 " -8, --8x8dct Adaptive spatial transform size\n"
260 " --cqm <string> Preset quant matrices [\"flat\"]\n"
262 " --cqmfile <string> Read quant matrices from a JM-compatible file\n"
263 " Overrides any other --cqm* options.\n"
264 " --cqm4 <list> Set all 4x4 quant matrices\n"
265 " Takes a comma-separated list of 16 integers.\n"
266 " --cqm8 <list> Set all 8x8 quant matrices\n"
267 " Takes a comma-separated list of 64 integers.\n"
268 " --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
269 " Set both luma and chroma quant matrices\n"
270 " --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
271 " Set individual quant matrices\n"
273 "Video Usability Info (Annex E):\n"
274 "The VUI settings are not used by the encoder but are merely suggestions to\n"
275 "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n"
277 " --sar width:height Specify Sample Aspect Ratio\n"
278 " --overscan <string> Specify crop overscan setting [\"%s\"]\n"
279 " - undef, show, crop\n"
280 " --videoformat <string> Specify video format [\"%s\"]\n"
281 " - component, pal, ntsc, secam, mac, undef\n"
282 " --fullrange <string> Specify full range samples setting [\"%s\"]\n"
284 " --colorprim <string> Specify color primaries [\"%s\"]\n"
285 " - undef, bt709, bt470m, bt470bg\n"
286 " smpte170m, smpte240m, film\n"
287 " --transfer <string> Specify transfer characteristics [\"%s\"]\n"
288 " - undef, bt709, bt470m, bt470bg, linear,\n"
289 " log100, log316, smpte170m, smpte240m\n"
290 " --colormatrix <string> Specify color matrix setting [\"%s\"]\n"
291 " - undef, bt709, fcc, bt470bg\n"
292 " smpte170m, smpte240m, GBR, YCgCo\n"
293 " --chromaloc <integer> Specify chroma sample location (0 to 5) [%d]\n"
297 " --level <integer> Specify level (as defined by Annex A)\n"
298 " --fps <float|rational> Specify framerate\n"
299 " --seek <integer> First frame to encode\n"
300 " --frames <integer> Maximum number of frames to encode\n"
301 " -o, --output Specify output file\n"
303 " --threads <integer> Parallel encoding (uses slices)\n"
304 " --no-asm Disable all CPU optimizations\n"
305 " --no-psnr Disable PSNR computation\n"
306 " --quiet Quiet Mode\n"
307 " -v, --verbose Print stats for each frame\n"
308 " --progress Show a progress indicator while encoding\n"
309 " --visualize Show MB types overlayed on the encoded video\n"
310 " --aud Use access unit delimiters\n"
312 X264_BUILD, X264_VERSION,
323 defaults->i_keyint_max,
324 defaults->i_keyint_min,
325 defaults->i_scenecut_threshold,
327 defaults->i_bframe_bias,
328 defaults->i_frame_reference,
329 defaults->i_deblocking_filter_alphac0,
330 defaults->i_deblocking_filter_beta,
331 defaults->rc.i_qp_constant,
332 defaults->rc.i_qp_min,
333 defaults->rc.i_qp_max,
334 defaults->rc.i_qp_step,
335 defaults->rc.f_rate_tolerance,
336 defaults->rc.i_vbv_max_bitrate,
337 defaults->rc.i_vbv_buffer_size,
338 defaults->rc.f_vbv_buffer_init,
339 defaults->rc.f_ip_factor,
340 defaults->rc.f_pb_factor,
341 defaults->analyse.i_chroma_qp_offset,
342 defaults->rc.psz_stat_out,
343 defaults->rc.psz_rc_eq,
344 defaults->rc.f_qcompress,
345 defaults->rc.f_complexity_blur,
346 defaults->rc.f_qblur,
347 strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ),
348 strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ),
349 defaults->analyse.i_me_range,
350 defaults->analyse.i_subpel_refine,
351 strtable_lookup( overscan_str, defaults->vui.i_overscan ),
352 strtable_lookup( vidformat_str, defaults->vui.i_vidformat ),
353 strtable_lookup( fullrange_str, defaults->vui.b_fullrange ),
354 strtable_lookup( colorprim_str, defaults->vui.i_colorprim ),
355 strtable_lookup( transfer_str, defaults->vui.i_transfer ),
356 strtable_lookup( colmatrix_str, defaults->vui.i_colmatrix ),
357 defaults->vui.i_chroma_loc
361 static int parse_enum( const char *arg, const char * const *names, int *dst )
364 for( i = 0; names[i]; i++ )
365 if( !strcmp( arg, names[i] ) )
373 static int parse_cqm( const char *str, uint8_t *cqm, int length )
378 if( !sscanf( str, "%d", &coef ) || coef < 1 || coef > 255 )
381 } while( i < length && (str = strchr( str, ',' )) && str++ );
382 return (i == length) ? 0 : -1;
385 /*****************************************************************************
387 *****************************************************************************/
388 static int Parse( int argc, char **argv,
389 x264_param_t *param, cli_opt_t *opt )
391 char *psz_filename = NULL;
392 x264_param_t defaults = *param;
396 memset( opt, 0, sizeof(cli_opt_t) );
398 /* Default input file driver */
399 p_open_infile = open_file_yuv;
400 p_get_frame_total = get_frame_total_yuv;
401 p_read_frame = read_frame_yuv;
402 p_close_infile = close_file_yuv;
404 /* Default output file driver */
405 p_open_outfile = open_file_bsf;
406 p_set_outfile_param = set_param_bsf;
407 p_write_nalu = write_nalu_bsf;
408 p_set_eop = set_eop_bsf;
409 p_close_outfile = close_file_bsf;
411 /* Parse command line options */
412 opterr = 0; // no error message
416 int long_options_index;
417 #define OPT_QPMIN 256
418 #define OPT_QPMAX 257
419 #define OPT_QPSTEP 258
420 #define OPT_IPRATIO 260
421 #define OPT_PBRATIO 261
422 #define OPT_RATETOL 262
423 #define OPT_RCSTATS 264
425 #define OPT_QCOMP 266
426 #define OPT_NOPSNR 267
427 #define OPT_QUIET 268
428 #define OPT_SCENECUT 270
429 #define OPT_QBLUR 271
430 #define OPT_CPLXBLUR 272
431 #define OPT_FRAMES 273
433 #define OPT_DIRECT 275
434 #define OPT_LEVEL 276
435 #define OPT_NOBADAPT 277
436 #define OPT_BBIAS 278
437 #define OPT_BPYRAMID 279
438 #define OPT_CHROMA_QP 280
439 #define OPT_NO_CHROMA_ME 281
440 #define OPT_NO_CABAC 282
442 #define OPT_PROGRESS 284
444 #define OPT_MERANGE 286
445 #define OPT_VBVMAXRATE 287
446 #define OPT_VBVBUFSIZE 288
447 #define OPT_VBVINIT 289
448 #define OPT_VISUALIZE 290
450 #define OPT_ZONES 292
451 #define OPT_THREADS 293
454 #define OPT_CQM4I 296
455 #define OPT_CQM4IY 297
456 #define OPT_CQM4IC 298
457 #define OPT_CQM4P 299
458 #define OPT_CQM4PY 300
459 #define OPT_CQM4PC 301
461 #define OPT_CQM8I 303
462 #define OPT_CQM8P 304
463 #define OPT_CQMFILE 305
465 #define OPT_OVERSCAN 307
466 #define OPT_VIDFORMAT 308
467 #define OPT_FULLRANGE 309
468 #define OPT_COLOURPRIM 310
469 #define OPT_TRANSFER 311
470 #define OPT_COLOURMATRIX 312
471 #define OPT_CHROMALOC 313
472 #define OPT_MIXED_REFS 314
475 static struct option long_options[] =
477 { "help", no_argument, NULL, 'h' },
478 { "bitrate", required_argument, NULL, 'B' },
479 { "bframes", required_argument, NULL, 'b' },
480 { "no-b-adapt", no_argument, NULL, OPT_NOBADAPT },
481 { "b-bias", required_argument, NULL, OPT_BBIAS },
482 { "b-pyramid", no_argument, NULL, OPT_BPYRAMID },
483 { "min-keyint",required_argument,NULL,'i' },
484 { "keyint", required_argument, NULL, 'I' },
485 { "scenecut",required_argument, NULL, OPT_SCENECUT },
486 { "nf", no_argument, NULL, 'n' },
487 { "filter", required_argument, NULL, 'f' },
488 { "no-cabac",no_argument, NULL, OPT_NO_CABAC },
489 { "qp", required_argument, NULL, 'q' },
490 { "qpmin", required_argument, NULL, OPT_QPMIN },
491 { "qpmax", required_argument, NULL, OPT_QPMAX },
492 { "qpstep", required_argument, NULL, OPT_QPSTEP },
493 { "crf", required_argument, NULL, OPT_CRF },
494 { "ref", required_argument, NULL, 'r' },
495 { "no-asm", no_argument, NULL, 'C' },
496 { "sar", required_argument, NULL, OPT_SAR },
497 { "fps", required_argument, NULL, OPT_FPS },
498 { "frames", required_argument, NULL, OPT_FRAMES },
499 { "seek", required_argument, NULL, OPT_SEEK },
500 { "output", required_argument, NULL, 'o' },
501 { "analyse", required_argument, NULL, 'A' },
502 { "direct", required_argument, NULL, OPT_DIRECT },
503 { "weightb", no_argument, NULL, 'w' },
504 { "me", required_argument, NULL, OPT_ME },
505 { "merange", required_argument, NULL, OPT_MERANGE },
506 { "subme", required_argument, NULL, 'm' },
507 { "mixed-refs", no_argument, NULL, OPT_MIXED_REFS },
508 { "no-chroma-me", no_argument, NULL, OPT_NO_CHROMA_ME },
509 { "8x8dct", no_argument, NULL, '8' },
510 { "level", required_argument, NULL, OPT_LEVEL },
511 { "ratetol", required_argument, NULL, OPT_RATETOL },
512 { "vbv-maxrate", required_argument, NULL, OPT_VBVMAXRATE },
513 { "vbv-bufsize", required_argument, NULL, OPT_VBVBUFSIZE },
514 { "vbv-init", required_argument,NULL, OPT_VBVINIT },
515 { "ipratio", required_argument, NULL, OPT_IPRATIO },
516 { "pbratio", required_argument, NULL, OPT_PBRATIO },
517 { "chroma-qp-offset", required_argument, NULL, OPT_CHROMA_QP },
518 { "pass", required_argument, NULL, 'p' },
519 { "stats", required_argument, NULL, OPT_RCSTATS },
520 { "rceq", required_argument, NULL, OPT_RCEQ },
521 { "qcomp", required_argument, NULL, OPT_QCOMP },
522 { "qblur", required_argument, NULL, OPT_QBLUR },
523 { "cplxblur",required_argument, NULL, OPT_CPLXBLUR },
524 { "zones", required_argument, NULL, OPT_ZONES },
525 { "threads", required_argument, NULL, OPT_THREADS },
526 { "no-psnr", no_argument, NULL, OPT_NOPSNR },
527 { "quiet", no_argument, NULL, OPT_QUIET },
528 { "verbose", no_argument, NULL, 'v' },
529 { "progress",no_argument, NULL, OPT_PROGRESS },
530 { "visualize",no_argument, NULL, OPT_VISUALIZE },
531 { "aud", no_argument, NULL, OPT_AUD },
532 { "cqm", required_argument, NULL, OPT_CQM },
533 { "cqmfile", required_argument, NULL, OPT_CQMFILE },
534 { "cqm4", required_argument, NULL, OPT_CQM4 },
535 { "cqm4i", required_argument, NULL, OPT_CQM4I },
536 { "cqm4iy", required_argument, NULL, OPT_CQM4IY },
537 { "cqm4ic", required_argument, NULL, OPT_CQM4IC },
538 { "cqm4p", required_argument, NULL, OPT_CQM4P },
539 { "cqm4py", required_argument, NULL, OPT_CQM4PY },
540 { "cqm4pc", required_argument, NULL, OPT_CQM4PC },
541 { "cqm8", required_argument, NULL, OPT_CQM8 },
542 { "cqm8i", required_argument, NULL, OPT_CQM8I },
543 { "cqm8p", required_argument, NULL, OPT_CQM8P },
544 { "overscan", required_argument, NULL, OPT_OVERSCAN },
545 { "videoformat", required_argument, NULL, OPT_VIDFORMAT },
546 { "fullrange", required_argument, NULL, OPT_FULLRANGE },
547 { "colorprim", required_argument, NULL, OPT_COLOURPRIM },
548 { "transfer", required_argument, NULL, OPT_TRANSFER },
549 { "colormatrix", required_argument, NULL, OPT_COLOURMATRIX },
550 { "chromaloc", required_argument, NULL, OPT_CHROMALOC },
556 c = getopt_long( argc, argv, "hi:I:b:r:cxB:q:f:o:A:m:p:vw8",
557 long_options, &long_options_index);
573 param->rc.i_bitrate = atol( optarg );
577 param->rc.i_rf_constant = atol( optarg );
580 param->i_bframe = atol( optarg );
583 param->b_bframe_adaptive = 0;
586 param->i_bframe_bias = atol( optarg );
589 param->b_bframe_pyramid = 1;
592 param->i_keyint_min = atol( optarg );
593 if( param->i_keyint_max < param->i_keyint_min )
594 param->i_keyint_max = param->i_keyint_min;
597 param->i_keyint_max = atol( optarg );
598 if( param->i_keyint_min > param->i_keyint_max )
599 param->i_keyint_min = param->i_keyint_max;
602 param->i_scenecut_threshold = atol( optarg );
605 param->b_deblocking_filter = 0;
609 char *p = strchr( optarg, ':' );
610 param->i_deblocking_filter_alphac0 = atoi( optarg );
611 param->i_deblocking_filter_beta = p ? atoi( p+1 ) : param->i_deblocking_filter_alphac0;
615 param->rc.i_qp_constant = atoi( optarg );
618 param->rc.i_qp_min = atoi( optarg );
621 param->rc.i_qp_max = atoi( optarg );
624 param->rc.i_qp_step = atoi( optarg );
627 param->i_frame_reference = atoi( optarg );
633 opt->b_decompress = 1;
639 param->i_frame_total = atoi( optarg );
642 opt->i_seek = atoi( optarg );
645 if( !strncasecmp(optarg + strlen(optarg) - 4, ".mp4", 4) )
648 p_open_outfile = open_file_mp4;
649 p_write_nalu = write_nalu_mp4;
650 p_set_outfile_param = set_param_mp4;
651 p_set_eop = set_eop_mp4;
652 p_close_outfile = close_file_mp4;
654 fprintf( stderr, "not compiled with MP4 output support\n" );
658 else if( !strncasecmp(optarg + strlen(optarg) - 4, ".mkv", 4) )
660 p_open_outfile = open_file_mkv;
661 p_write_nalu = write_nalu_mkv;
662 p_set_outfile_param = set_param_mkv;
663 p_set_eop = set_eop_mkv;
664 p_close_outfile = close_file_mkv;
666 if( !strcmp(optarg, "-") )
668 else if( p_open_outfile( optarg, &opt->hout ) )
670 fprintf( stderr, "cannot open output file `%s'\n", optarg );
676 char *p = strchr( optarg, ':' );
679 param->vui.i_sar_width = atoi( optarg );
680 param->vui.i_sar_height = atoi( p + 1 );
687 if( sscanf( optarg, "%d/%d", ¶m->i_fps_num, ¶m->i_fps_den ) == 2 )
689 else if( sscanf( optarg, "%f", &fps ) )
691 param->i_fps_num = (int)(fps * 1000 + .5);
692 param->i_fps_den = 1000;
696 fprintf( stderr, "bad fps `%s'\n", optarg );
702 param->analyse.inter = 0;
703 if( strstr( optarg, "none" ) ) param->analyse.inter = 0;
704 if( strstr( optarg, "all" ) ) param->analyse.inter = ~0;
706 if( strstr( optarg, "i4x4" ) ) param->analyse.inter |= X264_ANALYSE_I4x4;
707 if( strstr( optarg, "i8x8" ) ) param->analyse.inter |= X264_ANALYSE_I8x8;
708 if( strstr( optarg, "p8x8" ) ) param->analyse.inter |= X264_ANALYSE_PSUB16x16;
709 if( strstr( optarg, "p4x4" ) ) param->analyse.inter |= X264_ANALYSE_PSUB8x8;
710 if( strstr( optarg, "b8x8" ) ) param->analyse.inter |= X264_ANALYSE_BSUB16x16;
713 b_error |= parse_enum( optarg, x264_direct_pred_names, ¶m->analyse.i_direct_mv_pred );
716 param->analyse.b_weighted_bipred = 1;
719 b_error |= parse_enum( optarg, x264_motion_est_names, ¶m->analyse.i_me_method );
722 param->analyse.i_me_range = atoi(optarg);
725 param->analyse.i_subpel_refine = atoi(optarg);
728 param->analyse.b_mixed_references = 1;
730 case OPT_NO_CHROMA_ME:
731 param->analyse.b_chroma_me = 0;
734 param->analyse.b_transform_8x8 = 1;
737 param->i_level_idc = atoi(optarg);
740 param->rc.f_rate_tolerance = !strncmp("inf", optarg, 3) ? 1e9 : atof(optarg);
743 param->rc.i_vbv_max_bitrate = atoi( optarg );
746 param->rc.i_vbv_buffer_size = atoi( optarg );
749 param->rc.f_vbv_buffer_init = atof(optarg);
752 param->rc.f_ip_factor = atof(optarg);
755 param->rc.f_pb_factor = atof(optarg);
758 param->analyse.i_chroma_qp_offset = atoi(optarg);
762 int i_pass = atoi(optarg);
764 param->rc.b_stat_write = 1;
765 else if( i_pass == 2 )
766 param->rc.b_stat_read = 1;
767 else if( i_pass > 2 )
768 param->rc.b_stat_read =
769 param->rc.b_stat_write = 1;
773 param->rc.psz_stat_in = optarg;
774 param->rc.psz_stat_out = optarg;
777 param->rc.psz_rc_eq = optarg;
780 param->rc.f_qcompress = atof(optarg);
783 param->rc.f_qblur = atof(optarg);
786 param->rc.f_complexity_blur = atof(optarg);
789 param->rc.psz_zones = optarg;
792 param->i_threads = atoi(optarg);
795 param->analyse.b_psnr = 0;
798 param->i_log_level = X264_LOG_NONE;
801 param->i_log_level = X264_LOG_DEBUG;
811 param->b_visualize = 1;
812 b_exit_on_ctrl_c = 1;
814 fprintf( stderr, "not compiled with visualization support\n" );
818 if( strstr( optarg, "flat" ) )
819 param->i_cqm_preset = X264_CQM_FLAT;
820 else if( strstr( optarg, "jvt" ) )
821 param->i_cqm_preset = X264_CQM_JVT;
824 fprintf( stderr, "bad CQM preset `%s'\n", optarg );
829 param->psz_cqm_file = optarg;
832 param->i_cqm_preset = X264_CQM_CUSTOM;
833 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
834 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
835 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
836 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
839 param->i_cqm_preset = X264_CQM_CUSTOM;
840 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
841 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
844 param->i_cqm_preset = X264_CQM_CUSTOM;
845 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
846 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
849 param->i_cqm_preset = X264_CQM_CUSTOM;
850 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
851 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
854 param->i_cqm_preset = X264_CQM_CUSTOM;
855 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
858 param->i_cqm_preset = X264_CQM_CUSTOM;
859 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
862 param->i_cqm_preset = X264_CQM_CUSTOM;
863 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
866 param->i_cqm_preset = X264_CQM_CUSTOM;
867 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
870 param->i_cqm_preset = X264_CQM_CUSTOM;
871 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
874 param->i_cqm_preset = X264_CQM_CUSTOM;
875 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
878 b_error |= parse_enum( optarg, overscan_str, ¶m->vui.i_overscan );
881 b_error |= parse_enum( optarg, vidformat_str, ¶m->vui.i_vidformat );
884 b_error |= parse_enum( optarg, fullrange_str, ¶m->vui.b_fullrange );
887 b_error |= parse_enum( optarg, colorprim_str, ¶m->vui.i_colorprim );
890 b_error |= parse_enum( optarg, transfer_str, ¶m->vui.i_transfer );
892 case OPT_COLOURMATRIX:
893 b_error |= parse_enum( optarg, colmatrix_str, ¶m->vui.i_colmatrix );
896 param->vui.i_chroma_loc = atoi( optarg );
897 b_error = ( param->vui.i_chroma_loc < 0 || param->vui.i_chroma_loc > 5 );
900 fprintf( stderr, "unknown option (%c)\n", optopt );
906 fprintf( stderr, "bad argument: %s %s\n", argv[optind-2], optarg );
911 /* Get the file name */
912 if( optind > argc - 1 || !opt->hout )
917 psz_filename = argv[optind++];
919 if( !opt->b_decompress )
921 if( optind > argc - 1 )
923 /* try to parse the file name */
924 for( psz = psz_filename; *psz; psz++ )
926 if( *psz >= '0' && *psz <= '9'
927 && sscanf( psz, "%ux%u", ¶m->i_width, ¶m->i_height ) == 2 )
929 if( param->i_log_level >= X264_LOG_INFO )
930 fprintf( stderr, "x264 [info]: file name gives %dx%d\n", param->i_width, param->i_height );
937 sscanf( argv[optind++], "%ux%u", ¶m->i_width, ¶m->i_height );
940 /* check avis input */
941 psz = psz_filename + strlen(psz_filename) - 1;
942 while( psz > psz_filename && *psz != '.' )
945 if( !strncasecmp( psz, ".avi", 4 ) || !strncasecmp( psz, ".avs", 4 ) )
948 if( !b_avis && ( !param->i_width || !param->i_height ) )
956 if( !strcmp( psz_filename, "-" ) )
966 p_open_infile = open_file_avis;
967 p_get_frame_total = get_frame_total_avis;
968 p_read_frame = read_frame_avis;
969 p_close_infile = close_file_avis;
971 fprintf( stderr, "not compiled with AVIS input support\n" );
975 if( p_open_infile( psz_filename, &opt->hin, param ) )
977 fprintf( stderr, "could not open input file '%s'\n", psz_filename );
985 /*****************************************************************************
987 *****************************************************************************/
989 static int Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
991 x264_picture_t pic_out;
996 /* Do not force any parameters */
999 pic->i_type = X264_TYPE_AUTO;
1002 if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
1004 fprintf( stderr, "x264_encoder_encode failed\n" );
1007 for( i = 0; i < i_nal; i++ )
1013 if( ( i_size = x264_nal_encode( data, &i_data, 1, &nal[i] ) ) > 0 )
1015 i_file += p_write_nalu( hout, data, i_size );
1017 else if( i_size < 0 )
1019 fprintf( stderr, "need to increase buffer size (size=%d)\n", -i_size );
1023 p_set_eop( hout, &pic_out );
1028 /*****************************************************************************
1030 *****************************************************************************/
1031 static int Encode( x264_param_t *param, cli_opt_t *opt )
1036 int i_frame, i_frame_total;
1037 int64_t i_start, i_end;
1042 i_frame_total = p_get_frame_total( opt->hin, param->i_width, param->i_height );
1043 i_frame_total -= opt->i_seek;
1044 if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
1045 && param->i_frame_total > 0 )
1046 i_frame_total = param->i_frame_total;
1047 param->i_frame_total = i_frame_total;
1049 if( ( h = x264_encoder_open( param ) ) == NULL )
1051 fprintf( stderr, "x264_encoder_open failed\n" );
1052 p_close_infile( opt->hin );
1053 p_close_outfile( opt->hout );
1057 if( p_set_outfile_param( opt->hout, param ) )
1059 fprintf( stderr, "can't set outfile param\n" );
1060 p_close_infile( opt->hin );
1061 p_close_outfile( opt->hout );
1065 /* Create a new pic */
1066 x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height );
1068 i_start = x264_mdate();
1071 for( i_frame = 0, i_file = 0, i_progress = 0;
1072 b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1074 if( p_read_frame( &pic, opt->hin, i_frame + opt->i_seek, param->i_width, param->i_height ) )
1077 pic.i_pts = (int64_t)i_frame * param->i_fps_den;
1079 i_file += Encode_frame( h, opt->hout, &pic );
1083 /* update status line (up to 1000 times per input file) */
1084 if( opt->b_progress && param->i_log_level < X264_LOG_DEBUG &&
1085 ( i_frame_total ? i_frame * 1000 / i_frame_total > i_progress
1086 : i_frame % 10 == 0 ) )
1088 int64_t i_elapsed = x264_mdate() - i_start;
1089 double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1092 i_progress = i_frame * 1000 / i_frame_total;
1093 fprintf( stderr, "encoded frames: %d/%d (%.1f%%), %.2f fps \r", i_frame,
1094 i_frame_total, (float)i_progress / 10, fps );
1097 fprintf( stderr, "encoded frames: %d, %.2f fps \r", i_frame, fps );
1098 fflush( stderr ); // needed in windows
1101 /* Flush delayed B-frames */
1104 i_frame_size = Encode_frame( h, opt->hout, NULL );
1105 } while( i_frame_size );
1107 i_end = x264_mdate();
1108 x264_picture_clean( &pic );
1109 x264_encoder_close( h );
1110 fprintf( stderr, "\n" );
1113 fprintf( stderr, "aborted at input frame %d\n", opt->i_seek + i_frame );
1115 p_close_infile( opt->hin );
1116 p_close_outfile( opt->hout );
1120 double fps = (double)i_frame * (double)1000000 /
1121 (double)( i_end - i_start );
1123 fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame, fps,
1124 (double) i_file * 8 * param->i_fps_num / ( param->i_fps_den * i_frame * 1000 ) );
1130 /* raw 420 yuv file operation */
1131 static int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1133 if ((*p_handle = fopen(psz_filename, "rb")) == NULL)
1138 static int get_frame_total_yuv( hnd_t handle, int i_width, int i_height )
1140 FILE *f = (FILE *)handle;
1141 int i_frame_total = 0;
1143 if( !fseek( f, 0, SEEK_END ) )
1145 int64_t i_size = ftell( f );
1146 fseek( f, 0, SEEK_SET );
1147 i_frame_total = (int)(i_size / ( i_width * i_height * 3 / 2 ));
1150 return i_frame_total;
1153 static int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1155 static int prev_frame = -1;
1156 FILE *f = (FILE *)handle;
1158 if( i_frame != prev_frame+1 )
1159 if( fseek( f, i_frame * i_width * i_height * 3 / 2, SEEK_SET ) )
1162 if( fread( p_pic->img.plane[0], 1, i_width * i_height, f ) <= 0
1163 || fread( p_pic->img.plane[1], 1, i_width * i_height / 4, f ) <= 0
1164 || fread( p_pic->img.plane[2], 1, i_width * i_height / 4, f ) <= 0 )
1167 prev_frame = i_frame;
1172 static int close_file_yuv(hnd_t handle)
1176 return fclose((FILE *)handle);
1180 /* avs/avi input file support under cygwin */
1184 static int gcd(int a, int b)
1198 static int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1201 PAVISTREAM p_avi = NULL;
1207 if( AVIStreamOpenFromFile( &p_avi, psz_filename, streamtypeVIDEO, 0, OF_READ, NULL ) )
1213 if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1215 AVIStreamRelease(p_avi);
1220 // check input format
1221 if (info.fccHandler != MAKEFOURCC('Y', 'V', '1', '2'))
1223 fprintf( stderr, "avis [error]: unsupported input format (%c%c%c%c)\n",
1224 (char)(info.fccHandler & 0xff), (char)((info.fccHandler >> 8) & 0xff),
1225 (char)((info.fccHandler >> 16) & 0xff), (char)((info.fccHandler >> 24)) );
1227 AVIStreamRelease(p_avi);
1233 p_param->i_width = info.rcFrame.right - info.rcFrame.left;
1234 p_param->i_height = info.rcFrame.bottom - info.rcFrame.top;
1235 i = gcd(info.dwRate, info.dwScale);
1236 p_param->i_fps_den = info.dwScale / i;
1237 p_param->i_fps_num = info.dwRate / i;
1239 fprintf( stderr, "avis [info]: %dx%d @ %.2f fps (%d frames)\n",
1240 p_param->i_width, p_param->i_height,
1241 (double)p_param->i_fps_num / (double)p_param->i_fps_den,
1242 (int)info.dwLength );
1244 *p_handle = (hnd_t)p_avi;
1249 static int get_frame_total_avis( hnd_t handle, int i_width, int i_height )
1251 PAVISTREAM p_avi = (PAVISTREAM)handle;
1254 if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1257 return info.dwLength;
1260 static int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1262 PAVISTREAM p_avi = (PAVISTREAM)handle;
1264 p_pic->img.i_csp = X264_CSP_YV12;
1266 if( AVIStreamRead(p_avi, i_frame, 1, p_pic->img.plane[0], i_width * i_height * 3 / 2, NULL, NULL ) )
1272 static int close_file_avis( hnd_t handle )
1274 PAVISTREAM p_avi = (PAVISTREAM)handle;
1276 AVIStreamRelease(p_avi);
1285 static int open_file_bsf( char *psz_filename, hnd_t *p_handle )
1287 if ((*p_handle = fopen(psz_filename, "w+b")) == NULL)
1293 static int set_param_bsf( hnd_t handle, x264_param_t *p_param )
1298 static int write_nalu_bsf( hnd_t handle, uint8_t *p_nalu, int i_size )
1300 if (fwrite(p_nalu, i_size, 1, (FILE *)handle) > 0)
1305 static int set_eop_bsf( hnd_t handle, x264_picture_t *p_picture )
1310 static int close_file_bsf( hnd_t handle )
1312 if ((handle == NULL) || (handle == stdout))
1315 return fclose((FILE *)handle);
1318 /* -- mp4 muxing support ------------------------------------------------- */
1324 GF_AVCConfig *p_config;
1325 GF_ISOSample *p_sample;
1337 static void recompute_bitrate_mp4(GF_ISOFile *p_file, int i_track)
1339 u32 i, count, di, timescale, time_wnd, rate;
1344 esd = gf_isom_get_esd(p_file, i_track, 1);
1347 esd->decoderConfig->avgBitrate = 0;
1348 esd->decoderConfig->maxBitrate = 0;
1349 rate = time_wnd = 0;
1351 timescale = gf_isom_get_media_timescale(p_file, i_track);
1352 count = gf_isom_get_sample_count(p_file, i_track);
1353 for (i=0; i<count; i++) {
1354 GF_ISOSample *samp = gf_isom_get_sample_info(p_file, i_track, i+1, &di, &offset);
1356 if (samp->dataLength>esd->decoderConfig->bufferSizeDB) esd->decoderConfig->bufferSizeDB = samp->dataLength;
1358 if (esd->decoderConfig->bufferSizeDB < samp->dataLength) esd->decoderConfig->bufferSizeDB = samp->dataLength;
1359 esd->decoderConfig->avgBitrate += samp->dataLength;
1360 rate += samp->dataLength;
1361 if (samp->DTS > time_wnd + timescale) {
1362 if (rate > esd->decoderConfig->maxBitrate) esd->decoderConfig->maxBitrate = rate;
1363 time_wnd = samp->DTS;
1367 gf_isom_sample_del(&samp);
1370 br = (Double) (s64) gf_isom_get_media_duration(p_file, i_track);
1372 esd->decoderConfig->avgBitrate = (u32) (esd->decoderConfig->avgBitrate / br);
1374 esd->decoderConfig->avgBitrate *= 8;
1375 esd->decoderConfig->maxBitrate *= 8;
1377 gf_isom_change_mpeg4_description(p_file, i_track, 1, esd);
1378 gf_odf_desc_del((GF_Descriptor *) esd);
1382 static int close_file_mp4( hnd_t handle )
1384 mp4_t *p_mp4 = (mp4_t *)handle;
1389 if (p_mp4->p_config)
1390 gf_odf_avc_cfg_del(p_mp4->p_config);
1392 if (p_mp4->p_sample)
1394 if (p_mp4->p_sample->data)
1395 free(p_mp4->p_sample->data);
1397 gf_isom_sample_del(&p_mp4->p_sample);
1402 recompute_bitrate_mp4(p_mp4->p_file, p_mp4->i_track);
1403 gf_isom_set_pl_indication(p_mp4->p_file, GF_ISOM_PL_VISUAL, 0x15);
1404 gf_isom_set_storage_mode(p_mp4->p_file, GF_ISOM_STORE_FLAT);
1405 gf_isom_close(p_mp4->p_file);
1413 static int open_file_mp4( char *psz_filename, hnd_t *p_handle )
1419 if ((p_mp4 = (mp4_t *)malloc(sizeof(mp4_t))) == NULL)
1422 memset(p_mp4, 0, sizeof(mp4_t));
1423 p_mp4->p_file = gf_isom_open(psz_filename, GF_ISOM_OPEN_WRITE, NULL);
1425 if ((p_mp4->p_sample = gf_isom_sample_new()) == NULL)
1427 close_file_mp4( p_mp4 );
1431 gf_isom_set_brand_info(p_mp4->p_file, GF_ISOM_BRAND_AVC1, 0);
1439 static int set_param_mp4( hnd_t handle, x264_param_t *p_param )
1441 mp4_t *p_mp4 = (mp4_t *)handle;
1443 p_mp4->i_track = gf_isom_new_track(p_mp4->p_file, 0, GF_ISOM_MEDIA_VISUAL,
1444 p_param->i_fps_num);
1446 p_mp4->p_config = gf_odf_avc_cfg_new();
1447 gf_isom_avc_config_new(p_mp4->p_file, p_mp4->i_track, p_mp4->p_config,
1448 NULL, NULL, &p_mp4->i_descidx);
1450 gf_isom_set_visual_info(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx,
1451 p_param->i_width, p_param->i_height);
1453 p_mp4->p_sample->data = (char *)malloc(p_param->i_width * p_param->i_height * 3 / 2);
1454 if (p_mp4->p_sample->data == NULL)
1457 p_mp4->i_time_res = p_param->i_fps_num;
1458 p_mp4->i_time_inc = p_param->i_fps_den;
1459 p_mp4->i_init_delay = p_param->i_bframe ? (p_param->b_bframe_pyramid ? 2 : 1) : 0;
1460 p_mp4->i_init_delay *= p_mp4->i_time_inc;
1461 fprintf(stderr, "mp4 [info]: initial delay %d (scale %d)\n",
1462 p_mp4->i_init_delay, p_mp4->i_time_res);
1468 static int write_nalu_mp4( hnd_t handle, uint8_t *p_nalu, int i_size )
1470 mp4_t *p_mp4 = (mp4_t *)handle;
1471 GF_AVCConfigSlot *p_slot;
1472 uint8_t type = p_nalu[4] & 0x1f;
1481 p_mp4->p_config->configurationVersion = 1;
1482 p_mp4->p_config->AVCProfileIndication = p_nalu[5];
1483 p_mp4->p_config->profile_compatibility = p_nalu[6];
1484 p_mp4->p_config->AVCLevelIndication = p_nalu[7];
1485 p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
1486 p_slot->size = i_size - 4;
1487 p_slot->data = (char *)malloc(p_slot->size);
1488 memcpy(p_slot->data, p_nalu + 4, i_size - 4);
1489 gf_list_add(p_mp4->p_config->sequenceParameterSets, p_slot);
1499 p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
1500 p_slot->size = i_size - 4;
1501 p_slot->data = (char *)malloc(p_slot->size);
1502 memcpy(p_slot->data, p_nalu + 4, i_size - 4);
1503 gf_list_add(p_mp4->p_config->pictureParameterSets, p_slot);
1507 gf_isom_avc_config_update(p_mp4->p_file, p_mp4->i_track, 1, p_mp4->p_config);
1515 psize = i_size - 4 ;
1516 memcpy(p_mp4->p_sample->data + p_mp4->p_sample->dataLength, p_nalu, i_size);
1517 p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 0] = (psize >> 24) & 0xff;
1518 p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 1] = (psize >> 16) & 0xff;
1519 p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 2] = (psize >> 8) & 0xff;
1520 p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 3] = (psize >> 0) & 0xff;
1521 p_mp4->p_sample->dataLength += i_size;
1528 static int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture )
1530 mp4_t *p_mp4 = (mp4_t *)handle;
1531 uint32_t dts = p_mp4->i_numframe * p_mp4->i_time_inc;
1532 uint32_t pts = p_picture->i_pts;
1533 int offset = p_mp4->i_init_delay + pts - dts;
1535 p_mp4->p_sample->IsRAP = p_picture->i_type == X264_TYPE_IDR ? 1 : 0;
1536 p_mp4->p_sample->DTS = dts;
1537 p_mp4->p_sample->CTS_Offset = offset;
1538 gf_isom_add_sample(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, p_mp4->p_sample);
1540 p_mp4->p_sample->dataLength = 0;
1541 p_mp4->i_numframe++;
1549 /* -- mkv muxing support ------------------------------------------------- */
1555 int sps_len, pps_len;
1557 int width, height, d_width, d_height;
1559 int64_t frame_duration;
1562 int b_header_written;
1563 char b_writing_frame;
1566 static int write_header_mkv( mkv_t *p_mkv )
1572 if( p_mkv->sps == NULL || p_mkv->pps == NULL ||
1573 p_mkv->width == 0 || p_mkv->height == 0 ||
1574 p_mkv->d_width == 0 || p_mkv->d_height == 0)
1577 avcC_len = 5 + 1 + 2 + p_mkv->sps_len + 1 + 2 + p_mkv->pps_len;
1578 avcC = malloc(avcC_len);
1583 avcC[1] = p_mkv->sps[1];
1584 avcC[2] = p_mkv->sps[2];
1585 avcC[3] = p_mkv->sps[3];
1586 avcC[4] = 0xfe; // nalu size length is three bytes
1587 avcC[5] = 0xe1; // one sps
1589 avcC[6] = p_mkv->sps_len >> 8;
1590 avcC[7] = p_mkv->sps_len;
1592 memcpy(avcC+8, p_mkv->sps, p_mkv->sps_len);
1594 avcC[8+p_mkv->sps_len] = 1; // one pps
1595 avcC[9+p_mkv->sps_len] = p_mkv->pps_len >> 8;
1596 avcC[10+p_mkv->sps_len] = p_mkv->pps_len;
1598 memcpy( avcC+11+p_mkv->sps_len, p_mkv->pps, p_mkv->pps_len );
1600 ret = mk_writeHeader( p_mkv->w, "x264", "V_MPEG4/ISO/AVC",
1601 avcC, avcC_len, p_mkv->frame_duration, 50000,
1602 p_mkv->width, p_mkv->height,
1603 p_mkv->d_width, p_mkv->d_height );
1607 p_mkv->b_header_written = 1;
1612 static int open_file_mkv( char *psz_filename, hnd_t *p_handle )
1618 p_mkv = malloc(sizeof(*p_mkv));
1622 memset(p_mkv, 0, sizeof(*p_mkv));
1624 p_mkv->w = mk_createWriter(psz_filename);
1625 if (p_mkv->w == NULL)
1636 static int set_param_mkv( hnd_t handle, x264_param_t *p_param )
1638 mkv_t *p_mkv = handle;
1641 if( p_param->i_fps_num > 0 )
1643 p_mkv->frame_duration = (int64_t)p_param->i_fps_den *
1644 (int64_t)1000000000 / p_param->i_fps_num;
1645 p_mkv->fps_num = p_param->i_fps_num;
1649 p_mkv->frame_duration = 0;
1653 p_mkv->width = p_param->i_width;
1654 p_mkv->height = p_param->i_height;
1656 if( p_param->vui.i_sar_width && p_param->vui.i_sar_height )
1658 dw = (int64_t)p_param->i_width * p_param->vui.i_sar_width;
1659 dh = (int64_t)p_param->i_height * p_param->vui.i_sar_height;
1663 dw = p_param->i_width;
1664 dh = p_param->i_height;
1667 if( dw > 0 && dh > 0 )
1669 int64_t a = dw, b = dh;
1684 p_mkv->d_width = (int)dw;
1685 p_mkv->d_height = (int)dh;
1690 static int write_nalu_mkv( hnd_t handle, uint8_t *p_nalu, int i_size )
1692 mkv_t *p_mkv = handle;
1693 uint8_t type = p_nalu[4] & 0x1f;
1703 p_mkv->sps = malloc(i_size - 4);
1704 if (p_mkv->sps == NULL)
1706 p_mkv->sps_len = i_size - 4;
1707 memcpy(p_mkv->sps, p_nalu + 4, i_size - 4);
1715 p_mkv->pps = malloc(i_size - 4);
1716 if (p_mkv->pps == NULL)
1718 p_mkv->pps_len = i_size - 4;
1719 memcpy(p_mkv->pps, p_nalu + 4, i_size - 4);
1727 if( !p_mkv->b_writing_frame )
1729 if( mk_startFrame(p_mkv->w) < 0 )
1731 p_mkv->b_writing_frame = 1;
1733 psize = i_size - 4 ;
1734 dsize[0] = psize >> 16;
1735 dsize[1] = psize >> 8;
1737 if( mk_addFrameData(p_mkv->w, dsize, 3) < 0 ||
1738 mk_addFrameData(p_mkv->w, p_nalu + 4, i_size - 4) < 0 )
1746 if( !p_mkv->b_header_written && p_mkv->pps && p_mkv->sps &&
1747 write_header_mkv(p_mkv) < 0 )
1753 static int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture )
1755 mkv_t *p_mkv = handle;
1756 int64_t i_stamp = (int64_t)(p_picture->i_pts * 1e9 / p_mkv->fps_num);
1758 p_mkv->b_writing_frame = 0;
1760 return mk_setFrameFlags( p_mkv->w, i_stamp,
1761 p_picture->i_type == X264_TYPE_IDR );
1764 static int close_file_mkv( hnd_t handle )
1766 mkv_t *p_mkv = handle;
1774 ret = mk_close(p_mkv->w);