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