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