]> git.sesse.net Git - vlc/blob - modules/mux/mp4.c
Make Zorglub less unhappy
[vlc] / modules / mux / mp4.c
1 /*****************************************************************************
2  * mp4.c: mp4/mov muxer
3  *****************************************************************************
4  * Copyright (C) 2001, 2002, 2003 the VideoLAN team
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
31 #include <vlc/vlc.h>
32 #include <vlc/input.h>
33 #include <vlc/sout.h>
34
35 #ifdef HAVE_TIME_H
36 #include <time.h>
37 #endif
38
39 #include "iso_lang.h"
40 #include "vlc_meta.h"
41
42 /*****************************************************************************
43  * Module descriptor
44  *****************************************************************************/
45 #define FASTSTART_TEXT N_("Create \"Fast start\" files")
46 #define FASTSTART_LONGTEXT N_( \
47     "When this option is turned on, \"Fast start\" files will be created. " \
48     "(\"Fast start\" files are optimized for download, allowing the user " \
49     "to start previewing the file while it is downloading).")
50 static int  Open   ( vlc_object_t * );
51 static void Close  ( vlc_object_t * );
52
53 #define SOUT_CFG_PREFIX "sout-mp4-"
54
55 vlc_module_begin();
56     set_description( _("MP4/MOV muxer") );
57     set_category( CAT_SOUT );
58     set_subcategory( SUBCAT_SOUT_MUX );
59     set_shortname( "MP4" );
60
61     add_bool( SOUT_CFG_PREFIX "faststart", 1, NULL, FASTSTART_TEXT, FASTSTART_LONGTEXT,
62               VLC_TRUE );
63     set_capability( "sout mux", 5 );
64     add_shortcut( "mp4" );
65     add_shortcut( "mov" );
66     add_shortcut( "3gp" );
67     set_callbacks( Open, Close );
68 vlc_module_end();
69
70 /*****************************************************************************
71  * Exported prototypes
72  *****************************************************************************/
73 static const char *ppsz_sout_options[] = {
74     "faststart", NULL
75 };
76
77 static int Control( sout_mux_t *, int, va_list );
78 static int AddStream( sout_mux_t *, sout_input_t * );
79 static int DelStream( sout_mux_t *, sout_input_t * );
80 static int Mux      ( sout_mux_t * );
81
82 /*****************************************************************************
83  * Local prototypes
84  *****************************************************************************/
85 typedef struct
86 {
87     uint64_t i_pos;
88     int      i_size;
89
90     mtime_t  i_pts_dts;
91     mtime_t  i_length;
92     unsigned int i_flags;
93
94 } mp4_entry_t;
95
96 typedef struct
97 {
98     es_format_t   fmt;
99     int           i_track_id;
100
101     /* index */
102     unsigned int i_entry_count;
103     unsigned int i_entry_max;
104     mp4_entry_t  *entry;
105     int64_t      i_length_neg;
106
107     /* stats */
108     int64_t      i_dts_start;
109     int64_t      i_duration;
110
111     /* for later stco fix-up (fast start files) */
112     uint64_t i_stco_pos;
113     vlc_bool_t b_stco64;
114
115     /* for h264 */
116     struct
117     {
118         int     i_profile;
119         int     i_level;
120
121         int     i_sps;
122         uint8_t *sps;
123         int     i_pps;
124         uint8_t *pps;
125     } avc;
126
127     /* for spu */
128     int64_t i_last_dts;
129
130 } mp4_stream_t;
131
132 struct sout_mux_sys_t
133 {
134     vlc_bool_t b_mov;
135     vlc_bool_t b_3gp;
136     vlc_bool_t b_64_ext;
137     vlc_bool_t b_fast_start;
138
139     uint64_t i_mdat_pos;
140     uint64_t i_pos;
141
142     int64_t  i_dts_start;
143
144     int          i_nb_streams;
145     mp4_stream_t **pp_streams;
146 };
147
148 typedef struct bo_t
149 {
150     vlc_bool_t b_grow;
151
152     int        i_buffer_size;
153     int        i_buffer;
154     uint8_t    *p_buffer;
155
156 } bo_t;
157
158 static void bo_init     ( bo_t *, int , uint8_t *, vlc_bool_t  );
159 static void bo_add_8    ( bo_t *, uint8_t );
160 static void bo_add_16be ( bo_t *, uint16_t );
161 static void bo_add_24be ( bo_t *, uint32_t );
162 static void bo_add_32be ( bo_t *, uint32_t );
163 static void bo_add_64be ( bo_t *, uint64_t );
164 static void bo_add_fourcc(bo_t *, char * );
165 static void bo_add_bo   ( bo_t *, bo_t * );
166 static void bo_add_mem  ( bo_t *, int , uint8_t * );
167 static void bo_add_descr( bo_t *, uint8_t , uint32_t );
168
169 static void bo_fix_32be ( bo_t *, int , uint32_t );
170
171 static bo_t *box_new     ( char *fcc );
172 static bo_t *box_full_new( char *fcc, uint8_t v, uint32_t f );
173 static void  box_fix     ( bo_t *box );
174 static void  box_free    ( bo_t *box );
175 static void  box_gather  ( bo_t *box, bo_t *box2 );
176
177 static void box_send( sout_mux_t *p_mux,  bo_t *box );
178
179 static block_t *bo_to_sout( sout_instance_t *p_sout,  bo_t *box );
180
181 static bo_t *GetMoovBox( sout_mux_t *p_mux );
182
183 static block_t *ConvertSUBT( sout_mux_t *, mp4_stream_t *, block_t *);
184 static void ConvertAVC1( sout_mux_t *, mp4_stream_t *, block_t * );
185
186 /*****************************************************************************
187  * Open:
188  *****************************************************************************/
189 static int Open( vlc_object_t *p_this )
190 {
191     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
192     sout_mux_sys_t  *p_sys;
193     bo_t            *box;
194
195     msg_Dbg( p_mux, "Mp4 muxer opend" );
196     sout_CfgParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
197
198     p_mux->pf_control   = Control;
199     p_mux->pf_addstream = AddStream;
200     p_mux->pf_delstream = DelStream;
201     p_mux->pf_mux       = Mux;
202     p_mux->p_sys        = p_sys = malloc( sizeof( sout_mux_sys_t ) );
203     p_sys->i_pos        = 0;
204     p_sys->i_nb_streams = 0;
205     p_sys->pp_streams   = NULL;
206     p_sys->i_mdat_pos   = 0;
207     p_sys->b_mov        = p_mux->psz_mux && !strcmp( p_mux->psz_mux, "mov" );
208     p_sys->b_3gp        = p_mux->psz_mux && !strcmp( p_mux->psz_mux, "3gp" );
209     p_sys->i_dts_start  = 0;
210
211
212     if( !p_sys->b_mov )
213     {
214         /* Now add ftyp header */
215         box = box_new( "ftyp" );
216         if( p_sys->b_3gp ) bo_add_fourcc( box, "3gp4" );
217         else bo_add_fourcc( box, "isom" );
218         bo_add_32be  ( box, 0 );
219         if( p_sys->b_3gp ) bo_add_fourcc( box, "3gp4" );
220         else bo_add_fourcc( box, "mp41" );
221         box_fix( box );
222
223         p_sys->i_pos += box->i_buffer;
224         p_sys->i_mdat_pos = p_sys->i_pos;
225
226         box_send( p_mux, box );
227     }
228
229     /* FIXME FIXME
230      * Quicktime actually doesn't like the 64 bits extensions !!! */
231     p_sys->b_64_ext = VLC_FALSE;
232
233     /* Now add mdat header */
234     box = box_new( "mdat" );
235     bo_add_64be  ( box, 0 ); // enough to store an extended size
236
237     p_sys->i_pos += box->i_buffer;
238
239     box_send( p_mux, box );
240
241     return VLC_SUCCESS;
242 }
243
244 /*****************************************************************************
245  * Close:
246  *****************************************************************************/
247 static void Close( vlc_object_t * p_this )
248 {
249     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
250     sout_mux_sys_t  *p_sys = p_mux->p_sys;
251     block_t   *p_hdr;
252     bo_t            bo, *moov;
253     vlc_value_t     val;
254
255     int             i_trak;
256     uint64_t        i_moov_pos;
257
258     msg_Dbg( p_mux, "Close" );
259
260     /* Update mdat size */
261     bo_init( &bo, 0, NULL, VLC_TRUE );
262     if( p_sys->i_pos - p_sys->i_mdat_pos >= (((uint64_t)1)<<32) )
263     {
264         /* Extended size */
265         bo_add_32be  ( &bo, 1 );
266         bo_add_fourcc( &bo, "mdat" );
267         bo_add_64be  ( &bo, p_sys->i_pos - p_sys->i_mdat_pos );
268     }
269     else
270     {
271         bo_add_32be  ( &bo, 8 );
272         bo_add_fourcc( &bo, "wide" );
273         bo_add_32be  ( &bo, p_sys->i_pos - p_sys->i_mdat_pos - 8 );
274         bo_add_fourcc( &bo, "mdat" );
275     }
276     p_hdr = bo_to_sout( p_mux->p_sout, &bo );
277     free( bo.p_buffer );
278
279     sout_AccessOutSeek( p_mux->p_access, p_sys->i_mdat_pos );
280     sout_AccessOutWrite( p_mux->p_access, p_hdr );
281
282     /* Create MOOV header */
283     i_moov_pos = p_sys->i_pos;
284     moov = GetMoovBox( p_mux );
285
286     /* Check we need to create "fast start" files */
287     var_Get( p_this, SOUT_CFG_PREFIX "faststart", &val );
288     p_sys->b_fast_start = val.b_bool;
289     while( p_sys->b_fast_start )
290     {
291         /* Move data to the end of the file so we can fit the moov header
292          * at the start */
293         block_t *p_buf;
294         int64_t i_chunk, i_size = p_sys->i_pos - p_sys->i_mdat_pos;
295         int i_moov_size = moov->i_buffer;
296
297         while( i_size > 0 )
298         {
299             i_chunk = __MIN( 32768, i_size );
300             p_buf = block_New( p_mux, i_chunk );
301             sout_AccessOutSeek( p_mux->p_access,
302                                 p_sys->i_mdat_pos + i_size - i_chunk );
303             if( sout_AccessOutRead( p_mux->p_access, p_buf ) < i_chunk )
304             {
305                 msg_Warn( p_this, "read() not supported by acces output, "
306                           "won't create a fast start file" );
307                 p_sys->b_fast_start = VLC_FALSE;
308                 block_Release( p_buf );
309                 break;
310             }
311             sout_AccessOutSeek( p_mux->p_access, p_sys->i_mdat_pos + i_size +
312                                 i_moov_size - i_chunk );
313             sout_AccessOutWrite( p_mux->p_access, p_buf );
314             i_size -= i_chunk;
315         }
316
317         if( !p_sys->b_fast_start ) break;
318
319         /* Fix-up samples to chunks table in MOOV header */
320         for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
321         {
322             mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
323             unsigned int i;
324             int i_chunk;
325
326             moov->i_buffer = p_stream->i_stco_pos;
327             for( i_chunk = 0, i = 0; i < p_stream->i_entry_count; i_chunk++ )
328             {
329                 if( p_stream->b_stco64 )
330                     bo_add_64be( moov, p_stream->entry[i].i_pos + i_moov_size);
331                 else
332                     bo_add_32be( moov, p_stream->entry[i].i_pos + i_moov_size);
333
334                 while( i < p_stream->i_entry_count )
335                 {
336                     if( i + 1 < p_stream->i_entry_count &&
337                         p_stream->entry[i].i_pos + p_stream->entry[i].i_size
338                         != p_stream->entry[i + 1].i_pos )
339                     {
340                         i++;
341                         break;
342                     }
343
344                     i++;
345                 }
346             }
347         }
348
349         moov->i_buffer = i_moov_size;
350         i_moov_pos = p_sys->i_mdat_pos;
351         p_sys->b_fast_start = VLC_FALSE;
352     }
353
354     /* Write MOOV header */
355     sout_AccessOutSeek( p_mux->p_access, i_moov_pos );
356     box_send( p_mux, moov );
357
358     /* Clean-up */
359     for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
360     {
361         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
362
363         es_format_Clean( &p_stream->fmt );
364         if( p_stream->avc.i_sps ) free( p_stream->avc.sps );
365         if( p_stream->avc.i_pps ) free( p_stream->avc.pps );
366         free( p_stream->entry );
367         free( p_stream );
368     }
369     if( p_sys->i_nb_streams ) free( p_sys->pp_streams );
370     free( p_sys );
371 }
372
373 /*****************************************************************************
374  * Control:
375  *****************************************************************************/
376 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
377 {
378     vlc_bool_t *pb_bool;
379
380    switch( i_query )
381    {
382        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
383            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
384            *pb_bool = VLC_FALSE;
385            return VLC_SUCCESS;
386
387        case MUX_GET_ADD_STREAM_WAIT:
388            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
389            *pb_bool = VLC_TRUE;
390            return VLC_SUCCESS;
391
392        case MUX_GET_MIME:   /* Not needed, as not streamable */
393         default:
394             return VLC_EGENERIC;
395    }
396 }
397
398 /*****************************************************************************
399  * AddStream:
400  *****************************************************************************/
401 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
402 {
403     sout_mux_sys_t  *p_sys = p_mux->p_sys;
404     mp4_stream_t    *p_stream;
405
406     switch( p_input->p_fmt->i_codec )
407     {
408         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
409         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
410         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
411         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
412         case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
413         case VLC_FOURCC( 'm', 'j', 'p', 'b' ):
414         case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
415         case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
416         case VLC_FOURCC( 'H', '2', '6', '3' ):
417         case VLC_FOURCC( 'h', '2', '6', '4' ):
418         case VLC_FOURCC( 's', 'a', 'm', 'r' ):
419         case VLC_FOURCC( 's', 'a', 'w', 'b' ):
420             break;
421         case VLC_FOURCC( 's', 'u', 'b', 't' ):
422             msg_Warn( p_mux, "subtitle track added like in .mov (even when creating .mp4)" );
423             break;
424         default:
425             msg_Err( p_mux, "unsupported codec %4.4s in mp4",
426                      (char*)&p_input->p_fmt->i_codec );
427             return VLC_EGENERIC;
428     }
429
430     p_stream                = malloc( sizeof( mp4_stream_t ) );
431     es_format_Copy( &p_stream->fmt, p_input->p_fmt );
432     p_stream->i_track_id    = p_sys->i_nb_streams + 1;
433     p_stream->i_length_neg  = 0;
434     p_stream->i_entry_count = 0;
435     p_stream->i_entry_max   = 1000;
436     p_stream->entry         =
437         calloc( p_stream->i_entry_max, sizeof( mp4_entry_t ) );
438     p_stream->i_dts_start   = 0;
439     p_stream->i_duration    = 0;
440     p_stream->avc.i_profile = 77;
441     p_stream->avc.i_level   = 51;
442     p_stream->avc.i_sps     = 0;
443     p_stream->avc.sps       = NULL;
444     p_stream->avc.i_pps     = 0;
445     p_stream->avc.pps       = NULL;
446
447     p_input->p_sys          = p_stream;
448
449     msg_Dbg( p_mux, "adding input" );
450
451     TAB_APPEND( p_sys->i_nb_streams, p_sys->pp_streams, p_stream );
452     return VLC_SUCCESS;
453 }
454
455 /*****************************************************************************
456  * DelStream:
457  *****************************************************************************/
458 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
459 {
460     msg_Dbg( p_mux, "removing input" );
461     return VLC_SUCCESS;
462 }
463
464 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
465 {
466     mtime_t i_dts;
467     int     i_stream;
468     int     i;
469
470     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
471     {
472         block_fifo_t   *p_fifo = p_mux->pp_inputs[i]->p_fifo;
473         block_t *p_buf;
474
475         if( p_fifo->i_depth <= 1 )
476         {
477             if( p_mux->pp_inputs[i]->p_fmt->i_cat != SPU_ES )
478             {
479                 return -1; // wait that all fifo have at least 2 packets
480             }
481             /* For SPU, we wait only 1 packet */
482             continue;
483         }
484
485         p_buf = block_FifoShow( p_fifo );
486         if( i_stream < 0 || p_buf->i_dts < i_dts )
487         {
488             i_dts = p_buf->i_dts;
489             i_stream = i;
490         }
491     }
492     if( pi_stream )
493     {
494         *pi_stream = i_stream;
495     }
496     if( pi_dts )
497     {
498         *pi_dts = i_dts;
499     }
500     return i_stream;
501 }
502
503 /*****************************************************************************
504  * Mux:
505  *****************************************************************************/
506 static int Mux( sout_mux_t *p_mux )
507 {
508     sout_mux_sys_t *p_sys = p_mux->p_sys;
509
510     for( ;; )
511     {
512         sout_input_t    *p_input;
513         int             i_stream;
514         mp4_stream_t    *p_stream;
515         block_t         *p_data;
516         mtime_t         i_dts;
517
518         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
519         {
520             return( VLC_SUCCESS );
521         }
522
523         p_input  = p_mux->pp_inputs[i_stream];
524         p_stream = (mp4_stream_t*)p_input->p_sys;
525
526         p_data  = block_FifoGet( p_input->p_fifo );
527         if( p_stream->fmt.i_codec == VLC_FOURCC( 'h', '2', '6', '4' ) )
528         {
529             ConvertAVC1( p_mux, p_stream, p_data );
530         }
531         else if( p_stream->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) )
532         {
533             p_data = ConvertSUBT( p_mux, p_stream, p_data );
534         }
535
536         if( p_stream->fmt.i_cat != SPU_ES )
537         {
538             /* Fix length of the sample */
539             if( p_input->p_fifo->i_depth > 0 )
540             {
541                 block_t *p_next = block_FifoShow( p_input->p_fifo );
542                 int64_t       i_diff  = p_next->i_dts - p_data->i_dts;
543
544                 if( i_diff < I64C(1000000 ) )   /* protection */
545                 {
546                     p_data->i_length = i_diff;
547                 }
548             }
549             if( p_data->i_length <= 0 )
550             {
551                 msg_Warn( p_mux, "i_length <= 0" );
552                 p_stream->i_length_neg += p_data->i_length - 1;
553                 p_data->i_length = 1;
554             }
555             else if( p_stream->i_length_neg < 0 )
556             {
557                 int64_t i_recover = __MIN( p_data->i_length / 4, - p_stream->i_length_neg );
558
559                 p_data->i_length -= i_recover;
560                 p_stream->i_length_neg += i_recover;
561             }
562         }
563
564         /* Save starting time */
565         if( p_stream->i_entry_count == 0 )
566         {
567             p_stream->i_dts_start = p_data->i_dts;
568
569             /* Update global dts_start */
570             if( p_sys->i_dts_start <= 0 ||
571                 p_stream->i_dts_start < p_sys->i_dts_start )
572             {
573                 p_sys->i_dts_start = p_stream->i_dts_start;
574             }
575         }
576
577         if( p_stream->fmt.i_cat == SPU_ES && p_stream->i_entry_count > 0 )
578         {
579             int64_t i_length = p_data->i_dts - p_stream->i_last_dts;
580
581             if( i_length <= 0 )
582             {
583                 /* FIXME handle this broken case */
584                 i_length = 1;
585             }
586
587             /* Fix last entry */
588             if( p_stream->entry[p_stream->i_entry_count-1].i_length <= 0 )
589             {
590                 p_stream->entry[p_stream->i_entry_count-1].i_length = i_length;
591             }
592         }
593
594
595         /* add index entry */
596         p_stream->entry[p_stream->i_entry_count].i_pos    = p_sys->i_pos;
597         p_stream->entry[p_stream->i_entry_count].i_size   = p_data->i_buffer;
598         p_stream->entry[p_stream->i_entry_count].i_pts_dts=
599             __MAX( p_data->i_pts - p_data->i_dts, 0 );
600         p_stream->entry[p_stream->i_entry_count].i_length = p_data->i_length;
601         p_stream->entry[p_stream->i_entry_count].i_flags  = p_data->i_flags;
602
603         p_stream->i_entry_count++;
604         /* XXX: -1 to always have 2 entry for easy adding of empty SPU */
605         if( p_stream->i_entry_count >= p_stream->i_entry_max - 1 )
606         {
607             p_stream->i_entry_max += 1000;
608             p_stream->entry =
609                 realloc( p_stream->entry,
610                          p_stream->i_entry_max * sizeof( mp4_entry_t ) );
611         }
612
613         /* update */
614         p_stream->i_duration += p_data->i_length;
615         p_sys->i_pos += p_data->i_buffer;
616
617         /* Save the DTS */
618         p_stream->i_last_dts = p_data->i_dts;
619
620         /* write data */
621         sout_AccessOutWrite( p_mux->p_access, p_data );
622
623         if( p_stream->fmt.i_cat == SPU_ES )
624         {
625             int64_t i_length = p_stream->entry[p_stream->i_entry_count-1].i_length;
626
627             if( i_length != 0 )
628             {
629                 /* TODO */
630                 msg_Dbg( p_mux, "writing a empty subs" ) ;
631
632                 /* Append a idx entry */
633                 p_stream->entry[p_stream->i_entry_count].i_pos    = p_sys->i_pos;
634                 p_stream->entry[p_stream->i_entry_count].i_size   = 3;
635                 p_stream->entry[p_stream->i_entry_count].i_pts_dts= 0;
636                 p_stream->entry[p_stream->i_entry_count].i_length = 0;
637                 p_stream->entry[p_stream->i_entry_count].i_flags  = 0;
638
639                 /* XXX: No need to grow the entry here */
640                 p_stream->i_entry_count++;
641
642                 /* Fix last dts */
643                 p_stream->i_last_dts += i_length;
644
645                 /* Write a " " */
646                 p_data = block_New( p_mux, 3 );
647                 p_data->p_buffer[0] = 0;
648                 p_data->p_buffer[1] = 1;
649                 p_data->p_buffer[2] = ' ';
650
651                 p_sys->i_pos += p_data->i_buffer;
652
653                 sout_AccessOutWrite( p_mux->p_access, p_data );
654             }
655
656             /* Fix duration */
657             p_stream->i_duration = p_stream->i_last_dts - p_stream->i_dts_start;
658         }
659     }
660
661     return( VLC_SUCCESS );
662 }
663
664 /*****************************************************************************
665  *
666  *****************************************************************************/
667 static block_t *ConvertSUBT( sout_mux_t *p_mux, mp4_stream_t *tk, block_t *p_block )
668 {
669     p_block = block_Realloc( p_block, 2, p_block->i_buffer );
670
671     /* No trailling '\0' */
672     if( p_block->i_buffer > 2 && p_block->p_buffer[p_block->i_buffer-1] == '\0' )
673         p_block->i_buffer--;
674
675     p_block->p_buffer[0] = ( (p_block->i_buffer - 2) >> 8 )&0xff;
676     p_block->p_buffer[1] = ( (p_block->i_buffer - 2)      )&0xff;
677
678     return p_block;
679 }
680
681 static void ConvertAVC1( sout_mux_t *p_mux, mp4_stream_t *tk, block_t *p_block )
682 {
683     uint8_t *last = p_block->p_buffer;  /* Assume it starts with 0x00000001 */
684     uint8_t *dat  = &p_block->p_buffer[4];
685     uint8_t *end = &p_block->p_buffer[p_block->i_buffer];
686
687
688     /* Replace the 4 bytes start code with 4 bytes size,
689      * FIXME are all startcode 4 bytes ? (I don't think :( */
690     while( dat < end )
691     {
692         int i_size;
693
694         while( dat < end - 4 )
695         {
696             if( dat[0] == 0x00 && dat[1] == 0x00  &&
697                 dat[2] == 0x00 && dat[3] == 0x01 )
698             {
699                 break;
700             }
701             dat++;
702         }
703         if( dat >= end - 4 )
704         {
705             dat = end;
706         }
707
708         /* Fix size */
709         i_size = dat - &last[4];
710         last[0] = ( i_size >> 24 )&0xff;
711         last[1] = ( i_size >> 16 )&0xff;
712         last[2] = ( i_size >>  8 )&0xff;
713         last[3] = ( i_size       )&0xff;
714
715         if( (last[4]&0x1f) == 7 && tk->avc.i_sps <= 0 )  /* SPS */
716         {
717             tk->avc.i_sps = i_size;
718             tk->avc.sps = malloc( i_size );
719             memcpy( tk->avc.sps, &last[4], i_size );
720
721             tk->avc.i_profile = tk->avc.sps[1];
722             tk->avc.i_level   = tk->avc.sps[3];
723         }
724         else if( (last[4]&0x1f) == 8 && tk->avc.i_pps <= 0 )   /* PPS */
725         {
726             tk->avc.i_pps = i_size;
727             tk->avc.pps = malloc( i_size );
728             memcpy( tk->avc.pps, &last[4], i_size );
729         }
730
731         last = dat;
732
733         dat += 4;
734     }
735 }
736
737
738 static int GetDescrLength( int i_size )
739 {
740     if( i_size < 0x00000080 )
741         return 2 + i_size;
742     else if( i_size < 0x00004000 )
743         return 3 + i_size;
744     else if( i_size < 0x00200000 )
745         return 4 + i_size;
746     else
747         return 5 + i_size;
748 }
749
750 static bo_t *GetESDS( mp4_stream_t *p_stream )
751 {
752     bo_t *esds;
753     int  i_stream_type;
754     int  i_object_type_indication;
755     int  i_decoder_specific_info_size;
756     unsigned int i;
757     int64_t i_bitrate_avg = 0;
758     int64_t i_bitrate_max = 0;
759
760     /* Compute avg/max bitrate */
761     for( i = 0; i < p_stream->i_entry_count; i++ )
762     {
763         i_bitrate_avg += p_stream->entry[i].i_size;
764         if( p_stream->entry[i].i_length > 0)
765         {
766             int64_t i_bitrate = I64C(8000000) * p_stream->entry[i].i_size / p_stream->entry[i].i_length;
767             if( i_bitrate > i_bitrate_max )
768                 i_bitrate_max = i_bitrate;
769         }
770     }
771
772     if( p_stream->i_duration > 0 )
773         i_bitrate_avg = I64C(8000000) * i_bitrate_avg / p_stream->i_duration;
774     else
775         i_bitrate_avg = 0;
776     if( i_bitrate_max <= 1 )
777         i_bitrate_max = 0x7fffffff;
778
779     /* */
780     if( p_stream->fmt.i_extra > 0 )
781     {
782         i_decoder_specific_info_size =
783             GetDescrLength( p_stream->fmt.i_extra );
784     }
785     else
786     {
787         i_decoder_specific_info_size = 0;
788     }
789
790     esds = box_full_new( "esds", 0, 0 );
791
792     /* ES_Descr */
793     bo_add_descr( esds, 0x03, 3 +
794                   GetDescrLength( 13 + i_decoder_specific_info_size ) +
795                   GetDescrLength( 1 ) );
796     bo_add_16be( esds, p_stream->i_track_id );
797     bo_add_8   ( esds, 0x1f );      // flags=0|streamPriority=0x1f
798
799     /* DecoderConfigDescr */
800     bo_add_descr( esds, 0x04, 13 + i_decoder_specific_info_size );
801
802     switch( p_stream->fmt.i_codec )
803     {
804         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
805             i_object_type_indication = 0x20;
806             break;
807         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
808             /* FIXME MPEG-I=0x6b, MPEG-II = 0x60 -> 0x65 */
809             i_object_type_indication = 0x60;
810             break;
811         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
812             /* FIXME for mpeg2-aac == 0x66->0x68 */
813             i_object_type_indication = 0x40;
814             break;
815         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
816             i_object_type_indication =
817                 p_stream->fmt.audio.i_rate < 32000 ? 0x69 : 0x6b;
818             break;
819         default:
820             i_object_type_indication = 0x00;
821             break;
822     }
823     i_stream_type = p_stream->fmt.i_cat == VIDEO_ES ? 0x04 : 0x05;
824
825     bo_add_8   ( esds, i_object_type_indication );
826     bo_add_8   ( esds, ( i_stream_type << 2 ) | 1 );
827     bo_add_24be( esds, 1024 * 1024 );       // bufferSizeDB
828     bo_add_32be( esds, i_bitrate_max );     // maxBitrate
829     bo_add_32be( esds, i_bitrate_avg );     // avgBitrate
830
831     if( p_stream->fmt.i_extra > 0 )
832     {
833         int i;
834
835         /* DecoderSpecificInfo */
836         bo_add_descr( esds, 0x05, p_stream->fmt.i_extra );
837
838         for( i = 0; i < p_stream->fmt.i_extra; i++ )
839         {
840             bo_add_8( esds, ((uint8_t*)p_stream->fmt.p_extra)[i] );
841         }
842     }
843
844     /* SL_Descr mandatory */
845     bo_add_descr( esds, 0x06, 1 );
846     bo_add_8    ( esds, 0x02 );  // sl_predefined
847
848     box_fix( esds );
849
850     return esds;
851 }
852
853 static bo_t *GetWaveTag( mp4_stream_t *p_stream )
854 {
855     bo_t *wave;
856     bo_t *box;
857
858     wave = box_new( "wave" );
859
860     box = box_new( "frma" );
861     bo_add_fourcc( box, "mp4a" );
862     box_fix( box );
863     box_gather( wave, box );
864
865     box = box_new( "mp4a" );
866     bo_add_32be( box, 0 );
867     box_fix( box );
868     box_gather( wave, box );
869
870     box = GetESDS( p_stream );
871     box_fix( box );
872     box_gather( wave, box );
873
874     box = box_new( "srcq" );
875     bo_add_32be( box, 0x40 );
876     box_fix( box );
877     box_gather( wave, box );
878
879     /* wazza ? */
880     bo_add_32be( wave, 8 ); /* new empty box */
881     bo_add_32be( wave, 0 ); /* box label */
882
883     box_fix( wave );
884
885     return wave;
886 }
887
888 static bo_t *GetDamrTag( mp4_stream_t *p_stream )
889 {
890     bo_t *damr;
891
892     damr = box_new( "damr" );
893
894     bo_add_fourcc( damr, "REFC" );
895     bo_add_8( damr, 0 );
896
897     if( p_stream->fmt.i_codec == VLC_FOURCC( 's', 'a', 'm', 'r' ) )
898         bo_add_16be( damr, 0x81ff ); /* Mode set (all modes for AMR_NB) */
899     else
900         bo_add_16be( damr, 0x83ff ); /* Mode set (all modes for AMR_WB) */
901     bo_add_16be( damr, 0x1 ); /* Mode change period (no restriction) */
902
903     box_fix( damr );
904
905     return damr;
906 }
907
908 static bo_t *GetD263Tag( mp4_stream_t *p_stream )
909 {
910     bo_t *d263;
911
912     d263 = box_new( "d263" );
913
914     bo_add_fourcc( d263, "VLC " );
915     bo_add_16be( d263, 0xa );
916     bo_add_8( d263, 0 );
917
918     box_fix( d263 );
919
920     return d263;
921 }
922
923 static bo_t *GetAvcCTag( mp4_stream_t *p_stream )
924 {
925     bo_t *avcC;
926
927     /* FIXME use better value */
928     avcC = box_new( "avcC" );
929     bo_add_8( avcC, 1 );      /* configuration version */
930     bo_add_8( avcC, p_stream->avc.i_profile );
931     bo_add_8( avcC, p_stream->avc.i_profile );     /* profile compatible ??? */
932     bo_add_8( avcC, p_stream->avc.i_level );       /* level, 5.1 */
933     bo_add_8( avcC, 0xff );   /* 0b11111100 | lengthsize = 0x11 */
934
935     bo_add_8( avcC, 0xe0 | (p_stream->avc.i_sps > 0 ? 1 : 0) );   /* 0b11100000 | sps_count */
936     if( p_stream->avc.i_sps > 0 )
937     {
938         bo_add_16be( avcC, p_stream->avc.i_sps );
939         bo_add_mem( avcC, p_stream->avc.i_sps, p_stream->avc.sps );
940     }
941
942     bo_add_8( avcC, (p_stream->avc.i_pps > 0 ? 1 : 0) );   /* pps_count */
943     if( p_stream->avc.i_pps > 0 )
944     {
945         bo_add_16be( avcC, p_stream->avc.i_pps );
946         bo_add_mem( avcC, p_stream->avc.i_pps, p_stream->avc.pps );
947     }
948     box_fix( avcC );
949
950     return avcC;
951 }
952
953 /* TODO: No idea about these values */
954 static bo_t *GetSVQ3Tag( mp4_stream_t *p_stream )
955 {
956     bo_t *smi = box_new( "SMI " );
957
958     if( p_stream->fmt.i_extra > 0x4e )
959     {
960         uint8_t *p_end = &((uint8_t*)p_stream->fmt.p_extra)[p_stream->fmt.i_extra];
961         uint8_t *p     = &((uint8_t*)p_stream->fmt.p_extra)[0x46];
962
963         while( p + 8 < p_end )
964         {
965             int i_size = GetDWBE( p );
966             if( i_size <= 1 )
967             {
968                 /* FIXME handle 1 as long size */
969                 break;
970             }
971             if( !strncmp( &p[4], "SMI ", 4 ) )
972             {
973                 bo_add_mem( smi, p_end - p - 8, &p[8] );
974                 return smi;
975             }
976             p += i_size;
977         }
978     }
979
980     /* Create a dummy one in fallback */
981     bo_add_fourcc( smi, "SEQH" );
982     bo_add_32be( smi, 0x5 );
983     bo_add_32be( smi, 0xe2c0211d );
984     bo_add_8( smi, 0xc0 );
985     box_fix( smi );
986
987     return smi;
988 }
989
990 static bo_t *GetUdtaTag( sout_mux_t *p_mux )
991 {
992     sout_mux_sys_t *p_sys = p_mux->p_sys;
993     bo_t *udta = box_new( "udta" );
994     vlc_meta_t *p_meta = p_mux->p_sout->p_meta;
995     int i_track;
996
997     /* Requirements */
998     for( i_track = 0; i_track < p_sys->i_nb_streams; i_track++ )
999     {
1000         mp4_stream_t *p_stream = p_sys->pp_streams[i_track];
1001
1002         if( p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','v') ||
1003             p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','a') )
1004         {
1005             bo_t *box = box_new( "\251req" );
1006             /* String length */
1007             bo_add_16be( box, sizeof("QuickTime 6.0 or greater") - 1);
1008             bo_add_16be( box, 0 );
1009             bo_add_mem( box, sizeof("QuickTime 6.0 or greater") - 1,
1010                         "QuickTime 6.0 or greater" );
1011             box_fix( box );
1012             box_gather( udta, box );
1013             break;
1014         }
1015     }
1016
1017     /* Encoder */
1018     {
1019         bo_t *box = box_new( "\251enc" );
1020         /* String length */
1021         bo_add_16be( box, sizeof(PACKAGE_STRING " stream output") - 1);
1022         bo_add_16be( box, 0 );
1023         bo_add_mem( box, sizeof(PACKAGE_STRING " stream output") - 1,
1024                     PACKAGE_STRING " stream output" );
1025         box_fix( box );
1026         box_gather( udta, box );
1027     }
1028
1029     /* Misc atoms */
1030     if( p_meta )
1031     {
1032         int i;
1033         for( i = 0; i < p_meta->i_meta; i++ )
1034         {
1035             bo_t *box = NULL;
1036
1037             if( !strcmp( p_meta->name[i], VLC_META_TITLE ) )
1038                 box = box_new( "\251nam" );
1039             else if( !strcmp( p_meta->name[i], VLC_META_AUTHOR ) )
1040                 box = box_new( "\251aut" );
1041             else if( !strcmp( p_meta->name[i], VLC_META_ARTIST ) )
1042                 box = box_new( "\251ART" );
1043             else if( !strcmp( p_meta->name[i], VLC_META_GENRE ) )
1044                 box = box_new( "\251gen" );
1045             else if( !strcmp( p_meta->name[i], VLC_META_COPYRIGHT ) )
1046                 box = box_new( "\251cpy" );
1047             else if( !strcmp( p_meta->name[i], VLC_META_DESCRIPTION ) )
1048                 box = box_new( "\251des" );
1049             else if( !strcmp( p_meta->name[i], VLC_META_DATE ) )
1050                 box = box_new( "\251day" );
1051             else if( !strcmp( p_meta->name[i], VLC_META_URL ) )
1052                 box = box_new( "\251url" );
1053
1054             if( box )
1055             {
1056                 bo_add_16be( box, strlen( p_meta->value[i] ) );
1057                 bo_add_16be( box, 0 );
1058                 bo_add_mem( box, strlen( p_meta->value[i] ),
1059                             p_meta->value[i] );
1060                 box_fix( box );
1061                 box_gather( udta, box );
1062             }
1063         }
1064     }
1065
1066     box_fix( udta );
1067     return udta;
1068 }
1069
1070 static bo_t *GetSounBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
1071 {
1072     sout_mux_sys_t *p_sys = p_mux->p_sys;
1073     vlc_bool_t b_descr = VLC_FALSE;
1074     bo_t *soun;
1075     char fcc[4] = "    ";
1076     int  i;
1077
1078     switch( p_stream->fmt.i_codec )
1079     {
1080     case VLC_FOURCC('m','p','4','a'):
1081         memcpy( fcc, "mp4a", 4 );
1082         b_descr = VLC_TRUE;
1083         break;
1084
1085     case VLC_FOURCC('s','a','m','r'):
1086     case VLC_FOURCC('s','a','w','b'):
1087         memcpy( fcc, (char*)&p_stream->fmt.i_codec, 4 );
1088         b_descr = VLC_TRUE;
1089         break;
1090
1091     case VLC_FOURCC('m','p','g','a'):
1092         if( p_sys->b_mov )
1093             memcpy( fcc, ".mp3", 4 );
1094         else
1095         {
1096             memcpy( fcc, "mp4a", 4 );
1097             b_descr = VLC_TRUE;
1098         }
1099         break;
1100
1101     default:
1102         memcpy( fcc, (char*)&p_stream->fmt.i_codec, 4 );
1103         break;
1104     }
1105
1106     soun = box_new( fcc );
1107     for( i = 0; i < 6; i++ )
1108     {
1109         bo_add_8( soun, 0 );        // reserved;
1110     }
1111     bo_add_16be( soun, 1 );         // data-reference-index
1112
1113     /* SoundDescription */
1114     if( p_sys->b_mov &&
1115         p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','a') )
1116     {
1117         bo_add_16be( soun, 1 );     // version 1;
1118     }
1119     else
1120     {
1121         bo_add_16be( soun, 0 );     // version 0;
1122     }
1123     bo_add_16be( soun, 0 );         // revision level (0)
1124     bo_add_32be( soun, 0 );         // vendor
1125     // channel-count
1126     bo_add_16be( soun, p_stream->fmt.audio.i_channels );
1127     // sample size
1128     bo_add_16be( soun, p_stream->fmt.audio.i_bitspersample ?
1129                  p_stream->fmt.audio.i_bitspersample : 16 );
1130     bo_add_16be( soun, -2 );        // compression id
1131     bo_add_16be( soun, 0 );         // packet size (0)
1132     bo_add_16be( soun, p_stream->fmt.audio.i_rate ); // sampleratehi
1133     bo_add_16be( soun, 0 );                             // sampleratelo
1134
1135     /* Extended data for SoundDescription V1 */
1136     if( p_sys->b_mov &&
1137         p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','a') )
1138     {
1139         /* samples per packet */
1140         bo_add_32be( soun, p_stream->fmt.audio.i_frame_length );
1141         bo_add_32be( soun, 1536 ); /* bytes per packet */
1142         bo_add_32be( soun, 2 );    /* bytes per frame */
1143         /* bytes per sample */
1144         bo_add_32be( soun, 2 /*p_stream->fmt.audio.i_bitspersample/8 */);
1145     }
1146
1147     /* Add an ES Descriptor */
1148     if( b_descr )
1149     {
1150         bo_t *box;
1151
1152         if( p_sys->b_mov &&
1153             p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','a') )
1154         {
1155             box = GetWaveTag( p_stream );
1156         }
1157         else if( p_stream->fmt.i_codec == VLC_FOURCC('s','a','m','r') )
1158         {
1159             box = GetDamrTag( p_stream );
1160         }
1161         else
1162         {
1163             box = GetESDS( p_stream );
1164         }
1165         box_fix( box );
1166         box_gather( soun, box );
1167     }
1168
1169     box_fix( soun );
1170
1171     return soun;
1172 }
1173
1174 static bo_t *GetVideBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
1175 {
1176
1177     bo_t *vide;
1178     char fcc[4] = "    ";
1179     int  i;
1180
1181     switch( p_stream->fmt.i_codec )
1182     {
1183     case VLC_FOURCC('m','p','4','v'):
1184     case VLC_FOURCC('m','p','g','v'):
1185         memcpy( fcc, "mp4v", 4 );
1186         break;
1187
1188     case VLC_FOURCC('M','J','P','G'):
1189         memcpy( fcc, "mjpa", 4 );
1190         break;
1191
1192     case VLC_FOURCC('S','V','Q','1'):
1193         memcpy( fcc, "SVQ1", 4 );
1194         break;
1195
1196     case VLC_FOURCC('S','V','Q','3'):
1197         memcpy( fcc, "SVQ3", 4 );
1198         break;
1199
1200     case VLC_FOURCC('H','2','6','3'):
1201         memcpy( fcc, "s263", 4 );
1202         break;
1203
1204     case VLC_FOURCC('h','2','6','4'):
1205         memcpy( fcc, "avc1", 4 );
1206         break;
1207
1208     default:
1209         memcpy( fcc, (char*)&p_stream->fmt.i_codec, 4 );
1210         break;
1211     }
1212
1213     vide = box_new( fcc );
1214     for( i = 0; i < 6; i++ )
1215     {
1216         bo_add_8( vide, 0 );        // reserved;
1217     }
1218     bo_add_16be( vide, 1 );         // data-reference-index
1219
1220     bo_add_16be( vide, 0 );         // predefined;
1221     bo_add_16be( vide, 0 );         // reserved;
1222     for( i = 0; i < 3; i++ )
1223     {
1224         bo_add_32be( vide, 0 );     // predefined;
1225     }
1226
1227     bo_add_16be( vide, p_stream->fmt.video.i_width );  // i_width
1228     bo_add_16be( vide, p_stream->fmt.video.i_height ); // i_height
1229
1230     bo_add_32be( vide, 0x00480000 );                // h 72dpi
1231     bo_add_32be( vide, 0x00480000 );                // v 72dpi
1232
1233     bo_add_32be( vide, 0 );         // data size, always 0
1234     bo_add_16be( vide, 1 );         // frames count per sample
1235
1236     // compressor name;
1237     for( i = 0; i < 32; i++ )
1238     {
1239         bo_add_8( vide, 0 );
1240     }
1241
1242     bo_add_16be( vide, 0x18 );      // depth
1243     bo_add_16be( vide, 0xffff );    // predefined
1244
1245     /* add an ES Descriptor */
1246     switch( p_stream->fmt.i_codec )
1247     {
1248     case VLC_FOURCC('m','p','4','v'):
1249     case VLC_FOURCC('m','p','g','v'):
1250         {
1251             bo_t *esds = GetESDS( p_stream );
1252
1253             box_fix( esds );
1254             box_gather( vide, esds );
1255         }
1256         break;
1257
1258     case VLC_FOURCC('H','2','6','3'):
1259         {
1260             bo_t *d263 = GetD263Tag( p_stream );
1261
1262             box_fix( d263 );
1263             box_gather( vide, d263 );
1264         }
1265         break;
1266
1267     case VLC_FOURCC('S','V','Q','3'):
1268         {
1269             bo_t *esds = GetSVQ3Tag( p_stream );
1270
1271             box_fix( esds );
1272             box_gather( vide, esds );
1273         }
1274         break;
1275
1276     case VLC_FOURCC('h','2','6','4'):
1277         box_gather( vide, GetAvcCTag( p_stream ) );
1278         break;
1279
1280     default:
1281         break;
1282     }
1283
1284     box_fix( vide );
1285
1286     return vide;
1287 }
1288
1289 static bo_t *GetTextBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
1290 {
1291
1292     bo_t *text = box_new( "text" );
1293     int  i;
1294
1295     for( i = 0; i < 6; i++ )
1296     {
1297         bo_add_8( text, 0 );        // reserved;
1298     }
1299     bo_add_16be( text, 1 );         // data-reference-index
1300
1301     bo_add_32be( text, 0 );         // display flags
1302     bo_add_32be( text, 0 );         // justification
1303     for( i = 0; i < 3; i++ )
1304     {
1305         bo_add_16be( text, 0 );     // back ground color
1306     }
1307
1308     bo_add_16be( text, 0 );         // box text
1309     bo_add_16be( text, 0 );         // box text
1310     bo_add_16be( text, 0 );         // box text
1311     bo_add_16be( text, 0 );         // box text
1312
1313     bo_add_64be( text, 0 );         // reserved
1314     for( i = 0; i < 3; i++ )
1315     {
1316         bo_add_16be( text, 0xff );  // foreground color
1317     }
1318
1319     bo_add_8 ( text, 9 );
1320     bo_add_mem( text, 9, "Helvetica" );
1321
1322     box_fix( text );
1323
1324     return text;
1325 }
1326
1327 static bo_t *GetStblBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
1328 {
1329     sout_mux_sys_t *p_sys = p_mux->p_sys;
1330     unsigned int i_chunk, i_stsc_last_val, i_stsc_entries, i, i_index;
1331     bo_t *stbl, *stsd, *stts, *stco, *stsc, *stsz, *stss;
1332     uint32_t i_timescale;
1333     int64_t i_dts, i_dts_q;
1334
1335     stbl = box_new( "stbl" );
1336
1337     /* sample description */
1338     stsd = box_full_new( "stsd", 0, 0 );
1339     bo_add_32be( stsd, 1 );
1340     if( p_stream->fmt.i_cat == AUDIO_ES )
1341     {
1342         bo_t *soun = GetSounBox( p_mux, p_stream );
1343         box_gather( stsd, soun );
1344     }
1345     else if( p_stream->fmt.i_cat == VIDEO_ES )
1346     {
1347         bo_t *vide = GetVideBox( p_mux, p_stream );
1348         box_gather( stsd, vide );
1349     }
1350     else if( p_stream->fmt.i_cat == SPU_ES )
1351     {
1352         box_gather( stsd, GetTextBox( p_mux, p_stream ) );
1353     }
1354     box_fix( stsd );
1355
1356     /* chunk offset table */
1357     if( p_sys->i_pos >= (((uint64_t)0x1) << 32) )
1358     {
1359         /* 64 bits version */
1360         p_stream->b_stco64 = VLC_TRUE;
1361         stco = box_full_new( "co64", 0, 0 );
1362     }
1363     else
1364     {
1365         /* 32 bits version */
1366         p_stream->b_stco64 = VLC_FALSE;
1367         stco = box_full_new( "stco", 0, 0 );
1368     }
1369     bo_add_32be( stco, 0 );     // entry-count (fixed latter)
1370
1371     /* sample to chunk table */
1372     stsc = box_full_new( "stsc", 0, 0 );
1373     bo_add_32be( stsc, 0 );     // entry-count (fixed latter)
1374
1375     for( i_chunk = 0, i_stsc_last_val = 0, i_stsc_entries = 0, i = 0;
1376          i < p_stream->i_entry_count; i_chunk++ )
1377     {
1378         int i_first = i;
1379
1380         if( p_stream->b_stco64 )
1381             bo_add_64be( stco, p_stream->entry[i].i_pos );
1382         else
1383             bo_add_32be( stco, p_stream->entry[i].i_pos );
1384
1385         while( i < p_stream->i_entry_count )
1386         {
1387             if( i + 1 < p_stream->i_entry_count &&
1388                 p_stream->entry[i].i_pos + p_stream->entry[i].i_size
1389                 != p_stream->entry[i + 1].i_pos )
1390             {
1391                 i++;
1392                 break;
1393             }
1394
1395             i++;
1396         }
1397
1398         /* Add entry to the stsc table */
1399         if( i_stsc_last_val != i - i_first )
1400         {
1401             bo_add_32be( stsc, 1 + i_chunk );   // first-chunk
1402             bo_add_32be( stsc, i - i_first ) ;  // samples-per-chunk
1403             bo_add_32be( stsc, 1 );             // sample-descr-index
1404             i_stsc_last_val = i - i_first;
1405             i_stsc_entries++;
1406         }
1407     }
1408
1409     /* Fix stco entry count */
1410     bo_fix_32be( stco, 12, i_chunk );
1411     msg_Dbg( p_mux, "created %d chunks (stco)", i_chunk );
1412     box_fix( stco );
1413
1414     /* Fix stsc entry count */
1415     bo_fix_32be( stsc, 12, i_stsc_entries  );
1416     box_fix( stsc );
1417
1418     /* add stts */
1419     stts = box_full_new( "stts", 0, 0 );
1420     bo_add_32be( stts, 0 );     // entry-count (fixed latter)
1421
1422     if( p_stream->fmt.i_cat == AUDIO_ES )
1423         i_timescale = p_stream->fmt.audio.i_rate;
1424     else
1425         i_timescale = 1001;
1426
1427     /* first, create quantified length */
1428     for( i = 0, i_dts = 0, i_dts_q = 0; i < p_stream->i_entry_count; i++ )
1429     {
1430         int64_t i_dts_deq = i_dts_q * I64C(1000000) / (int64_t)i_timescale;
1431         int64_t i_delta = p_stream->entry[i].i_length + i_dts - i_dts_deq;
1432
1433         i_dts += p_stream->entry[i].i_length;
1434
1435         p_stream->entry[i].i_length =
1436             i_delta * (int64_t)i_timescale / I64C(1000000);
1437
1438         i_dts_q += p_stream->entry[i].i_length;
1439     }
1440     /* then write encoded table */
1441     for( i = 0, i_index = 0; i < p_stream->i_entry_count; i_index++)
1442     {
1443         int     i_first = i;
1444         int64_t i_delta = p_stream->entry[i].i_length;
1445
1446         while( i < p_stream->i_entry_count )
1447         {
1448             i++;
1449             if( i >= p_stream->i_entry_count ||
1450                 p_stream->entry[i].i_length != i_delta )
1451             {
1452                 break;
1453             }
1454         }
1455
1456         bo_add_32be( stts, i - i_first ); // sample-count
1457         bo_add_32be( stts, i_delta );     // sample-delta
1458     }
1459     bo_fix_32be( stts, 12, i_index );
1460     box_fix( stts );
1461
1462     /* FIXME add ctts ?? FIXME */
1463
1464     stsz = box_full_new( "stsz", 0, 0 );
1465     bo_add_32be( stsz, 0 );                             // sample-size
1466     bo_add_32be( stsz, p_stream->i_entry_count );       // sample-count
1467     for( i = 0; i < p_stream->i_entry_count; i++ )
1468     {
1469         bo_add_32be( stsz, p_stream->entry[i].i_size ); // sample-size
1470     }
1471     box_fix( stsz );
1472
1473     /* create stss table */
1474     stss = NULL;
1475     for( i = 0, i_index = 0; i < p_stream->i_entry_count; i++ )
1476     {
1477         if( p_stream->entry[i].i_flags & BLOCK_FLAG_TYPE_I )
1478         {
1479             if( stss == NULL )
1480             {
1481                 stss = box_full_new( "stss", 0, 0 );
1482                 bo_add_32be( stss, 0 ); /* fixed later */
1483             }
1484             bo_add_32be( stss, 1 + i );
1485             i_index++;
1486         }
1487     }
1488     if( stss )
1489     {
1490         bo_fix_32be( stss, 12, i_index );
1491         box_fix( stss );
1492     }
1493
1494     /* Now gather all boxes into stbl */
1495     box_gather( stbl, stsd );
1496     box_gather( stbl, stts );
1497     if( stss )
1498     {
1499         box_gather( stbl, stss );
1500     }
1501     box_gather( stbl, stsc );
1502     box_gather( stbl, stsz );
1503     p_stream->i_stco_pos = stbl->i_buffer + 16;
1504     box_gather( stbl, stco );
1505
1506     /* finish stbl */
1507     box_fix( stbl );
1508
1509     return stbl;
1510 }
1511
1512 static int64_t get_timestamp();
1513
1514 static uint32_t mvhd_matrix[9] =
1515     { 0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000 };
1516
1517 static bo_t *GetMoovBox( sout_mux_t *p_mux )
1518 {
1519     sout_mux_sys_t *p_sys = p_mux->p_sys;
1520
1521     bo_t            *moov, *mvhd;
1522     int             i_trak, i;
1523
1524     uint32_t        i_movie_timescale = 90000;
1525     int64_t         i_movie_duration  = 0;
1526
1527     moov = box_new( "moov" );
1528
1529     /* Create general info */
1530     for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
1531     {
1532         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
1533         i_movie_duration = __MAX( i_movie_duration, p_stream->i_duration );
1534     }
1535     msg_Dbg( p_mux, "movie duration %ds",
1536              (uint32_t)( i_movie_duration / (mtime_t)1000000 ) );
1537
1538     i_movie_duration = i_movie_duration * i_movie_timescale / 1000000;
1539
1540     /* *** add /moov/mvhd *** */
1541     if( !p_sys->b_64_ext )
1542     {
1543         mvhd = box_full_new( "mvhd", 0, 0 );
1544         bo_add_32be( mvhd, get_timestamp() );   // creation time
1545         bo_add_32be( mvhd, get_timestamp() );   // modification time
1546         bo_add_32be( mvhd, i_movie_timescale);  // timescale
1547         bo_add_32be( mvhd, i_movie_duration );  // duration
1548     }
1549     else
1550     {
1551         mvhd = box_full_new( "mvhd", 1, 0 );
1552         bo_add_64be( mvhd, get_timestamp() );   // creation time
1553         bo_add_64be( mvhd, get_timestamp() );   // modification time
1554         bo_add_32be( mvhd, i_movie_timescale);  // timescale
1555         bo_add_64be( mvhd, i_movie_duration );  // duration
1556     }
1557     bo_add_32be( mvhd, 0x10000 );           // rate
1558     bo_add_16be( mvhd, 0x100 );             // volume
1559     bo_add_16be( mvhd, 0 );                 // reserved
1560     for( i = 0; i < 2; i++ )
1561     {
1562         bo_add_32be( mvhd, 0 );             // reserved
1563     }
1564     for( i = 0; i < 9; i++ )
1565     {
1566         bo_add_32be( mvhd, mvhd_matrix[i] );// matrix
1567     }
1568     for( i = 0; i < 6; i++ )
1569     {
1570         bo_add_32be( mvhd, 0 );             // pre-defined
1571     }
1572
1573     /* Next available track id */
1574     bo_add_32be( mvhd, p_sys->i_nb_streams + 1 ); // next-track-id
1575
1576     box_fix( mvhd );
1577     box_gather( moov, mvhd );
1578
1579     for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
1580     {
1581         mp4_stream_t *p_stream;
1582         uint32_t     i_timescale;
1583
1584         bo_t *trak, *tkhd, *edts, *elst, *mdia, *mdhd, *hdlr;
1585         bo_t *minf, *dinf, *dref, *url, *stbl;
1586
1587         p_stream = p_sys->pp_streams[i_trak];
1588
1589         if( p_stream->fmt.i_cat == AUDIO_ES )
1590             i_timescale = p_stream->fmt.audio.i_rate;
1591         else
1592             i_timescale = 1001;
1593
1594         /* *** add /moov/trak *** */
1595         trak = box_new( "trak" );
1596
1597         /* *** add /moov/trak/tkhd *** */
1598         if( !p_sys->b_64_ext )
1599         {
1600             if( p_sys->b_mov )
1601                 tkhd = box_full_new( "tkhd", 0, 0x0f );
1602             else
1603                 tkhd = box_full_new( "tkhd", 0, 1 );
1604
1605             bo_add_32be( tkhd, get_timestamp() );       // creation time
1606             bo_add_32be( tkhd, get_timestamp() );       // modification time
1607             bo_add_32be( tkhd, p_stream->i_track_id );
1608             bo_add_32be( tkhd, 0 );                     // reserved 0
1609             bo_add_32be( tkhd, p_stream->i_duration *
1610                          (int64_t)i_movie_timescale /
1611                          (mtime_t)1000000 );            // duration
1612         }
1613         else
1614         {
1615             if( p_sys->b_mov )
1616                 tkhd = box_full_new( "tkhd", 1, 0x0f );
1617             else
1618                 tkhd = box_full_new( "tkhd", 1, 1 );
1619
1620             bo_add_64be( tkhd, get_timestamp() );       // creation time
1621             bo_add_64be( tkhd, get_timestamp() );       // modification time
1622             bo_add_32be( tkhd, p_stream->i_track_id );
1623             bo_add_32be( tkhd, 0 );                     // reserved 0
1624             bo_add_64be( tkhd, p_stream->i_duration *
1625                          (int64_t)i_movie_timescale /
1626                          (mtime_t)1000000 );            // duration
1627         }
1628
1629         for( i = 0; i < 2; i++ )
1630         {
1631             bo_add_32be( tkhd, 0 );                 // reserved
1632         }
1633         bo_add_16be( tkhd, 0 );                     // layer
1634         bo_add_16be( tkhd, 0 );                     // pre-defined
1635         // volume
1636         bo_add_16be( tkhd, p_stream->fmt.i_cat == AUDIO_ES ? 0x100 : 0 );
1637         bo_add_16be( tkhd, 0 );                     // reserved
1638         for( i = 0; i < 9; i++ )
1639         {
1640             bo_add_32be( tkhd, mvhd_matrix[i] );    // matrix
1641         }
1642         if( p_stream->fmt.i_cat == AUDIO_ES )
1643         {
1644             bo_add_32be( tkhd, 0 );                 // width (presentation)
1645             bo_add_32be( tkhd, 0 );                 // height(presentation)
1646         }
1647         else if( p_stream->fmt.i_cat == VIDEO_ES )
1648         {
1649             int i_width = p_stream->fmt.video.i_width << 16;
1650             if( p_stream->fmt.video.i_aspect > 0 )
1651             {
1652                 i_width = (int64_t)p_stream->fmt.video.i_aspect *
1653                           ((int64_t)p_stream->fmt.video.i_height << 16) /
1654                           VOUT_ASPECT_FACTOR;
1655             }
1656             // width (presentation)
1657             bo_add_32be( tkhd, i_width );
1658             // height(presentation)
1659             bo_add_32be( tkhd, p_stream->fmt.video.i_height << 16 );
1660         }
1661         else
1662         {
1663             int i_width = 320 << 16;
1664             int i_height = 200;
1665             int i;
1666             for( i = 0; i < p_sys->i_nb_streams; i++ )
1667             {
1668                 mp4_stream_t *tk = p_sys->pp_streams[i];
1669                 if( tk->fmt.i_cat == VIDEO_ES )
1670                 {
1671                     if( p_stream->fmt.video.i_aspect )
1672                         i_width = (int64_t)p_stream->fmt.video.i_aspect *
1673                                    ((int64_t)p_stream->fmt.video.i_height<<16) / VOUT_ASPECT_FACTOR;
1674                     else
1675                         i_width = p_stream->fmt.video.i_width << 16;
1676                     i_height = p_stream->fmt.video.i_height;
1677                     break;
1678                 }
1679             }
1680             bo_add_32be( tkhd, i_width );     // width (presentation)
1681             bo_add_32be( tkhd, i_height << 16 );    // height(presentation)
1682         }
1683
1684         box_fix( tkhd );
1685         box_gather( trak, tkhd );
1686
1687         /* *** add /moov/trak/edts and elst */
1688         edts = box_new( "edts" );
1689         elst = box_full_new( "elst", p_sys->b_64_ext ? 1 : 0, 0 );
1690         if( p_stream->i_dts_start > p_sys->i_dts_start )
1691         {
1692             bo_add_32be( elst, 2 );
1693
1694             if( p_sys->b_64_ext )
1695             {
1696                 bo_add_64be( elst, (p_stream->i_dts_start-p_sys->i_dts_start) *
1697                              i_movie_timescale / I64C(1000000) );
1698                 bo_add_64be( elst, -1 );
1699             }
1700             else
1701             {
1702                 bo_add_32be( elst, (p_stream->i_dts_start-p_sys->i_dts_start) *
1703                              i_movie_timescale / I64C(1000000) );
1704                 bo_add_32be( elst, -1 );
1705             }
1706             bo_add_16be( elst, 1 );
1707             bo_add_16be( elst, 0 );
1708         }
1709         else
1710         {
1711             bo_add_32be( elst, 1 );
1712         }
1713         if( p_sys->b_64_ext )
1714         {
1715             bo_add_64be( elst, p_stream->i_duration *
1716                          i_movie_timescale / I64C(1000000) );
1717             bo_add_64be( elst, 0 );
1718         }
1719         else
1720         {
1721             bo_add_32be( elst, p_stream->i_duration *
1722                          i_movie_timescale / I64C(1000000) );
1723             bo_add_32be( elst, 0 );
1724         }
1725         bo_add_16be( elst, 1 );
1726         bo_add_16be( elst, 0 );
1727
1728         box_fix( elst );
1729         box_gather( edts, elst );
1730         box_fix( edts );
1731         box_gather( trak, edts );
1732
1733         /* *** add /moov/trak/mdia *** */
1734         mdia = box_new( "mdia" );
1735
1736         /* media header */
1737         if( !p_sys->b_64_ext )
1738         {
1739             mdhd = box_full_new( "mdhd", 0, 0 );
1740             bo_add_32be( mdhd, get_timestamp() );   // creation time
1741             bo_add_32be( mdhd, get_timestamp() );   // modification time
1742             bo_add_32be( mdhd, i_timescale);        // timescale
1743             bo_add_32be( mdhd, p_stream->i_duration * (int64_t)i_timescale /
1744                                (mtime_t)1000000 );  // duration
1745         }
1746         else
1747         {
1748             mdhd = box_full_new( "mdhd", 1, 0 );
1749             bo_add_64be( mdhd, get_timestamp() );   // creation time
1750             bo_add_64be( mdhd, get_timestamp() );   // modification time
1751             bo_add_32be( mdhd, i_timescale);        // timescale
1752             bo_add_64be( mdhd, p_stream->i_duration * (int64_t)i_timescale /
1753                                (mtime_t)1000000 );  // duration
1754         }
1755
1756         if( p_stream->fmt.psz_language )
1757         {
1758             char *psz = p_stream->fmt.psz_language;
1759             const iso639_lang_t *pl = NULL;
1760             uint16_t lang = 0x0;
1761
1762             if( strlen( psz ) == 2 )
1763             {
1764                 pl = GetLang_1( psz );
1765             }
1766             else if( strlen( psz ) == 3 )
1767             {
1768                 pl = GetLang_2B( psz );
1769                 if( !strcmp( pl->psz_iso639_1, "??" ) )
1770                 {
1771                     pl = GetLang_2T( psz );
1772                 }
1773             }
1774             if( pl && strcmp( pl->psz_iso639_1, "??" ) )
1775             {
1776                 lang = ( ( pl->psz_iso639_2T[0] - 0x60 ) << 10 ) |
1777                        ( ( pl->psz_iso639_2T[1] - 0x60 ) <<  5 ) |
1778                        ( ( pl->psz_iso639_2T[2] - 0x60 ) );
1779             }
1780             bo_add_16be( mdhd, lang );          // language
1781         }
1782         else
1783         {
1784             bo_add_16be( mdhd, 0    );          // language
1785         }
1786         bo_add_16be( mdhd, 0    );              // predefined
1787         box_fix( mdhd );
1788         box_gather( mdia, mdhd );
1789
1790         /* handler reference */
1791         hdlr = box_full_new( "hdlr", 0, 0 );
1792
1793         if( p_sys->b_mov )
1794             bo_add_fourcc( hdlr, "mhlr" );         // media handler
1795         else
1796             bo_add_32be( hdlr, 0 );
1797
1798         if( p_stream->fmt.i_cat == AUDIO_ES )
1799             bo_add_fourcc( hdlr, "soun" );
1800         else if( p_stream->fmt.i_cat == VIDEO_ES )
1801             bo_add_fourcc( hdlr, "vide" );
1802         else if( p_stream->fmt.i_cat == SPU_ES )
1803             bo_add_fourcc( hdlr, "text" );
1804
1805         bo_add_32be( hdlr, 0 );         // reserved
1806         bo_add_32be( hdlr, 0 );         // reserved
1807         bo_add_32be( hdlr, 0 );         // reserved
1808
1809         if( p_sys->b_mov )
1810             bo_add_8( hdlr, 12 );   /* Pascal string for .mov */
1811
1812         if( p_stream->fmt.i_cat == AUDIO_ES )
1813             bo_add_mem( hdlr, 12, "SoundHandler" );
1814         else if( p_stream->fmt.i_cat == VIDEO_ES )
1815             bo_add_mem( hdlr, 12, "VideoHandler" );
1816         else
1817             bo_add_mem( hdlr, 12, "Text Handler" );
1818
1819         if( !p_sys->b_mov )
1820             bo_add_8( hdlr, 0 );   /* asciiz string for .mp4, yes that's BRAIN DAMAGED F**K MP4 */
1821
1822         box_fix( hdlr );
1823         box_gather( mdia, hdlr );
1824
1825         /* minf*/
1826         minf = box_new( "minf" );
1827
1828         /* add smhd|vmhd */
1829         if( p_stream->fmt.i_cat == AUDIO_ES )
1830         {
1831             bo_t *smhd;
1832
1833             smhd = box_full_new( "smhd", 0, 0 );
1834             bo_add_16be( smhd, 0 );     // balance
1835             bo_add_16be( smhd, 0 );     // reserved
1836             box_fix( smhd );
1837
1838             box_gather( minf, smhd );
1839         }
1840         else if( p_stream->fmt.i_cat == VIDEO_ES )
1841         {
1842             bo_t *vmhd;
1843
1844             vmhd = box_full_new( "vmhd", 0, 1 );
1845             bo_add_16be( vmhd, 0 );     // graphicsmode
1846             for( i = 0; i < 3; i++ )
1847             {
1848                 bo_add_16be( vmhd, 0 ); // opcolor
1849             }
1850             box_fix( vmhd );
1851
1852             box_gather( minf, vmhd );
1853         }
1854         else if( p_stream->fmt.i_cat == SPU_ES )
1855         {
1856             bo_t *gmhd = box_new( "gmhd" );
1857             bo_t *gmin = box_full_new( "gmin", 0, 1 );
1858
1859             bo_add_16be( gmin, 0 );     // graphicsmode
1860             for( i = 0; i < 3; i++ )
1861             {
1862                 bo_add_16be( gmin, 0 ); // opcolor
1863             }
1864             bo_add_16be( gmin, 0 );     // balance
1865             bo_add_16be( gmin, 0 );     // reserved
1866             box_fix( gmin );
1867
1868             box_gather( gmhd, gmin );
1869             box_fix( gmhd );
1870
1871             box_gather( minf, gmhd );
1872         }
1873
1874         /* dinf */
1875         dinf = box_new( "dinf" );
1876         dref = box_full_new( "dref", 0, 0 );
1877         bo_add_32be( dref, 1 );
1878         url = box_full_new( "url ", 0, 0x01 );
1879         box_fix( url );
1880         box_gather( dref, url );
1881         box_fix( dref );
1882         box_gather( dinf, dref );
1883
1884         /* append dinf to mdia */
1885         box_fix( dinf );
1886         box_gather( minf, dinf );
1887
1888         /* add stbl */
1889         stbl = GetStblBox( p_mux, p_stream );
1890
1891         /* append stbl to minf */
1892         p_stream->i_stco_pos += minf->i_buffer;
1893         box_gather( minf, stbl );
1894
1895         /* append minf to mdia */
1896         box_fix( minf );
1897         p_stream->i_stco_pos += mdia->i_buffer;
1898         box_gather( mdia, minf );
1899
1900         /* append mdia to trak */
1901         box_fix( mdia );
1902         p_stream->i_stco_pos += trak->i_buffer;
1903         box_gather( trak, mdia );
1904
1905         /* append trak to moov */
1906         box_fix( trak );
1907         p_stream->i_stco_pos += moov->i_buffer;
1908         box_gather( moov, trak );
1909     }
1910
1911     /* Add user data tags */
1912     box_gather( moov, GetUdtaTag( p_mux ) );
1913
1914     box_fix( moov );
1915     return moov;
1916 }
1917
1918 /****************************************************************************/
1919
1920 static void bo_init( bo_t *p_bo, int i_size, uint8_t *p_buffer,
1921                      vlc_bool_t b_grow )
1922 {
1923     if( !p_buffer )
1924     {
1925         p_bo->i_buffer_size = __MAX( i_size, 1024 );
1926         p_bo->p_buffer = malloc( p_bo->i_buffer_size );
1927     }
1928     else
1929     {
1930         p_bo->i_buffer_size = i_size;
1931         p_bo->p_buffer = p_buffer;
1932     }
1933
1934     p_bo->b_grow = b_grow;
1935     p_bo->i_buffer = 0;
1936 }
1937
1938 static void bo_add_8( bo_t *p_bo, uint8_t i )
1939 {
1940     if( p_bo->i_buffer < p_bo->i_buffer_size )
1941     {
1942         p_bo->p_buffer[p_bo->i_buffer] = i;
1943     }
1944     else if( p_bo->b_grow )
1945     {
1946         p_bo->i_buffer_size += 1024;
1947         p_bo->p_buffer = realloc( p_bo->p_buffer, p_bo->i_buffer_size );
1948
1949         p_bo->p_buffer[p_bo->i_buffer] = i;
1950     }
1951
1952     p_bo->i_buffer++;
1953 }
1954
1955 static void bo_add_16be( bo_t *p_bo, uint16_t i )
1956 {
1957     bo_add_8( p_bo, ( ( i >> 8) &0xff ) );
1958     bo_add_8( p_bo, i &0xff );
1959 }
1960
1961 static void bo_add_24be( bo_t *p_bo, uint32_t i )
1962 {
1963     bo_add_8( p_bo, ( ( i >> 16) &0xff ) );
1964     bo_add_8( p_bo, ( ( i >> 8) &0xff ) );
1965     bo_add_8( p_bo, (   i &0xff ) );
1966 }
1967 static void bo_add_32be( bo_t *p_bo, uint32_t i )
1968 {
1969     bo_add_16be( p_bo, ( ( i >> 16) &0xffff ) );
1970     bo_add_16be( p_bo, i &0xffff );
1971 }
1972
1973 static void bo_fix_32be ( bo_t *p_bo, int i_pos, uint32_t i)
1974 {
1975     p_bo->p_buffer[i_pos    ] = ( i >> 24 )&0xff;
1976     p_bo->p_buffer[i_pos + 1] = ( i >> 16 )&0xff;
1977     p_bo->p_buffer[i_pos + 2] = ( i >>  8 )&0xff;
1978     p_bo->p_buffer[i_pos + 3] = ( i       )&0xff;
1979 }
1980
1981 static void bo_add_64be( bo_t *p_bo, uint64_t i )
1982 {
1983     bo_add_32be( p_bo, ( ( i >> 32) &0xffffffff ) );
1984     bo_add_32be( p_bo, i &0xffffffff );
1985 }
1986
1987 static void bo_add_fourcc( bo_t *p_bo, char *fcc )
1988 {
1989     bo_add_8( p_bo, fcc[0] );
1990     bo_add_8( p_bo, fcc[1] );
1991     bo_add_8( p_bo, fcc[2] );
1992     bo_add_8( p_bo, fcc[3] );
1993 }
1994
1995 static void bo_add_mem( bo_t *p_bo, int i_size, uint8_t *p_mem )
1996 {
1997     int i;
1998
1999     for( i = 0; i < i_size; i++ )
2000     {
2001         bo_add_8( p_bo, p_mem[i] );
2002     }
2003 }
2004
2005 static void bo_add_descr( bo_t *p_bo, uint8_t tag, uint32_t i_size )
2006 {
2007     uint32_t i_length;
2008     uint8_t  vals[4];
2009
2010     i_length = i_size;
2011     vals[3] = (unsigned char)(i_length & 0x7f);
2012     i_length >>= 7;
2013     vals[2] = (unsigned char)((i_length & 0x7f) | 0x80); 
2014     i_length >>= 7;
2015     vals[1] = (unsigned char)((i_length & 0x7f) | 0x80); 
2016     i_length >>= 7;
2017     vals[0] = (unsigned char)((i_length & 0x7f) | 0x80);
2018
2019     bo_add_8( p_bo, tag );
2020
2021     if( i_size < 0x00000080 )
2022     {
2023         bo_add_8( p_bo, vals[3] );
2024     }
2025     else if( i_size < 0x00004000 )
2026     {
2027         bo_add_8( p_bo, vals[2] );
2028         bo_add_8( p_bo, vals[3] );
2029     }
2030     else if( i_size < 0x00200000 )
2031     {
2032         bo_add_8( p_bo, vals[1] );
2033         bo_add_8( p_bo, vals[2] );
2034         bo_add_8( p_bo, vals[3] );
2035     }
2036     else if( i_size < 0x10000000 )
2037     {
2038         bo_add_8( p_bo, vals[0] );
2039         bo_add_8( p_bo, vals[1] );
2040         bo_add_8( p_bo, vals[2] );
2041         bo_add_8( p_bo, vals[3] );
2042     }
2043 }
2044
2045 static void bo_add_bo( bo_t *p_bo, bo_t *p_bo2 )
2046 {
2047     int i;
2048
2049     for( i = 0; i < p_bo2->i_buffer; i++ )
2050     {
2051         bo_add_8( p_bo, p_bo2->p_buffer[i] );
2052     }
2053 }
2054
2055 static bo_t * box_new( char *fcc )
2056 {
2057     bo_t *box;
2058
2059     if( ( box = malloc( sizeof( bo_t ) ) ) )
2060     {
2061         bo_init( box, 0, NULL, VLC_TRUE );
2062
2063         bo_add_32be  ( box, 0 );
2064         bo_add_fourcc( box, fcc );
2065     }
2066
2067     return box;
2068 }
2069
2070 static bo_t * box_full_new( char *fcc, uint8_t v, uint32_t f )
2071 {
2072     bo_t *box;
2073
2074     if( ( box = malloc( sizeof( bo_t ) ) ) )
2075     {
2076         bo_init( box, 0, NULL, VLC_TRUE );
2077
2078         bo_add_32be  ( box, 0 );
2079         bo_add_fourcc( box, fcc );
2080         bo_add_8     ( box, v );
2081         bo_add_24be  ( box, f );
2082     }
2083
2084     return box;
2085 }
2086
2087 static void box_fix( bo_t *box )
2088 {
2089     bo_t box_tmp;
2090
2091     memcpy( &box_tmp, box, sizeof( bo_t ) );
2092
2093     box_tmp.i_buffer = 0;
2094     bo_add_32be( &box_tmp, box->i_buffer );
2095 }
2096
2097 static void box_free( bo_t *box )
2098 {
2099     if( box->p_buffer )
2100     {
2101         free( box->p_buffer );
2102     }
2103
2104     free( box );
2105 }
2106
2107 static void box_gather ( bo_t *box, bo_t *box2 )
2108 {
2109     bo_add_bo( box, box2 );
2110     box_free( box2 );
2111 }
2112
2113 static block_t * bo_to_sout( sout_instance_t *p_sout,  bo_t *box )
2114 {
2115     block_t *p_buf;
2116
2117     p_buf = block_New( p_sout, box->i_buffer );
2118     if( box->i_buffer > 0 )
2119     {
2120         memcpy( p_buf->p_buffer, box->p_buffer, box->i_buffer );
2121     }
2122
2123     return p_buf;
2124 }
2125
2126 static void box_send( sout_mux_t *p_mux,  bo_t *box )
2127 {
2128     block_t *p_buf;
2129
2130     p_buf = bo_to_sout( p_mux->p_sout, box );
2131     box_free( box );
2132
2133     sout_AccessOutWrite( p_mux->p_access, p_buf );
2134 }
2135
2136 static int64_t get_timestamp()
2137 {
2138     int64_t i_timestamp = 0;
2139
2140 #ifdef HAVE_TIME_H
2141     i_timestamp = time(NULL);
2142     i_timestamp += 2082844800; // MOV/MP4 start date is 1/1/1904
2143     // 208284480 is (((1970 - 1904) * 365) + 17) * 24 * 60 * 60
2144 #endif
2145
2146     return i_timestamp;
2147 }