]> git.sesse.net Git - vlc/blob - modules/mux/asf.c
* modules/mux/asf.c: flush our buffers on close.
[vlc] / modules / mux / asf.c
1 /*****************************************************************************
2  * asf.c: asf muxer module for vlc
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>
28
29 #include <vlc/vlc.h>
30 #include <vlc/input.h>
31 #include <vlc/sout.h>
32
33 #include "codecs.h"
34 typedef GUID guid_t;
35
36 /*****************************************************************************
37  * Module descriptor
38  *****************************************************************************/
39 static int  Open   ( vlc_object_t * );
40 static void Close  ( vlc_object_t * );
41
42 #define SOUT_CFG_PREFIX "sout-asf-"
43
44 #define TITLE_TEXT N_("Title")
45 #define TITLE_LONGTEXT N_("Allows you to define the title that will be put " \
46                           "in ASF comments.")
47 #define AUTHOR_TEXT N_("Author")
48 #define AUTHOR_LONGTEXT N_("Allows you to define the author that will be put "\
49                            "in ASF comments.")
50 #define COPYRIGHT_TEXT N_("Copyright")
51 #define COPYRIGHT_LONGTEXT N_("Allows you to define the copyright string " \
52                               "that will be put in ASF comments.")
53 #define COMMENT_TEXT N_("Comment")
54 #define COMMENT_LONGTEXT N_("Allows you to define the comment that will be " \
55                             "put in ASF comments.")
56 #define RATING_TEXT N_("Rating")
57 #define RATING_LONGTEXT N_("Allows you to define the \"rating\" that will " \
58                            "be put in ASF comments.")
59
60 vlc_module_begin();
61     set_description( _("ASF muxer") );
62     set_capability( "sout mux", 5 );
63     add_shortcut( "asf" );
64     add_shortcut( "asfh" );
65     set_callbacks( Open, Close );
66
67     add_string( SOUT_CFG_PREFIX "title", "", NULL, TITLE_TEXT, TITLE_LONGTEXT,
68                                  VLC_TRUE );
69     add_string( SOUT_CFG_PREFIX "author",   "", NULL, AUTHOR_TEXT,
70                                  AUTHOR_LONGTEXT, VLC_TRUE );
71     add_string( SOUT_CFG_PREFIX "copyright","", NULL, COPYRIGHT_TEXT,
72                                  COPYRIGHT_LONGTEXT, VLC_TRUE );
73     add_string( SOUT_CFG_PREFIX "comment",  "", NULL, COMMENT_TEXT,
74                                  COMMENT_LONGTEXT, VLC_TRUE );
75     add_string( SOUT_CFG_PREFIX "rating",  "", NULL, RATING_TEXT,
76                                  RATING_LONGTEXT, VLC_TRUE );
77 vlc_module_end();
78
79 /*****************************************************************************
80  * Locales prototypes
81  *****************************************************************************/
82 static const char *ppsz_sout_options[] = {
83     "title", "author", "copyright", "comment", "rating", NULL
84 };
85
86 static int Control  ( sout_mux_t *, int, va_list );
87 static int AddStream( sout_mux_t *, sout_input_t * );
88 static int DelStream( sout_mux_t *, sout_input_t * );
89 static int Mux      ( sout_mux_t * );
90
91 typedef struct
92 {
93     int          i_id;
94     int          i_cat;
95
96     /* codec information */
97     uint16_t     i_tag;     /* for audio */
98     vlc_fourcc_t i_fourcc;  /* for video */
99     char         *psz_name; /* codec name */
100
101     int          i_sequence;
102
103     int          i_extra;
104     uint8_t     *p_extra;
105
106 } asf_track_t;
107
108 struct sout_mux_sys_t
109 {
110     guid_t          fid;    /* file id */
111     int             i_packet_size;
112     int64_t         i_packet_count;
113     mtime_t         i_dts_first;
114     mtime_t         i_dts_last;
115     mtime_t         i_preroll_time;
116     int64_t         i_bitrate;
117
118     int             i_track;
119     asf_track_t     track[128];
120
121     vlc_bool_t      b_write_header;
122
123     block_t         *pk;
124     int             i_pk_used;
125     int             i_pk_frame;
126     mtime_t         i_pk_dts;
127
128     vlc_bool_t      b_asf_http;
129     int             i_seq;
130
131     /* meta data */
132     char            *psz_title;
133     char            *psz_author;
134     char            *psz_copyright;
135     char            *psz_comment;
136     char            *psz_rating;
137 };
138
139 static int MuxGetStream( sout_mux_t *, int *pi_stream, mtime_t *pi_dts );
140
141 static block_t *asf_header_create( sout_mux_t *, vlc_bool_t );
142 static block_t *asf_packet_create( sout_mux_t *, asf_track_t *, block_t * );
143 static block_t *asf_stream_end_create( sout_mux_t *);
144 static block_t *asf_packet_flush( sout_mux_t * );
145
146 typedef struct
147 {
148     int      i_buffer_size;
149     int      i_buffer;
150     uint8_t  *p_buffer;
151
152 } bo_t;
153
154 static void bo_init     ( bo_t *, uint8_t *, int  );
155 static void bo_add_u8   ( bo_t *, uint8_t  );
156 static void bo_addle_u16( bo_t *, uint16_t );
157 static void bo_addle_u32( bo_t *, uint32_t );
158 static void bo_addle_u64( bo_t *, uint64_t );
159 static void bo_add_mem  ( bo_t *, uint8_t *, int );
160
161 static void bo_addle_str16( bo_t *, char * );
162
163 /*****************************************************************************
164  * Open:
165  *****************************************************************************/
166 static int Open( vlc_object_t *p_this )
167 {
168     sout_mux_t     *p_mux = (sout_mux_t*)p_this;
169     sout_mux_sys_t *p_sys;
170     vlc_value_t    val;
171     int i;
172
173     msg_Dbg( p_mux, "Asf muxer opened" );
174     sout_CfgParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
175
176     p_mux->pf_control   = Control;
177     p_mux->pf_addstream = AddStream;
178     p_mux->pf_delstream = DelStream;
179     p_mux->pf_mux       = Mux;
180
181     p_mux->p_sys = p_sys = malloc( sizeof( sout_mux_sys_t ) );
182     p_sys->b_asf_http = p_mux->psz_mux && !strcmp( p_mux->psz_mux, "asfh" );
183     if( p_sys->b_asf_http )
184     {
185         msg_Dbg( p_mux, "creating asf stream to be used with mmsh" );
186     }
187     p_sys->pk = NULL;
188     p_sys->i_pk_used    = 0;
189     p_sys->i_pk_frame   = 0;
190     p_sys->i_dts_first  = -1;
191     p_sys->i_dts_last   = 0;
192     p_sys->i_preroll_time = 2000;
193     p_sys->i_bitrate    = 0;
194     p_sys->i_seq        = 0;
195
196     p_sys->b_write_header = VLC_TRUE;
197     p_sys->i_track = 1;
198     p_sys->i_packet_size = 4096;
199     p_sys->i_packet_count= 0;
200
201     /* Generate a random fid */
202     srand( mdate() & 0xffffffff );
203     p_sys->fid.Data1 = 0xbabac001;
204     p_sys->fid.Data2 = ( (uint64_t)rand() << 16 ) / RAND_MAX;
205     p_sys->fid.Data3 = ( (uint64_t)rand() << 16 ) / RAND_MAX;
206     for( i = 0; i < 8; i++ )
207     {
208         p_sys->fid.Data4[i] = ( (uint64_t)rand() << 8 ) / RAND_MAX;
209     }
210
211     /* Meta data */
212     var_Get( p_mux, SOUT_CFG_PREFIX "title", &val );
213     p_sys->psz_title = val.psz_string;
214
215     var_Get( p_mux, SOUT_CFG_PREFIX "author", &val );
216     p_sys->psz_author = val.psz_string;
217
218     var_Get( p_mux, SOUT_CFG_PREFIX "copyright", &val );
219     p_sys->psz_copyright = val.psz_string;
220
221     var_Get( p_mux, SOUT_CFG_PREFIX "comment", &val );
222     p_sys->psz_comment = val.psz_string;
223
224     var_Get( p_mux, SOUT_CFG_PREFIX "rating", &val );
225     p_sys->psz_rating = val.psz_string;
226
227     msg_Dbg( p_mux, "meta data: title='%s' author='%s' copyright='%s' "
228              "comment='%s' rating='%s'",
229              p_sys->psz_title, p_sys->psz_author, p_sys->psz_copyright,
230              p_sys->psz_comment, p_sys->psz_rating );
231
232     return VLC_SUCCESS;
233 }
234
235 /*****************************************************************************
236  * Close:
237  *****************************************************************************/
238 static void Close( vlc_object_t * p_this )
239 {
240     sout_mux_t     *p_mux = (sout_mux_t*)p_this;
241     sout_mux_sys_t *p_sys = p_mux->p_sys;
242     block_t  *out;
243     int i;
244
245     msg_Dbg( p_mux, "Asf muxer closed" );
246
247     /* Flush last packet if any */
248     if( (out = asf_packet_flush( p_mux ) ) )
249     {
250         sout_AccessOutWrite( p_mux->p_access, out );
251     }
252
253     if( ( out = asf_stream_end_create( p_mux ) ) )
254     {
255         sout_AccessOutWrite( p_mux->p_access, out );
256     }
257
258     /* rewrite header */
259     if( !sout_AccessOutSeek( p_mux->p_access, 0 ) )
260     {
261         out = asf_header_create( p_mux, VLC_FALSE );
262         sout_AccessOutWrite( p_mux->p_access, out );
263     }
264
265     for( i = 1; i < p_sys->i_track; i++ )
266     {
267         free( p_sys->track[i].p_extra );
268     }
269     free( p_sys );
270 }
271
272 /*****************************************************************************
273  * Capability:
274  *****************************************************************************/
275 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
276 {
277     sout_mux_sys_t *p_sys = p_mux->p_sys;
278     vlc_bool_t *pb_bool;
279     char **ppsz;
280
281     switch( i_query )
282     {
283        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
284            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
285            if( p_sys->b_asf_http ) *pb_bool = VLC_TRUE;
286            else *pb_bool = VLC_FALSE;
287            return VLC_SUCCESS;
288
289        case MUX_GET_ADD_STREAM_WAIT:
290            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
291            *pb_bool = VLC_FALSE;
292            return VLC_SUCCESS;
293
294        case MUX_GET_MIME:
295            ppsz = (char**)va_arg( args, char ** );
296            if( p_sys->b_asf_http )
297                *ppsz = strdup( "video/x-ms-asf-stream" );
298            else
299                *ppsz = strdup( "video/x-ms-asf" );
300            return VLC_SUCCESS;
301
302         default:
303             return VLC_EGENERIC;
304     }
305 }
306
307 /*****************************************************************************
308  * AddStream:
309  *****************************************************************************/
310 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
311 {
312     sout_mux_sys_t   *p_sys = p_mux->p_sys;
313     asf_track_t      *tk;
314     bo_t             bo;
315
316     msg_Dbg( p_mux, "adding input" );
317     if( p_sys->i_track > 127 )
318     {
319         msg_Dbg( p_mux, "cannot add this track (too much track)" );
320         return VLC_EGENERIC;
321     }
322
323     tk = p_input->p_sys = &p_sys->track[p_sys->i_track];
324     tk->i_id  = p_sys->i_track;
325     tk->i_cat = p_input->p_fmt->i_cat;
326     tk->i_sequence = 0;
327
328     switch( tk->i_cat )
329     {
330         case AUDIO_ES:
331         {
332             int i_blockalign = p_input->p_fmt->audio.i_blockalign;
333             int i_bitspersample = 0;
334             int i_extra = 0;
335
336             switch( p_input->p_fmt->i_codec )
337             {
338                 case VLC_FOURCC( 'a', '5', '2', ' ' ):
339                     tk->i_tag = WAVE_FORMAT_A52;
340                     tk->psz_name = "A/52";
341                     break;
342                 case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
343 #if 1
344                     tk->psz_name = "MPEG Audio Layer 3";
345                     tk->i_tag = WAVE_FORMAT_MPEGLAYER3;
346                     i_blockalign = 1;
347                     i_extra = 12;
348                     break;
349 #else
350                     tk->psz_name = "MPEG Audio Layer 1/2";
351                     tk->i_tag = WAVE_FORMAT_MPEG;
352                     i_blockalign = 1;
353                     i_extra = 22;
354                     break;
355 #endif
356                 case VLC_FOURCC( 'w', 'm', 'a', '1' ):
357                     tk->psz_name = "Windows Media Audio 1";
358                     tk->i_tag = WAVE_FORMAT_WMA1;
359                     break;
360                 case VLC_FOURCC( 'w', 'm', 'a', '2' ):
361                     tk->psz_name = "Windows Media Audio 2";
362                     tk->i_tag = WAVE_FORMAT_WMA2;
363                     break;
364                 case VLC_FOURCC( 'w', 'm', 'a', '3' ):
365                     tk->psz_name = "Windows Media Audio 3";
366                     tk->i_tag = WAVE_FORMAT_WMA3;
367                     break;
368                     /* raw codec */
369                 case VLC_FOURCC( 'u', '8', ' ', ' ' ):
370                     tk->psz_name = "Raw audio 8bits";
371                     tk->i_tag = WAVE_FORMAT_PCM;
372                     i_blockalign= p_input->p_fmt->audio.i_channels;
373                     i_bitspersample = 8;
374                     break;
375                 case VLC_FOURCC( 's', '1', '6', 'l' ):
376                     tk->psz_name = "Raw audio 16bits";
377                     tk->i_tag = WAVE_FORMAT_PCM;
378                     i_blockalign= 2 * p_input->p_fmt->audio.i_channels;
379                     i_bitspersample = 16;
380                     break;
381                 case VLC_FOURCC( 's', '2', '4', 'l' ):
382                     tk->psz_name = "Raw audio 24bits";
383                     tk->i_tag = WAVE_FORMAT_PCM;
384                     i_blockalign= 3 * p_input->p_fmt->audio.i_channels;
385                     i_bitspersample = 24;
386                     break;
387                 case VLC_FOURCC( 's', '3', '2', 'l' ):
388                     tk->psz_name = "Raw audio 32bits";
389                     tk->i_tag = WAVE_FORMAT_PCM;
390                     i_blockalign= 4 * p_input->p_fmt->audio.i_channels;
391                     i_bitspersample = 32;
392                     break;
393                 default:
394                     return VLC_EGENERIC;
395             }
396
397             tk->i_extra = sizeof( WAVEFORMATEX ) +
398                           p_input->p_fmt->i_extra + i_extra;
399             tk->p_extra = malloc( tk->i_extra );
400             bo_init( &bo, tk->p_extra, tk->i_extra );
401             bo_addle_u16( &bo, tk->i_tag );
402             bo_addle_u16( &bo, p_input->p_fmt->audio.i_channels );
403             bo_addle_u32( &bo, p_input->p_fmt->audio.i_rate );
404             bo_addle_u32( &bo, p_input->p_fmt->i_bitrate / 8 );
405             bo_addle_u16( &bo, i_blockalign );
406             bo_addle_u16( &bo, i_bitspersample );
407             if( p_input->p_fmt->i_extra > 0 )
408             {
409                 bo_addle_u16( &bo, p_input->p_fmt->i_extra );
410                 bo_add_mem  ( &bo, p_input->p_fmt->p_extra,
411                               p_input->p_fmt->i_extra );
412             }
413             else
414             {
415                 bo_addle_u16( &bo, i_extra );
416                 if( tk->i_tag == WAVE_FORMAT_MPEGLAYER3 )
417                 {
418                     msg_Dbg( p_mux, "adding mp3 header" );
419                     bo_addle_u16( &bo, 1 );     /* wId */
420                     bo_addle_u32( &bo, 2 );     /* fdwFlags */
421                     bo_addle_u16( &bo, 1152 );  /* nBlockSize */
422                     bo_addle_u16( &bo, 1 );     /* nFramesPerBlock */
423                     bo_addle_u16( &bo, 1393 );  /* nCodecDelay */
424                 }
425                 else if( tk->i_tag == WAVE_FORMAT_MPEG )
426                 {
427                     msg_Dbg( p_mux, "adding mp2 header" );
428                     bo_addle_u16( &bo, 2 );     /* fwHeadLayer */
429                     bo_addle_u32( &bo, p_input->p_fmt->i_bitrate );
430                     bo_addle_u16( &bo, p_input->p_fmt->audio.i_channels == 2 ?1:8 );
431                     bo_addle_u16( &bo, 0 );     /* fwHeadModeExt */
432                     bo_addle_u16( &bo, 1 );     /* wHeadEmphasis */
433                     bo_addle_u16( &bo, 16 );    /* fwHeadFlags */
434                     bo_addle_u32( &bo, 0 );     /* dwPTSLow */
435                     bo_addle_u32( &bo, 0 );     /* dwPTSHigh */
436                 }
437             }
438
439             if( p_input->p_fmt->i_bitrate > 24000 )
440             {
441                 p_sys->i_bitrate += p_input->p_fmt->i_bitrate;
442             }
443             else
444             {
445                 p_sys->i_bitrate += 512000;
446             }
447             break;
448         }
449         case VIDEO_ES:
450         {
451             tk->i_extra = 11 + sizeof( BITMAPINFOHEADER ) +
452                           p_input->p_fmt->i_extra;
453             tk->p_extra = malloc( tk->i_extra );
454             bo_init( &bo, tk->p_extra, tk->i_extra );
455             bo_addle_u32( &bo, p_input->p_fmt->video.i_width );
456             bo_addle_u32( &bo, p_input->p_fmt->video.i_height );
457             bo_add_u8   ( &bo, 0x02 );  /* flags */
458             bo_addle_u16( &bo, sizeof( BITMAPINFOHEADER ) +
459                                p_input->p_fmt->i_extra );
460             bo_addle_u32( &bo, sizeof( BITMAPINFOHEADER ) +
461                                p_input->p_fmt->i_extra );
462             bo_addle_u32( &bo, p_input->p_fmt->video.i_width );
463             bo_addle_u32( &bo, p_input->p_fmt->video.i_height );
464             bo_addle_u16( &bo, 1 );
465             bo_addle_u16( &bo, 24 );
466             if( p_input->p_fmt->i_codec == VLC_FOURCC('m','p','4','v') )
467             {
468                 tk->psz_name = "MPEG-4 Video";
469                 tk->i_fourcc = VLC_FOURCC( 'M', 'P', '4', 'S' );
470             }
471             else if( p_input->p_fmt->i_codec == VLC_FOURCC('D','I','V','3') )
472             {
473                 tk->psz_name = "MSMPEG-4 V3 Video";
474                 tk->i_fourcc = VLC_FOURCC( 'M', 'P', '4', '3' );
475             }
476             else if( p_input->p_fmt->i_codec == VLC_FOURCC('D','I','V','2') )
477             {
478                 tk->psz_name = "MSMPEG-4 V2 Video";
479                 tk->i_fourcc = VLC_FOURCC( 'M', 'P', '4', '2' );
480             }
481             else if( p_input->p_fmt->i_codec == VLC_FOURCC('D','I','V','1') )
482             {
483                 tk->psz_name = "MSMPEG-4 V1 Video";
484                 tk->i_fourcc = VLC_FOURCC( 'M', 'P', 'G', '4' );
485             }
486             else if( p_input->p_fmt->i_codec == VLC_FOURCC('W','M','V','1') )
487             {
488                 tk->psz_name = "Windows Media Video 1";
489                 tk->i_fourcc = VLC_FOURCC( 'W', 'M', 'V', '1' );
490             }
491             else if( p_input->p_fmt->i_codec == VLC_FOURCC('W','M','V','2') )
492             {
493                 tk->psz_name = "Windows Media Video 2";
494                 tk->i_fourcc = VLC_FOURCC( 'W', 'M', 'V', '2' );
495             }
496             else if( p_input->p_fmt->i_codec == VLC_FOURCC('W','M','V','3') )
497             {
498                 tk->psz_name = "Windows Media Video 3";
499                 tk->i_fourcc = VLC_FOURCC( 'W', 'M', 'V', '3' );
500             }
501             else
502             {
503                 tk->psz_name = _("Unknown Video");
504                 tk->i_fourcc = p_input->p_fmt->i_codec;
505             }
506             bo_add_mem( &bo, (uint8_t*)&tk->i_fourcc, 4 );
507             bo_addle_u32( &bo, 0 );
508             bo_addle_u32( &bo, 0 );
509             bo_addle_u32( &bo, 0 );
510             bo_addle_u32( &bo, 0 );
511             bo_addle_u32( &bo, 0 );
512             if( p_input->p_fmt->i_extra > 0 )
513             {
514                 bo_add_mem  ( &bo, p_input->p_fmt->p_extra,
515                               p_input->p_fmt->i_extra );
516             }
517
518             if( p_input->p_fmt->i_bitrate > 50000 )
519             {
520                 p_sys->i_bitrate += p_input->p_fmt->i_bitrate;
521             }
522             else
523             {
524                 p_sys->i_bitrate += 1000000;
525             }
526             break;
527         }
528         default:
529             msg_Err(p_mux, "unhandled track type" );
530             return VLC_EGENERIC;
531     }
532
533     p_sys->i_track++;
534     return VLC_SUCCESS;
535 }
536
537 /*****************************************************************************
538  * DelStream:
539  *****************************************************************************/
540 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
541 {
542     msg_Dbg( p_mux, "removing input" );
543     return VLC_SUCCESS;
544 }
545
546 /*****************************************************************************
547  * Mux:
548  *****************************************************************************/
549 static int Mux( sout_mux_t *p_mux )
550 {
551     sout_mux_sys_t *p_sys = p_mux->p_sys;
552
553     if( p_sys->b_write_header )
554     {
555         block_t *out = asf_header_create( p_mux, VLC_TRUE );
556
557         out->i_flags |= BLOCK_FLAG_HEADER;
558         sout_AccessOutWrite( p_mux->p_access, out );
559
560         p_sys->b_write_header = VLC_FALSE;
561     }
562
563     for( ;; )
564     {
565         sout_input_t  *p_input;
566         asf_track_t   *tk;
567         int           i_stream;
568         mtime_t       i_dts;
569         block_t *data;
570         block_t *pk;
571
572         if( MuxGetStream( p_mux, &i_stream, &i_dts ) )
573         {
574             /* not enough data */
575             return VLC_SUCCESS;
576         }
577
578         if( p_sys->i_dts_first < 0 )
579         {
580             p_sys->i_dts_first = i_dts;
581         }
582         if( p_sys->i_dts_last < i_dts )
583         {
584             p_sys->i_dts_last = i_dts;
585         }
586
587         p_input = p_mux->pp_inputs[i_stream];
588         tk      = (asf_track_t*)p_input->p_sys;
589
590         data = block_FifoGet( p_input->p_fifo );
591
592         if( ( pk = asf_packet_create( p_mux, tk, data ) ) )
593         {
594             sout_AccessOutWrite( p_mux->p_access, pk );
595         }
596     }
597
598     return VLC_SUCCESS;
599 }
600
601 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
602 {
603     mtime_t i_dts;
604     int     i_stream;
605     int     i;
606
607     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
608     {
609         sout_input_t  *p_input = p_mux->pp_inputs[i];
610         block_t *p_data;
611
612         if( p_input->p_fifo->i_depth <= 0 )
613         {
614             if( p_input->p_fmt->i_cat == AUDIO_ES ||
615                 p_input->p_fmt->i_cat == VIDEO_ES )
616             {
617                 /* We need that audio+video fifo contain at least 1 packet */
618                 return VLC_EGENERIC;
619             }
620             /* SPU */
621             continue;
622         }
623
624         p_data = block_FifoShow( p_input->p_fifo );
625         if( i_stream == -1 || p_data->i_dts < i_dts )
626         {
627             i_stream = i;
628             i_dts    = p_data->i_dts;
629         }
630     }
631
632     *pi_stream = i_stream;
633     *pi_dts = i_dts;
634
635     return VLC_SUCCESS;
636 }
637
638 /****************************************************************************
639  * Asf header construction
640  ****************************************************************************/
641
642 /****************************************************************************
643  * Buffer out
644  ****************************************************************************/
645 static void bo_init( bo_t *p_bo, uint8_t *p_buffer, int i_size )
646 {
647     p_bo->i_buffer_size = i_size;
648     p_bo->i_buffer = 0;
649     p_bo->p_buffer = p_buffer;
650 }
651 static void bo_add_u8( bo_t *p_bo, uint8_t i )
652 {
653     if( p_bo->i_buffer < p_bo->i_buffer_size )
654     {
655         p_bo->p_buffer[p_bo->i_buffer] = i;
656     }
657     p_bo->i_buffer++;
658 }
659 static void bo_addle_u16( bo_t *p_bo, uint16_t i )
660 {
661     bo_add_u8( p_bo, i &0xff );
662     bo_add_u8( p_bo, ( ( i >> 8) &0xff ) );
663 }
664 static void bo_addle_u32( bo_t *p_bo, uint32_t i )
665 {
666     bo_addle_u16( p_bo, i &0xffff );
667     bo_addle_u16( p_bo, ( ( i >> 16) &0xffff ) );
668 }
669 static void bo_addle_u64( bo_t *p_bo, uint64_t i )
670 {
671     bo_addle_u32( p_bo, i &0xffffffff );
672     bo_addle_u32( p_bo, ( ( i >> 32) &0xffffffff ) );
673 }
674
675 static void bo_add_mem( bo_t *p_bo, uint8_t *p_mem, int i_size )
676 {
677     int i_copy = __MIN( i_size, p_bo->i_buffer_size - p_bo->i_buffer );
678
679     if( i_copy > 0 )
680     {
681         memcpy( &p_bo->p_buffer[p_bo->i_buffer], p_mem, i_copy );
682     }
683     p_bo->i_buffer += i_size;
684 }
685
686 static void bo_addle_str16( bo_t *bo, char *str )
687 {
688     bo_addle_u16( bo, strlen( str ) + 1 );
689     for( ;; )
690     {
691         uint16_t c = (uint8_t)*str++;
692         bo_addle_u16( bo, c );
693         if( c == '\0' ) break;
694     }
695 }
696
697 static void bo_addle_str16_nosize( bo_t *bo, char *str )
698 {
699     for( ;; )
700     {
701         uint16_t c = (uint8_t)*str++;
702         bo_addle_u16( bo, c );
703         if( c == '\0' ) break;
704     }
705 }
706
707 /****************************************************************************
708  * GUID definitions
709  ****************************************************************************/
710 static void bo_add_guid( bo_t *p_bo, const guid_t *id )
711 {
712     int i;
713     bo_addle_u32( p_bo, id->Data1 );
714     bo_addle_u16( p_bo, id->Data2 );
715     bo_addle_u16( p_bo, id->Data3 );
716     for( i = 0; i < 8; i++ )
717     {
718         bo_add_u8( p_bo, id->Data4[i] );
719     }
720 }
721
722 static const guid_t asf_object_header_guid =
723 {0x75B22630, 0x668E, 0x11CF, {0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C}};
724 static const guid_t asf_object_data_guid =
725 {0x75B22636, 0x668E, 0x11CF, {0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C}};
726 static const guid_t asf_object_file_properties_guid =
727 {0x8cabdca1, 0xa947, 0x11cf, {0x8e, 0xe4, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65}};
728 static const guid_t asf_object_stream_properties_guid =
729 {0xB7DC0791, 0xA9B7, 0x11CF, {0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65}};
730 static const guid_t asf_object_header_extention_guid =
731 {0x5FBF03B5, 0xA92E, 0x11CF, {0x8E, 0xE3, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65}};
732 static const guid_t asf_object_stream_type_audio =
733 {0xF8699E40, 0x5B4D, 0x11CF, {0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B}};
734 static const guid_t asf_object_stream_type_video =
735 {0xbc19efc0, 0x5B4D, 0x11CF, {0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B}};
736 static const guid_t asf_guid_audio_conceal_none =
737 {0x20FB5700, 0x5B55, 0x11CF, {0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B}};
738 static const guid_t asf_guid_video_conceal_none =
739 {0x20FB5700, 0x5B55, 0x11CF, {0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B}};
740 static const guid_t asf_guid_reserved_1 =
741 {0xABD3D211, 0xA9BA, 0x11cf, {0x8E, 0xE6, 0x00, 0xC0, 0x0C ,0x20, 0x53, 0x65}};
742 static const guid_t asf_object_codec_comment_guid =
743 {0x86D15240, 0x311D, 0x11D0, {0xA3, 0xA4, 0x00, 0xA0, 0xC9, 0x03, 0x48, 0xF6}};
744 static const guid_t asf_object_codec_comment_reserved_guid =
745 {0x86D15241, 0x311D, 0x11D0, {0xA3, 0xA4, 0x00, 0xA0, 0xC9, 0x03, 0x48, 0xF6}};
746 static const guid_t asf_object_content_description_guid =
747 {0x75B22633, 0x668E, 0x11CF, {0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c}};
748 static const guid_t asf_object_index_guid =
749 {0x33000890, 0xE5B1, 0x11CF, {0x89, 0xF4, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xCB}};
750
751 /****************************************************************************
752  * Misc
753  ****************************************************************************/
754 static void asf_chunk_add( bo_t *bo,
755                            int i_type, int i_len, int i_flags, int i_seq )
756 {
757     bo_addle_u16( bo, i_type );
758     bo_addle_u16( bo, i_len + 8 );
759     bo_addle_u32( bo, i_seq );
760     bo_addle_u16( bo, i_flags );
761     bo_addle_u16( bo, i_len + 8 );
762 }
763
764 static block_t *asf_header_create( sout_mux_t *p_mux, vlc_bool_t b_broadcast )
765 {
766     sout_mux_sys_t *p_sys = p_mux->p_sys;
767     asf_track_t    *tk;
768
769     mtime_t i_duration = 0;
770     int i_size;
771     int i_ci_size;
772     int i_cd_size = 0;
773     block_t *out;
774     bo_t bo;
775     int i;
776
777     msg_Dbg( p_mux, "Asf muxer creating header" );
778
779     if( p_sys->i_dts_first > 0 )
780     {
781         i_duration = p_sys->i_dts_last - p_sys->i_dts_first;
782         if( i_duration < 0 ) i_duration = 0;
783     }
784
785     /* calculate header size */
786     i_size = 30 + 104 + 46;
787     i_ci_size = 44;
788     for( i = 1; i < p_sys->i_track; i++ )
789     {
790         i_size += 78 + p_sys->track[i].i_extra;
791         i_ci_size += 8 + 2 * strlen( p_sys->track[i].psz_name );
792         if( p_sys->track[i].i_cat == AUDIO_ES )
793         {
794             i_ci_size += 4;
795         }
796         else if( p_sys->track[i].i_cat == VIDEO_ES )
797         {
798             i_ci_size += 6;
799         }
800     }
801
802     if( *p_sys->psz_title || *p_sys->psz_author || *p_sys->psz_copyright ||
803         *p_sys->psz_comment || *p_sys->psz_rating )
804     {
805         i_cd_size = 34 + 2 * ( strlen( p_sys->psz_title ) + 1 +
806                              strlen( p_sys->psz_author ) + 1 +
807                              strlen( p_sys->psz_copyright ) + 1 +
808                              strlen( p_sys->psz_comment ) + 1 +
809                              strlen( p_sys->psz_rating ) + 1 );
810     }
811
812     i_size += i_ci_size + i_cd_size;
813
814     if( p_sys->b_asf_http )
815     {
816         out = block_New( p_mux, i_size + 50 + 12 );
817         bo_init( &bo, out->p_buffer, i_size + 50 + 12 );
818         asf_chunk_add( &bo, 0x4824, i_size + 50, 0xc00, p_sys->i_seq++ );
819     }
820     else
821     {
822         out = block_New( p_mux, i_size + 50 );
823         bo_init( &bo, out->p_buffer, i_size + 50 );
824     }
825
826     /* header object */
827     bo_add_guid ( &bo, &asf_object_header_guid );
828     bo_addle_u64( &bo, i_size );
829     bo_addle_u32( &bo, 2 + p_sys->i_track - 1 );
830     bo_add_u8   ( &bo, 1 );
831     bo_add_u8   ( &bo, 2 );
832
833     /* sub object */
834
835     /* file properties */
836     bo_add_guid ( &bo, &asf_object_file_properties_guid );
837     bo_addle_u64( &bo, 104 );
838     bo_add_guid ( &bo, &p_sys->fid );
839     bo_addle_u64( &bo, i_size + 50 + p_sys->i_packet_count *
840                                 p_sys->i_packet_size ); /* file size */
841     bo_addle_u64( &bo, 0 );                 /* creation date */
842     bo_addle_u64( &bo, b_broadcast ? 0xffffffffLL : p_sys->i_packet_count );
843     bo_addle_u64( &bo, i_duration * 10 );   /* play duration (100ns) */
844     bo_addle_u64( &bo, i_duration * 10 );   /* send duration (100ns) */
845     bo_addle_u64( &bo, p_sys->i_preroll_time ); /* preroll duration (ms) */
846     bo_addle_u32( &bo, b_broadcast ? 0x01 : 0x00);      /* flags */
847     bo_addle_u32( &bo, p_sys->i_packet_size );  /* packet size min */
848     bo_addle_u32( &bo, p_sys->i_packet_size );  /* packet size max */
849     bo_addle_u32( &bo, p_sys->i_bitrate );      /* maxbitrate */
850
851     /* header extention */
852     bo_add_guid ( &bo, &asf_object_header_extention_guid );
853     bo_addle_u64( &bo, 46 );
854     bo_add_guid ( &bo, &asf_guid_reserved_1 );
855     bo_addle_u16( &bo, 6 );
856     bo_addle_u32( &bo, 0 );
857
858     /* content description header */
859     if( i_cd_size > 0 )
860     {
861         bo_add_guid ( &bo, &asf_object_content_description_guid );
862         bo_addle_u64( &bo, i_cd_size );
863         bo_addle_u16( &bo, 2 * strlen( p_sys->psz_title ) + 2 );
864         bo_addle_u16( &bo, 2 * strlen( p_sys->psz_author ) + 2 );
865         bo_addle_u16( &bo, 2 * strlen( p_sys->psz_copyright ) + 2 );
866         bo_addle_u16( &bo, 2 * strlen( p_sys->psz_comment ) + 2 );
867         bo_addle_u16( &bo, 2 * strlen( p_sys->psz_rating ) + 2 );
868
869         bo_addle_str16_nosize( &bo, p_sys->psz_title );
870         bo_addle_str16_nosize( &bo, p_sys->psz_author );
871         bo_addle_str16_nosize( &bo, p_sys->psz_copyright );
872         bo_addle_str16_nosize( &bo, p_sys->psz_comment );
873         bo_addle_str16_nosize( &bo, p_sys->psz_rating );
874     }
875
876     /* stream properties */
877     for( i = 1; i < p_sys->i_track; i++ )
878     {
879         tk = &p_sys->track[i];
880
881         bo_add_guid ( &bo, &asf_object_stream_properties_guid );
882         bo_addle_u64( &bo, 78 + tk->i_extra );
883         if( tk->i_cat == AUDIO_ES )
884         {
885             bo_add_guid( &bo, &asf_object_stream_type_audio );
886             bo_add_guid( &bo, &asf_guid_audio_conceal_none );
887         }
888         else if( tk->i_cat == VIDEO_ES )
889         {
890             bo_add_guid( &bo, &asf_object_stream_type_video );
891             bo_add_guid( &bo, &asf_guid_video_conceal_none );
892         }
893         bo_addle_u64( &bo, 0 );         /* time offset */
894         bo_addle_u32( &bo, tk->i_extra );
895         bo_addle_u32( &bo, 0 );         /* 0 */
896         bo_addle_u16( &bo, tk->i_id );  /* stream number */
897         bo_addle_u32( &bo, 0 );
898         bo_add_mem  ( &bo, tk->p_extra, tk->i_extra );
899     }
900
901     /* Codec Infos */
902     bo_add_guid ( &bo, &asf_object_codec_comment_guid );
903     bo_addle_u64( &bo, i_ci_size );
904     bo_add_guid ( &bo, &asf_object_codec_comment_reserved_guid );
905     bo_addle_u32( &bo, p_sys->i_track - 1 );
906     for( i = 1; i < p_sys->i_track; i++ )
907     {
908         tk = &p_sys->track[i];
909
910         bo_addle_u16( &bo, tk->i_id );
911         bo_addle_str16( &bo, tk->psz_name );
912         bo_addle_u16( &bo, 0 );
913         if( tk->i_cat == AUDIO_ES )
914         {
915             bo_addle_u16( &bo, 2 );
916             bo_addle_u16( &bo, tk->i_tag );
917         }
918         else if( tk->i_cat == VIDEO_ES )
919         {
920             bo_addle_u16( &bo, 4 );
921             bo_add_mem  ( &bo, (uint8_t*)&tk->i_fourcc, 4 );
922
923         }
924     }
925
926     /* data object */
927     bo_add_guid ( &bo, &asf_object_data_guid );
928     bo_addle_u64( &bo, 50 + p_sys->i_packet_count * p_sys->i_packet_size );
929     bo_add_guid ( &bo, &p_sys->fid );
930     bo_addle_u64( &bo, p_sys->i_packet_count );
931     bo_addle_u16( &bo, 0x101 );
932
933     return out;
934 }
935
936 /****************************************************************************
937  *
938  ****************************************************************************/
939 static block_t *asf_packet_flush( sout_mux_t *p_mux )
940 {
941     sout_mux_sys_t *p_sys = p_mux->p_sys;
942     int i_pad, i_preheader = p_sys->b_asf_http ? 12 : 0;
943     block_t *pk;
944     bo_t bo;
945
946     if( !p_sys->pk ) return 0;
947
948     i_pad = p_sys->i_packet_size - p_sys->i_pk_used;
949     memset( p_sys->pk->p_buffer + p_sys->i_pk_used, 0, i_pad );
950
951     bo_init( &bo, p_sys->pk->p_buffer, 14 + i_preheader );
952
953     if( p_sys->b_asf_http )
954         asf_chunk_add( &bo, 0x4424, p_sys->i_packet_size, 0x0, p_sys->i_seq++);
955
956     bo_add_u8   ( &bo, 0x82 );
957     bo_addle_u16( &bo, 0 );
958     bo_add_u8( &bo, 0x11 );
959     bo_add_u8( &bo, 0x5d );
960     bo_addle_u16( &bo, i_pad );
961     bo_addle_u32( &bo, (p_sys->i_pk_dts - p_sys->i_dts_first) / 1000 +
962                   p_sys->i_preroll_time );
963     bo_addle_u16( &bo, 0 /* data->i_length */ );
964     bo_add_u8( &bo, 0x80 | p_sys->i_pk_frame );
965
966     pk = p_sys->pk;
967     p_sys->pk = NULL;
968
969     p_sys->i_packet_count++;
970
971     return pk;
972 }
973
974 static block_t *asf_packet_create( sout_mux_t *p_mux,
975                                    asf_track_t *tk, block_t *data )
976 {
977     sout_mux_sys_t *p_sys = p_mux->p_sys;
978
979     int     i_data = data->i_buffer;
980     int     i_pos  = 0;
981     uint8_t *p_data= data->p_buffer;
982     block_t *first = NULL, **last = &first;
983     int     i_preheader = p_sys->b_asf_http ? 12 : 0;
984
985     while( i_pos < i_data )
986     {
987         bo_t bo;
988         int i_payload;
989
990         if( p_sys->pk == NULL )
991         {
992             p_sys->pk = block_New( p_mux, p_sys->i_packet_size + i_preheader );
993             /* reserve 14 bytes for the packet header */
994             p_sys->i_pk_used = 14 + i_preheader;
995             p_sys->i_pk_frame = 0;
996             p_sys->i_pk_dts = data->i_dts;
997         }
998
999         bo_init( &bo, &p_sys->pk->p_buffer[p_sys->i_pk_used],
1000                  p_sys->i_packet_size - p_sys->i_pk_used );
1001
1002         /* add payload (header size = 17) */
1003         i_payload = __MIN( i_data - i_pos,
1004                            p_sys->i_packet_size - p_sys->i_pk_used - 17 );
1005         bo_add_u8   ( &bo, !(data->i_flags & BLOCK_FLAG_TYPE_P ||
1006                       data->i_flags & BLOCK_FLAG_TYPE_B) ?
1007                       0x80 | tk->i_id : tk->i_id );
1008         bo_add_u8   ( &bo, tk->i_sequence );
1009         bo_addle_u32( &bo, i_pos );
1010         bo_add_u8   ( &bo, 0x08 );  /* flags */
1011         bo_addle_u32( &bo, i_data );
1012         bo_addle_u32( &bo, (data->i_dts - p_sys->i_dts_first) / 1000 +
1013                       p_sys->i_preroll_time );
1014         bo_addle_u16( &bo, i_payload );
1015         bo_add_mem  ( &bo, &p_data[i_pos], i_payload );
1016         i_pos += i_payload;
1017         p_sys->i_pk_used += 17 + i_payload;
1018
1019         p_sys->i_pk_frame++;
1020
1021         if( p_sys->i_pk_used + 17 >= p_sys->i_packet_size )
1022         {
1023             /* Not enough data for another payload, flush the packet */
1024             *last = asf_packet_flush( p_mux );
1025             last  = &(*last)->p_next;
1026         }
1027     }
1028
1029     tk->i_sequence++;
1030     block_Release( data );
1031
1032     return first;
1033 }
1034
1035 static block_t *asf_stream_end_create( sout_mux_t *p_mux )
1036 {
1037     sout_mux_sys_t *p_sys = p_mux->p_sys;
1038
1039     block_t *out = NULL;
1040     bo_t bo;
1041
1042     if( p_sys->b_asf_http )
1043     {
1044         out = block_New( p_mux, 12 );
1045         bo_init( &bo, out->p_buffer, 12 );
1046         asf_chunk_add( &bo, 0x4524, 0, 0x00, p_sys->i_seq++ );
1047     }
1048     else
1049     {
1050         /* Create index */
1051         out = block_New( p_mux, 56 );
1052         bo_init( &bo, out->p_buffer, 56 );
1053         bo_add_guid ( &bo, &asf_object_index_guid );
1054         bo_addle_u64( &bo, 56 );
1055         bo_add_guid ( &bo, &p_sys->fid );
1056         bo_addle_u64( &bo, 10000000 );
1057         bo_addle_u32( &bo, 5 );
1058         bo_addle_u32( &bo, 0 );
1059     }
1060
1061     return out;
1062 }