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