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