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