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