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