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