]> git.sesse.net Git - x264/blob - muxers.c
Major API change: encapsulate NALs within libx264
[x264] / muxers.c
1 /*****************************************************************************
2  * muxers.c: h264 file i/o plugins
3  *****************************************************************************
4  * Copyright (C) 2003-2008 x264 project
5  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *          Loren Merritt <lorenm@u.washington.edu>
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., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 #include "common/common.h"
25 #include "x264.h"
26 #include "matroska.h"
27 #include "muxers.h"
28
29 #ifndef _MSC_VER
30 #include "config.h"
31 #endif
32
33 #include <sys/types.h>
34
35 #ifdef AVIS_INPUT
36 #include <windows.h>
37 #include <vfw.h>
38 #endif
39
40 #ifdef MP4_OUTPUT
41 #include <gpac/isomedia.h>
42 #endif
43
44 static int64_t gcd( int64_t a, int64_t b )
45 {
46     while (1)
47     {
48         int64_t c = a % b;
49         if( !c )
50             return b;
51         a = b;
52         b = c;
53     }
54 }
55
56 typedef struct {
57     FILE *fh;
58     int width, height;
59     int next_frame;
60 } yuv_input_t;
61
62 /* raw 420 yuv file operation */
63 int open_file_yuv( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
64 {
65     yuv_input_t *h = malloc(sizeof(yuv_input_t));
66     if( !h )
67         return -1;
68     h->width = p_param->i_width;
69     h->height = p_param->i_height;
70     h->next_frame = 0;
71
72     if( !strcmp(psz_filename, "-") )
73         h->fh = stdin;
74     else
75         h->fh = fopen(psz_filename, "rb");
76     if( h->fh == NULL )
77         return -1;
78
79     *p_handle = (hnd_t)h;
80     return 0;
81 }
82
83 int get_frame_total_yuv( hnd_t handle )
84 {
85     yuv_input_t *h = handle;
86     int i_frame_total = 0;
87
88     if( !fseek( h->fh, 0, SEEK_END ) )
89     {
90         uint64_t i_size = ftell( h->fh );
91         fseek( h->fh, 0, SEEK_SET );
92         i_frame_total = (int)(i_size / ( h->width * h->height * 3 / 2 ));
93     }
94
95     return i_frame_total;
96 }
97
98 int read_frame_yuv( x264_picture_t *p_pic, hnd_t handle, int i_frame )
99 {
100     yuv_input_t *h = handle;
101
102     if( i_frame != h->next_frame )
103         if( fseek( h->fh, (uint64_t)i_frame * h->width * h->height * 3 / 2, SEEK_SET ) )
104             return -1;
105
106     if( fread( p_pic->img.plane[0], 1, h->width * h->height, h->fh ) <= 0
107             || fread( p_pic->img.plane[1], 1, h->width * h->height / 4, h->fh ) <= 0
108             || fread( p_pic->img.plane[2], 1, h->width * h->height / 4, h->fh ) <= 0 )
109         return -1;
110
111     h->next_frame = i_frame+1;
112
113     return 0;
114 }
115
116 int close_file_yuv(hnd_t handle)
117 {
118     yuv_input_t *h = handle;
119     if( !h || !h->fh )
120         return 0;
121     fclose( h->fh );
122     free( h );
123     return 0;
124 }
125
126 /* YUV4MPEG2 raw 420 yuv file operation */
127 typedef struct {
128     FILE *fh;
129     int width, height;
130     int next_frame;
131     int seq_header_len, frame_header_len;
132     int frame_size;
133 } y4m_input_t;
134
135 #define Y4M_MAGIC "YUV4MPEG2"
136 #define MAX_YUV4_HEADER 80
137 #define Y4M_FRAME_MAGIC "FRAME"
138 #define MAX_FRAME_HEADER 80
139
140 int open_file_y4m( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
141 {
142     int  i, n, d;
143     char header[MAX_YUV4_HEADER+10];
144     char *tokstart, *tokend, *header_end;
145     y4m_input_t *h = malloc(sizeof(y4m_input_t));
146     if( !h )
147         return -1;
148
149     h->next_frame = 0;
150
151     if( !strcmp(psz_filename, "-") )
152         h->fh = stdin;
153     else
154         h->fh = fopen(psz_filename, "rb");
155     if( h->fh == NULL )
156         return -1;
157
158     h->frame_header_len = strlen(Y4M_FRAME_MAGIC)+1;
159
160     /* Read header */
161     for( i=0; i<MAX_YUV4_HEADER; i++ )
162     {
163         header[i] = fgetc(h->fh);
164         if( header[i] == '\n' )
165         {
166             /* Add a space after last option. Makes parsing "444" vs
167                "444alpha" easier. */
168             header[i+1] = 0x20;
169             header[i+2] = 0;
170             break;
171         }
172     }
173     if( i == MAX_YUV4_HEADER || strncmp(header, Y4M_MAGIC, strlen(Y4M_MAGIC)) )
174         return -1;
175
176     /* Scan properties */
177     header_end = &header[i+1]; /* Include space */
178     h->seq_header_len = i+1;
179     for( tokstart = &header[strlen(Y4M_MAGIC)+1]; tokstart < header_end; tokstart++ )
180     {
181         if(*tokstart==0x20) continue;
182         switch(*tokstart++)
183         {
184         case 'W': /* Width. Required. */
185             h->width = p_param->i_width = strtol(tokstart, &tokend, 10);
186             tokstart=tokend;
187             break;
188         case 'H': /* Height. Required. */
189             h->height = p_param->i_height = strtol(tokstart, &tokend, 10);
190             tokstart=tokend;
191             break;
192         case 'C': /* Color space */
193             if( strncmp("420", tokstart, 3) )
194             {
195                 fprintf(stderr, "Colorspace unhandled\n");
196                 return -1;
197             }
198             tokstart = strchr(tokstart, 0x20);
199             break;
200         case 'I': /* Interlace type */
201             switch(*tokstart++)
202             {
203             case 'p': break;
204             case '?':
205             case 't':
206             case 'b':
207             case 'm':
208             default:
209                 fprintf(stderr, "Warning, this sequence might be interlaced\n");
210             }
211             break;
212         case 'F': /* Frame rate - 0:0 if unknown */
213             if( sscanf(tokstart, "%d:%d", &n, &d) == 2 && n && d )
214             {
215                 x264_reduce_fraction( &n, &d );
216                 p_param->i_fps_num = n;
217                 p_param->i_fps_den = d;
218             }
219             tokstart = strchr(tokstart, 0x20);
220             break;
221         case 'A': /* Pixel aspect - 0:0 if unknown */
222             /* Don't override the aspect ratio if sar has been explicitly set on the commandline. */
223             if( sscanf(tokstart, "%d:%d", &n, &d) == 2 && n && d && !p_param->vui.i_sar_width && !p_param->vui.i_sar_height )
224             {
225                 x264_reduce_fraction( &n, &d );
226                 p_param->vui.i_sar_width = n;
227                 p_param->vui.i_sar_height = d;
228             }
229             tokstart = strchr(tokstart, 0x20);
230             break;
231         case 'X': /* Vendor extensions */
232             if( !strncmp("YSCSS=",tokstart,6) )
233             {
234                 /* Older nonstandard pixel format representation */
235                 tokstart += 6;
236                 if( strncmp("420JPEG",tokstart,7) &&
237                     strncmp("420MPEG2",tokstart,8) &&
238                     strncmp("420PALDV",tokstart,8) )
239                 {
240                     fprintf(stderr, "Unsupported extended colorspace\n");
241                     return -1;
242                 }
243             }
244             tokstart = strchr(tokstart, 0x20);
245             break;
246         }
247     }
248
249     fprintf(stderr, "yuv4mpeg: %ix%i@%i/%ifps, %i:%i\n",
250             h->width, h->height, p_param->i_fps_num, p_param->i_fps_den,
251             p_param->vui.i_sar_width, p_param->vui.i_sar_height);
252
253     *p_handle = (hnd_t)h;
254     return 0;
255 }
256
257 /* Most common case: frame_header = "FRAME" */
258 int get_frame_total_y4m( hnd_t handle )
259 {
260     y4m_input_t *h             = handle;
261     int          i_frame_total = 0;
262     uint64_t     init_pos      = ftell(h->fh);
263
264     if( !fseek( h->fh, 0, SEEK_END ) )
265     {
266         uint64_t i_size = ftell( h->fh );
267         fseek( h->fh, init_pos, SEEK_SET );
268         i_frame_total = (int)((i_size - h->seq_header_len) /
269                               (3*(h->width*h->height)/2+h->frame_header_len));
270     }
271
272     return i_frame_total;
273 }
274
275 int read_frame_y4m( x264_picture_t *p_pic, hnd_t handle, int i_frame )
276 {
277     int          slen = strlen(Y4M_FRAME_MAGIC);
278     int          i    = 0;
279     char         header[16];
280     y4m_input_t *h    = handle;
281
282     if( i_frame != h->next_frame )
283     {
284         if (fseek(h->fh, (uint64_t)i_frame*(3*(h->width*h->height)/2+h->frame_header_len)
285                   + h->seq_header_len, SEEK_SET))
286             return -1;
287     }
288
289     /* Read frame header - without terminating '\n' */
290     if (fread(header, 1, slen, h->fh) != slen)
291         return -1;
292
293     header[slen] = 0;
294     if (strncmp(header, Y4M_FRAME_MAGIC, slen))
295     {
296         fprintf(stderr, "Bad header magic (%"PRIx32" <=> %s)\n",
297                 *((uint32_t*)header), header);
298         return -1;
299     }
300
301     /* Skip most of it */
302     while (i<MAX_FRAME_HEADER && fgetc(h->fh) != '\n')
303         i++;
304     if (i == MAX_FRAME_HEADER)
305     {
306         fprintf(stderr, "Bad frame header!\n");
307         return -1;
308     }
309     h->frame_header_len = i+slen+1;
310
311     if( fread(p_pic->img.plane[0], 1, h->width*h->height, h->fh) <= 0
312         || fread(p_pic->img.plane[1], 1, h->width * h->height / 4, h->fh) <= 0
313         || fread(p_pic->img.plane[2], 1, h->width * h->height / 4, h->fh) <= 0)
314         return -1;
315
316     h->next_frame = i_frame+1;
317
318     return 0;
319 }
320
321 int close_file_y4m(hnd_t handle)
322 {
323     y4m_input_t *h = handle;
324     if( !h || !h->fh )
325         return 0;
326     fclose( h->fh );
327     free( h );
328     return 0;
329 }
330
331 /* avs/avi input file support under cygwin */
332
333 #ifdef AVIS_INPUT
334 typedef struct {
335     PAVISTREAM p_avi;
336     int width, height;
337 } avis_input_t;
338
339 int open_file_avis( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
340 {
341     avis_input_t *h = malloc(sizeof(avis_input_t));
342     if( !h )
343         return -1;
344     AVISTREAMINFO info;
345     int i;
346
347     *p_handle = (hnd_t)h;
348
349     AVIFileInit();
350     if( AVIStreamOpenFromFile( &h->p_avi, psz_filename, streamtypeVIDEO, 0, OF_READ, NULL ) )
351     {
352         AVIFileExit();
353         return -1;
354     }
355
356     if( AVIStreamInfo(h->p_avi, &info, sizeof(AVISTREAMINFO)) )
357     {
358         AVIStreamRelease(h->p_avi);
359         AVIFileExit();
360         return -1;
361     }
362
363     // check input format
364     if (info.fccHandler != MAKEFOURCC('Y', 'V', '1', '2'))
365     {
366         fprintf( stderr, "avis [error]: unsupported input format (%c%c%c%c)\n",
367             (char)(info.fccHandler & 0xff), (char)((info.fccHandler >> 8) & 0xff),
368             (char)((info.fccHandler >> 16) & 0xff), (char)((info.fccHandler >> 24)) );
369
370         AVIStreamRelease(h->p_avi);
371         AVIFileExit();
372
373         return -1;
374     }
375
376     h->width =
377     p_param->i_width = info.rcFrame.right - info.rcFrame.left;
378     h->height =
379     p_param->i_height = info.rcFrame.bottom - info.rcFrame.top;
380     i = gcd(info.dwRate, info.dwScale);
381     p_param->i_fps_den = info.dwScale / i;
382     p_param->i_fps_num = info.dwRate / i;
383
384     fprintf( stderr, "avis [info]: %dx%d @ %.2f fps (%d frames)\n",
385         p_param->i_width, p_param->i_height,
386         (double)p_param->i_fps_num / (double)p_param->i_fps_den,
387         (int)info.dwLength );
388
389     return 0;
390 }
391
392 int get_frame_total_avis( hnd_t handle )
393 {
394     avis_input_t *h = handle;
395     AVISTREAMINFO info;
396
397     if( AVIStreamInfo(h->p_avi, &info, sizeof(AVISTREAMINFO)) )
398         return -1;
399
400     return info.dwLength;
401 }
402
403 int read_frame_avis( x264_picture_t *p_pic, hnd_t handle, int i_frame )
404 {
405     avis_input_t *h = handle;
406
407     p_pic->img.i_csp = X264_CSP_YV12;
408
409     if( AVIStreamRead(h->p_avi, i_frame, 1, p_pic->img.plane[0], h->width * h->height * 3 / 2, NULL, NULL ) )
410         return -1;
411
412     return 0;
413 }
414
415 int close_file_avis( hnd_t handle )
416 {
417     avis_input_t *h = handle;
418     AVIStreamRelease(h->p_avi);
419     AVIFileExit();
420     free(h);
421     return 0;
422 }
423 #endif
424
425
426 #ifdef HAVE_PTHREAD
427 typedef struct {
428     int (*p_read_frame)( x264_picture_t *p_pic, hnd_t handle, int i_frame );
429     int (*p_close_infile)( hnd_t handle );
430     hnd_t p_handle;
431     x264_picture_t pic;
432     x264_pthread_t tid;
433     int next_frame;
434     int frame_total;
435     int in_progress;
436     struct thread_input_arg_t *next_args;
437 } thread_input_t;
438
439 typedef struct thread_input_arg_t {
440     thread_input_t *h;
441     x264_picture_t *pic;
442     int i_frame;
443     int status;
444 } thread_input_arg_t;
445
446 int open_file_thread( char *psz_filename, hnd_t *p_handle, x264_param_t *p_param )
447 {
448     thread_input_t *h = malloc(sizeof(thread_input_t));
449     if( !h || x264_picture_alloc( &h->pic, X264_CSP_I420, p_param->i_width, p_param->i_height ) < 0 )
450     {
451         fprintf( stderr, "x264 [error]: malloc failed\n" );
452         return -1;
453     }
454     h->p_read_frame = p_read_frame;
455     h->p_close_infile = p_close_infile;
456     h->p_handle = *p_handle;
457     h->in_progress = 0;
458     h->next_frame = -1;
459     h->next_args = malloc(sizeof(thread_input_arg_t));
460     if( !h->next_args )
461         return -1;
462     h->next_args->h = h;
463     h->next_args->status = 0;
464     h->frame_total = p_get_frame_total( h->p_handle );
465
466     *p_handle = (hnd_t)h;
467     return 0;
468 }
469
470 int get_frame_total_thread( hnd_t handle )
471 {
472     thread_input_t *h = handle;
473     return h->frame_total;
474 }
475
476 static void read_frame_thread_int( thread_input_arg_t *i )
477 {
478     i->status = i->h->p_read_frame( i->pic, i->h->p_handle, i->i_frame );
479 }
480
481 int read_frame_thread( x264_picture_t *p_pic, hnd_t handle, int i_frame )
482 {
483     thread_input_t *h = handle;
484     int ret = 0;
485
486     if( h->next_frame >= 0 )
487     {
488         x264_pthread_join( h->tid, NULL );
489         ret |= h->next_args->status;
490         h->in_progress = 0;
491     }
492
493     if( h->next_frame == i_frame )
494     {
495         XCHG( x264_picture_t, *p_pic, h->pic );
496     }
497     else
498     {
499         ret |= h->p_read_frame( p_pic, h->p_handle, i_frame );
500     }
501
502     if( !h->frame_total || i_frame+1 < h->frame_total )
503     {
504         h->next_frame =
505         h->next_args->i_frame = i_frame+1;
506         h->next_args->pic = &h->pic;
507         if( x264_pthread_create( &h->tid, NULL, (void*)read_frame_thread_int, h->next_args ) )
508             return -1;
509         h->in_progress = 1;
510     }
511     else
512         h->next_frame = -1;
513
514     return ret;
515 }
516
517 int close_file_thread( hnd_t handle )
518 {
519     thread_input_t *h = handle;
520     if( h->in_progress )
521         x264_pthread_join( h->tid, NULL );
522     h->p_close_infile( h->p_handle );
523     x264_picture_clean( &h->pic );
524     free( h->next_args );
525     free( h );
526     return 0;
527 }
528 #endif
529
530
531 int open_file_bsf( char *psz_filename, hnd_t *p_handle )
532 {
533     if ((*p_handle = fopen(psz_filename, "w+b")) == NULL)
534         return -1;
535
536     return 0;
537 }
538
539 int set_param_bsf( hnd_t handle, x264_param_t *p_param )
540 {
541     return 0;
542 }
543
544 int write_nalu_bsf( hnd_t handle, uint8_t *p_nalu, int i_size )
545 {
546     if (fwrite(p_nalu, i_size, 1, (FILE *)handle) > 0)
547         return i_size;
548     return -1;
549 }
550
551 int set_eop_bsf( hnd_t handle,  x264_picture_t *p_picture )
552 {
553     return 0;
554 }
555
556 int close_file_bsf( hnd_t handle )
557 {
558     if ((handle == NULL) || (handle == stdout))
559         return 0;
560
561     return fclose((FILE *)handle);
562 }
563
564 /* -- mp4 muxing support ------------------------------------------------- */
565 #ifdef MP4_OUTPUT
566
567 typedef struct
568 {
569     GF_ISOFile *p_file;
570     GF_AVCConfig *p_config;
571     GF_ISOSample *p_sample;
572     int i_track;
573     uint32_t i_descidx;
574     int i_time_inc;
575     int i_time_res;
576     int i_numframe;
577     int i_init_delay;
578     uint8_t b_sps;
579     uint8_t b_pps;
580 } mp4_t;
581
582
583 static void recompute_bitrate_mp4(GF_ISOFile *p_file, int i_track)
584 {
585     u32 i, count, di, timescale, time_wnd, rate;
586     u64 offset;
587     Double br;
588     GF_ESD *esd;
589
590     esd = gf_isom_get_esd(p_file, i_track, 1);
591     if (!esd) return;
592
593     esd->decoderConfig->avgBitrate = 0;
594     esd->decoderConfig->maxBitrate = 0;
595     rate = time_wnd = 0;
596
597     timescale = gf_isom_get_media_timescale(p_file, i_track);
598     count = gf_isom_get_sample_count(p_file, i_track);
599     for (i=0; i<count; i++) {
600         GF_ISOSample *samp = gf_isom_get_sample_info(p_file, i_track, i+1, &di, &offset);
601
602         if (samp->dataLength>esd->decoderConfig->bufferSizeDB) esd->decoderConfig->bufferSizeDB = samp->dataLength;
603
604         if (esd->decoderConfig->bufferSizeDB < samp->dataLength) esd->decoderConfig->bufferSizeDB = samp->dataLength;
605         esd->decoderConfig->avgBitrate += samp->dataLength;
606         rate += samp->dataLength;
607         if (samp->DTS > time_wnd + timescale) {
608             if (rate > esd->decoderConfig->maxBitrate) esd->decoderConfig->maxBitrate = rate;
609             time_wnd = samp->DTS;
610             rate = 0;
611         }
612
613         gf_isom_sample_del(&samp);
614     }
615
616     br = (Double) (s64) gf_isom_get_media_duration(p_file, i_track);
617     br /= timescale;
618     esd->decoderConfig->avgBitrate = (u32) (esd->decoderConfig->avgBitrate / br);
619     /*move to bps*/
620     esd->decoderConfig->avgBitrate *= 8;
621     esd->decoderConfig->maxBitrate *= 8;
622
623     gf_isom_change_mpeg4_description(p_file, i_track, 1, esd);
624     gf_odf_desc_del((GF_Descriptor *) esd);
625 }
626
627
628 int close_file_mp4( hnd_t handle )
629 {
630     mp4_t *p_mp4 = (mp4_t *)handle;
631
632     if (p_mp4 == NULL)
633         return 0;
634
635     if (p_mp4->p_config)
636         gf_odf_avc_cfg_del(p_mp4->p_config);
637
638     if (p_mp4->p_sample)
639     {
640         if (p_mp4->p_sample->data)
641             free(p_mp4->p_sample->data);
642
643         gf_isom_sample_del(&p_mp4->p_sample);
644     }
645
646     if (p_mp4->p_file)
647     {
648         recompute_bitrate_mp4(p_mp4->p_file, p_mp4->i_track);
649         gf_isom_set_pl_indication(p_mp4->p_file, GF_ISOM_PL_VISUAL, 0x15);
650         gf_isom_set_storage_mode(p_mp4->p_file, GF_ISOM_STORE_FLAT);
651         gf_isom_close(p_mp4->p_file);
652     }
653
654     free(p_mp4);
655
656     return 0;
657 }
658
659 int open_file_mp4( char *psz_filename, hnd_t *p_handle )
660 {
661     mp4_t *p_mp4;
662
663     *p_handle = NULL;
664
665     if ((p_mp4 = (mp4_t *)malloc(sizeof(mp4_t))) == NULL)
666         return -1;
667
668     memset(p_mp4, 0, sizeof(mp4_t));
669     p_mp4->p_file = gf_isom_open(psz_filename, GF_ISOM_OPEN_WRITE, NULL);
670
671     if ((p_mp4->p_sample = gf_isom_sample_new()) == NULL)
672     {
673         close_file_mp4( p_mp4 );
674         return -1;
675     }
676
677     gf_isom_set_brand_info(p_mp4->p_file, GF_ISOM_BRAND_AVC1, 0);
678
679     *p_handle = p_mp4;
680
681     return 0;
682 }
683
684
685 int set_param_mp4( hnd_t handle, x264_param_t *p_param )
686 {
687     mp4_t *p_mp4 = (mp4_t *)handle;
688
689     p_mp4->i_track = gf_isom_new_track(p_mp4->p_file, 0, GF_ISOM_MEDIA_VISUAL,
690         p_param->i_fps_num);
691
692     p_mp4->p_config = gf_odf_avc_cfg_new();
693     gf_isom_avc_config_new(p_mp4->p_file, p_mp4->i_track, p_mp4->p_config,
694         NULL, NULL, &p_mp4->i_descidx);
695
696     gf_isom_set_track_enabled(p_mp4->p_file, p_mp4->i_track, 1);
697
698     gf_isom_set_visual_info(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx,
699         p_param->i_width, p_param->i_height);
700
701     if( p_param->vui.i_sar_width && p_param->vui.i_sar_height )
702     {
703         uint64_t dw = p_param->i_width << 16;
704         uint64_t dh = p_param->i_height << 16;
705         double sar = (double)p_param->vui.i_sar_width / p_param->vui.i_sar_height;
706         if( sar > 1.0 )
707             dw *= sar ;
708         else
709             dh /= sar;
710         gf_isom_set_track_layout_info( p_mp4->p_file, p_mp4->i_track, dw, dh, 0, 0, 0 );
711     }
712
713     p_mp4->p_sample->data = (char *)malloc(p_param->i_width * p_param->i_height * 3 / 2);
714     if (p_mp4->p_sample->data == NULL)
715         return -1;
716
717     p_mp4->i_time_res = p_param->i_fps_num;
718     p_mp4->i_time_inc = p_param->i_fps_den;
719     p_mp4->i_init_delay = p_param->i_bframe ? (p_param->b_bframe_pyramid ? 2 : 1) : 0;
720     p_mp4->i_init_delay *= p_mp4->i_time_inc;
721     fprintf(stderr, "mp4 [info]: initial delay %d (scale %d)\n",
722         p_mp4->i_init_delay, p_mp4->i_time_res);
723
724     return 0;
725 }
726
727
728 int write_nalu_mp4( hnd_t handle, uint8_t *p_nalu, int i_size )
729 {
730     mp4_t *p_mp4 = (mp4_t *)handle;
731     GF_AVCConfigSlot *p_slot;
732     uint8_t type = p_nalu[4] & 0x1f;
733     int psize;
734
735     switch(type)
736     {
737     // sps
738     case 0x07:
739         if (!p_mp4->b_sps)
740         {
741             p_mp4->p_config->configurationVersion = 1;
742             p_mp4->p_config->AVCProfileIndication = p_nalu[5];
743             p_mp4->p_config->profile_compatibility = p_nalu[6];
744             p_mp4->p_config->AVCLevelIndication = p_nalu[7];
745             p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
746             if( !p_slot )
747                 return -1;
748             p_slot->size = i_size - 4;
749             p_slot->data = (char *)malloc(p_slot->size);
750             if( !p_slot->data )
751                 return -1;
752             memcpy(p_slot->data, p_nalu + 4, i_size - 4);
753             gf_list_add(p_mp4->p_config->sequenceParameterSets, p_slot);
754             p_slot = NULL;
755             p_mp4->b_sps = 1;
756         }
757         break;
758
759     // pps
760     case 0x08:
761         if (!p_mp4->b_pps)
762         {
763             p_slot = (GF_AVCConfigSlot *)malloc(sizeof(GF_AVCConfigSlot));
764             if( !p_slot )
765                 return -1;
766             p_slot->size = i_size - 4;
767             p_slot->data = (char *)malloc(p_slot->size);
768             if( !p_slot->data )
769                 return -1;
770             memcpy(p_slot->data, p_nalu + 4, i_size - 4);
771             gf_list_add(p_mp4->p_config->pictureParameterSets, p_slot);
772             p_slot = NULL;
773             p_mp4->b_pps = 1;
774             if (p_mp4->b_sps)
775                 gf_isom_avc_config_update(p_mp4->p_file, p_mp4->i_track, 1, p_mp4->p_config);
776         }
777         break;
778
779     // slice, sei
780     case 0x1:
781     case 0x5:
782     case 0x6:
783         psize = i_size - 4 ;
784         memcpy(p_mp4->p_sample->data + p_mp4->p_sample->dataLength, p_nalu, i_size);
785         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 0] = (psize >> 24) & 0xff;
786         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 1] = (psize >> 16) & 0xff;
787         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 2] = (psize >> 8) & 0xff;
788         p_mp4->p_sample->data[p_mp4->p_sample->dataLength + 3] = (psize >> 0) & 0xff;
789         p_mp4->p_sample->dataLength += i_size;
790         break;
791     }
792
793     return i_size;
794 }
795
796 int set_eop_mp4( hnd_t handle, x264_picture_t *p_picture )
797 {
798     mp4_t *p_mp4 = (mp4_t *)handle;
799     uint64_t dts = (uint64_t)p_mp4->i_numframe * p_mp4->i_time_inc;
800     uint64_t pts = (uint64_t)p_picture->i_pts;
801     int32_t offset = p_mp4->i_init_delay + pts - dts;
802
803     p_mp4->p_sample->IsRAP = p_picture->i_type == X264_TYPE_IDR ? 1 : 0;
804     p_mp4->p_sample->DTS = dts;
805     p_mp4->p_sample->CTS_Offset = offset;
806     gf_isom_add_sample(p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, p_mp4->p_sample);
807
808     p_mp4->p_sample->dataLength = 0;
809     p_mp4->i_numframe++;
810
811     return 0;
812 }
813
814 #endif
815
816
817 /* -- mkv muxing support ------------------------------------------------- */
818 typedef struct
819 {
820     mk_Writer *w;
821
822     uint8_t   *sps, *pps;
823     int       sps_len, pps_len;
824
825     int       width, height, d_width, d_height;
826
827     int64_t   frame_duration;
828     int       fps_num;
829
830     int       b_header_written;
831     char      b_writing_frame;
832 } mkv_t;
833
834 static int write_header_mkv( mkv_t *p_mkv )
835 {
836     int       ret;
837     uint8_t   *avcC;
838     int  avcC_len;
839
840     if( p_mkv->sps == NULL || p_mkv->pps == NULL ||
841         p_mkv->width == 0 || p_mkv->height == 0 ||
842         p_mkv->d_width == 0 || p_mkv->d_height == 0)
843         return -1;
844
845     avcC_len = 5 + 1 + 2 + p_mkv->sps_len + 1 + 2 + p_mkv->pps_len;
846     avcC = malloc(avcC_len);
847     if (avcC == NULL)
848         return -1;
849
850     avcC[0] = 1;
851     avcC[1] = p_mkv->sps[1];
852     avcC[2] = p_mkv->sps[2];
853     avcC[3] = p_mkv->sps[3];
854     avcC[4] = 0xff; // nalu size length is four bytes
855     avcC[5] = 0xe1; // one sps
856
857     avcC[6] = p_mkv->sps_len >> 8;
858     avcC[7] = p_mkv->sps_len;
859
860     memcpy(avcC+8, p_mkv->sps, p_mkv->sps_len);
861
862     avcC[8+p_mkv->sps_len] = 1; // one pps
863     avcC[9+p_mkv->sps_len] = p_mkv->pps_len >> 8;
864     avcC[10+p_mkv->sps_len] = p_mkv->pps_len;
865
866     memcpy( avcC+11+p_mkv->sps_len, p_mkv->pps, p_mkv->pps_len );
867
868     ret = mk_writeHeader( p_mkv->w, "x264", "V_MPEG4/ISO/AVC",
869                           avcC, avcC_len, p_mkv->frame_duration, 50000,
870                           p_mkv->width, p_mkv->height,
871                           p_mkv->d_width, p_mkv->d_height );
872
873     free( avcC );
874
875     p_mkv->b_header_written = 1;
876
877     return ret;
878 }
879
880 int open_file_mkv( char *psz_filename, hnd_t *p_handle )
881 {
882     mkv_t *p_mkv;
883
884     *p_handle = NULL;
885
886     p_mkv  = malloc(sizeof(*p_mkv));
887     if (p_mkv == NULL)
888         return -1;
889
890     memset(p_mkv, 0, sizeof(*p_mkv));
891
892     p_mkv->w = mk_createWriter(psz_filename);
893     if (p_mkv->w == NULL)
894     {
895         free(p_mkv);
896         return -1;
897     }
898
899     *p_handle = p_mkv;
900
901     return 0;
902 }
903
904 int set_param_mkv( hnd_t handle, x264_param_t *p_param )
905 {
906     mkv_t   *p_mkv = handle;
907     int64_t dw, dh;
908
909     if( p_param->i_fps_num > 0 )
910     {
911         p_mkv->frame_duration = (int64_t)p_param->i_fps_den *
912                                 (int64_t)1000000000 / p_param->i_fps_num;
913         p_mkv->fps_num = p_param->i_fps_num;
914     }
915     else
916     {
917         p_mkv->frame_duration = 0;
918         p_mkv->fps_num = 1;
919     }
920
921     p_mkv->width = p_param->i_width;
922     p_mkv->height = p_param->i_height;
923
924     if( p_param->vui.i_sar_width && p_param->vui.i_sar_height )
925     {
926         dw = (int64_t)p_param->i_width  * p_param->vui.i_sar_width;
927         dh = (int64_t)p_param->i_height * p_param->vui.i_sar_height;
928     }
929     else
930     {
931         dw = p_param->i_width;
932         dh = p_param->i_height;
933     }
934
935     if( dw > 0 && dh > 0 )
936     {
937         int64_t x = gcd( dw, dh );
938         dw /= x;
939         dh /= x;
940     }
941
942     p_mkv->d_width = (int)dw;
943     p_mkv->d_height = (int)dh;
944
945     return 0;
946 }
947
948 int write_nalu_mkv( hnd_t handle, uint8_t *p_nalu, int i_size )
949 {
950     mkv_t *p_mkv = handle;
951     uint8_t type = p_nalu[4] & 0x1f;
952     uint8_t dsize[4];
953     int psize;
954
955     switch( type )
956     {
957     // sps
958     case 0x07:
959         if( !p_mkv->sps )
960         {
961             p_mkv->sps = malloc(i_size - 4);
962             if (p_mkv->sps == NULL)
963                 return -1;
964             p_mkv->sps_len = i_size - 4;
965             memcpy(p_mkv->sps, p_nalu + 4, i_size - 4);
966         }
967         break;
968
969     // pps
970     case 0x08:
971         if( !p_mkv->pps )
972         {
973             p_mkv->pps = malloc(i_size - 4);
974             if (p_mkv->pps == NULL)
975                 return -1;
976             p_mkv->pps_len = i_size - 4;
977             memcpy(p_mkv->pps, p_nalu + 4, i_size - 4);
978         }
979         break;
980
981     // slice, sei
982     case 0x1:
983     case 0x5:
984     case 0x6:
985         if( !p_mkv->b_writing_frame )
986         {
987             if( mk_startFrame(p_mkv->w) < 0 )
988                 return -1;
989             p_mkv->b_writing_frame = 1;
990         }
991         psize = i_size - 4 ;
992         dsize[0] = psize >> 24;
993         dsize[1] = psize >> 16;
994         dsize[2] = psize >> 8;
995         dsize[3] = psize;
996         if( mk_addFrameData(p_mkv->w, dsize, 4) < 0 ||
997             mk_addFrameData(p_mkv->w, p_nalu + 4, i_size - 4) < 0 )
998             return -1;
999         break;
1000
1001     default:
1002         break;
1003     }
1004
1005     if( !p_mkv->b_header_written && p_mkv->pps && p_mkv->sps &&
1006         write_header_mkv(p_mkv) < 0 )
1007         return -1;
1008
1009     return i_size;
1010 }
1011
1012 int set_eop_mkv( hnd_t handle, x264_picture_t *p_picture )
1013 {
1014     mkv_t *p_mkv = handle;
1015     int64_t i_stamp = (int64_t)(p_picture->i_pts * 1e9 / p_mkv->fps_num);
1016
1017     p_mkv->b_writing_frame = 0;
1018
1019     return mk_setFrameFlags( p_mkv->w, i_stamp,
1020                              p_picture->i_type == X264_TYPE_IDR );
1021 }
1022
1023 int close_file_mkv( hnd_t handle )
1024 {
1025     mkv_t *p_mkv = handle;
1026     int   ret;
1027
1028     if( p_mkv->sps )
1029         free( p_mkv->sps );
1030     if( p_mkv->pps )
1031         free( p_mkv->pps );
1032
1033     ret = mk_close(p_mkv->w);
1034
1035     free( p_mkv );
1036
1037     return ret;
1038 }
1039