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