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