]> git.sesse.net Git - vlc/blob - modules/mux/mp4.c
* mp4.c: - accept adding ES at any time
[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', '3' ):
377             break;
378         default:
379             msg_Err( p_mux, "unsupported codec %4.4s in mp4",
380                      (char*)&p_input->p_fmt->i_codec );
381             return VLC_EGENERIC;
382     }
383
384     p_stream                = malloc( sizeof( mp4_stream_t ) );
385     es_format_Copy( &p_stream->fmt, p_input->p_fmt );
386     p_stream->i_track_id    = p_sys->i_nb_streams + 1;
387     p_stream->i_length_neg  = 0;
388     p_stream->i_entry_count = 0;
389     p_stream->i_entry_max   = 1000;
390     p_stream->entry         =
391         calloc( p_stream->i_entry_max, sizeof( mp4_entry_t ) );
392     p_stream->i_dts_start   = 0;
393     p_stream->i_duration    = 0;
394
395     p_input->p_sys          = p_stream;
396
397     msg_Dbg( p_mux, "adding input" );
398
399     TAB_APPEND( p_sys->i_nb_streams, p_sys->pp_streams, p_stream );
400     return VLC_SUCCESS;
401 }
402
403 /*****************************************************************************
404  * DelStream:
405  *****************************************************************************/
406 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
407 {
408     msg_Dbg( p_mux, "removing input" );
409     return VLC_SUCCESS;
410 }
411
412 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
413 {
414     mtime_t i_dts;
415     int     i_stream;
416     int     i;
417
418     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
419     {
420         sout_fifo_t   *p_fifo = p_mux->pp_inputs[i]->p_fifo;
421         sout_buffer_t *p_buf;
422
423         if( p_fifo->i_depth <= 1 )
424         {
425             return -1; // wait that all fifo have at least 2 packets
426         }
427
428         p_buf = sout_FifoShow( p_fifo );
429         if( i_stream < 0 || p_buf->i_dts < i_dts )
430         {
431             i_dts = p_buf->i_dts;
432             i_stream = i;
433         }
434     }
435     if( pi_stream )
436     {
437         *pi_stream = i_stream;
438     }
439     if( pi_dts )
440     {
441         *pi_dts = i_dts;
442     }
443     return i_stream;
444 }
445
446 /*****************************************************************************
447  * Mux:
448  *****************************************************************************/
449 static int Mux( sout_mux_t *p_mux )
450 {
451     sout_mux_sys_t *p_sys = p_mux->p_sys;
452
453     for( ;; )
454     {
455         sout_input_t    *p_input;
456         int             i_stream;
457         mp4_stream_t    *p_stream;
458         sout_buffer_t   *p_data;
459         mtime_t         i_dts;
460
461         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
462         {
463             return( VLC_SUCCESS );
464         }
465
466         p_input  = p_mux->pp_inputs[i_stream];
467         p_stream = (mp4_stream_t*)p_input->p_sys;
468
469         p_data  = sout_FifoGet( p_input->p_fifo );
470         if( p_input->p_fifo->i_depth > 0 )
471         {
472             sout_buffer_t *p_next = sout_FifoShow( p_input->p_fifo );
473             int64_t       i_diff  = p_next->i_dts - p_data->i_dts;
474
475             if( i_diff < I64C(1000000 ) )   /* protection */
476             {
477                 p_data->i_length = i_diff;
478             }
479         }
480         if( p_data->i_length <= 0 )
481         {
482             msg_Warn( p_mux, "i_length <= 0" );
483             p_stream->i_length_neg += p_data->i_length - 1;
484             p_data->i_length = 1;
485         }
486         else if( p_stream->i_length_neg < 0 )
487         {
488             int64_t i_recover = __MIN( p_data->i_length / 4, - p_stream->i_length_neg );
489
490             p_data->i_length -= i_recover;
491             p_stream->i_length_neg += i_recover;
492         }
493
494         /* Save starting time */
495         if( p_stream->i_entry_count == 0 )
496         {
497             p_stream->i_dts_start = p_data->i_dts;
498
499             /* Update global dts_start */
500             if( p_sys->i_dts_start <= 0 ||
501                 p_stream->i_dts_start < p_sys->i_dts_start )
502             {
503                 p_sys->i_dts_start = p_stream->i_dts_start;
504             }
505         }
506
507         /* add index entry */
508         p_stream->entry[p_stream->i_entry_count].i_pos    = p_sys->i_pos;
509         p_stream->entry[p_stream->i_entry_count].i_size   = p_data->i_size;
510         p_stream->entry[p_stream->i_entry_count].i_pts_dts= __MAX( p_data->i_pts - p_data->i_dts, 0 );
511         p_stream->entry[p_stream->i_entry_count].i_length = p_data->i_length;
512         p_stream->entry[p_stream->i_entry_count].i_flags  = p_data->i_flags;
513
514         p_stream->i_entry_count++;
515         if( p_stream->i_entry_count >= p_stream->i_entry_max )
516         {
517             p_stream->i_entry_max += 1000;
518             p_stream->entry =
519                 realloc( p_stream->entry,
520                          p_stream->i_entry_max * sizeof( mp4_entry_t ) );
521         }
522
523         /* update */
524         p_stream->i_duration += p_data->i_length;
525         p_sys->i_pos += p_data->i_size;
526
527         /* write data */
528         sout_AccessOutWrite( p_mux->p_access, p_data );
529     }
530
531     return( VLC_SUCCESS );
532 }
533
534 /*****************************************************************************
535  *
536  *****************************************************************************/
537 static int GetDescrLength( int i_size )
538 {
539     if( i_size < 0x00000080 )
540         return 2 + i_size;
541     else if( i_size < 0x00004000 )
542         return 3 + i_size;
543     else if( i_size < 0x00200000 )
544         return 4 + i_size;
545     else
546         return 5 + i_size;
547 }
548
549 static bo_t *GetESDS( mp4_stream_t *p_stream )
550 {
551     bo_t *esds;
552     int  i_stream_type;
553     int  i_object_type_indication;
554     int  i_decoder_specific_info_size;
555
556     if( p_stream->fmt.i_extra > 0 )
557     {
558         i_decoder_specific_info_size =
559             GetDescrLength( p_stream->fmt.i_extra );
560     }
561     else
562     {
563         i_decoder_specific_info_size = 0;
564     }
565
566     esds = box_full_new( "esds", 0, 0 );
567
568     /* ES_Descr */
569     bo_add_descr( esds, 0x03, 3 +
570                   GetDescrLength( 13 + i_decoder_specific_info_size ) +
571                   GetDescrLength( 1 ) );
572     bo_add_16be( esds, p_stream->i_track_id );
573     bo_add_8   ( esds, 0x1f );      // flags=0|streamPriority=0x1f
574
575     /* DecoderConfigDescr */
576     bo_add_descr( esds, 0x04, 13 + i_decoder_specific_info_size );
577
578     switch( p_stream->fmt.i_codec )
579     {
580         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
581             i_object_type_indication = 0x20;
582             break;
583         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
584             /* FIXME MPEG-I=0x6b, MPEG-II = 0x60 -> 0x65 */
585             i_object_type_indication = 0x60;
586             break;
587         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
588             /* FIXME for mpeg2-aac == 0x66->0x68 */
589             i_object_type_indication = 0x40;
590             break;
591         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
592             i_object_type_indication =
593                 p_stream->fmt.audio.i_rate < 32000 ? 0x69 : 0x6b;
594             break;
595         default:
596             i_object_type_indication = 0x00;
597             break;
598     }
599     i_stream_type = p_stream->fmt.i_cat == VIDEO_ES ? 0x04 : 0x05;
600
601     bo_add_8   ( esds, i_object_type_indication );
602     bo_add_8   ( esds, ( i_stream_type << 2 ) | 1 );
603     bo_add_24be( esds, 1024 * 1024 );       // bufferSizeDB
604     bo_add_32be( esds, 0x7fffffff );        // maxBitrate
605     bo_add_32be( esds, 0 );                 // avgBitrate
606
607     if( p_stream->fmt.i_extra > 0 )
608     {
609         int i;
610
611         /* DecoderSpecificInfo */
612         bo_add_descr( esds, 0x05, p_stream->fmt.i_extra );
613
614         for( i = 0; i < p_stream->fmt.i_extra; i++ )
615         {
616             bo_add_8( esds, ((uint8_t*)p_stream->fmt.p_extra)[i] );
617         }
618     }
619
620     /* SL_Descr mandatory */
621     bo_add_descr( esds, 0x06, 1 );
622     bo_add_8    ( esds, 0x02 );  // sl_predefined
623
624     box_fix( esds );
625
626     return esds;
627 }
628
629 static bo_t *GetWaveTag( mp4_stream_t *p_stream )
630 {
631     bo_t *wave;
632     bo_t *box;
633
634     wave = box_new( "wave" );
635
636     box = box_new( "frma" );
637     bo_add_fourcc( box, "mp4a" );
638     box_fix( box );
639     box_gather( wave, box );
640
641     box = box_new( "mp4a" );
642     bo_add_32be( box, 0 );
643     box_fix( box );
644     box_gather( wave, box );
645
646     box = GetESDS( p_stream );
647     box_fix( box );
648     box_gather( wave, box );
649
650     box = box_new( "srcq" );
651     bo_add_32be( box, 0x40 );
652     box_fix( box );
653     box_gather( wave, box );
654
655     /* wazza ? */
656     bo_add_32be( wave, 8 ); /* new empty box */
657     bo_add_32be( wave, 0 ); /* box label */
658
659     box_fix( wave );
660
661     return wave;
662 }
663
664 /* TODO: No idea about these values */
665 static bo_t *GetSVQ3Tag( mp4_stream_t *p_stream )
666 {
667     bo_t *smi = box_new( "SMI " );
668
669     if( p_stream->fmt.i_extra > 0x4e )
670     {
671         uint8_t *p_end = &((uint8_t*)p_stream->fmt.p_extra)[p_stream->fmt.i_extra];
672         uint8_t *p     = &((uint8_t*)p_stream->fmt.p_extra)[0x46];
673
674         while( p + 8 < p_end )
675         {
676             int i_size = GetDWBE( p );
677             if( i_size <= 1 )
678             {
679                 /* FIXME handle 1 as long size */
680                 break;
681             }
682             if( !strncmp( &p[4], "SMI ", 4 ) )
683             {
684                 bo_add_mem( smi, p_end - p - 8, &p[8] );
685                 return smi;
686             }
687             p += i_size;
688         }
689     }
690
691     /* Create a dummy one in fallback */
692     bo_add_fourcc( smi, "SEQH" );
693     bo_add_32be( smi, 0x5 );
694     bo_add_32be( smi, 0xe2c0211d );
695     bo_add_8( smi, 0xc0 );
696     box_fix( smi );
697
698     return smi;
699 }
700
701 static bo_t *GetUdtaTag( sout_mux_t *p_mux )
702 {
703     sout_mux_sys_t *p_sys = p_mux->p_sys;
704     bo_t *udta = box_new( "udta" );
705     int i_track;
706
707     /* Requirements */
708     for( i_track = 0; i_track < p_sys->i_nb_streams; i_track++ )
709     {
710         mp4_stream_t *p_stream = p_sys->pp_streams[i_track];
711
712         if( p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','v') ||
713             p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','a') )
714         {
715             bo_t *box = box_new( "\251req" );
716             /* String length */
717             bo_add_16be( box, sizeof("QuickTime 6.0 or greater") - 1);
718             bo_add_16be( box, 0 );
719             bo_add_mem( box, sizeof("QuickTime 6.0 or greater") - 1,
720                         "QuickTime 6.0 or greater" );
721             box_fix( box );
722             box_gather( udta, box );
723             break;
724         }
725     }
726
727     /* Encoder */
728     {
729         bo_t *box = box_new( "\251enc" );
730         /* String length */
731         bo_add_16be( box, sizeof(PACKAGE_STRING " stream output") - 1);
732         bo_add_16be( box, 0 );
733         bo_add_mem( box, sizeof(PACKAGE_STRING " stream output") - 1,
734                     PACKAGE_STRING " stream output" );
735         box_fix( box );
736         box_gather( udta, box );
737     }
738
739     box_fix( udta );
740     return udta;
741 }
742
743 static bo_t *GetSounBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
744 {
745     sout_mux_sys_t *p_sys = p_mux->p_sys;
746     vlc_bool_t b_descr = VLC_FALSE;
747     bo_t *soun;
748     char fcc[4] = "    ";
749     int  i;
750
751     switch( p_stream->fmt.i_codec )
752     {
753     case VLC_FOURCC('m','p','4','a'):
754         memcpy( fcc, "mp4a", 4 );
755         b_descr = VLC_TRUE;
756         break;
757
758     case VLC_FOURCC('m','p','g','a'):
759         if( p_sys->b_mov )
760             memcpy( fcc, ".mp3", 4 );
761         else
762         {
763             memcpy( fcc, "mp4a", 4 );
764             b_descr = VLC_TRUE;
765         }
766         break;
767
768     default:
769         memcpy( fcc, (char*)&p_stream->fmt.i_codec, 4 );
770         break;
771     }
772
773     soun = box_new( fcc );
774     for( i = 0; i < 6; i++ )
775     {
776         bo_add_8( soun, 0 );        // reserved;
777     }
778     bo_add_16be( soun, 1 );         // data-reference-index
779
780     /* SoundDescription */
781     if( p_sys->b_mov &&
782         p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','a') )
783     {
784         bo_add_16be( soun, 1 );     // version 1;
785     }
786     else
787     {
788         bo_add_16be( soun, 0 );     // version 0;
789     }
790     bo_add_16be( soun, 0 );         // revision level (0)
791     bo_add_32be( soun, 0 );         // vendor
792     // channel-count
793     bo_add_16be( soun, p_stream->fmt.audio.i_channels );
794     // sample size
795     bo_add_16be( soun, p_stream->fmt.audio.i_bitspersample ?
796                  p_stream->fmt.audio.i_bitspersample : 16 );
797     bo_add_16be( soun, -2 );        // compression id
798     bo_add_16be( soun, 0 );         // packet size (0)
799     bo_add_16be( soun, p_stream->fmt.audio.i_rate ); // sampleratehi
800     bo_add_16be( soun, 0 );                             // sampleratelo
801
802     /* Extended data for SoundDescription V1 */
803     if( p_sys->b_mov &&
804         p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','a') )
805     {
806         /* samples per packet */
807         bo_add_32be( soun, p_stream->fmt.audio.i_frame_length );
808         bo_add_32be( soun, 1536 ); /* bytes per packet */
809         bo_add_32be( soun, 2 );    /* bytes per frame */
810         /* bytes per sample */
811         bo_add_32be( soun, 2 /*p_stream->fmt.audio.i_bitspersample/8 */);
812     }
813
814     /* Add an ES Descriptor */
815     if( b_descr )
816     {
817         bo_t *box;
818
819         if( p_sys->b_mov &&
820             p_stream->fmt.i_codec == VLC_FOURCC('m','p','4','a') )
821         {
822             box = GetWaveTag( p_stream );
823         }
824         else
825         {
826             box = GetESDS( p_stream );
827         }
828         box_fix( box );
829         box_gather( soun, box );
830     }
831
832     box_fix( soun );
833
834     return soun;
835 }
836
837 static bo_t *GetVideBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
838 {
839
840     bo_t *vide;
841     char fcc[4] = "    ";
842     int  i;
843
844     switch( p_stream->fmt.i_codec )
845     {
846     case VLC_FOURCC('m','p','4','v'):
847     case VLC_FOURCC('m','p','g','v'):
848         memcpy( fcc, "mp4v", 4 );
849         break;
850
851     case VLC_FOURCC('M','J','P','G'):
852         memcpy( fcc, "mjpa", 4 );
853         break;
854
855     case VLC_FOURCC('S','V','Q','3'):
856         memcpy( fcc, "SVQ3", 4 );
857         break;
858
859     default:
860         memcpy( fcc, (char*)&p_stream->fmt.i_codec, 4 );
861         break;
862     }
863
864     vide = box_new( fcc );
865     for( i = 0; i < 6; i++ )
866     {
867         bo_add_8( vide, 0 );        // reserved;
868     }
869     bo_add_16be( vide, 1 );         // data-reference-index
870
871     bo_add_16be( vide, 0 );         // predefined;
872     bo_add_16be( vide, 0 );         // reserved;
873     for( i = 0; i < 3; i++ )
874     {
875         bo_add_32be( vide, 0 );     // predefined;
876     }
877
878     bo_add_16be( vide, p_stream->fmt.video.i_width );  // i_width
879     bo_add_16be( vide, p_stream->fmt.video.i_height ); // i_height
880
881     bo_add_32be( vide, 0x00480000 );                // h 72dpi
882     bo_add_32be( vide, 0x00480000 );                // v 72dpi
883
884     bo_add_32be( vide, 0 );         // data size, always 0
885     bo_add_16be( vide, 1 );         // frames count per sample
886
887     // compressor name;
888     for( i = 0; i < 32; i++ )
889     {
890         bo_add_8( vide, 0 );
891     }
892
893     bo_add_16be( vide, 0x18 );      // depth
894     bo_add_16be( vide, 0xffff );    // predefined
895
896     /* add an ES Descriptor */
897     switch( p_stream->fmt.i_codec )
898     {
899     case VLC_FOURCC('m','p','4','v'):
900     case VLC_FOURCC('m','p','g','v'):
901         {
902             bo_t *esds = GetESDS( p_stream );
903
904             box_fix( esds );
905             box_gather( vide, esds );
906         }
907         break;
908
909     case VLC_FOURCC('S','V','Q','3'):
910         {
911             bo_t *esds = GetSVQ3Tag( p_stream );
912
913             box_fix( esds );
914             box_gather( vide, esds );
915         }
916         break;
917
918     default:
919         break;
920     }
921
922     box_fix( vide );
923
924     return vide;
925 }
926
927 static bo_t *GetStblBox( sout_mux_t *p_mux, mp4_stream_t *p_stream )
928 {
929     sout_mux_sys_t *p_sys = p_mux->p_sys;
930     unsigned int i_chunk, i_stsc_last_val, i_stsc_entries, i, i_index;
931     bo_t *stbl, *stsd, *stts, *stco, *stsc, *stsz, *stss;
932     uint32_t i_timescale;
933     int64_t i_dts, i_dts_q;
934
935     stbl = box_new( "stbl" );
936
937     /* sample description */
938     stsd = box_full_new( "stsd", 0, 0 );
939     bo_add_32be( stsd, 1 );
940     if( p_stream->fmt.i_cat == AUDIO_ES )
941     {
942         bo_t *soun = GetSounBox( p_mux, p_stream );
943         box_gather( stsd, soun );
944     }
945     else if( p_stream->fmt.i_cat == VIDEO_ES )
946     {
947         bo_t *vide = GetVideBox( p_mux, p_stream );
948         box_gather( stsd, vide );
949     }
950     box_fix( stsd );
951
952     /* chunk offset table */
953     if( p_sys->i_pos >= (((uint64_t)0x1) << 32) )
954     {
955         /* 64 bits version */
956         p_stream->b_stco64 = VLC_TRUE;
957         stco = box_full_new( "co64", 0, 0 );
958     }
959     else
960     {
961         /* 32 bits version */
962         p_stream->b_stco64 = VLC_FALSE;
963         stco = box_full_new( "stco", 0, 0 );
964     }
965     bo_add_32be( stco, 0 );     // entry-count (fixed latter)
966
967     /* sample to chunk table */
968     stsc = box_full_new( "stsc", 0, 0 );
969     bo_add_32be( stsc, 0 );     // entry-count (fixed latter)
970
971     for( i_chunk = 0, i_stsc_last_val = 0, i_stsc_entries = 0, i = 0;
972          i < p_stream->i_entry_count; i_chunk++ )
973     {
974         int i_first = i;
975
976         if( p_stream->b_stco64 )
977             bo_add_64be( stco, p_stream->entry[i].i_pos );
978         else
979             bo_add_32be( stco, p_stream->entry[i].i_pos );
980
981         while( i < p_stream->i_entry_count )
982         {
983             if( i + 1 < p_stream->i_entry_count &&
984                 p_stream->entry[i].i_pos + p_stream->entry[i].i_size
985                 != p_stream->entry[i + 1].i_pos )
986             {
987                 i++;
988                 break;
989             }
990
991             i++;
992         }
993
994         /* Add entry to the stsc table */
995         if( i_stsc_last_val != i - i_first )
996         {
997             bo_add_32be( stsc, 1 + i_chunk );   // first-chunk
998             bo_add_32be( stsc, i - i_first ) ;  // samples-per-chunk
999             bo_add_32be( stsc, 1 );             // sample-descr-index
1000             i_stsc_last_val = i - i_first;
1001             i_stsc_entries++;
1002         }
1003     }
1004
1005     /* Fix stco entry count */
1006     bo_fix_32be( stco, 12, i_chunk );
1007     msg_Dbg( p_mux, "created %d chunks (stco)", i_chunk );
1008     box_fix( stco );
1009
1010     /* Fix stsc entry count */
1011     bo_fix_32be( stsc, 12, i_stsc_entries  );
1012     box_fix( stsc );
1013
1014     /* add stts */
1015     stts = box_full_new( "stts", 0, 0 );
1016     bo_add_32be( stts, 0 );     // entry-count (fixed latter)
1017
1018     if( p_stream->fmt.i_cat == AUDIO_ES )
1019         i_timescale = p_stream->fmt.audio.i_rate;
1020     else
1021         i_timescale = 1001;
1022
1023     /* first, create quantified length */
1024     for( i = 0, i_dts = 0, i_dts_q = 0; i < p_stream->i_entry_count; i++ )
1025     {
1026         int64_t i_dts_deq = i_dts_q * I64C(1000000) / (int64_t)i_timescale;
1027         int64_t i_delta = p_stream->entry[i].i_length + i_dts - i_dts_deq;
1028
1029         i_dts += p_stream->entry[i].i_length;
1030
1031         p_stream->entry[i].i_length = i_delta * (int64_t)i_timescale / I64C(1000000);;
1032
1033         i_dts_q += p_stream->entry[i].i_length;
1034     }
1035     /* then write encoded table */
1036     for( i = 0, i_index = 0; i < p_stream->i_entry_count; i_index++)
1037     {
1038         int     i_first = i;
1039         int64_t i_delta = p_stream->entry[i].i_length;
1040
1041         while( i < p_stream->i_entry_count )
1042         {
1043             i++;
1044             if( i >= p_stream->i_entry_count ||
1045                 p_stream->entry[i].i_length != i_delta )
1046             {
1047                 break;
1048             }
1049         }
1050
1051         bo_add_32be( stts, i - i_first ); // sample-count
1052         bo_add_32be( stts, i_delta );     // sample-delta
1053     }
1054     bo_fix_32be( stts, 12, i_index );
1055     box_fix( stts );
1056
1057     /* FIXME add ctts ?? FIXME */
1058
1059     stsz = box_full_new( "stsz", 0, 0 );
1060     bo_add_32be( stsz, 0 );                             // sample-size
1061     bo_add_32be( stsz, p_stream->i_entry_count );       // sample-count
1062     for( i = 0; i < p_stream->i_entry_count; i++ )
1063     {
1064         bo_add_32be( stsz, p_stream->entry[i].i_size ); // sample-size
1065     }
1066     box_fix( stsz );
1067
1068     /* create stss table */
1069     stss = NULL;
1070     for( i = 0, i_index = 0; i < p_stream->i_entry_count; i++ )
1071     {
1072         if( p_stream->entry[i].i_flags & (BLOCK_FLAG_TYPE_I<<SOUT_BUFFER_FLAGS_BLOCK_SHIFT) )
1073         {
1074             if( stss == NULL )
1075             {
1076                 stss = box_full_new( "stss", 0, 0 );
1077                 bo_add_32be( stss, 0 ); /* fixed later */
1078             }
1079             bo_add_32be( stss, 1 + i );
1080             i_index++;
1081         }
1082     }
1083     if( stss )
1084     {
1085         bo_fix_32be( stss, 12, i_index );
1086         box_fix( stss );
1087     }
1088
1089     /* Now gather all boxes into stbl */
1090     box_gather( stbl, stsd );
1091     box_gather( stbl, stts );
1092     if( stss )
1093     {
1094         box_gather( stbl, stss );
1095     }
1096     box_gather( stbl, stsc );
1097     box_gather( stbl, stsz );
1098     p_stream->i_stco_pos = stbl->i_buffer + 16;
1099     box_gather( stbl, stco );
1100
1101     /* finish stbl */
1102     box_fix( stbl );
1103
1104     return stbl;
1105 }
1106
1107 static int64_t get_timestamp();
1108
1109 static uint32_t mvhd_matrix[9] =
1110     { 0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000 };
1111
1112 static bo_t *GetMoovBox( sout_mux_t *p_mux )
1113 {
1114     sout_mux_sys_t *p_sys = p_mux->p_sys;
1115
1116     bo_t            *moov, *mvhd;
1117     int             i_trak, i;
1118
1119     uint32_t        i_movie_timescale = 90000;
1120     int64_t         i_movie_duration  = 0;
1121
1122     moov = box_new( "moov" );
1123
1124     /* Create general info */
1125     for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
1126     {
1127         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
1128         i_movie_duration = __MAX( i_movie_duration, p_stream->i_duration );
1129     }
1130     msg_Dbg( p_mux, "movie duration %ds",
1131              (uint32_t)( i_movie_duration / (mtime_t)1000000 ) );
1132
1133     i_movie_duration = i_movie_duration * i_movie_timescale / 1000000;
1134
1135     /* *** add /moov/mvhd *** */
1136     if( !p_sys->b_64_ext )
1137     {
1138         mvhd = box_full_new( "mvhd", 0, 0 );
1139         bo_add_32be( mvhd, get_timestamp() );   // creation time
1140         bo_add_32be( mvhd, get_timestamp() );   // modification time
1141         bo_add_32be( mvhd, i_movie_timescale);  // timescale
1142         bo_add_32be( mvhd, i_movie_duration );  // duration
1143     }
1144     else
1145     {
1146         mvhd = box_full_new( "mvhd", 1, 0 );
1147         bo_add_64be( mvhd, get_timestamp() );   // creation time
1148         bo_add_64be( mvhd, get_timestamp() );   // modification time
1149         bo_add_32be( mvhd, i_movie_timescale);  // timescale
1150         bo_add_64be( mvhd, i_movie_duration );  // duration
1151     }
1152     bo_add_32be( mvhd, 0x10000 );           // rate
1153     bo_add_16be( mvhd, 0x100 );             // volume
1154     bo_add_16be( mvhd, 0 );                 // reserved
1155     for( i = 0; i < 2; i++ )
1156     {
1157         bo_add_32be( mvhd, 0 );             // reserved
1158     }
1159     for( i = 0; i < 9; i++ )
1160     {
1161         bo_add_32be( mvhd, mvhd_matrix[i] );// matrix
1162     }
1163     for( i = 0; i < 6; i++ )
1164     {
1165         bo_add_32be( mvhd, 0 );             // pre-defined
1166     }
1167
1168     /* Next available track id */
1169     bo_add_32be( mvhd, p_sys->i_nb_streams + 1 ); // next-track-id
1170
1171     box_fix( mvhd );
1172     box_gather( moov, mvhd );
1173
1174     for( i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++ )
1175     {
1176         mp4_stream_t *p_stream;
1177         uint32_t     i_timescale;
1178
1179         bo_t *trak, *tkhd, *edts, *elst, *mdia, *mdhd, *hdlr;
1180         bo_t *minf, *dinf, *dref, *url, *stbl;
1181
1182         p_stream = p_sys->pp_streams[i_trak];
1183
1184         if( p_stream->fmt.i_cat != AUDIO_ES &&
1185             p_stream->fmt.i_cat != VIDEO_ES )
1186         {
1187             msg_Err( p_mux, "FIXME ignoring trak (noaudio&&novideo)" );
1188             continue;
1189         }
1190
1191         if( p_stream->fmt.i_cat == AUDIO_ES )
1192             i_timescale = p_stream->fmt.audio.i_rate;
1193         else
1194             i_timescale = 1001;
1195
1196         /* *** add /moov/trak *** */
1197         trak = box_new( "trak" );
1198
1199         /* *** add /moov/trak/tkhd *** */
1200         if( !p_sys->b_64_ext )
1201         {
1202             if( p_sys->b_mov )
1203                 tkhd = box_full_new( "tkhd", 0, 0x0f );
1204             else
1205                 tkhd = box_full_new( "tkhd", 0, 1 );
1206
1207             bo_add_32be( tkhd, get_timestamp() );       // creation time
1208             bo_add_32be( tkhd, get_timestamp() );       // modification time
1209             bo_add_32be( tkhd, p_stream->i_track_id );
1210             bo_add_32be( tkhd, 0 );                     // reserved 0
1211             bo_add_32be( tkhd, p_stream->i_duration *
1212                          (int64_t)i_movie_timescale /
1213                          (mtime_t)1000000 );            // duration
1214         }
1215         else
1216         {
1217             if( p_sys->b_mov )
1218                 tkhd = box_full_new( "tkhd", 1, 0x0f );
1219             else
1220                 tkhd = box_full_new( "tkhd", 1, 1 );
1221
1222             bo_add_64be( tkhd, get_timestamp() );       // creation time
1223             bo_add_64be( tkhd, get_timestamp() );       // modification time
1224             bo_add_32be( tkhd, p_stream->i_track_id );
1225             bo_add_32be( tkhd, 0 );                     // reserved 0
1226             bo_add_64be( tkhd, p_stream->i_duration *
1227                          (int64_t)i_movie_timescale /
1228                          (mtime_t)1000000 );            // duration
1229         }
1230
1231         for( i = 0; i < 2; i++ )
1232         {
1233             bo_add_32be( tkhd, 0 );                 // reserved
1234         }
1235         bo_add_16be( tkhd, 0 );                     // layer
1236         bo_add_16be( tkhd, 0 );                     // pre-defined
1237         // volume
1238         bo_add_16be( tkhd, p_stream->fmt.i_cat == AUDIO_ES ? 0x100 : 0 );
1239         bo_add_16be( tkhd, 0 );                     // reserved
1240         for( i = 0; i < 9; i++ )
1241         {
1242             bo_add_32be( tkhd, mvhd_matrix[i] );    // matrix
1243         }
1244         if( p_stream->fmt.i_cat == AUDIO_ES )
1245         {
1246             bo_add_32be( tkhd, 0 );                 // width (presentation)
1247             bo_add_32be( tkhd, 0 );                 // height(presentation)
1248         }
1249         else
1250         {
1251             // width (presentation)
1252             bo_add_32be( tkhd, p_stream->fmt.video.i_aspect *
1253                          p_stream->fmt.video.i_height /
1254                          VOUT_ASPECT_FACTOR << 16 );
1255             // height(presentation)
1256             bo_add_32be( tkhd, p_stream->fmt.video.i_height << 16 );
1257         }
1258         box_fix( tkhd );
1259         box_gather( trak, tkhd );
1260
1261         /* *** add /moov/trak/edts and elst */
1262         edts = box_new( "edts" );
1263         elst = box_full_new( "elst", p_sys->b_64_ext ? 1 : 0, 0 );
1264         if( p_stream->i_dts_start > p_sys->i_dts_start )
1265         {
1266             bo_add_32be( elst, 2 );
1267
1268             if( p_sys->b_64_ext )
1269             {
1270                 bo_add_64be( elst, (p_stream->i_dts_start-p_sys->i_dts_start) * i_movie_timescale / I64C(1000000) );
1271                 bo_add_64be( elst, -1 );
1272             }
1273             else
1274             {
1275                 bo_add_32be( elst, (p_stream->i_dts_start-p_sys->i_dts_start) * i_movie_timescale / I64C(1000000) );
1276                 bo_add_32be( elst, -1 );
1277             }
1278             bo_add_16be( elst, 1 );
1279             bo_add_16be( elst, 0 );
1280         }
1281         else
1282         {
1283             bo_add_32be( elst, 1 );
1284         }
1285         if( p_sys->b_64_ext )
1286         {
1287             bo_add_64be( elst, p_stream->i_duration * i_movie_timescale / I64C(1000000) );
1288             bo_add_64be( elst, 0 );
1289         }
1290         else
1291         {
1292             bo_add_32be( elst, p_stream->i_duration * i_movie_timescale / I64C(1000000) );
1293             bo_add_32be( elst, 0 );
1294         }
1295         bo_add_16be( elst, 1 );
1296         bo_add_16be( elst, 0 );
1297
1298         box_fix( elst );
1299         box_gather( edts, elst );
1300         box_fix( edts );
1301         box_gather( trak, edts );
1302
1303         /* *** add /moov/trak/mdia *** */
1304         mdia = box_new( "mdia" );
1305
1306         /* media header */
1307         if( !p_sys->b_64_ext )
1308         {
1309             mdhd = box_full_new( "mdhd", 0, 0 );
1310             bo_add_32be( mdhd, get_timestamp() );   // creation time
1311             bo_add_32be( mdhd, get_timestamp() );   // modification time
1312             bo_add_32be( mdhd, i_timescale);        // timescale
1313             bo_add_32be( mdhd, p_stream->i_duration * (int64_t)i_timescale /
1314                                (mtime_t)1000000 );  // duration
1315         }
1316         else
1317         {
1318             mdhd = box_full_new( "mdhd", 1, 0 );
1319             bo_add_64be( mdhd, get_timestamp() );   // creation time
1320             bo_add_64be( mdhd, get_timestamp() );   // modification time
1321             bo_add_32be( mdhd, i_timescale);        // timescale
1322             bo_add_64be( mdhd, p_stream->i_duration * (int64_t)i_timescale /
1323                                (mtime_t)1000000 );  // duration
1324         }
1325
1326         if( p_stream->fmt.psz_language )
1327         {
1328             char *psz = p_stream->fmt.psz_language;
1329             const iso639_lang_t *pl = NULL;
1330             uint16_t lang = 0x0;
1331
1332             if( strlen( psz ) == 2 )
1333             {
1334                 pl = GetLang_1( psz );
1335             }
1336             else if( strlen( psz ) == 3 )
1337             {
1338                 pl = GetLang_2B( psz );
1339                 if( !strcmp( pl->psz_iso639_1, "??" ) )
1340                 {
1341                     pl = GetLang_2T( psz );
1342                 }
1343             }
1344             if( pl && strcmp( pl->psz_iso639_1, "??" ) )
1345             {
1346                 lang = ( ( pl->psz_iso639_2T[0] - 0x60 ) << 10 ) |
1347                        ( ( pl->psz_iso639_2T[1] - 0x60 ) <<  5 ) |
1348                        ( ( pl->psz_iso639_2T[2] - 0x60 ) );
1349             }
1350             bo_add_16be( mdhd, lang );          // language
1351         }
1352         else
1353         {
1354             bo_add_16be( mdhd, 0    );          // language
1355         }
1356         bo_add_16be( mdhd, 0    );              // predefined
1357         box_fix( mdhd );
1358         box_gather( mdia, mdhd );
1359
1360         /* handler reference */
1361         hdlr = box_full_new( "hdlr", 0, 0 );
1362
1363         bo_add_fourcc( hdlr, "mhlr" );         // media handler
1364         if( p_stream->fmt.i_cat == AUDIO_ES )
1365         {
1366             bo_add_fourcc( hdlr, "soun" );
1367         }
1368         else
1369         {
1370             bo_add_fourcc( hdlr, "vide" );
1371         }
1372
1373         bo_add_32be( hdlr, 0 );         // reserved
1374         bo_add_32be( hdlr, 0 );         // reserved
1375         bo_add_32be( hdlr, 0 );         // reserved
1376
1377         bo_add_8( hdlr, 12 );
1378         if( p_stream->fmt.i_cat == AUDIO_ES )
1379             bo_add_mem( hdlr, 12, "SoundHandler" );
1380         else
1381             bo_add_mem( hdlr, 12, "VideoHandler" );
1382
1383         box_fix( hdlr );
1384         box_gather( mdia, hdlr );
1385
1386         /* minf*/
1387         minf = box_new( "minf" );
1388
1389         /* add smhd|vmhd */
1390         if( p_stream->fmt.i_cat == AUDIO_ES )
1391         {
1392             bo_t *smhd;
1393
1394             smhd = box_full_new( "smhd", 0, 0 );
1395             bo_add_16be( smhd, 0 );     // balance
1396             bo_add_16be( smhd, 0 );     // reserved
1397             box_fix( smhd );
1398
1399             box_gather( minf, smhd );
1400         }
1401         else if( p_stream->fmt.i_cat == VIDEO_ES )
1402         {
1403             bo_t *vmhd;
1404
1405             vmhd = box_full_new( "vmhd", 0, 1 );
1406             bo_add_16be( vmhd, 0 );     // graphicsmode
1407             for( i = 0; i < 3; i++ )
1408             {
1409                 bo_add_16be( vmhd, 0 ); // opcolor
1410             }
1411             box_fix( vmhd );
1412
1413             box_gather( minf, vmhd );
1414         }
1415
1416         /* dinf */
1417         dinf = box_new( "dinf" );
1418         dref = box_full_new( "dref", 0, 0 );
1419         bo_add_32be( dref, 1 );
1420         url = box_full_new( "url ", 0, 0x01 );
1421         box_fix( url );
1422         box_gather( dref, url );
1423         box_fix( dref );
1424         box_gather( dinf, dref );
1425
1426         /* append dinf to mdia */
1427         box_fix( dinf );
1428         box_gather( minf, dinf );
1429
1430         /* add stbl */
1431         stbl = GetStblBox( p_mux, p_stream );
1432
1433         /* append stbl to minf */
1434         p_stream->i_stco_pos += minf->i_buffer;
1435         box_gather( minf, stbl );
1436
1437         /* append minf to mdia */
1438         box_fix( minf );
1439         p_stream->i_stco_pos += mdia->i_buffer;
1440         box_gather( mdia, minf );
1441
1442         /* append mdia to trak */
1443         box_fix( mdia );
1444         p_stream->i_stco_pos += trak->i_buffer;
1445         box_gather( trak, mdia );
1446
1447         /* append trak to moov */
1448         box_fix( trak );
1449         p_stream->i_stco_pos += moov->i_buffer;
1450         box_gather( moov, trak );
1451     }
1452
1453     /* Add user data tags */
1454     box_gather( moov, GetUdtaTag( p_mux ) );
1455
1456     box_fix( moov );
1457     return moov;
1458 }
1459
1460
1461
1462 /****************************************************************************/
1463
1464 static void bo_init( bo_t *p_bo, int i_size, uint8_t *p_buffer,
1465                      vlc_bool_t b_grow )
1466 {
1467     if( !p_buffer )
1468     {
1469         p_bo->i_buffer_size = __MAX( i_size, 1024 );
1470         p_bo->p_buffer = malloc( p_bo->i_buffer_size );
1471     }
1472     else
1473     {
1474         p_bo->i_buffer_size = i_size;
1475         p_bo->p_buffer = p_buffer;
1476     }
1477
1478     p_bo->b_grow = b_grow;
1479     p_bo->i_buffer = 0;
1480 }
1481
1482 static void bo_add_8( bo_t *p_bo, uint8_t i )
1483 {
1484     if( p_bo->i_buffer < p_bo->i_buffer_size )
1485     {
1486         p_bo->p_buffer[p_bo->i_buffer] = i;
1487     }
1488     else if( p_bo->b_grow )
1489     {
1490         p_bo->i_buffer_size += 1024;
1491         p_bo->p_buffer = realloc( p_bo->p_buffer, p_bo->i_buffer_size );
1492
1493         p_bo->p_buffer[p_bo->i_buffer] = i;
1494     }
1495
1496     p_bo->i_buffer++;
1497 }
1498
1499 static void bo_add_16be( bo_t *p_bo, uint16_t i )
1500 {
1501     bo_add_8( p_bo, ( ( i >> 8) &0xff ) );
1502     bo_add_8( p_bo, i &0xff );
1503 }
1504
1505 static void bo_add_24be( bo_t *p_bo, uint32_t i )
1506 {
1507     bo_add_8( p_bo, ( ( i >> 16) &0xff ) );
1508     bo_add_8( p_bo, ( ( i >> 8) &0xff ) );
1509     bo_add_8( p_bo, (   i &0xff ) );
1510 }
1511 static void bo_add_32be( bo_t *p_bo, uint32_t i )
1512 {
1513     bo_add_16be( p_bo, ( ( i >> 16) &0xffff ) );
1514     bo_add_16be( p_bo, i &0xffff );
1515 }
1516
1517 static void bo_fix_32be ( bo_t *p_bo, int i_pos, uint32_t i)
1518 {
1519     p_bo->p_buffer[i_pos    ] = ( i >> 24 )&0xff;
1520     p_bo->p_buffer[i_pos + 1] = ( i >> 16 )&0xff;
1521     p_bo->p_buffer[i_pos + 2] = ( i >>  8 )&0xff;
1522     p_bo->p_buffer[i_pos + 3] = ( i       )&0xff;
1523 }
1524
1525 static void bo_add_64be( bo_t *p_bo, uint64_t i )
1526 {
1527     bo_add_32be( p_bo, ( ( i >> 32) &0xffffffff ) );
1528     bo_add_32be( p_bo, i &0xffffffff );
1529 }
1530
1531 static void bo_add_fourcc( bo_t *p_bo, char *fcc )
1532 {
1533     bo_add_8( p_bo, fcc[0] );
1534     bo_add_8( p_bo, fcc[1] );
1535     bo_add_8( p_bo, fcc[2] );
1536     bo_add_8( p_bo, fcc[3] );
1537 }
1538
1539 static void bo_add_mem( bo_t *p_bo, int i_size, uint8_t *p_mem )
1540 {
1541     int i;
1542
1543     for( i = 0; i < i_size; i++ )
1544     {
1545         bo_add_8( p_bo, p_mem[i] );
1546     }
1547 }
1548
1549 static void bo_add_descr( bo_t *p_bo, uint8_t tag, uint32_t i_size )
1550 {
1551     uint32_t i_length;
1552     uint8_t  vals[4];
1553
1554     i_length = i_size;
1555     vals[3] = (unsigned char)(i_length & 0x7f);
1556     i_length >>= 7;
1557     vals[2] = (unsigned char)((i_length & 0x7f) | 0x80); 
1558     i_length >>= 7;
1559     vals[1] = (unsigned char)((i_length & 0x7f) | 0x80); 
1560     i_length >>= 7;
1561     vals[0] = (unsigned char)((i_length & 0x7f) | 0x80);
1562
1563     bo_add_8( p_bo, tag );
1564
1565     if( i_size < 0x00000080 )
1566     {
1567         bo_add_8( p_bo, vals[3] );
1568     }
1569     else if( i_size < 0x00004000 )
1570     {
1571         bo_add_8( p_bo, vals[2] );
1572         bo_add_8( p_bo, vals[3] );
1573     }
1574     else if( i_size < 0x00200000 )
1575     {
1576         bo_add_8( p_bo, vals[1] );
1577         bo_add_8( p_bo, vals[2] );
1578         bo_add_8( p_bo, vals[3] );
1579     }
1580     else if( i_size < 0x10000000 )
1581     {
1582         bo_add_8( p_bo, vals[0] );
1583         bo_add_8( p_bo, vals[1] );
1584         bo_add_8( p_bo, vals[2] );
1585         bo_add_8( p_bo, vals[3] );
1586     }
1587 }
1588
1589 static void bo_add_bo( bo_t *p_bo, bo_t *p_bo2 )
1590 {
1591     int i;
1592
1593     for( i = 0; i < p_bo2->i_buffer; i++ )
1594     {
1595         bo_add_8( p_bo, p_bo2->p_buffer[i] );
1596     }
1597 }
1598
1599 static bo_t * box_new( char *fcc )
1600 {
1601     bo_t *box;
1602
1603     if( ( box = malloc( sizeof( bo_t ) ) ) )
1604     {
1605         bo_init( box, 0, NULL, VLC_TRUE );
1606
1607         bo_add_32be  ( box, 0 );
1608         bo_add_fourcc( box, fcc );
1609     }
1610
1611     return box;
1612 }
1613
1614 static bo_t * box_full_new( char *fcc, uint8_t v, uint32_t f )
1615 {
1616     bo_t *box;
1617
1618     if( ( box = malloc( sizeof( bo_t ) ) ) )
1619     {
1620         bo_init( box, 0, NULL, VLC_TRUE );
1621
1622         bo_add_32be  ( box, 0 );
1623         bo_add_fourcc( box, fcc );
1624         bo_add_8     ( box, v );
1625         bo_add_24be  ( box, f );
1626     }
1627
1628     return box;
1629 }
1630
1631 static void box_fix( bo_t *box )
1632 {
1633     bo_t box_tmp;
1634
1635     memcpy( &box_tmp, box, sizeof( bo_t ) );
1636
1637     box_tmp.i_buffer = 0;
1638     bo_add_32be( &box_tmp, box->i_buffer );
1639 }
1640
1641 static void box_free( bo_t *box )
1642 {
1643     if( box->p_buffer )
1644     {
1645         free( box->p_buffer );
1646     }
1647
1648     free( box );
1649 }
1650
1651 static void box_gather ( bo_t *box, bo_t *box2 )
1652 {
1653     bo_add_bo( box, box2 );
1654     box_free( box2 );
1655 }
1656
1657 static sout_buffer_t * bo_to_sout( sout_instance_t *p_sout,  bo_t *box )
1658 {
1659     sout_buffer_t *p_buf;
1660
1661     p_buf = sout_BufferNew( p_sout, box->i_buffer );
1662     if( box->i_buffer > 0 )
1663     {
1664         memcpy( p_buf->p_buffer, box->p_buffer, box->i_buffer );
1665     }
1666
1667     p_buf->i_size = box->i_buffer;
1668
1669     return p_buf;
1670 }
1671
1672 static void box_send( sout_mux_t *p_mux,  bo_t *box )
1673 {
1674     sout_buffer_t *p_buf;
1675
1676     p_buf = bo_to_sout( p_mux->p_sout, box );
1677     box_free( box );
1678
1679     sout_AccessOutWrite( p_mux->p_access, p_buf );
1680 }
1681
1682 static int64_t get_timestamp()
1683 {
1684     int64_t i_timestamp = 0;
1685
1686 #ifdef HAVE_TIME_H
1687     i_timestamp = time(NULL);
1688     i_timestamp += 2082844800; // MOV/MP4 start date is 1/1/1904
1689     // 208284480 is (((1970 - 1904) * 365) + 17) * 24 * 60 * 60
1690 #endif
1691
1692     return i_timestamp;
1693 }