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