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