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