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