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