]> git.sesse.net Git - vlc/blob - modules/mux/mp4.c
* mp4: fixed SVQ3 in .mov
[vlc] / modules / mux / mp4.c
1 /*****************************************************************************
2  * mp4.c: mp4/mov muxer
3  *****************************************************************************
4  * Copyright (C) 2001, 2002, 2003 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin at videolan dot org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>
29 #include <string.h>
30 #include <errno.h>
31
32 #include <vlc/vlc.h>
33 #include <vlc/input.h>
34 #include <vlc/sout.h>
35
36 #ifdef HAVE_TIME_H
37 #include <time.h>
38 #endif
39
40 #include "codecs.h"
41
42 /*****************************************************************************
43  * Exported prototypes
44  *****************************************************************************/
45 static int  Open   ( vlc_object_t * );
46 static void Close  ( vlc_object_t * );
47
48 static int Capability(sout_mux_t *, int, void *, void * );
49 static int AddStream( sout_mux_t *, sout_input_t * );
50 static int DelStream( sout_mux_t *, sout_input_t * );
51 static int Mux      ( sout_mux_t * );
52
53 /*****************************************************************************
54  * Module descriptor
55  *****************************************************************************/
56 #define FASTSTART_TEXT N_("Create \"Fast start\" files")
57 #define FASTSTART_LONGTEXT N_( \
58     "When this option is turned on, \"Fast start\" files will be created. " \
59     "(\"Fast start\" files are optimized for download, allowing the user " \
60     "to start previewing the file while it is downloading).")
61
62 vlc_module_begin();
63     set_description( _("MP4/MOV muxer") );
64
65     add_bool( "mp4-faststart", 1, NULL, FASTSTART_TEXT, FASTSTART_LONGTEXT,
66               VLC_TRUE );
67
68     set_capability( "sout mux", 5 );
69     add_shortcut( "mp4" );
70     add_shortcut( "mov" );
71     set_callbacks( Open, Close );
72 vlc_module_end();
73
74 /*****************************************************************************
75  * Local prototypes
76  *****************************************************************************/
77 typedef struct
78 {
79     uint64_t i_pos;
80     int      i_size;
81
82     mtime_t  i_pts;
83     mtime_t  i_dts;
84     mtime_t  i_length;
85
86 } mp4_entry_t;
87
88 typedef struct
89 {
90     es_format_t   *p_fmt;
91     int           i_track_id;
92
93     /* index */
94     unsigned int i_entry_count;
95     unsigned int i_entry_max;
96     mp4_entry_t  *entry;
97
98     /* stats */
99     mtime_t      i_duration;
100
101     /* for later stco fix-up (fast start files) */
102     uint64_t i_stco_pos;
103     vlc_bool_t b_stco64;
104
105 } mp4_stream_t;
106
107 struct sout_mux_sys_t
108 {
109     vlc_bool_t b_mov;
110     vlc_bool_t b_64_ext;
111     vlc_bool_t b_fast_start;
112
113     uint64_t i_mdat_pos;
114     uint64_t i_pos;
115
116     mtime_t  i_start_dts;
117
118     int          i_nb_streams;
119     mp4_stream_t **pp_streams;
120 };
121
122 typedef struct bo_t
123 {
124     vlc_bool_t b_grow;
125
126     int        i_buffer_size;
127     int        i_buffer;
128     uint8_t    *p_buffer;
129
130 } bo_t;
131
132 static void bo_init     ( bo_t *, int , uint8_t *, vlc_bool_t  );
133 static void bo_add_8    ( bo_t *, uint8_t );
134 static void bo_add_16be ( bo_t *, uint16_t );
135 static void bo_add_24be ( bo_t *, uint32_t );
136 static void bo_add_32be ( bo_t *, uint32_t );
137 static void bo_add_64be ( bo_t *, uint64_t );
138 static void bo_add_fourcc(bo_t *, char * );
139 static void bo_add_bo   ( bo_t *, bo_t * );
140 static void bo_add_mem  ( bo_t *, int , uint8_t * );
141 static void bo_add_descr( bo_t *, uint8_t , uint32_t );
142
143 static void bo_fix_32be ( bo_t *, int , uint32_t );
144
145 static bo_t *box_new     ( char *fcc );
146 static bo_t *box_full_new( char *fcc, uint8_t v, uint32_t f );
147 static void  box_fix     ( bo_t *box );
148 static void  box_free    ( bo_t *box );
149 static void  box_gather  ( bo_t *box, bo_t *box2 );
150
151 static void box_send( sout_mux_t *p_mux,  bo_t *box );
152
153 static int64_t get_timestamp();
154
155 static sout_buffer_t *bo_to_sout( sout_instance_t *p_sout,  bo_t *box );
156
157 /*****************************************************************************
158  * Open:
159  *****************************************************************************/
160 static int Open( vlc_object_t *p_this )
161 {
162     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
163     sout_mux_sys_t  *p_sys;
164     bo_t            *box;
165
166     p_sys = malloc( sizeof( sout_mux_sys_t ) );
167     p_sys->i_pos        = 0;
168     p_sys->i_nb_streams = 0;
169     p_sys->pp_streams   = NULL;
170     p_sys->i_mdat_pos   = 0;
171     p_sys->b_mov        = p_mux->psz_mux && !strcmp( p_mux->psz_mux, "mov" );
172     p_sys->i_start_dts  = 0;
173
174     msg_Dbg( p_mux, "Open" );
175
176     p_mux->pf_capacity  = Capability;
177     p_mux->pf_addstream = AddStream;
178     p_mux->pf_delstream = DelStream;
179     p_mux->pf_mux       = Mux;
180     p_mux->p_sys        = p_sys;
181
182     if( !p_sys->b_mov )
183     {
184         /* Now add ftyp header */
185         box = box_new( "ftyp" );
186         bo_add_fourcc( box, "isom" );
187         bo_add_32be  ( box, 0 );
188         bo_add_fourcc( box, "mp41" );
189         box_fix( box );
190
191         p_sys->i_pos += box->i_buffer;
192         p_sys->i_mdat_pos = p_sys->i_pos;
193
194         box_send( p_mux, box );
195     }
196
197     /* FIXME FIXME
198      * Quicktime actually doesn't like the 64 bits extensions !!! */
199     p_sys->b_64_ext = VLC_FALSE;
200
201     /* Now add mdat header */
202     box = box_new( "mdat" );
203     bo_add_64be  ( box, 0 ); // enough to store an extended size
204
205     p_sys->i_pos += box->i_buffer;
206
207     box_send( p_mux, box );
208
209     return VLC_SUCCESS;
210 }
211
212 static int GetDescrLength( int i_size )
213 {
214     if( i_size < 0x00000080 )
215         return 2 + i_size;
216     else if( i_size < 0x00004000 )
217         return 3 + i_size;
218     else if( i_size < 0x00200000 )
219         return 4 + i_size;
220     else
221         return 5 + i_size;
222 }
223
224 static bo_t *GetESDS( mp4_stream_t *p_stream )
225 {
226     bo_t *esds;
227     int  i_stream_type;
228     int  i_object_type_indication;
229     int  i_decoder_specific_info_size;
230
231     if( p_stream->p_fmt->i_extra > 0 )
232     {
233         i_decoder_specific_info_size =
234             GetDescrLength( p_stream->p_fmt->i_extra );
235     }
236     else
237     {
238         i_decoder_specific_info_size = 0;
239     }
240
241     esds = box_full_new( "esds", 0, 0 );
242
243     /* ES_Descr */
244     bo_add_descr( esds, 0x03, 3 +
245                   GetDescrLength( 13 + i_decoder_specific_info_size ) +
246                   GetDescrLength( 1 ) );
247     bo_add_16be( esds, p_stream->i_track_id );
248     bo_add_8   ( esds, 0x1f );      // flags=0|streamPriority=0x1f
249
250     /* DecoderConfigDescr */
251     bo_add_descr( esds, 0x04, 13 + i_decoder_specific_info_size );
252
253     switch( p_stream->p_fmt->i_codec )
254     {
255         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
256             i_object_type_indication = 0x20;
257             break;
258         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
259             /* FIXME MPEG-I=0x6b, MPEG-II = 0x60 -> 0x65 */
260             i_object_type_indication = 0x60;
261             break;
262         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
263             /* FIXME for mpeg2-aac == 0x66->0x68 */
264             i_object_type_indication = 0x40;
265             break;
266         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
267             i_object_type_indication =
268                 p_stream->p_fmt->audio.i_rate < 32000 ? 0x69 : 0x6b;
269             break;
270         default:
271             i_object_type_indication = 0x00;
272             break;
273     }
274     i_stream_type = p_stream->p_fmt->i_cat == VIDEO_ES ? 0x04 : 0x05;
275
276     bo_add_8   ( esds, i_object_type_indication );
277     bo_add_8   ( esds, ( i_stream_type << 2 ) | 1 );
278     bo_add_24be( esds, 1024 * 1024 );       // bufferSizeDB
279     bo_add_32be( esds, 0x7fffffff );        // maxBitrate
280     bo_add_32be( esds, 0 );                 // avgBitrate
281
282     if( p_stream->p_fmt->i_extra > 0 )
283     {
284         int i;
285
286         /* DecoderSpecificInfo */
287         bo_add_descr( esds, 0x05, p_stream->p_fmt->i_extra );
288
289         for( i = 0; i < p_stream->p_fmt->i_extra; i++ )
290         {
291             bo_add_8( esds, ((uint8_t*)p_stream->p_fmt->p_extra)[i] );
292         }
293     }
294
295     /* SL_Descr mandatory */
296     bo_add_descr( esds, 0x06, 1 );
297     bo_add_8    ( esds, 0x02 );  // sl_predefined
298
299     box_fix( esds );
300
301     return esds;
302 }
303
304 static bo_t *GetWaveTag( mp4_stream_t *p_stream )
305 {
306     bo_t *wave;
307     bo_t *box;
308
309     wave = box_new( "wave" );
310
311     box = box_new( "frma" );
312     bo_add_fourcc( box, "mp4a" );
313     box_fix( box );
314     box_gather( wave, box );
315
316     box = box_new( "mp4a" );
317     bo_add_32be( box, 0 );
318     box_fix( box );
319     box_gather( wave, box );
320
321     box = GetESDS( p_stream );
322     box_fix( box );
323     box_gather( wave, box );
324
325     box = box_new( "srcq" );
326     bo_add_32be( box, 0x40 );
327     box_fix( box );
328     box_gather( wave, box );
329
330     /* wazza ? */
331     bo_add_32be( wave, 8 ); /* new empty box */
332     bo_add_32be( wave, 0 ); /* box label */
333
334     box_fix( wave );
335
336     return wave;
337 }
338
339 /* TODO: No idea about these values */
340 static bo_t *GetSVQ3Tag( mp4_stream_t *p_stream )
341 {
342     bo_t *smi = box_new( "SMI " );
343
344     if( p_stream->p_fmt->i_extra > 0x4e )
345     {
346         uint8_t *p_end = &((uint8_t*)p_stream->p_fmt->p_extra)[p_stream->p_fmt->i_extra];
347         uint8_t *p     = &((uint8_t*)p_stream->p_fmt->p_extra)[0x46];
348
349         while( p + 8 < p_end )
350         {
351             int i_size = GetDWBE( p );
352             if( i_size <= 1 )
353             {
354                 /* FIXME handle 1 as long size */
355                 break;
356             }
357             if( !strncmp( &p[4], "SMI ", 4 ) )
358             {
359                 bo_add_mem( smi, p_end - p - 8, &p[8] );
360                 return smi;
361             }
362             p += i_size;
363         }
364     }
365
366     /* Create a dummy one in fallback */
367     bo_add_fourcc( smi, "SEQH" );
368     bo_add_32be( smi, 0x5 );
369     bo_add_32be( smi, 0xe2c0211d );
370     bo_add_8( smi, 0xc0 );
371     box_fix( smi );
372
373     return smi;
374 }
375
376 static bo_t *GetUdtaTag( sout_mux_t *p_mux )
377 {
378     sout_mux_sys_t *p_sys = p_mux->p_sys;
379     bo_t *udta = box_new( "udta" );
380     int i_track;
381
382     /* Requirements */
383     for( i_track = 0; i_track < p_sys->i_nb_streams; i_track++ )
384     {
385         mp4_stream_t *p_stream = p_sys->pp_streams[i_track];
386
387         if( p_stream->p_fmt->i_codec == VLC_FOURCC('m','p','4','v') ||
388             p_stream->p_fmt->i_codec == VLC_FOURCC('m','p','4','a') )
389         {
390             bo_t *box = box_new( "\251req" );
391             /* String length */
392             bo_add_16be( box, sizeof("QuickTime 6.0 or greater") - 1);
393             bo_add_16be( box, 0 );
394             bo_add_mem( box, sizeof("QuickTime 6.0 or greater") - 1,
395                         "QuickTime 6.0 or greater" );
396             box_fix( box );
397             box_gather( udta, box );
398             break;
399         }
400     }
401
402     /* Encoder */
403     {
404         bo_t *box = box_new( "\251enc" );
405         /* String length */
406         bo_add_16be( box, sizeof(PACKAGE_STRING " stream output") - 1);
407         bo_add_16be( box, 0 );
408         bo_add_mem( box, sizeof(PACKAGE_STRING " stream output") - 1,
409                     PACKAGE_STRING " stream output" );
410         box_fix( box );
411         box_gather( udta, box );
412     }
413
414     box_fix( udta );
415     return udta;
416 }
417
418 static bo_t *GetSounBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
419 {
420     sout_mux_sys_t *p_sys = p_mux->p_sys;
421     vlc_bool_t b_descr = VLC_FALSE;
422     bo_t *soun;
423     char fcc[4] = "    ";
424     int  i;
425
426     switch( p_stream->p_fmt->i_codec )
427     {
428     case VLC_FOURCC('m','p','4','a'):
429         memcpy( fcc, "mp4a", 4 );
430         b_descr = VLC_TRUE;
431         break;
432
433     case VLC_FOURCC('m','p','g','a'):
434         if( p_sys->b_mov )
435             memcpy( fcc, ".mp3", 4 );
436         else
437         {
438             memcpy( fcc, "mp4a", 4 );
439             b_descr = VLC_TRUE;
440         }
441         break;
442
443     default:
444         memcpy( fcc, (char*)&p_stream->p_fmt->i_codec, 4 );
445         break;
446     }
447
448     soun = box_new( fcc );
449     for( i = 0; i < 6; i++ )
450     {
451         bo_add_8( soun, 0 );        // reserved;
452     }
453     bo_add_16be( soun, 1 );         // data-reference-index
454
455     /* SoundDescription */
456     if( p_sys->b_mov &&
457         p_stream->p_fmt->i_codec == VLC_FOURCC('m','p','4','a') )
458     {
459         bo_add_16be( soun, 1 );     // version 1;
460     }
461     else
462     {
463         bo_add_16be( soun, 0 );     // version 0;
464     }
465     bo_add_16be( soun, 0 );         // revision level (0)
466     bo_add_32be( soun, 0 );         // vendor
467     // channel-count
468     bo_add_16be( soun, p_stream->p_fmt->audio.i_channels );
469     // sample size
470     bo_add_16be( soun, p_stream->p_fmt->audio.i_bitspersample ?
471                  p_stream->p_fmt->audio.i_bitspersample : 16 );
472     bo_add_16be( soun, -2 );        // compression id
473     bo_add_16be( soun, 0 );         // packet size (0)
474     bo_add_16be( soun, p_stream->p_fmt->audio.i_rate ); // sampleratehi
475     bo_add_16be( soun, 0 );                             // sampleratelo
476
477     /* Extended data for SoundDescription V1 */
478     if( p_sys->b_mov &&
479         p_stream->p_fmt->i_codec == VLC_FOURCC('m','p','4','a') )
480     {
481         /* samples per packet */
482         bo_add_32be( soun, p_stream->p_fmt->audio.i_frame_length );
483         bo_add_32be( soun, 1536 ); /* bytes per packet */
484         bo_add_32be( soun, 2 );    /* bytes per frame */
485         /* bytes per sample */
486         bo_add_32be( soun, 2 /*p_stream->p_fmt->audio.i_bitspersample/8 */);
487     }
488
489     /* Add an ES Descriptor */
490     if( b_descr )
491     {
492         bo_t *box;
493
494         if( p_sys->b_mov &&
495             p_stream->p_fmt->i_codec == VLC_FOURCC('m','p','4','a') )
496         {
497             box = GetWaveTag( p_stream );
498         }
499         else
500         {
501             box = GetESDS( p_stream );
502         }
503         box_fix( box );
504         box_gather( soun, box );
505     }
506
507     box_fix( soun );
508
509     return soun;
510 }
511
512 static bo_t *GetVideBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
513 {
514
515     bo_t *vide;
516     char fcc[4] = "    ";
517     int  i;
518
519     switch( p_stream->p_fmt->i_codec )
520     {
521     case VLC_FOURCC('m','p','4','v'):
522     case VLC_FOURCC('m','p','g','v'):
523         memcpy( fcc, "mp4v", 4 );
524         break;
525
526     case VLC_FOURCC('M','J','P','G'):
527         memcpy( fcc, "mjpa", 4 );
528         break;
529
530     case VLC_FOURCC('S','V','Q','3'):
531         memcpy( fcc, "SVQ3", 4 );
532         break;
533
534     default:
535         memcpy( fcc, (char*)&p_stream->p_fmt->i_codec, 4 );
536         break;
537     }
538
539     vide = box_new( fcc );
540     for( i = 0; i < 6; i++ )
541     {
542         bo_add_8( vide, 0 );        // reserved;
543     }
544     bo_add_16be( vide, 1 );         // data-reference-index
545
546     bo_add_16be( vide, 0 );         // predefined;
547     bo_add_16be( vide, 0 );         // reserved;
548     for( i = 0; i < 3; i++ )
549     {
550         bo_add_32be( vide, 0 );     // predefined;
551     }
552
553     bo_add_16be( vide, p_stream->p_fmt->video.i_width );  // i_width
554     bo_add_16be( vide, p_stream->p_fmt->video.i_height ); // i_height
555
556     bo_add_32be( vide, 0x00480000 );                // h 72dpi
557     bo_add_32be( vide, 0x00480000 );                // v 72dpi
558
559     bo_add_32be( vide, 0 );         // data size, always 0
560     bo_add_16be( vide, 1 );         // frames count per sample
561
562     // compressor name;
563     for( i = 0; i < 32; i++ )
564     {
565         bo_add_8( vide, 0 );
566     }
567
568     bo_add_16be( vide, 0x18 );      // depth
569     bo_add_16be( vide, 0xffff );    // predefined
570
571     /* add an ES Descriptor */
572     switch( p_stream->p_fmt->i_codec )
573     {
574     case VLC_FOURCC('m','p','4','v'):
575     case VLC_FOURCC('m','p','g','v'):
576         {
577             bo_t *esds = GetESDS( p_stream );
578
579             box_fix( esds );
580             box_gather( vide, esds );
581         }
582         break;
583
584     case VLC_FOURCC('S','V','Q','3'):
585         {
586             bo_t *esds = GetSVQ3Tag( p_stream );
587
588             box_fix( esds );
589             box_gather( vide, esds );
590         }
591         break;
592
593     default:
594         break;
595     }
596
597     box_fix( vide );
598
599     return vide;
600 }
601
602 static bo_t *GetStblBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
603 {
604     sout_mux_sys_t *p_sys = p_mux->p_sys;
605     unsigned int i_chunk, i_stsc_last_val, i_stsc_entries, i, i_index;
606     bo_t *stbl, *stsd, *stts, *stco, *stsc, *stsz;
607     uint32_t i_timescale;
608
609     stbl = box_new( "stbl" );
610     stsd = box_full_new( "stsd", 0, 0 );
611     bo_add_32be( stsd, 1 );
612
613     if( p_stream->p_fmt->i_cat == AUDIO_ES )
614     {
615         bo_t *soun = GetSounBox( p_mux, p_stream );
616         box_gather( stsd, soun );
617     }
618     else if( p_stream->p_fmt->i_cat == VIDEO_ES )
619     {
620         bo_t *vide = GetVideBox( p_mux, p_stream );
621         box_gather( stsd, vide );
622     }
623
624     /* append stsd to stbl */
625     box_fix( stsd );
626     box_gather( stbl, stsd );
627
628     /* chunk offset table */
629     p_stream->i_stco_pos = stbl->i_buffer + 16;
630     if( p_sys->i_pos >= (((uint64_t)0x1) << 32) )
631     {
632         /* 64 bits version */
633         p_stream->b_stco64 = VLC_TRUE;
634         stco = box_full_new( "co64", 0, 0 );
635     }
636     else
637     {
638         /* 32 bits version */
639         p_stream->b_stco64 = VLC_FALSE;
640         stco = box_full_new( "stco", 0, 0 );
641     }
642     bo_add_32be( stco, 0 );     // entry-count (fixed latter)
643
644     /* sample to chunk table */
645     stsc = box_full_new( "stsc", 0, 0 );
646     bo_add_32be( stsc, 0 );     // entry-count (fixed latter)
647
648     for( i_chunk = 0, i_stsc_last_val = 0, i_stsc_entries = 0, i = 0;
649          i < p_stream->i_entry_count; i_chunk++ )
650     {
651         int i_first = i;
652
653         if( p_stream->b_stco64 )
654             bo_add_64be( stco, p_stream->entry[i].i_pos );
655         else
656             bo_add_32be( stco, p_stream->entry[i].i_pos );
657
658         while( i < p_stream->i_entry_count )
659         {
660             if( i + 1 < p_stream->i_entry_count &&
661                 p_stream->entry[i].i_pos + p_stream->entry[i].i_size
662                 != p_stream->entry[i + 1].i_pos )
663             {
664                 i++;
665                 break;
666             }
667
668             i++;
669         }
670
671         /* Add entry to the stsc table */
672         if( i_stsc_last_val != i - i_first )
673         {
674             bo_add_32be( stsc, 1 + i_chunk );   // first-chunk
675             bo_add_32be( stsc, i - i_first ) ;  // samples-per-chunk
676             bo_add_32be( stsc, 1 );             // sample-descr-index
677             i_stsc_last_val = i - i_first;
678             i_stsc_entries++;
679         }
680     }
681
682     /* Fix stco entry count */
683     bo_fix_32be( stco, 12, i_chunk );
684     msg_Dbg( p_mux, "created %d chunks (stco)", i_chunk );
685
686     /* append stco to stbl */
687     box_fix( stco );
688     box_gather( stbl, stco );
689
690     /* Fix stsc entry count */
691     bo_fix_32be( stsc, 12, i_stsc_entries  );
692
693     /* append stsc to stbl */
694     box_fix( stsc );
695     box_gather( stbl, stsc );
696
697     /* add stts */
698     stts = box_full_new( "stts", 0, 0 );
699     bo_add_32be( stts, 0 );     // entry-count (fixed latter)
700
701     if( p_stream->p_fmt->i_cat == AUDIO_ES )
702         i_timescale = p_stream->p_fmt->audio.i_rate;
703     else
704         i_timescale = 1001;
705
706     for( i = 0, i_index = 0; i < p_stream->i_entry_count; i_index++)
707     {
708         int64_t i_delta;
709         int     i_first;
710
711         i_first = i;
712         i_delta = p_stream->entry[i].i_length;
713
714         while( i < p_stream->i_entry_count )
715         {
716             if( i + 1 < p_stream->i_entry_count &&
717                 p_stream->entry[i + 1].i_length != i_delta )
718             {
719                 i++;
720                 break;
721             }
722
723             i++;
724         }
725
726         bo_add_32be( stts, i - i_first );           // sample-count
727         bo_add_32be( stts, i_delta * (int64_t)i_timescale /
728                      (int64_t)1000000 );            // sample-delta
729     }
730     bo_fix_32be( stts, 12, i_index );
731
732     /* append stts to stbl */
733     box_fix( stts );
734     box_gather( stbl, stts );
735
736     /* FIXME add ctts ?? FIXME */
737
738     stsz = box_full_new( "stsz", 0, 0 );
739     bo_add_32be( stsz, 0 );                             // sample-size
740     bo_add_32be( stsz, p_stream->i_entry_count );       // sample-count
741     for( i = 0; i < p_stream->i_entry_count; i++ )
742     {
743         bo_add_32be( stsz, p_stream->entry[i].i_size ); // sample-size
744     }
745     /* append stsz to stbl */
746     box_fix( stsz );
747     box_gather( stbl, stsz );
748
749     box_fix( stbl );
750
751     return stbl;
752 }
753
754 static uint32_t mvhd_matrix[9] =
755     { 0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000 };
756
757 static bo_t *GetMoovBox( sout_mux_t *p_mux )
758 {
759     sout_mux_sys_t *p_sys = p_mux->p_sys;
760
761     bo_t            *moov, *mvhd;
762     int             i_trak, i;
763
764     uint32_t        i_movie_timescale = 90000;
765     int64_t         i_movie_duration  = 0;
766
767     moov = box_new( "moov" );
768
769     /* Create general info */
770     for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
771     {
772         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
773         i_movie_duration = __MAX( i_movie_duration, p_stream->i_duration );
774     }
775     msg_Dbg( p_mux, "movie duration %ds",
776              (uint32_t)( i_movie_duration / (mtime_t)1000000 ) );
777
778     i_movie_duration = i_movie_duration * i_movie_timescale / 1000000;
779
780     /* *** add /moov/mvhd *** */
781     if( !p_sys->b_64_ext )
782     {
783         mvhd = box_full_new( "mvhd", 0, 0 );
784         bo_add_32be( mvhd, get_timestamp() );   // creation time
785         bo_add_32be( mvhd, get_timestamp() );   // modification time
786         bo_add_32be( mvhd, i_movie_timescale);  // timescale
787         bo_add_32be( mvhd, i_movie_duration );  // duration
788     }
789     else
790     {
791         mvhd = box_full_new( "mvhd", 1, 0 );
792         bo_add_64be( mvhd, get_timestamp() );   // creation time
793         bo_add_64be( mvhd, get_timestamp() );   // modification time
794         bo_add_32be( mvhd, i_movie_timescale);  // timescale
795         bo_add_64be( mvhd, i_movie_duration );  // duration
796     }
797     bo_add_32be( mvhd, 0x10000 );           // rate
798     bo_add_16be( mvhd, 0x100 );             // volume
799     bo_add_16be( mvhd, 0 );                 // reserved
800     for( i = 0; i < 2; i++ )
801     {
802         bo_add_32be( mvhd, 0 );             // reserved
803     }
804     for( i = 0; i < 9; i++ )
805     {
806         bo_add_32be( mvhd, mvhd_matrix[i] );// matrix
807     }
808     for( i = 0; i < 6; i++ )
809     {
810         bo_add_32be( mvhd, 0 );             // pre-defined
811     }
812
813     /* Next available track id */
814     bo_add_32be( mvhd, p_sys->i_nb_streams + 1 ); // next-track-id
815
816     box_fix( mvhd );
817     box_gather( moov, mvhd );
818
819     for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
820     {
821         mp4_stream_t *p_stream;
822         uint32_t     i_timescale;
823
824         bo_t *trak, *tkhd, *mdia, *mdhd, *hdlr;
825         bo_t *minf, *dinf, *dref, *url, *stbl;
826
827         p_stream = p_sys->pp_streams[i_trak];
828
829         if( p_stream->p_fmt->i_cat != AUDIO_ES &&
830             p_stream->p_fmt->i_cat != VIDEO_ES )
831         {
832             msg_Err( p_mux, "FIXME ignoring trak (noaudio&&novideo)" );
833             continue;
834         }
835
836         if( p_stream->p_fmt->i_cat == AUDIO_ES )
837             i_timescale = p_stream->p_fmt->audio.i_rate;
838         else
839             i_timescale = 1001;
840
841         /* *** add /moov/trak *** */
842         trak = box_new( "trak" );
843
844         /* *** add /moov/trak/tkhd *** */
845         if( !p_sys->b_64_ext )
846         {
847             if( p_sys->b_mov )
848                 tkhd = box_full_new( "tkhd", 0, 0x0f );
849             else
850                 tkhd = box_full_new( "tkhd", 0, 1 );
851
852             bo_add_32be( tkhd, get_timestamp() );       // creation time
853             bo_add_32be( tkhd, get_timestamp() );       // modification time
854             bo_add_32be( tkhd, p_stream->i_track_id );
855             bo_add_32be( tkhd, 0 );                     // reserved 0
856             bo_add_32be( tkhd, p_stream->i_duration *
857                          (int64_t)i_movie_timescale /
858                          (mtime_t)1000000 );            // duration
859         }
860         else
861         {
862             if( p_sys->b_mov )
863                 tkhd = box_full_new( "tkhd", 1, 0x0f );
864             else
865                 tkhd = box_full_new( "tkhd", 1, 1 );
866
867             bo_add_64be( tkhd, get_timestamp() );       // creation time
868             bo_add_64be( tkhd, get_timestamp() );       // modification time
869             bo_add_32be( tkhd, p_stream->i_track_id );
870             bo_add_32be( tkhd, 0 );                     // reserved 0
871             bo_add_64be( tkhd, p_stream->i_duration *
872                          (int64_t)i_movie_timescale /
873                          (mtime_t)1000000 );            // duration
874         }
875
876         for( i = 0; i < 2; i++ )
877         {
878             bo_add_32be( tkhd, 0 );                 // reserved
879         }
880         bo_add_16be( tkhd, 0 );                     // layer
881         bo_add_16be( tkhd, 0 );                     // pre-defined
882         // volume
883         bo_add_16be( tkhd, p_stream->p_fmt->i_cat == AUDIO_ES ? 0x100 : 0 );
884         bo_add_16be( tkhd, 0 );                     // reserved
885         for( i = 0; i < 9; i++ )
886         {
887             bo_add_32be( tkhd, mvhd_matrix[i] );    // matrix
888         }
889         if( p_stream->p_fmt->i_cat == AUDIO_ES )
890         {
891             bo_add_32be( tkhd, 0 );                 // width (presentation)
892             bo_add_32be( tkhd, 0 );                 // height(presentation)
893         }
894         else
895         {
896             // width (presentation)
897             bo_add_32be( tkhd, p_stream->p_fmt->video.i_aspect *
898                          p_stream->p_fmt->video.i_height /
899                          VOUT_ASPECT_FACTOR << 16 );
900             // height(presentation)
901             bo_add_32be( tkhd, p_stream->p_fmt->video.i_height << 16 );
902         }
903         box_fix( tkhd );
904         box_gather( trak, tkhd );
905
906         /* *** add /moov/trak/mdia *** */
907         mdia = box_new( "mdia" );
908
909         /* media header */
910         if( !p_sys->b_64_ext )
911         {
912             mdhd = box_full_new( "mdhd", 0, 0 );
913             bo_add_32be( mdhd, get_timestamp() );   // creation time
914             bo_add_32be( mdhd, get_timestamp() );   // modification time
915             bo_add_32be( mdhd, i_timescale);        // timescale
916             bo_add_32be( mdhd, p_stream->i_duration * (int64_t)i_timescale /
917                                (mtime_t)1000000 );  // duration
918         }
919         else
920         {
921             mdhd = box_full_new( "mdhd", 1, 0 );
922             bo_add_64be( mdhd, get_timestamp() );   // creation time
923             bo_add_64be( mdhd, get_timestamp() );   // modification time
924             bo_add_32be( mdhd, i_timescale);        // timescale
925             bo_add_64be( mdhd, p_stream->i_duration * (int64_t)i_timescale /
926                                (mtime_t)1000000 );  // duration
927         }
928
929         bo_add_16be( mdhd, 0    );              // language   FIXME
930         bo_add_16be( mdhd, 0    );              // predefined
931         box_fix( mdhd );
932         box_gather( mdia, mdhd );
933
934         /* handler reference */
935         hdlr = box_full_new( "hdlr", 0, 0 );
936
937         bo_add_fourcc( hdlr, "mhlr" );         // media handler
938         if( p_stream->p_fmt->i_cat == AUDIO_ES )
939         {
940             bo_add_fourcc( hdlr, "soun" );
941         }
942         else
943         {
944             bo_add_fourcc( hdlr, "vide" );
945         }
946
947         bo_add_32be( hdlr, 0 );         // reserved
948         bo_add_32be( hdlr, 0 );         // reserved
949         bo_add_32be( hdlr, 0 );         // reserved
950
951         bo_add_8( hdlr, 12 );
952         if( p_stream->p_fmt->i_cat == AUDIO_ES )
953             bo_add_mem( hdlr, 12, "SoundHandler" );
954         else
955             bo_add_mem( hdlr, 12, "VideoHandler" );
956
957         box_fix( hdlr );
958         box_gather( mdia, hdlr );
959
960         /* minf*/
961         minf = box_new( "minf" );
962
963         /* add smhd|vmhd */
964         if( p_stream->p_fmt->i_cat == AUDIO_ES )
965         {
966             bo_t *smhd;
967
968             smhd = box_full_new( "smhd", 0, 0 );
969             bo_add_16be( smhd, 0 );     // balance
970             bo_add_16be( smhd, 0 );     // reserved
971             box_fix( smhd );
972
973             box_gather( minf, smhd );
974         }
975         else if( p_stream->p_fmt->i_cat == VIDEO_ES )
976         {
977             bo_t *vmhd;
978
979             vmhd = box_full_new( "vmhd", 0, 1 );
980             bo_add_16be( vmhd, 0 );     // graphicsmode
981             for( i = 0; i < 3; i++ )
982             {
983                 bo_add_16be( vmhd, 0 ); // opcolor
984             }
985             box_fix( vmhd );
986
987             box_gather( minf, vmhd );
988         }
989
990         /* dinf */
991         dinf = box_new( "dinf" );
992         dref = box_full_new( "dref", 0, 0 );
993         bo_add_32be( dref, 1 );
994         url = box_full_new( "url ", 0, 0x01 );
995         box_fix( url );
996         box_gather( dref, url );
997         box_fix( dref );
998         box_gather( dinf, dref );
999
1000         /* append dinf to mdia */
1001         box_fix( dinf );
1002         box_gather( minf, dinf );
1003
1004         /* add stbl */
1005         stbl = GetStblBox( p_mux, p_stream );
1006
1007         /* append stbl to minf */
1008         p_stream->i_stco_pos += minf->i_buffer;
1009         box_gather( minf, stbl );
1010
1011         /* append minf to mdia */
1012         box_fix( minf );
1013         p_stream->i_stco_pos += mdia->i_buffer;
1014         box_gather( mdia, minf );
1015
1016         /* append mdia to trak */
1017         box_fix( mdia );
1018         p_stream->i_stco_pos += trak->i_buffer;
1019         box_gather( trak, mdia );
1020
1021         /* append trak to moov */
1022         box_fix( trak );
1023         p_stream->i_stco_pos += moov->i_buffer;
1024         box_gather( moov, trak );
1025     }
1026
1027     /* Add user data tags */
1028     box_gather( moov, GetUdtaTag( p_mux ) );
1029
1030     box_fix( moov );
1031     return moov;
1032 }
1033
1034 /*****************************************************************************
1035  * Close:
1036  *****************************************************************************/
1037 static void Close( vlc_object_t * p_this )
1038 {
1039     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
1040     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1041     sout_buffer_t   *p_hdr;
1042     bo_t            bo, *moov;
1043     vlc_value_t     val;
1044
1045     int             i_trak;
1046     uint64_t        i_moov_pos;
1047
1048     msg_Dbg( p_mux, "Close" );
1049
1050     /* Update mdat size */
1051     bo_init( &bo, 0, NULL, VLC_TRUE );
1052     if( p_sys->i_pos - p_sys->i_mdat_pos >= (((uint64_t)1)<<32) )
1053     {
1054         /* Extended size */
1055         bo_add_32be  ( &bo, 1 );
1056         bo_add_fourcc( &bo, "mdat" );
1057         bo_add_64be  ( &bo, p_sys->i_pos - p_sys->i_mdat_pos );
1058     }
1059     else
1060     {
1061         bo_add_32be  ( &bo, 8 );
1062         bo_add_fourcc( &bo, "wide" );
1063         bo_add_32be  ( &bo, p_sys->i_pos - p_sys->i_mdat_pos - 8 );
1064         bo_add_fourcc( &bo, "mdat" );
1065     }
1066     p_hdr = bo_to_sout( p_mux->p_sout, &bo );
1067     free( bo.p_buffer );
1068
1069     sout_AccessOutSeek( p_mux->p_access, p_sys->i_mdat_pos );
1070     sout_AccessOutWrite( p_mux->p_access, p_hdr );
1071
1072     /* Create MOOV header */
1073     i_moov_pos = p_sys->i_pos;
1074     moov = GetMoovBox( p_mux );
1075
1076     /* Check we need to create "fast start" files */
1077     var_Create( p_this, "mp4-faststart", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
1078     var_Get( p_this, "mp4-faststart", &val );
1079     p_sys->b_fast_start = val.b_bool;
1080     while( p_sys->b_fast_start )
1081     {
1082         /* Move data to the end of the file so we can fit the moov header
1083          * at the start */
1084         sout_buffer_t *p_buf;
1085         int64_t i_chunk, i_size = p_sys->i_pos - p_sys->i_mdat_pos;
1086         int i_moov_size = moov->i_buffer;
1087
1088         while( i_size > 0 )
1089         {
1090             i_chunk = __MIN( 32768, i_size );
1091             p_buf = sout_BufferNew( p_mux->p_sout, i_chunk );
1092             sout_AccessOutSeek( p_mux->p_access,
1093                                 p_sys->i_mdat_pos + i_size - i_chunk );
1094             if( sout_AccessOutRead( p_mux->p_access, p_buf ) < i_chunk )
1095             {
1096                 msg_Warn( p_this, "read() not supported by acces output, "
1097                           "won't create a fast start file" );
1098                 p_sys->b_fast_start = VLC_FALSE;
1099                 break;
1100             }
1101             sout_AccessOutSeek( p_mux->p_access, p_sys->i_mdat_pos + i_size +
1102                                 i_moov_size - i_chunk );
1103             sout_AccessOutWrite( p_mux->p_access, p_buf );
1104             i_size -= i_chunk;
1105         }
1106
1107         if( !p_sys->b_fast_start ) break;
1108
1109         /* Fix-up samples to chunks table in MOOV header */
1110         for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
1111         {
1112             mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
1113             unsigned int i;
1114             int i_chunk;
1115
1116             moov->i_buffer = p_stream->i_stco_pos;
1117             for( i_chunk = 0, i = 0; i < p_stream->i_entry_count; i_chunk++ )
1118             {
1119                 if( p_stream->b_stco64 )
1120                     bo_add_64be( moov, p_stream->entry[i].i_pos + i_moov_size);
1121                 else
1122                     bo_add_32be( moov, p_stream->entry[i].i_pos + i_moov_size);
1123
1124                 while( i < p_stream->i_entry_count )
1125                 {
1126                     if( i + 1 < p_stream->i_entry_count &&
1127                         p_stream->entry[i].i_pos + p_stream->entry[i].i_size
1128                         != p_stream->entry[i + 1].i_pos )
1129                     {
1130                         i++;
1131                         break;
1132                     }
1133
1134                     i++;
1135                 }
1136             }
1137         }
1138
1139         moov->i_buffer = i_moov_size;
1140         i_moov_pos = p_sys->i_mdat_pos;
1141         p_sys->b_fast_start = VLC_FALSE;
1142     }
1143
1144     /* Write MOOV header */
1145     sout_AccessOutSeek( p_mux->p_access, i_moov_pos );
1146     box_send( p_mux, moov );
1147
1148     /* Clean-up */
1149     for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
1150     {
1151         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
1152
1153         if( p_stream->p_fmt->p_extra )
1154         {
1155             free( p_stream->p_fmt->p_extra );
1156         }
1157         free( p_stream->p_fmt );
1158         free( p_stream->entry );
1159         free( p_stream );
1160     }
1161     if( p_sys->i_nb_streams ) free( p_sys->pp_streams );
1162     free( p_sys );
1163 }
1164
1165 static int Capability( sout_mux_t *p_mux, int i_query, void *p_args,
1166                        void *p_answer )
1167 {
1168    switch( i_query )
1169    {
1170         case SOUT_MUX_CAP_GET_ADD_STREAM_ANY_TIME:
1171             *(vlc_bool_t*)p_answer = VLC_FALSE;
1172             return( SOUT_MUX_CAP_ERR_OK );
1173         default:
1174             return( SOUT_MUX_CAP_ERR_UNIMPLEMENTED );
1175    }
1176 }
1177
1178 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
1179 {
1180     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1181     mp4_stream_t    *p_stream;
1182
1183     switch( p_input->p_fmt->i_codec )
1184     {
1185         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
1186         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
1187         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
1188         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
1189         case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
1190         case VLC_FOURCC( 'm', 'j', 'p', 'b' ):
1191         case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1192             break;
1193         default:
1194             msg_Err( p_mux, "unsupported codec %4.4s in mp4",
1195                      (char*)&p_input->p_fmt->i_codec );
1196             return VLC_EGENERIC;
1197     }
1198
1199     p_stream                = malloc( sizeof( mp4_stream_t ) );
1200     p_stream->p_fmt         = malloc( sizeof( es_format_t ) );
1201     memcpy( p_stream->p_fmt, p_input->p_fmt, sizeof( es_format_t ) );
1202     if( p_stream->p_fmt->i_extra )
1203     {
1204         p_stream->p_fmt->p_extra =
1205             malloc( p_stream->p_fmt->i_extra );
1206         memcpy( p_stream->p_fmt->p_extra,
1207                 p_input->p_fmt->p_extra,
1208                 p_input->p_fmt->i_extra );
1209     }
1210     p_stream->i_track_id    = p_sys->i_nb_streams + 1;
1211     p_stream->i_entry_count = 0;
1212     p_stream->i_entry_max   = 1000;
1213     p_stream->entry         =
1214         calloc( p_stream->i_entry_max, sizeof( mp4_entry_t ) );
1215     p_stream->i_duration    = 0;
1216
1217     p_input->p_sys          = p_stream;
1218
1219     msg_Dbg( p_mux, "adding input" );
1220
1221     TAB_APPEND( p_sys->i_nb_streams, p_sys->pp_streams, p_stream );
1222     return VLC_SUCCESS;
1223 }
1224
1225 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
1226 {
1227     msg_Dbg( p_mux, "removing input" );
1228     return VLC_SUCCESS;
1229 }
1230
1231 /****************************************************************************/
1232
1233 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
1234 {
1235     mtime_t i_dts;
1236     int     i_stream;
1237     int     i;
1238
1239     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
1240     {
1241         sout_fifo_t  *p_fifo;
1242
1243         p_fifo = p_mux->pp_inputs[i]->p_fifo;
1244
1245         if( p_fifo->i_depth > 1 )
1246         {
1247             sout_buffer_t *p_buf;
1248
1249             p_buf = sout_FifoShow( p_fifo );
1250             if( i_stream < 0 || p_buf->i_dts < i_dts )
1251             {
1252                 i_dts = p_buf->i_dts;
1253                 i_stream = i;
1254             }
1255         }
1256         else
1257         {
1258             return( -1 ); // wait that all fifo have at least 2 packets
1259         }
1260     }
1261     if( pi_stream )
1262     {
1263         *pi_stream = i_stream;
1264     }
1265     if( pi_dts )
1266     {
1267         *pi_dts = i_dts;
1268     }
1269     return( i_stream );
1270 }
1271
1272 static int Mux( sout_mux_t *p_mux )
1273 {
1274     sout_mux_sys_t *p_sys = p_mux->p_sys;
1275
1276     for( ;; )
1277     {
1278         sout_input_t    *p_input;
1279         int             i_stream;
1280         mp4_stream_t    *p_stream;
1281         sout_buffer_t   *p_data;
1282         mtime_t         i_dts;
1283
1284         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
1285         {
1286             return( VLC_SUCCESS );
1287         }
1288
1289         if( !p_sys->i_start_dts )
1290             p_sys->i_start_dts = i_dts;
1291
1292         p_input  = p_mux->pp_inputs[i_stream];
1293         p_stream = (mp4_stream_t*)p_input->p_sys;
1294
1295         p_data  = sout_FifoGet( p_input->p_fifo );
1296
1297         /* add index entry */
1298         p_stream->entry[p_stream->i_entry_count].i_pos   = p_sys->i_pos;
1299         p_stream->entry[p_stream->i_entry_count].i_size  = p_data->i_size;
1300         p_stream->entry[p_stream->i_entry_count].i_pts   = p_data->i_pts;
1301         p_stream->entry[p_stream->i_entry_count].i_dts   = p_data->i_dts;
1302         p_stream->entry[p_stream->i_entry_count].i_length=
1303             __MAX( p_data->i_length, 0 );
1304
1305         if( p_stream->i_entry_count == 0 )
1306         {
1307             /* Here is another bad hack.
1308              * To make sure audio/video are in sync, we report a corrected
1309              * length for the 1st sample. */
1310             p_stream->entry[p_stream->i_entry_count].i_length =
1311                 __MAX( p_data->i_length, 0 ) +
1312                 p_data->i_pts - p_sys->i_start_dts;
1313         }
1314
1315         p_stream->i_entry_count++;
1316         if( p_stream->i_entry_count >= p_stream->i_entry_max )
1317         {
1318             p_stream->i_entry_max += 1000;
1319             p_stream->entry =
1320                 realloc( p_stream->entry,
1321                          p_stream->i_entry_max * sizeof( mp4_entry_t ) );
1322         }
1323
1324         /* update */
1325         p_stream->i_duration += __MAX( p_data->i_length, 0 );
1326         p_sys->i_pos += p_data->i_size;
1327
1328         /* write data */
1329         sout_AccessOutWrite( p_mux->p_access, p_data );
1330     }
1331
1332     return( VLC_SUCCESS );
1333 }
1334
1335
1336 /****************************************************************************/
1337
1338 static void bo_init( bo_t *p_bo, int i_size, uint8_t *p_buffer,
1339                      vlc_bool_t b_grow )
1340 {
1341     if( !p_buffer )
1342     {
1343         p_bo->i_buffer_size = __MAX( i_size, 1024 );
1344         p_bo->p_buffer = malloc( p_bo->i_buffer_size );
1345     }
1346     else
1347     {
1348         p_bo->i_buffer_size = i_size;
1349         p_bo->p_buffer = p_buffer;
1350     }
1351
1352     p_bo->b_grow = b_grow;
1353     p_bo->i_buffer = 0;
1354 }
1355
1356 static void bo_add_8( bo_t *p_bo, uint8_t i )
1357 {
1358     if( p_bo->i_buffer < p_bo->i_buffer_size )
1359     {
1360         p_bo->p_buffer[p_bo->i_buffer] = i;
1361     }
1362     else if( p_bo->b_grow )
1363     {
1364         p_bo->i_buffer_size += 1024;
1365         p_bo->p_buffer = realloc( p_bo->p_buffer, p_bo->i_buffer_size );
1366
1367         p_bo->p_buffer[p_bo->i_buffer] = i;
1368     }
1369
1370     p_bo->i_buffer++;
1371 }
1372
1373 static void bo_add_16be( bo_t *p_bo, uint16_t i )
1374 {
1375     bo_add_8( p_bo, ( ( i >> 8) &0xff ) );
1376     bo_add_8( p_bo, i &0xff );
1377 }
1378
1379 static void bo_add_24be( bo_t *p_bo, uint32_t i )
1380 {
1381     bo_add_8( p_bo, ( ( i >> 16) &0xff ) );
1382     bo_add_8( p_bo, ( ( i >> 8) &0xff ) );
1383     bo_add_8( p_bo, (   i &0xff ) );
1384 }
1385 static void bo_add_32be( bo_t *p_bo, uint32_t i )
1386 {
1387     bo_add_16be( p_bo, ( ( i >> 16) &0xffff ) );
1388     bo_add_16be( p_bo, i &0xffff );
1389 }
1390
1391 static void bo_fix_32be ( bo_t *p_bo, int i_pos, uint32_t i)
1392 {
1393     p_bo->p_buffer[i_pos    ] = ( i >> 24 )&0xff;
1394     p_bo->p_buffer[i_pos + 1] = ( i >> 16 )&0xff;
1395     p_bo->p_buffer[i_pos + 2] = ( i >>  8 )&0xff;
1396     p_bo->p_buffer[i_pos + 3] = ( i       )&0xff;
1397 }
1398
1399 static void bo_add_64be( bo_t *p_bo, uint64_t i )
1400 {
1401     bo_add_32be( p_bo, ( ( i >> 32) &0xffffffff ) );
1402     bo_add_32be( p_bo, i &0xffffffff );
1403 }
1404
1405 static void bo_add_fourcc( bo_t *p_bo, char *fcc )
1406 {
1407     bo_add_8( p_bo, fcc[0] );
1408     bo_add_8( p_bo, fcc[1] );
1409     bo_add_8( p_bo, fcc[2] );
1410     bo_add_8( p_bo, fcc[3] );
1411 }
1412
1413 static void bo_add_mem( bo_t *p_bo, int i_size, uint8_t *p_mem )
1414 {
1415     int i;
1416
1417     for( i = 0; i < i_size; i++ )
1418     {
1419         bo_add_8( p_bo, p_mem[i] );
1420     }
1421 }
1422
1423 static void bo_add_descr( bo_t *p_bo, uint8_t tag, uint32_t i_size )
1424 {
1425     uint32_t i_length;
1426     uint8_t  vals[4];
1427
1428     i_length = i_size;
1429     vals[3] = (unsigned char)(i_length & 0x7f);
1430     i_length >>= 7;
1431     vals[2] = (unsigned char)((i_length & 0x7f) | 0x80); 
1432     i_length >>= 7;
1433     vals[1] = (unsigned char)((i_length & 0x7f) | 0x80); 
1434     i_length >>= 7;
1435     vals[0] = (unsigned char)((i_length & 0x7f) | 0x80);
1436
1437     bo_add_8( p_bo, tag );
1438
1439     if( i_size < 0x00000080 )
1440     {
1441         bo_add_8( p_bo, vals[3] );
1442     }
1443     else if( i_size < 0x00004000 )
1444     {
1445         bo_add_8( p_bo, vals[2] );
1446         bo_add_8( p_bo, vals[3] );
1447     }
1448     else if( i_size < 0x00200000 )
1449     {
1450         bo_add_8( p_bo, vals[1] );
1451         bo_add_8( p_bo, vals[2] );
1452         bo_add_8( p_bo, vals[3] );
1453     }
1454     else if( i_size < 0x10000000 )
1455     {
1456         bo_add_8( p_bo, vals[0] );
1457         bo_add_8( p_bo, vals[1] );
1458         bo_add_8( p_bo, vals[2] );
1459         bo_add_8( p_bo, vals[3] );
1460     }
1461 }
1462
1463 static void bo_add_bo( bo_t *p_bo, bo_t *p_bo2 )
1464 {
1465     int i;
1466
1467     for( i = 0; i < p_bo2->i_buffer; i++ )
1468     {
1469         bo_add_8( p_bo, p_bo2->p_buffer[i] );
1470     }
1471 }
1472
1473 static bo_t * box_new( char *fcc )
1474 {
1475     bo_t *box;
1476
1477     if( ( box = malloc( sizeof( bo_t ) ) ) )
1478     {
1479         bo_init( box, 0, NULL, VLC_TRUE );
1480
1481         bo_add_32be  ( box, 0 );
1482         bo_add_fourcc( box, fcc );
1483     }
1484
1485     return box;
1486 }
1487
1488 static bo_t * box_full_new( char *fcc, uint8_t v, uint32_t f )
1489 {
1490     bo_t *box;
1491
1492     if( ( box = malloc( sizeof( bo_t ) ) ) )
1493     {
1494         bo_init( box, 0, NULL, VLC_TRUE );
1495
1496         bo_add_32be  ( box, 0 );
1497         bo_add_fourcc( box, fcc );
1498         bo_add_8     ( box, v );
1499         bo_add_24be  ( box, f );
1500     }
1501
1502     return box;
1503 }
1504
1505 static void box_fix( bo_t *box )
1506 {
1507     bo_t box_tmp;
1508
1509     memcpy( &box_tmp, box, sizeof( bo_t ) );
1510
1511     box_tmp.i_buffer = 0;
1512     bo_add_32be( &box_tmp, box->i_buffer );
1513 }
1514
1515 static void box_free( bo_t *box )
1516 {
1517     if( box->p_buffer )
1518     {
1519         free( box->p_buffer );
1520     }
1521
1522     free( box );
1523 }
1524
1525 static void box_gather ( bo_t *box, bo_t *box2 )
1526 {
1527     bo_add_bo( box, box2 );
1528     box_free( box2 );
1529 }
1530
1531 static sout_buffer_t * bo_to_sout( sout_instance_t *p_sout,  bo_t *box )
1532 {
1533     sout_buffer_t *p_buf;
1534
1535     p_buf = sout_BufferNew( p_sout, box->i_buffer );
1536     if( box->i_buffer > 0 )
1537     {
1538         memcpy( p_buf->p_buffer, box->p_buffer, box->i_buffer );
1539     }
1540
1541     p_buf->i_size = box->i_buffer;
1542
1543     return p_buf;
1544 }
1545
1546 static void box_send( sout_mux_t *p_mux,  bo_t *box )
1547 {
1548     sout_buffer_t *p_buf;
1549
1550     p_buf = bo_to_sout( p_mux->p_sout, box );
1551     box_free( box );
1552
1553     sout_AccessOutWrite( p_mux->p_access, p_buf );
1554 }
1555
1556 static int64_t get_timestamp()
1557 {
1558     int64_t i_timestamp = 0;
1559
1560 #ifdef HAVE_TIME_H
1561     i_timestamp = time(NULL);
1562     i_timestamp += 2082844800; // MOV/MP4 start date is 1/1/1904
1563     // 208284480 is (((1970 - 1904) * 365) + 17) * 24 * 60 * 60
1564 #endif
1565
1566     return i_timestamp;
1567 }