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