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