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