]> git.sesse.net Git - vlc/blob - modules/mux/ogg.c
* modules/mux/asf.c, ts.c, ogg.c: added WMV3 fourcc.
[vlc] / modules / mux / ogg.c
1 /*****************************************************************************
2  * ogg.c: ogg muxer module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@netcourrier.com>
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 #ifdef HAVE_TIME_H
32 #   include <time.h>
33 #endif
34
35 #include <vlc/vlc.h>
36 #include <vlc/input.h>
37 #include <vlc/sout.h>
38
39 #include "codecs.h"
40
41 #include <ogg/ogg.h>
42
43 /*****************************************************************************
44  * Module descriptor
45  *****************************************************************************/
46 static int  Open   ( vlc_object_t * );
47 static void Close  ( vlc_object_t * );
48
49 vlc_module_begin();
50     set_description( _("Ogg/ogm muxer") );
51     set_capability( "sout mux", 10 );
52     add_shortcut( "ogg" );
53     add_shortcut( "ogm" );
54     set_callbacks( Open, Close );
55 vlc_module_end();
56
57
58 /*****************************************************************************
59  * Exported prototypes
60  *****************************************************************************/
61 static int Control  ( sout_mux_t *, int, va_list );
62 static int AddStream( sout_mux_t *, sout_input_t * );
63 static int DelStream( sout_mux_t *, sout_input_t * );
64 static int Mux      ( sout_mux_t * );
65
66 static block_t *OggCreateHeader( sout_mux_t *, mtime_t );
67 static block_t *OggCreateFooter( sout_mux_t *, mtime_t );
68
69 /*****************************************************************************
70  * Misc declarations
71  *****************************************************************************/
72 #define FREE( p ) if( p ) { free( p ); (p) = NULL; }
73
74 /* Structures used for OggDS headers used in ogm files */
75
76 #define PACKET_TYPE_HEADER   0x01
77 #define PACKET_TYPE_COMMENT  0x03
78 #define PACKET_IS_SYNCPOINT  0x08
79
80 typedef struct
81 #ifdef HAVE_ATTRIBUTE_PACKED
82     __attribute__((__packed__))
83 #endif
84 {
85     int32_t i_width;
86     int32_t i_height;
87 } oggds_header_video_t;
88
89 typedef struct
90 #ifdef HAVE_ATTRIBUTE_PACKED
91     __attribute__((__packed__))
92 #endif
93 {
94     int16_t i_channels;
95     int16_t i_block_align;
96     int32_t i_avgbytespersec;
97 } oggds_header_audio_t;
98
99 typedef struct
100 #ifdef HAVE_ATTRIBUTE_PACKED
101     __attribute__((__packed__))
102 #endif
103 {
104     uint8_t i_packet_type;
105
106     char stream_type[8];
107     char sub_type[4];
108
109     int32_t i_size;
110
111     int64_t i_time_unit;
112     int64_t i_samples_per_unit;
113     int32_t i_default_len;
114
115     int32_t i_buffer_size;
116     int16_t i_bits_per_sample;
117
118     int16_t i_padding_0; /* Because the original is using MSVC packing style */
119
120     union
121     {
122         oggds_header_video_t video;
123         oggds_header_audio_t audio;
124     } header;
125
126     int32_t i_padding_1; /* Because the original is using MSVC packing style */
127
128 } oggds_header_t;
129
130 /*
131  * TODO  move this function to src/stream_output.c (used by nearly all muxers)
132  */
133 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
134 {
135     mtime_t i_dts;
136     int     i_stream;
137     int     i;
138
139     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
140     {
141         block_fifo_t  *p_fifo;
142
143         p_fifo = p_mux->pp_inputs[i]->p_fifo;
144
145         /* We don't really need to have anything in the SPU fifo */
146         if( p_mux->pp_inputs[i]->p_fmt->i_cat == SPU_ES &&
147             p_fifo->i_depth == 0 ) continue;
148
149         if( p_fifo->i_depth > 2 ||
150             /* Special case for SPUs */
151             ( p_mux->pp_inputs[i]->p_fmt->i_cat == SPU_ES &&
152               p_fifo->i_depth > 0 ) )
153         {
154             block_t *p_buf;
155
156             p_buf = block_FifoShow( p_fifo );
157             if( i_stream < 0 || p_buf->i_dts < i_dts )
158             {
159                 i_dts = p_buf->i_dts;
160                 i_stream = i;
161             }
162         }
163         else
164         {
165             // wait that all fifo have at least 3 packets (3 vorbis headers)
166             return -1;
167         }
168     }
169     if( pi_stream )
170     {
171         *pi_stream = i_stream;
172     }
173     if( pi_dts )
174     {
175         *pi_dts = i_dts;
176     }
177     return i_stream;
178 }
179
180 /*****************************************************************************
181  * Definitions of structures and functions used by this plugins 
182  *****************************************************************************/
183 typedef struct
184 {
185     int i_cat;
186     int i_fourcc;
187
188     int b_new;
189
190     mtime_t i_dts;
191     mtime_t i_length;
192     int     i_packet_no;
193     int     i_serial_no;
194     int     i_keyframe_granule_shift; /* Theora only */
195     ogg_stream_state os;
196
197     oggds_header_t oggds_header;
198
199     block_t *pp_sout_headers[3];
200     int           i_sout_headers;
201
202 } ogg_stream_t;
203
204 struct sout_mux_sys_t
205 {
206     int     i_streams;
207
208     mtime_t i_start_dts;
209     int     i_next_serial_no;
210
211     /* number of logical streams pending to be added */
212     int i_add_streams;
213
214     /* logical streams pending to be deleted */
215     int i_del_streams;
216     ogg_stream_t **pp_del_streams;
217 };
218
219 static void OggSetDate( block_t *, mtime_t , mtime_t  );
220 static block_t *OggStreamFlush( sout_mux_t *, ogg_stream_state *, mtime_t );
221
222 /*****************************************************************************
223  * Open: Open muxer
224  *****************************************************************************/
225 static int Open( vlc_object_t *p_this )
226 {
227     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
228     sout_mux_sys_t  *p_sys;
229
230     msg_Info( p_mux, "Open" );
231
232     p_sys                 = malloc( sizeof( sout_mux_sys_t ) );
233     p_sys->i_streams      = 0;
234     p_sys->i_add_streams  = 0;
235     p_sys->i_del_streams  = 0;
236     p_sys->pp_del_streams = 0;
237
238     p_mux->p_sys        = p_sys;
239     p_mux->pf_control   = Control;
240     p_mux->pf_addstream = AddStream;
241     p_mux->pf_delstream = DelStream;
242     p_mux->pf_mux       = Mux;
243
244     /* First serial number is random.
245      * (Done like this because on win32 you need to seed the random number
246      *  generator once per thread). */
247     srand( (unsigned int)time( NULL ) );
248     p_sys->i_next_serial_no = rand();
249
250     return VLC_SUCCESS;
251 }
252
253 /*****************************************************************************
254  * Close: Finalize ogg bitstream and close muxer
255  *****************************************************************************/
256 static void Close( vlc_object_t * p_this )
257 {
258     sout_mux_t     *p_mux = (sout_mux_t*)p_this;
259     sout_mux_sys_t *p_sys = p_mux->p_sys;
260
261     msg_Info( p_mux, "Close" );
262
263     if( p_sys->i_del_streams )
264     {
265         block_t *p_og = NULL;
266         mtime_t i_dts = -1;
267         int i;
268
269         /* Close the current ogg stream */
270         msg_Dbg( p_mux, "writing footer" );
271         block_ChainAppend( &p_og, OggCreateFooter( p_mux, 0 ) );
272
273         /* Remove deleted logical streams */
274         for( i = 0; i < p_sys->i_del_streams; i++ )
275         {
276             i_dts = p_sys->pp_del_streams[i]->i_dts;
277             ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
278             FREE( p_sys->pp_del_streams[i] );
279         }
280         FREE( p_sys->pp_del_streams );
281         p_sys->i_streams -= p_sys->i_del_streams;
282
283         /* Write footer */
284         OggSetDate( p_og, i_dts, 0 );
285         sout_AccessOutWrite( p_mux->p_access, p_og );
286     }
287
288     free( p_sys );
289 }
290
291 /*****************************************************************************
292  * Control:
293  *****************************************************************************/
294 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
295 {
296     vlc_bool_t *pb_bool;
297     char **ppsz;
298
299    switch( i_query )
300    {
301        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
302            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
303            *pb_bool = VLC_TRUE;
304            return VLC_SUCCESS;
305
306        case MUX_GET_ADD_STREAM_WAIT:
307            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
308            *pb_bool = VLC_TRUE;
309            return VLC_SUCCESS;
310
311        case MUX_GET_MIME:
312            ppsz = (char**)va_arg( args, char ** );
313            *ppsz = strdup( "application/ogg" );
314            return VLC_SUCCESS;
315
316         default:
317             return VLC_EGENERIC;
318    }
319 }
320 /*****************************************************************************
321  * AddStream: Add an elementary stream to the muxed stream
322  *****************************************************************************/
323 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
324 {
325     sout_mux_sys_t *p_sys = p_mux->p_sys;
326     ogg_stream_t   *p_stream;
327
328     msg_Dbg( p_mux, "adding input" );
329
330     p_input->p_sys = p_stream = malloc( sizeof( ogg_stream_t ) );
331
332     p_stream->i_cat       = p_input->p_fmt->i_cat;
333     p_stream->i_fourcc    = p_input->p_fmt->i_codec;
334     p_stream->i_serial_no = p_sys->i_next_serial_no++;
335     p_stream->i_packet_no = 0;
336
337     p_stream->i_sout_headers = 0;
338
339     memset( &p_stream->oggds_header, 0, sizeof(p_stream->oggds_header) );
340     p_stream->oggds_header.i_packet_type = PACKET_TYPE_HEADER;
341     switch( p_input->p_fmt->i_cat )
342     {
343     case VIDEO_ES:
344         if( !p_input->p_fmt->video.i_frame_rate ||
345             !p_input->p_fmt->video.i_frame_rate_base )
346         {
347             msg_Warn( p_mux, "Missing frame rate, assuming 25fps" );
348             p_input->p_fmt->video.i_frame_rate = 25;
349             p_input->p_fmt->video.i_frame_rate_base = 1;
350         }
351
352         switch( p_stream->i_fourcc )
353         {
354         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
355         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
356         case VLC_FOURCC( 'D', 'I', 'V', '3' ):
357         case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
358         case VLC_FOURCC( 'W', 'M', 'V', '1' ):
359         case VLC_FOURCC( 'W', 'M', 'V', '2' ):
360         case VLC_FOURCC( 'W', 'M', 'V', '3' ):
361             memcpy( p_stream->oggds_header.stream_type, "video", 5 );
362             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) )
363             {
364                 memcpy( p_stream->oggds_header.sub_type, "XVID", 4 );
365             }
366             else if( p_stream->i_fourcc == VLC_FOURCC( 'D', 'I', 'V', '3' ) )
367             {
368                 memcpy( p_stream->oggds_header.sub_type, "DIV3", 4 );
369             }
370             else
371             {
372                 memcpy(p_stream->oggds_header.sub_type,&p_stream->i_fourcc,4);
373             }
374             SetDWLE( &p_stream->oggds_header.i_size,
375                      sizeof( oggds_header_t ) - 1);
376             SetQWLE( &p_stream->oggds_header.i_time_unit,
377                      I64C(10000000) * p_input->p_fmt->video.i_frame_rate_base /
378                      (int64_t)p_input->p_fmt->video.i_frame_rate );
379             SetQWLE( &p_stream->oggds_header.i_samples_per_unit, 1 );
380             SetDWLE( &p_stream->oggds_header.i_default_len, 1 ); /* ??? */
381             SetDWLE( &p_stream->oggds_header.i_buffer_size, 1024*1024 );
382             SetWLE( &p_stream->oggds_header.i_bits_per_sample, 0 );
383             SetDWLE( &p_stream->oggds_header.header.video.i_width,
384                      p_input->p_fmt->video.i_width );
385             SetDWLE( &p_stream->oggds_header.header.video.i_height,
386                      p_input->p_fmt->video.i_height );
387             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
388             break;
389
390         case VLC_FOURCC( 't', 'h', 'e', 'o' ):
391             msg_Dbg( p_mux, "theora stream" );
392             break;
393
394         default:
395             FREE( p_input->p_sys );
396             return VLC_EGENERIC;
397         }
398         break;
399
400     case AUDIO_ES:
401         switch( p_stream->i_fourcc )
402         {
403         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
404         case VLC_FOURCC( 'a', '5', '2', ' ' ):
405             memcpy( p_stream->oggds_header.stream_type, "audio", 5 );
406             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', 'g', 'a' ) )
407             {
408                 memcpy( p_stream->oggds_header.sub_type, "55  ", 4 );
409             }
410             else if( p_stream->i_fourcc == VLC_FOURCC( 'a', '5', '2', ' ' ) )
411             {
412                 memcpy( p_stream->oggds_header.sub_type, "2000", 4 );
413             }
414             SetDWLE( &p_stream->oggds_header.i_size,
415                      sizeof( oggds_header_t ) - 1);
416             SetQWLE( &p_stream->oggds_header.i_time_unit, 0 /* not used */ );
417             SetDWLE( &p_stream->oggds_header.i_default_len, 1 );
418             SetDWLE( &p_stream->oggds_header.i_buffer_size, 30*1024 );
419             SetQWLE( &p_stream->oggds_header.i_samples_per_unit,
420                      p_input->p_fmt->audio.i_rate );
421             SetWLE( &p_stream->oggds_header.i_bits_per_sample, 0 );
422             SetDWLE( &p_stream->oggds_header.header.audio.i_channels,
423                      p_input->p_fmt->audio.i_channels );
424             SetDWLE( &p_stream->oggds_header.header.audio.i_block_align,
425                      p_input->p_fmt->audio.i_blockalign );
426             SetDWLE( &p_stream->oggds_header.header.audio.i_avgbytespersec, 0);
427             msg_Dbg( p_mux, "mpga/a52 stream" );
428             break;
429
430         case VLC_FOURCC( 'v', 'o', 'r', 'b' ):
431             msg_Dbg( p_mux, "vorbis stream" );
432             break;
433
434         case VLC_FOURCC( 's', 'p', 'x', ' ' ):
435             msg_Dbg( p_mux, "speex stream" );
436             break;
437
438         case VLC_FOURCC( 'f', 'l', 'a', 'c' ):
439             msg_Dbg( p_mux, "flac stream" );
440             break;
441
442         default:
443             FREE( p_input->p_sys );
444             return VLC_EGENERIC;
445         }
446         break;
447
448     case SPU_ES:
449         switch( p_stream->i_fourcc )
450         {
451         case VLC_FOURCC( 's', 'u','b', 't' ):
452             memcpy( p_stream->oggds_header.stream_type, "text", 4 );
453             msg_Dbg( p_mux, "subtitles stream" );
454             break;
455
456         default:
457             FREE( p_input->p_sys );
458             return VLC_EGENERIC;
459         }
460         break;
461     default:
462         FREE( p_input->p_sys );
463         return VLC_EGENERIC;
464     }
465
466     p_stream->b_new = VLC_TRUE;
467
468     p_sys->i_add_streams++;
469
470     return VLC_SUCCESS;
471 }
472
473 /*****************************************************************************
474  * DelStream: Delete an elementary stream from the muxed stream
475  *****************************************************************************/
476 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
477 {
478     sout_mux_sys_t *p_sys  = p_mux->p_sys;
479     ogg_stream_t   *p_stream = (ogg_stream_t*)p_input->p_sys;
480     block_t *p_og;
481
482     msg_Dbg( p_mux, "removing input" );
483
484     /* flush all remaining data */
485     if( p_input->p_sys )
486     {
487         int i;
488
489         if( !p_stream->b_new &&
490             ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
491         {
492             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
493             sout_AccessOutWrite( p_mux->p_access, p_og );
494         }
495
496         for( i = 0; i < p_stream->i_sout_headers; i++ )
497         {
498             block_Release( p_stream->pp_sout_headers[i] );
499             p_stream->i_sout_headers = 0;
500         }
501
502         /* move input in delete queue */
503         if( !p_stream->b_new )
504         {
505             p_sys->pp_del_streams = realloc( p_sys->pp_del_streams,
506                                              (p_sys->i_del_streams + 1) *
507                                              sizeof(ogg_stream_t *) );
508             p_sys->pp_del_streams[p_sys->i_del_streams++] = p_stream;
509         }
510         else
511         {
512             /* Wasn't already added so get rid of it */
513             FREE( p_stream );
514             p_sys->i_add_streams--;
515         }
516     }
517
518     p_input->p_sys = NULL;
519
520     return 0;
521 }
522
523 /*****************************************************************************
524  * Ogg bitstream manipulation routines
525  *****************************************************************************/
526 static block_t *OggStreamFlush( sout_mux_t *p_mux,
527                                 ogg_stream_state *p_os, mtime_t i_pts )
528 {
529     block_t *p_og, *p_og_first = NULL;
530     ogg_page og;
531
532     while( ogg_stream_flush( p_os, &og ) )
533     {
534         /* Flush all data */
535         p_og = block_New( p_mux, og.header_len + og.body_len );
536
537         memcpy( p_og->p_buffer, og.header, og.header_len );
538         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
539         p_og->i_dts     = 0;
540         p_og->i_pts     = i_pts;
541         p_og->i_length  = 0;
542
543         i_pts = 0; // write it only once
544
545         block_ChainAppend( &p_og_first, p_og );
546     }
547
548     return p_og_first;
549 }
550
551 static block_t *OggStreamPageOut( sout_mux_t *p_mux,
552                                   ogg_stream_state *p_os, mtime_t i_pts )
553 {
554     block_t *p_og, *p_og_first = NULL;
555     ogg_page og;
556
557     while( ogg_stream_pageout( p_os, &og ) )
558     {
559         /* Flush all data */
560         p_og = block_New( p_mux, og.header_len + og.body_len );
561
562         memcpy( p_og->p_buffer, og.header, og.header_len );
563         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
564         p_og->i_dts     = 0;
565         p_og->i_pts     = i_pts;
566         p_og->i_length  = 0;
567
568         i_pts = 0; // write them only once
569
570         block_ChainAppend( &p_og_first, p_og );
571     }
572
573     return p_og_first;
574 }
575
576 static block_t *OggCreateHeader( sout_mux_t *p_mux, mtime_t i_dts )
577 {
578     block_t *p_hdr = NULL;
579     block_t *p_og;
580     ogg_packet    op;
581     int i;
582
583     /* Write header for each stream. All b_o_s (beginning of stream) packets
584      * must appear first in the ogg stream so we take care of them first. */
585     for( i = 0; i < p_mux->i_nb_inputs; i++ )
586     {
587         ogg_stream_t *p_stream = (ogg_stream_t*)p_mux->pp_inputs[i]->p_sys;
588         p_stream->b_new = VLC_FALSE;
589
590         msg_Dbg( p_mux, "creating header for %4.4s",
591                  (char *)&p_stream->i_fourcc );
592
593         ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
594         p_stream->i_packet_no = 0;
595
596         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
597             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
598             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
599         {
600             /* Special case, headers are already there in the
601              * incoming stream or we backed them up earlier */
602
603             /* first packet in order: vorbis/speex/theora info */
604             if( !p_stream->i_sout_headers )
605             {
606                 p_og = block_FifoGet( p_mux->pp_inputs[i]->p_fifo );
607                 op.packet = p_og->p_buffer;
608                 op.bytes  = p_og->i_buffer;
609                 op.b_o_s  = 1;
610                 op.e_o_s  = 0;
611                 op.granulepos = 0;
612                 op.packetno = p_stream->i_packet_no++;
613                 ogg_stream_packetin( &p_stream->os, &op );
614                 p_stream->pp_sout_headers[0] =
615                     OggStreamFlush( p_mux, &p_stream->os, 0 );
616                 p_stream->i_sout_headers++;
617             }
618             p_og = block_Duplicate( p_stream->pp_sout_headers[0] );
619
620             /* Get keyframe_granule_shift for theora granulepos calculation */
621             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
622             {
623                 int i_keyframe_frequency_force =
624                       1 << ((op.packet[40] << 6 >> 3) | (op.packet[41] >> 5));
625
626                 /* granule_shift = i_log( frequency_force -1 ) */
627                 p_stream->i_keyframe_granule_shift = 0;
628                 i_keyframe_frequency_force--;
629                 while( i_keyframe_frequency_force )
630                 {
631                     p_stream->i_keyframe_granule_shift++;
632                     i_keyframe_frequency_force >>= 1;
633                 }
634             }
635         }
636         else if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
637         {
638             /* flac stream marker (yeah, only that in the 1st packet) */
639             op.packet = "fLaC";
640             op.bytes  = 4;
641             op.b_o_s  = 1;
642             op.e_o_s  = 0;
643             op.granulepos = 0;
644             op.packetno = p_stream->i_packet_no++;
645             ogg_stream_packetin( &p_stream->os, &op );
646             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
647         }
648         else
649         {
650             /* ds header */
651             op.packet = (uint8_t*)&p_stream->oggds_header;
652             op.bytes  = sizeof( oggds_header_t );
653             op.b_o_s  = 1;
654             op.e_o_s  = 0;
655             op.granulepos = 0;
656             op.packetno = p_stream->i_packet_no++;
657             ogg_stream_packetin( &p_stream->os, &op );
658             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
659         }
660
661         block_ChainAppend( &p_hdr, p_og );
662     }
663
664     /* Take care of the non b_o_s headers */
665     for( i = 0; i < p_mux->i_nb_inputs; i++ )
666     {
667         ogg_stream_t *p_stream = (ogg_stream_t*)p_mux->pp_inputs[i]->p_sys;
668
669         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
670             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
671             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
672         {
673             /* Special case, headers are already there in the incoming stream.
674              * We need to gather them an mark them as headers. */
675             int j;
676             for( j = 0; j < 2; j++ )
677             {
678                 if( p_stream->i_sout_headers < j + 2 )
679                 {
680                     /* next packets in order: comments and codebooks */
681                     p_og = block_FifoGet( p_mux->pp_inputs[i]->p_fifo );
682                     op.packet = p_og->p_buffer;
683                     op.bytes  = p_og->i_buffer;
684                     op.b_o_s  = 0;
685                     op.e_o_s  = 0;
686                     op.granulepos = 0;
687                     op.packetno = p_stream->i_packet_no++;
688                     ogg_stream_packetin( &p_stream->os, &op );
689                     p_stream->pp_sout_headers[j+1] =
690                         OggStreamFlush( p_mux, &p_stream->os, 0 );
691                     p_stream->i_sout_headers++;
692                 }
693
694                 p_og = block_Duplicate( p_stream->pp_sout_headers[j+1] );
695                 block_ChainAppend( &p_hdr, p_og );
696             }
697         }
698         else if( p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
699         {
700             uint8_t com[128];
701             int     i_com;
702
703             /* comment */
704             com[0] = PACKET_TYPE_COMMENT;
705             i_com = snprintf( &com[1], 128, VERSION" stream output" ) + 1;
706             op.packet = com;
707             op.bytes  = i_com;
708             op.b_o_s  = 0;
709             op.e_o_s  = 0;
710             op.granulepos = 0;
711             op.packetno = p_stream->i_packet_no++;
712             ogg_stream_packetin( &p_stream->os, &op );
713             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
714             block_ChainAppend( &p_hdr, p_og );
715         }
716
717         /* Special case for mp4v and flac */
718         if( ( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) ||
719               p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ) &&
720             p_mux->pp_inputs[i]->p_fmt->i_extra )
721         {
722             /* Send a packet with the VOL data for mp4v
723              * or STREAMINFO for flac */
724             msg_Dbg( p_mux, "writing extra data" );
725             op.bytes  = p_mux->pp_inputs[i]->p_fmt->i_extra;
726             op.packet = p_mux->pp_inputs[i]->p_fmt->p_extra;
727             if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
728             {
729                 /* Skip the flac stream marker */
730                 op.bytes -= 4;
731                 op.packet+= 4;
732             }
733             op.b_o_s  = 0;
734             op.e_o_s  = 0;
735             op.granulepos = 0;
736             op.packetno = p_stream->i_packet_no++;
737             ogg_stream_packetin( &p_stream->os, &op );
738             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
739             block_ChainAppend( &p_hdr, p_og );
740         }
741     }
742
743     /* set HEADER flag */
744     for( p_og = p_hdr; p_og != NULL; p_og = p_og->p_next )
745     {
746         p_og->i_flags |= BLOCK_FLAG_HEADER;
747     }
748     return p_hdr;
749 }
750
751 static block_t *OggCreateFooter( sout_mux_t *p_mux, mtime_t i_dts )
752 {
753     sout_mux_sys_t *p_sys = p_mux->p_sys;
754     block_t *p_hdr = NULL;
755     block_t *p_og;
756     ogg_packet    op;
757     int i;
758
759     /* flush all remaining data */
760     for( i = 0; i < p_mux->i_nb_inputs; i++ )
761     {
762         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
763
764         /* skip newly added streams */
765         if( p_stream->b_new ) continue;
766
767         if( ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
768         {
769             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
770             sout_AccessOutWrite( p_mux->p_access, p_og );
771         }
772     }
773
774     /* Write eos packets for each stream. */
775     for( i = 0; i < p_mux->i_nb_inputs; i++ )
776     {
777         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
778
779         /* skip newly added streams */
780         if( p_stream->b_new ) continue;
781
782         op.packet = NULL;
783         op.bytes  = 0;
784         op.b_o_s  = 0;
785         op.e_o_s  = 1;
786         op.granulepos = -1;
787         op.packetno = p_stream->i_packet_no++;
788         ogg_stream_packetin( &p_stream->os, &op );
789
790         p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
791         block_ChainAppend( &p_hdr, p_og );
792         ogg_stream_clear( &p_stream->os );
793     }
794
795     for( i = 0; i < p_sys->i_del_streams; i++ )
796     {
797         op.packet = NULL;
798         op.bytes  = 0;
799         op.b_o_s  = 0;
800         op.e_o_s  = 1;
801         op.granulepos = -1;
802         op.packetno = p_sys->pp_del_streams[i]->i_packet_no++;
803         ogg_stream_packetin( &p_sys->pp_del_streams[i]->os, &op );
804
805         p_og = OggStreamFlush( p_mux, &p_sys->pp_del_streams[i]->os, 0 );
806         block_ChainAppend( &p_hdr, p_og );
807         ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
808     }
809
810     return p_hdr;
811 }
812
813 static void OggSetDate( block_t *p_og, mtime_t i_dts, mtime_t i_length )
814 {
815     int i_count;
816     block_t *p_tmp;
817     mtime_t i_delta;
818
819     for( p_tmp = p_og, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->p_next )
820     {
821         i_count++;
822     }
823     i_delta = i_length / i_count;
824
825     for( p_tmp = p_og; p_tmp != NULL; p_tmp = p_tmp->p_next )
826     {
827         p_tmp->i_dts    = i_dts;
828         p_tmp->i_length = i_delta;
829
830         i_dts += i_delta;
831     }
832 }
833
834 /*****************************************************************************
835  * Mux: multiplex available data in input fifos into the Ogg bitstream
836  *****************************************************************************/
837 static int Mux( sout_mux_t *p_mux )
838 {
839     sout_mux_sys_t *p_sys = p_mux->p_sys;
840     block_t        *p_og = NULL;
841     int            i_stream;
842     mtime_t        i_dts;
843
844     if( p_sys->i_add_streams || p_sys->i_del_streams )
845     {
846         /* Open new ogg stream */
847         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
848         {
849             msg_Dbg( p_mux, "waiting for data..." );
850             return VLC_SUCCESS;
851         }
852
853         if( p_sys->i_streams )
854         {
855             /* Close current ogg stream */
856             int i;
857
858             msg_Dbg( p_mux, "writing footer" );
859             block_ChainAppend( &p_og, OggCreateFooter( p_mux, 0 ) );
860
861             /* Remove deleted logical streams */
862             for( i = 0; i < p_sys->i_del_streams; i++ )
863             {
864                 FREE( p_sys->pp_del_streams[i] );
865             }
866             FREE( p_sys->pp_del_streams );
867             p_sys->i_streams = 0;
868         }
869
870         msg_Dbg( p_mux, "writing header" );
871         p_sys->i_start_dts = i_dts;
872         p_sys->i_streams = p_mux->i_nb_inputs;
873         p_sys->i_del_streams = 0;
874         p_sys->i_add_streams = 0;
875         block_ChainAppend( &p_og, OggCreateHeader( p_mux, i_dts ) );
876
877         /* Write header and/or footer */
878         OggSetDate( p_og, i_dts, 0 );
879         sout_AccessOutWrite( p_mux->p_access, p_og );
880         p_og = NULL;
881     }
882
883     for( ;; )
884     {
885         sout_input_t *p_input;
886         ogg_stream_t *p_stream;
887         block_t *p_data;
888         ogg_packet op;
889
890         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
891         {
892             return VLC_SUCCESS;
893         }
894
895         p_input  = p_mux->pp_inputs[i_stream];
896         p_stream = (ogg_stream_t*)p_input->p_sys;
897         p_data   = block_FifoGet( p_input->p_fifo );
898
899         if( p_stream->i_fourcc != VLC_FOURCC( 'v', 'o', 'r', 'b' ) &&
900             p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) &&
901             p_stream->i_fourcc != VLC_FOURCC( 's', 'p', 'x', ' ' ) &&
902             p_stream->i_fourcc != VLC_FOURCC( 't', 'h', 'e', 'o' ) )
903         {
904             p_data = block_Realloc( p_data, 1, p_data->i_buffer );
905             p_data->p_buffer[0] = PACKET_IS_SYNCPOINT;      // FIXME
906         }
907
908         op.packet   = p_data->p_buffer;
909         op.bytes    = p_data->i_buffer;
910         op.b_o_s    = 0;
911         op.e_o_s    = 0;
912         op.packetno = p_stream->i_packet_no++;
913
914         if( p_stream->i_cat == AUDIO_ES )
915         {
916             if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
917                 p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ||
918                 p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) )
919             {
920                 /* number of sample from begining + current packet */
921                 op.granulepos =
922                     ( i_dts - p_sys->i_start_dts + p_data->i_length ) *
923                     (mtime_t)p_input->p_fmt->audio.i_rate / I64C(1000000);
924             }
925             else
926             {
927                 /* number of sample from begining */
928                 op.granulepos = ( i_dts - p_sys->i_start_dts ) *
929                     p_stream->oggds_header.i_samples_per_unit / I64C(1000000);
930             }
931         }
932         else if( p_stream->i_cat == VIDEO_ES )
933         {
934             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
935             {
936                 /* FIXME, we assume only keyframes */
937                 op.granulepos = ( ( i_dts - p_sys->i_start_dts ) *
938                     p_input->p_fmt->video.i_frame_rate /
939                     p_input->p_fmt->video.i_frame_rate_base /
940                     I64C(1000000) ) << p_stream->i_keyframe_granule_shift;
941             }
942             else
943                 op.granulepos = ( i_dts - p_sys->i_start_dts ) * I64C(10) /
944                     p_stream->oggds_header.i_time_unit;
945         }
946         else if( p_stream->i_cat == SPU_ES )
947         {
948             /* granulepos is in milisec */
949             op.granulepos = ( i_dts - p_sys->i_start_dts ) / 1000;
950         }
951
952         ogg_stream_packetin( &p_stream->os, &op );
953
954         if( p_stream->i_cat == SPU_ES ||
955             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) )
956         {
957             /* Subtitles or Speex packets are quite small so they 
958              * need to be flushed to be sent on time */
959             p_og = OggStreamFlush( p_mux, &p_stream->os, p_data->i_dts );
960         }
961         else
962         {
963             p_og = OggStreamPageOut( p_mux, &p_stream->os, p_data->i_dts );
964         }
965
966         if( p_og )
967         {
968             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
969             p_stream->i_dts = -1;
970             p_stream->i_length = 0;
971
972             sout_AccessOutWrite( p_mux->p_access, p_og );
973         }
974         else
975         {
976             if( p_stream->i_dts < 0 )
977             {
978                 p_stream->i_dts = p_data->i_dts;
979             }
980             p_stream->i_length += p_data->i_length;
981         }
982
983         block_Release( p_data );
984     }
985
986     return VLC_SUCCESS;
987 }