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 *****************************************************************************/
24 #define _LARGEFILE_SOURCE
25 #define _FILE_OFFSET_BITS 64
38 #include <io.h> /* _setmode() */
39 #include <fcntl.h> /* _O_BINARY */
52 #include <gpac/isomedia.h>
56 #include "common/common.h"
61 #define DATA_MAX 3000000
62 uint8_t data[DATA_MAX];
67 static int b_ctrl_c = 0;
68 static int b_exit_on_ctrl_c = 0;
69 static void SigIntHandler( int a )
71 if( b_exit_on_ctrl_c )
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 );
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 );
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 );
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 );
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 );
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 );
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 );
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 );
134 /****************************************************************************
136 ****************************************************************************/
137 int main( int argc, char **argv )
143 _setmode(_fileno(stdin), _O_BINARY); /* thanks to Marcos Morais <morais at dee.ufcg.edu.br> */
144 _setmode(_fileno(stdout), _O_BINARY);
147 x264_param_default( ¶m );
149 /* Parse command line */
150 if( Parse( argc, argv, ¶m, &opt ) < 0 )
153 /* Control-C handler */
154 signal( SIGINT, SigIntHandler );
156 return Encode( ¶m, &opt );
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 };
166 static char const *strtable_lookup( const char * const table[], int index )
168 int i = 0; while( table[i] ) i++;
169 return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
172 /*****************************************************************************
174 *****************************************************************************/
175 static void Help( x264_param_t *defaults )
179 "Syntax: x264 [options] -o outfile infile [widthxheight]\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"
190 " -h, --help Print this help\n"
192 "Frame-type options:\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"
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"
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"
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"
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"
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"
244 " -A, --analyse <string> Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
245 " - p8x8, p4x4, b8x8, i8x8, i4x4\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"
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"
271 " --cqm <string> Preset quant matrices [\"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"
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"
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"
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"
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"
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"
323 X264_BUILD, X264_VERSION,
334 defaults->i_keyint_max,
335 defaults->i_keyint_min,
336 defaults->i_scenecut_threshold,
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
374 static int parse_enum( const char *arg, const char * const *names, int *dst )
377 for( i = 0; names[i]; i++ )
378 if( !strcmp( arg, names[i] ) )
386 static int parse_cqm( const char *str, uint8_t *cqm, int length )
391 if( !sscanf( str, "%d", &coef ) || coef < 1 || coef > 255 )
394 } while( i < length && (str = strchr( str, ',' )) && str++ );
395 return (i == length) ? 0 : -1;
398 /*****************************************************************************
400 *****************************************************************************/
401 static int Parse( int argc, char **argv,
402 x264_param_t *param, cli_opt_t *opt )
404 char *psz_filename = NULL;
405 x264_param_t defaults = *param;
409 memset( opt, 0, sizeof(cli_opt_t) );
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;
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;
424 /* Parse command line options */
425 opterr = 0; // no error message
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
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
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
455 #define OPT_PROGRESS 284
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
463 #define OPT_ZONES 292
464 #define OPT_THREADS 293
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
474 #define OPT_CQM8I 303
475 #define OPT_CQM8P 304
476 #define OPT_CQMFILE 305
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
487 #define OPT_B_RDO 316
488 #define OPT_NO_FAST_PSKIP 317
492 static struct option long_options[] =
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 },
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);
595 param->rc.i_bitrate = atol( optarg );
599 param->rc.i_rf_constant = atol( optarg );
602 param->i_bframe = atol( optarg );
605 param->b_bframe_adaptive = 0;
608 param->i_bframe_bias = atol( optarg );
611 param->b_bframe_pyramid = 1;
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;
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;
624 param->i_scenecut_threshold = atol( optarg );
627 param->b_deblocking_filter = 0;
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;
638 param->rc.i_qp_constant = atoi( optarg );
641 param->rc.i_qp_min = atoi( optarg );
644 param->rc.i_qp_max = atoi( optarg );
647 param->rc.i_qp_step = atoi( optarg );
650 param->i_frame_reference = atoi( optarg );
656 opt->b_decompress = 1;
662 param->i_frame_total = atoi( optarg );
665 opt->i_seek = atoi( optarg );
668 if( !strncasecmp(optarg + strlen(optarg) - 4, ".mp4", 4) )
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;
677 fprintf( stderr, "not compiled with MP4 output support\n" );
681 else if( !strncasecmp(optarg + strlen(optarg) - 4, ".mkv", 4) )
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;
689 if( !strcmp(optarg, "-") )
691 else if( p_open_outfile( optarg, &opt->hout ) )
693 fprintf( stderr, "cannot open output file `%s'\n", optarg );
699 char *p = strchr( optarg, ':' );
700 if( !p ) p = strchr( optarg, '/' );
703 param->vui.i_sar_width = atoi( optarg );
704 param->vui.i_sar_height = atoi( p + 1 );
711 if( sscanf( optarg, "%d/%d", ¶m->i_fps_num, ¶m->i_fps_den ) == 2 )
713 else if( sscanf( optarg, "%f", &fps ) )
715 param->i_fps_num = (int)(fps * 1000 + .5);
716 param->i_fps_den = 1000;
720 fprintf( stderr, "bad fps `%s'\n", optarg );
726 param->analyse.inter = 0;
727 if( strstr( optarg, "none" ) ) param->analyse.inter = 0;
728 if( strstr( optarg, "all" ) ) param->analyse.inter = ~0;
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;
737 b_error |= parse_enum( optarg, x264_direct_pred_names, ¶m->analyse.i_direct_mv_pred );
740 param->analyse.b_weighted_bipred = 1;
743 b_error |= parse_enum( optarg, x264_motion_est_names, ¶m->analyse.i_me_method );
746 param->analyse.i_me_range = atoi(optarg);
749 param->analyse.i_subpel_refine = atoi(optarg);
752 param->analyse.b_bframe_rdo = 1;
755 param->analyse.b_mixed_references = 1;
757 case OPT_NO_CHROMA_ME:
758 param->analyse.b_chroma_me = 0;
761 param->analyse.b_bidir_me = 1;
764 param->analyse.b_transform_8x8 = 1;
767 param->analyse.i_trellis = atoi(optarg);
769 case OPT_NO_FAST_PSKIP:
770 param->analyse.b_fast_pskip = 0;
773 if( atof(optarg) < 6 )
774 param->i_level_idc = (int)(10*atof(optarg)+.5);
776 param->i_level_idc = atoi(optarg);
779 param->rc.f_rate_tolerance = !strncmp("inf", optarg, 3) ? 1e9 : atof(optarg);
782 param->rc.i_vbv_max_bitrate = atoi( optarg );
785 param->rc.i_vbv_buffer_size = atoi( optarg );
788 param->rc.f_vbv_buffer_init = atof(optarg);
791 param->rc.f_ip_factor = atof(optarg);
794 param->rc.f_pb_factor = atof(optarg);
797 param->analyse.i_chroma_qp_offset = atoi(optarg);
801 int i_pass = atoi(optarg);
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;
812 param->rc.psz_stat_in = optarg;
813 param->rc.psz_stat_out = optarg;
816 param->rc.psz_rc_eq = optarg;
819 param->rc.f_qcompress = atof(optarg);
822 param->rc.f_qblur = atof(optarg);
825 param->rc.f_complexity_blur = atof(optarg);
828 param->rc.psz_zones = optarg;
831 param->i_threads = atoi(optarg);
834 param->analyse.b_psnr = 0;
837 param->i_log_level = X264_LOG_NONE;
840 param->i_log_level = X264_LOG_DEBUG;
850 param->b_visualize = 1;
851 b_exit_on_ctrl_c = 1;
853 fprintf( stderr, "not compiled with visualization support\n" );
857 param->analyse.i_noise_reduction = atoi(optarg);
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;
866 fprintf( stderr, "bad CQM preset `%s'\n", optarg );
871 param->psz_cqm_file = optarg;
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 );
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 );
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 );
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 );
896 param->i_cqm_preset = X264_CQM_CUSTOM;
897 b_error |= parse_cqm( optarg, param->cqm_4iy, 16 );
900 param->i_cqm_preset = X264_CQM_CUSTOM;
901 b_error |= parse_cqm( optarg, param->cqm_4ic, 16 );
904 param->i_cqm_preset = X264_CQM_CUSTOM;
905 b_error |= parse_cqm( optarg, param->cqm_4py, 16 );
908 param->i_cqm_preset = X264_CQM_CUSTOM;
909 b_error |= parse_cqm( optarg, param->cqm_4pc, 16 );
912 param->i_cqm_preset = X264_CQM_CUSTOM;
913 b_error |= parse_cqm( optarg, param->cqm_8iy, 64 );
916 param->i_cqm_preset = X264_CQM_CUSTOM;
917 b_error |= parse_cqm( optarg, param->cqm_8py, 64 );
920 b_error |= parse_enum( optarg, overscan_str, ¶m->vui.i_overscan );
923 b_error |= parse_enum( optarg, vidformat_str, ¶m->vui.i_vidformat );
926 b_error |= parse_enum( optarg, fullrange_str, ¶m->vui.b_fullrange );
929 b_error |= parse_enum( optarg, colorprim_str, ¶m->vui.i_colorprim );
932 b_error |= parse_enum( optarg, transfer_str, ¶m->vui.i_transfer );
934 case OPT_COLOURMATRIX:
935 b_error |= parse_enum( optarg, colmatrix_str, ¶m->vui.i_colmatrix );
938 param->vui.i_chroma_loc = atoi( optarg );
939 b_error = ( param->vui.i_chroma_loc < 0 || param->vui.i_chroma_loc > 5 );
942 fprintf( stderr, "unknown option (%c)\n", optopt );
948 fprintf( stderr, "bad argument: %s %s\n", argv[optind-2], optarg );
953 /* Get the file name */
954 if( optind > argc - 1 || !opt->hout )
959 psz_filename = argv[optind++];
961 if( !opt->b_decompress )
963 if( optind > argc - 1 )
965 /* try to parse the file name */
966 for( psz = psz_filename; *psz; psz++ )
968 if( *psz >= '0' && *psz <= '9'
969 && sscanf( psz, "%ux%u", ¶m->i_width, ¶m->i_height ) == 2 )
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 );
979 sscanf( argv[optind++], "%ux%u", ¶m->i_width, ¶m->i_height );
982 /* check avis input */
983 psz = psz_filename + strlen(psz_filename) - 1;
984 while( psz > psz_filename && *psz != '.' )
987 if( !strncasecmp( psz, ".avi", 4 ) || !strncasecmp( psz, ".avs", 4 ) )
990 if( !b_avis && ( !param->i_width || !param->i_height ) )
998 if( !strcmp( psz_filename, "-" ) )
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;
1013 fprintf( stderr, "not compiled with AVIS input support\n" );
1017 if( p_open_infile( psz_filename, &opt->hin, param ) )
1019 fprintf( stderr, "could not open input file '%s'\n", psz_filename );
1027 /*****************************************************************************
1029 *****************************************************************************/
1031 static int Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic )
1033 x264_picture_t pic_out;
1038 /* Do not force any parameters */
1041 pic->i_type = X264_TYPE_AUTO;
1044 if( x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out ) < 0 )
1046 fprintf( stderr, "x264_encoder_encode failed\n" );
1049 for( i = 0; i < i_nal; i++ )
1055 if( ( i_size = x264_nal_encode( data, &i_data, 1, &nal[i] ) ) > 0 )
1057 i_file += p_write_nalu( hout, data, i_size );
1059 else if( i_size < 0 )
1061 fprintf( stderr, "need to increase buffer size (size=%d)\n", -i_size );
1065 p_set_eop( hout, &pic_out );
1070 /*****************************************************************************
1072 *****************************************************************************/
1073 static int Encode( x264_param_t *param, cli_opt_t *opt )
1078 int i_frame, i_frame_total;
1079 int64_t i_start, i_end;
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;
1091 if( ( h = x264_encoder_open( param ) ) == NULL )
1093 fprintf( stderr, "x264_encoder_open failed\n" );
1094 p_close_infile( opt->hin );
1095 p_close_outfile( opt->hout );
1099 if( p_set_outfile_param( opt->hout, param ) )
1101 fprintf( stderr, "can't set outfile param\n" );
1102 p_close_infile( opt->hin );
1103 p_close_outfile( opt->hout );
1107 /* Create a new pic */
1108 x264_picture_alloc( &pic, X264_CSP_I420, param->i_width, param->i_height );
1110 i_start = x264_mdate();
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); )
1116 if( p_read_frame( &pic, opt->hin, i_frame + opt->i_seek, param->i_width, param->i_height ) )
1119 pic.i_pts = (int64_t)i_frame * param->i_fps_den;
1121 i_file += Encode_frame( h, opt->hout, &pic );
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 ) )
1130 int64_t i_elapsed = x264_mdate() - i_start;
1131 double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
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 );
1141 fprintf( stderr, "encoded frames: %d, %.2f fps \r", i_frame, fps );
1142 fflush( stderr ); // needed in windows
1145 /* Flush delayed B-frames */
1148 i_frame_size = Encode_frame( h, opt->hout, NULL );
1149 } while( i_frame_size );
1151 i_end = x264_mdate();
1152 x264_picture_clean( &pic );
1153 x264_encoder_close( h );
1154 fprintf( stderr, "\n" );
1157 fprintf( stderr, "aborted at input frame %d\n", opt->i_seek + i_frame );
1159 p_close_infile( opt->hin );
1160 p_close_outfile( opt->hout );
1164 double fps = (double)i_frame * (double)1000000 /
1165 (double)( i_end - i_start );
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 ) );
1175 /* raw 420 yuv file operation */
1176 static int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1178 if ((*p_handle = fopen(psz_filename, "rb")) == NULL)
1183 static int get_frame_total_yuv( hnd_t handle, int i_width, int i_height )
1185 FILE *f = (FILE *)handle;
1186 int i_frame_total = 0;
1188 if( !fseek( f, 0, SEEK_END ) )
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 ));
1195 return i_frame_total;
1198 static int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1200 static int prev_frame = -1;
1201 FILE *f = (FILE *)handle;
1203 if( i_frame != prev_frame+1 )
1204 if( fseek( f, (uint64_t)i_frame * i_width * i_height * 3 / 2, SEEK_SET ) )
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 )
1212 prev_frame = i_frame;
1217 static int close_file_yuv(hnd_t handle)
1221 return fclose((FILE *)handle);
1225 /* avs/avi input file support under cygwin */
1229 static int gcd(int a, int b)
1243 static int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
1246 PAVISTREAM p_avi = NULL;
1252 if( AVIStreamOpenFromFile( &p_avi, psz_filename, streamtypeVIDEO, 0, OF_READ, NULL ) )
1258 if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1260 AVIStreamRelease(p_avi);
1265 // check input format
1266 if (info.fccHandler != MAKEFOURCC('Y', 'V', '1', '2'))
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)) );
1272 AVIStreamRelease(p_avi);
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;
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 );
1289 *p_handle = (hnd_t)p_avi;
1294 static int get_frame_total_avis( hnd_t handle, int i_width, int i_height )
1296 PAVISTREAM p_avi = (PAVISTREAM)handle;
1299 if( AVIStreamInfo(p_avi, &info, sizeof(AVISTREAMINFO)) )
1302 return info.dwLength;
1305 static int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame, int i_width, int i_height )
1307 PAVISTREAM p_avi = (PAVISTREAM)handle;
1309 p_pic->img.i_csp = X264_CSP_YV12;
1311 if( AVIStreamRead(p_avi, i_frame, 1, p_pic->img.plane[0], i_width * i_height * 3 / 2, NULL, NULL ) )
1317 static int close_file_avis( hnd_t handle )
1319 PAVISTREAM p_avi = (PAVISTREAM)handle;
1321 AVIStreamRelease(p_avi);
1330 static int open_file_bsf( char *psz_filename, hnd_t *p_handle )
1332 if ((*p_handle = fopen(psz_filename, "w+b")) == NULL)
1338 static int set_param_bsf( hnd_t handle, x264_param_t *p_param )
1343 static int write_nalu_bsf( hnd_t handle, uint8_t *p_nalu, int i_size )
1345 if (fwrite(p_nalu, i_size, 1, (FILE *)handle) > 0)
1350 static int set_eop_bsf( hnd_t handle, x264_picture_t *p_picture )
1355 static int close_file_bsf( hnd_t handle )
1357 if ((handle == NULL) || (handle == stdout))
1360 return fclose((FILE *)handle);
1363 /* -- mp4 muxing support ------------------------------------------------- */
1369 GF_AVCConfig *p_config;
1370 GF_ISOSample *p_sample;
1382 static void recompute_bitrate_mp4(GF_ISOFile *p_file, int i_track)
1384 u32 i, count, di, timescale, time_wnd, rate;
1389 esd = gf_isom_get_esd(p_file, i_track, 1);
1392 esd->decoderConfig->avgBitrate = 0;
1393 esd->decoderConfig->maxBitrate = 0;
1394 rate = time_wnd = 0;
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);
1401 if (samp->dataLength>esd->decoderConfig->bufferSizeDB) esd->decoderConfig->bufferSizeDB = samp->dataLength;
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;
1412 gf_isom_sample_del(&samp);
1415 br = (Double) (s64) gf_isom_get_media_duration(p_file, i_track);
1417 esd->decoderConfig->avgBitrate = (u32) (esd->decoderConfig->avgBitrate / br);
1419 esd->decoderConfig->avgBitrate *= 8;
1420 esd->decoderConfig->maxBitrate *= 8;
1422 gf_isom_change_mpeg4_description(p_file, i_track, 1, esd);
1423 gf_odf_desc_del((GF_Descriptor *) esd);
1427 static int close_file_mp4( hnd_t handle )
1429 mp4_t *p_mp4 = (mp4_t *)handle;
1434 if (p_mp4->p_config)
1435 gf_odf_avc_cfg_del(p_mp4->p_config);
1437 if (p_mp4->p_sample)
1439 if (p_mp4->p_sample->data)
1440 free(p_mp4->p_sample->data);
1442 gf_isom_sample_del(&p_mp4->p_sample);
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);
1458 static int open_file_mp4( char *psz_filename, hnd_t *p_handle )
1464 if ((p_mp4 = (mp4_t *)malloc(sizeof(mp4_t))) == NULL)
1467 memset(p_mp4, 0, sizeof(mp4_t));
1468 p_mp4->p_file = gf_isom_open(psz_filename, GF_ISOM_OPEN_WRITE, NULL);
1470 if ((p_mp4->p_sample = gf_isom_sample_new()) == NULL)
1472 close_file_mp4( p_mp4 );
1476 gf_isom_set_brand_info(p_mp4->p_file, GF_ISOM_BRAND_AVC1, 0);
1484 static int set_param_mp4( hnd_t handle, x264_param_t *p_param )
1486 mp4_t *p_mp4 = (mp4_t *)handle;
1488 p_mp4->i_track = gf_isom_new_track(p_mp4->p_file, 0, GF_ISOM_MEDIA_VISUAL,
1489 p_param->i_fps_num);
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);
1495 gf_isom_set_track_enabled(p_mp4->p_file, p_mp4->i_track, 1);
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);
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)
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);
1515 static int write_nalu_mp4( hnd_t handle, uint8_t *p_nalu, int i_size )
1517 mp4_t *p_mp4 = (mp4_t *)handle;
1518 GF_AVCConfigSlot *p_slot;
1519 uint8_t type = p_nalu[4] & 0x1f;
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);
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);
1554 gf_isom_avc_config_update(p_mp4->p_file, p_mp4->i_track, 1, p_mp4->p_config);
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;
1575 static int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture )
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;
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);
1587 p_mp4->p_sample->dataLength = 0;
1588 p_mp4->i_numframe++;
1596 /* -- mkv muxing support ------------------------------------------------- */
1602 int sps_len, pps_len;
1604 int width, height, d_width, d_height;
1606 int64_t frame_duration;
1609 int b_header_written;
1610 char b_writing_frame;
1613 static int write_header_mkv( mkv_t *p_mkv )
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)
1624 avcC_len = 5 + 1 + 2 + p_mkv->sps_len + 1 + 2 + p_mkv->pps_len;
1625 avcC = malloc(avcC_len);
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
1636 avcC[6] = p_mkv->sps_len >> 8;
1637 avcC[7] = p_mkv->sps_len;
1639 memcpy(avcC+8, p_mkv->sps, p_mkv->sps_len);
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;
1645 memcpy( avcC+11+p_mkv->sps_len, p_mkv->pps, p_mkv->pps_len );
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 );
1654 p_mkv->b_header_written = 1;
1659 static int open_file_mkv( char *psz_filename, hnd_t *p_handle )
1665 p_mkv = malloc(sizeof(*p_mkv));
1669 memset(p_mkv, 0, sizeof(*p_mkv));
1671 p_mkv->w = mk_createWriter(psz_filename);
1672 if (p_mkv->w == NULL)
1683 static int set_param_mkv( hnd_t handle, x264_param_t *p_param )
1685 mkv_t *p_mkv = handle;
1688 if( p_param->i_fps_num > 0 )
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;
1696 p_mkv->frame_duration = 0;
1700 p_mkv->width = p_param->i_width;
1701 p_mkv->height = p_param->i_height;
1703 if( p_param->vui.i_sar_width && p_param->vui.i_sar_height )
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;
1710 dw = p_param->i_width;
1711 dh = p_param->i_height;
1714 if( dw > 0 && dh > 0 )
1716 int64_t a = dw, b = dh;
1731 p_mkv->d_width = (int)dw;
1732 p_mkv->d_height = (int)dh;
1737 static int write_nalu_mkv( hnd_t handle, uint8_t *p_nalu, int i_size )
1739 mkv_t *p_mkv = handle;
1740 uint8_t type = p_nalu[4] & 0x1f;
1750 p_mkv->sps = malloc(i_size - 4);
1751 if (p_mkv->sps == NULL)
1753 p_mkv->sps_len = i_size - 4;
1754 memcpy(p_mkv->sps, p_nalu + 4, i_size - 4);
1762 p_mkv->pps = malloc(i_size - 4);
1763 if (p_mkv->pps == NULL)
1765 p_mkv->pps_len = i_size - 4;
1766 memcpy(p_mkv->pps, p_nalu + 4, i_size - 4);
1774 if( !p_mkv->b_writing_frame )
1776 if( mk_startFrame(p_mkv->w) < 0 )
1778 p_mkv->b_writing_frame = 1;
1780 psize = i_size - 4 ;
1781 dsize[0] = psize >> 24;
1782 dsize[1] = psize >> 16;
1783 dsize[2] = psize >> 8;
1785 if( mk_addFrameData(p_mkv->w, dsize, 4) < 0 ||
1786 mk_addFrameData(p_mkv->w, p_nalu + 4, i_size - 4) < 0 )
1794 if( !p_mkv->b_header_written && p_mkv->pps && p_mkv->sps &&
1795 write_header_mkv(p_mkv) < 0 )
1801 static int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture )
1803 mkv_t *p_mkv = handle;
1804 int64_t i_stamp = (int64_t)(p_picture->i_pts * 1e9 / p_mkv->fps_num);
1806 p_mkv->b_writing_frame = 0;
1808 return mk_setFrameFlags( p_mkv->w, i_stamp,
1809 p_picture->i_type == X264_TYPE_IDR );
1812 static int close_file_mkv( hnd_t handle )
1814 mkv_t *p_mkv = handle;
1822 ret = mk_close(p_mkv->w);