]> git.sesse.net Git - vlc/blob - modules/mux/ogg.c
* modules/mux/ogg.c, modules/codec/theora.c: changes for theora alpha 3 support ...
[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 Capability(sout_mux_t *, int, void *, void * );
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_capacity  = Capability;
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 static int Capability( sout_mux_t *p_mux, int i_query, void *p_args,
292                        void *p_answer )
293 {
294    switch( i_query )
295    {
296         case SOUT_MUX_CAP_GET_ADD_STREAM_ANY_TIME:
297             *(vlc_bool_t*)p_answer = VLC_TRUE;
298             return( SOUT_MUX_CAP_ERR_OK );
299         case SOUT_MUX_CAP_GET_ADD_STREAM_WAIT:
300             *(vlc_bool_t*)p_answer = VLC_TRUE;
301             return( SOUT_MUX_CAP_ERR_OK );
302         default:
303             return( SOUT_MUX_CAP_ERR_UNIMPLEMENTED );
304    }
305 }
306
307 /*****************************************************************************
308  * AddStream: Add an elementary stream to the muxed stream
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     ogg_stream_t   *p_stream;
314
315     msg_Dbg( p_mux, "adding input" );
316
317     p_input->p_sys = p_stream = malloc( sizeof( ogg_stream_t ) );
318
319     p_stream->i_cat       = p_input->p_fmt->i_cat;
320     p_stream->i_fourcc    = p_input->p_fmt->i_codec;
321     p_stream->i_serial_no = p_sys->i_next_serial_no++;
322     p_stream->i_packet_no = 0;
323
324     p_stream->i_sout_headers = 0;
325
326     memset( &p_stream->oggds_header, 0, sizeof(p_stream->oggds_header) );
327     p_stream->oggds_header.i_packet_type = PACKET_TYPE_HEADER;
328     switch( p_input->p_fmt->i_cat )
329     {
330     case VIDEO_ES:
331         if( !p_input->p_fmt->video.i_frame_rate ||
332             !p_input->p_fmt->video.i_frame_rate_base )
333         {
334             msg_Warn( p_mux, "Missing frame rate, assuming 25fps" );
335             p_input->p_fmt->video.i_frame_rate = 25;
336             p_input->p_fmt->video.i_frame_rate_base = 1;
337         }
338
339         switch( p_stream->i_fourcc )
340         {
341         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
342         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
343         case VLC_FOURCC( 'D', 'I', 'V', '3' ):
344         case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
345         case VLC_FOURCC( 'W', 'M', 'V', '1' ):
346         case VLC_FOURCC( 'W', 'M', 'V', '2' ):
347             memcpy( p_stream->oggds_header.stream_type, "video", 5 );
348             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) )
349             {
350                 memcpy( p_stream->oggds_header.sub_type, "XVID", 4 );
351             }
352             else if( p_stream->i_fourcc == VLC_FOURCC( 'D', 'I', 'V', '3' ) )
353             {
354                 memcpy( p_stream->oggds_header.sub_type, "DIV3", 4 );
355             }
356             else
357             {
358                 memcpy(p_stream->oggds_header.sub_type,&p_stream->i_fourcc,4);
359             }
360             SetDWLE( &p_stream->oggds_header.i_size,
361                      sizeof( oggds_header_t ) - 1);
362             SetQWLE( &p_stream->oggds_header.i_time_unit,
363                      I64C(10000000) * p_input->p_fmt->video.i_frame_rate_base /
364                      (int64_t)p_input->p_fmt->video.i_frame_rate );
365             SetQWLE( &p_stream->oggds_header.i_samples_per_unit, 1 );
366             SetDWLE( &p_stream->oggds_header.i_default_len, 1 ); /* ??? */
367             SetDWLE( &p_stream->oggds_header.i_buffer_size, 1024*1024 );
368             SetWLE( &p_stream->oggds_header.i_bits_per_sample, 0 );
369             SetDWLE( &p_stream->oggds_header.header.video.i_width,
370                      p_input->p_fmt->video.i_width );
371             SetDWLE( &p_stream->oggds_header.header.video.i_height,
372                      p_input->p_fmt->video.i_height );
373             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
374             break;
375
376         case VLC_FOURCC( 't', 'h', 'e', 'o' ):
377             msg_Dbg( p_mux, "theora stream" );
378             break;
379
380         default:
381             FREE( p_input->p_sys );
382             return VLC_EGENERIC;
383         }
384         break;
385
386     case AUDIO_ES:
387         switch( p_stream->i_fourcc )
388         {
389         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
390         case VLC_FOURCC( 'a', '5', '2', ' ' ):
391             memcpy( p_stream->oggds_header.stream_type, "audio", 5 );
392             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', 'g', 'a' ) )
393             {
394                 memcpy( p_stream->oggds_header.sub_type, "55  ", 4 );
395             }
396             else if( p_stream->i_fourcc == VLC_FOURCC( 'a', '5', '2', ' ' ) )
397             {
398                 memcpy( p_stream->oggds_header.sub_type, "2000", 4 );
399             }
400             SetDWLE( &p_stream->oggds_header.i_size,
401                      sizeof( oggds_header_t ) - 1);
402             SetQWLE( &p_stream->oggds_header.i_time_unit, 0 /* not used */ );
403             SetDWLE( &p_stream->oggds_header.i_default_len, 1 );
404             SetDWLE( &p_stream->oggds_header.i_buffer_size, 30*1024 );
405             SetQWLE( &p_stream->oggds_header.i_samples_per_unit,
406                      p_input->p_fmt->audio.i_rate );
407             SetWLE( &p_stream->oggds_header.i_bits_per_sample, 0 );
408             SetDWLE( &p_stream->oggds_header.header.audio.i_channels,
409                      p_input->p_fmt->audio.i_channels );
410             SetDWLE( &p_stream->oggds_header.header.audio.i_block_align,
411                      p_input->p_fmt->audio.i_blockalign );
412             SetDWLE( &p_stream->oggds_header.header.audio.i_avgbytespersec, 0);
413             msg_Dbg( p_mux, "mpga/a52 stream" );
414             break;
415
416         case VLC_FOURCC( 'v', 'o', 'r', 'b' ):
417             msg_Dbg( p_mux, "vorbis stream" );
418             break;
419
420         case VLC_FOURCC( 's', 'p', 'x', ' ' ):
421             msg_Dbg( p_mux, "speex stream" );
422             break;
423
424         case VLC_FOURCC( 'f', 'l', 'a', 'c' ):
425             msg_Dbg( p_mux, "flac stream" );
426             break;
427
428         default:
429             FREE( p_input->p_sys );
430             return VLC_EGENERIC;
431         }
432         break;
433
434     case SPU_ES:
435         switch( p_stream->i_fourcc )
436         {
437         case VLC_FOURCC( 's', 'u','b', 't' ):
438             memcpy( p_stream->oggds_header.stream_type, "text", 4 );
439             msg_Dbg( p_mux, "subtitles stream" );
440             break;
441
442         default:
443             FREE( p_input->p_sys );
444             return VLC_EGENERIC;
445         }
446         break;
447     default:
448         FREE( p_input->p_sys );
449         return VLC_EGENERIC;
450     }
451
452     p_stream->b_new = VLC_TRUE;
453
454     p_sys->i_add_streams++;
455
456     return VLC_SUCCESS;
457 }
458
459 /*****************************************************************************
460  * DelStream: Delete an elementary stream from the muxed stream
461  *****************************************************************************/
462 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
463 {
464     sout_mux_sys_t *p_sys  = p_mux->p_sys;
465     ogg_stream_t   *p_stream = (ogg_stream_t*)p_input->p_sys;
466     block_t *p_og;
467
468     msg_Dbg( p_mux, "removing input" );
469
470     /* flush all remaining data */
471     if( p_input->p_sys )
472     {
473         int i;
474
475         if( !p_stream->b_new &&
476             ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
477         {
478             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
479             sout_AccessOutWrite( p_mux->p_access, p_og );
480         }
481
482         for( i = 0; i < p_stream->i_sout_headers; i++ )
483         {
484             block_Release( p_stream->pp_sout_headers[i] );
485             p_stream->i_sout_headers = 0;
486         }
487
488         /* move input in delete queue */
489         if( !p_stream->b_new )
490         {
491             p_sys->pp_del_streams = realloc( p_sys->pp_del_streams,
492                                              (p_sys->i_del_streams + 1) *
493                                              sizeof(ogg_stream_t *) );
494             p_sys->pp_del_streams[p_sys->i_del_streams++] = p_stream;
495         }
496         else
497         {
498             /* Wasn't already added so get rid of it */
499             FREE( p_stream );
500             p_sys->i_add_streams--;
501         }
502     }
503
504     p_input->p_sys = NULL;
505
506     return 0;
507 }
508
509 /*****************************************************************************
510  * Ogg bitstream manipulation routines
511  *****************************************************************************/
512 static block_t *OggStreamFlush( sout_mux_t *p_mux,
513                                 ogg_stream_state *p_os, mtime_t i_pts )
514 {
515     block_t *p_og, *p_og_first = NULL;
516     ogg_page og;
517
518     while( ogg_stream_flush( p_os, &og ) )
519     {
520         /* Flush all data */
521         p_og = block_New( p_mux, og.header_len + og.body_len );
522
523         memcpy( p_og->p_buffer, og.header, og.header_len );
524         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
525         p_og->i_dts     = 0;
526         p_og->i_pts     = i_pts;
527         p_og->i_length  = 0;
528
529         i_pts = 0; // write it only once
530
531         block_ChainAppend( &p_og_first, p_og );
532     }
533
534     return p_og_first;
535 }
536
537 static block_t *OggStreamPageOut( sout_mux_t *p_mux,
538                                   ogg_stream_state *p_os, mtime_t i_pts )
539 {
540     block_t *p_og, *p_og_first = NULL;
541     ogg_page og;
542
543     while( ogg_stream_pageout( p_os, &og ) )
544     {
545         /* Flush all data */
546         p_og = block_New( p_mux, og.header_len + og.body_len );
547
548         memcpy( p_og->p_buffer, og.header, og.header_len );
549         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
550         p_og->i_dts     = 0;
551         p_og->i_pts     = i_pts;
552         p_og->i_length  = 0;
553
554         i_pts = 0; // write them only once
555
556         block_ChainAppend( &p_og_first, p_og );
557     }
558
559     return p_og_first;
560 }
561
562 static block_t *OggCreateHeader( sout_mux_t *p_mux, mtime_t i_dts )
563 {
564     block_t *p_hdr = NULL;
565     block_t *p_og;
566     ogg_packet    op;
567     int i;
568
569     /* Write header for each stream. All b_o_s (beginning of stream) packets
570      * must appear first in the ogg stream so we take care of them first. */
571     for( i = 0; i < p_mux->i_nb_inputs; i++ )
572     {
573         ogg_stream_t *p_stream = (ogg_stream_t*)p_mux->pp_inputs[i]->p_sys;
574         p_stream->b_new = VLC_FALSE;
575
576         msg_Dbg( p_mux, "creating header for %4.4s",
577                  (char *)&p_stream->i_fourcc );
578
579         ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
580         p_stream->i_packet_no = 0;
581
582         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
583             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
584             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
585         {
586             /* Special case, headers are already there in the
587              * incoming stream or we backed them up earlier */
588
589             /* first packet in order: vorbis/speex/theora info */
590             if( !p_stream->i_sout_headers )
591             {
592                 p_og = block_FifoGet( p_mux->pp_inputs[i]->p_fifo );
593                 op.packet = p_og->p_buffer;
594                 op.bytes  = p_og->i_buffer;
595                 op.b_o_s  = 1;
596                 op.e_o_s  = 0;
597                 op.granulepos = 0;
598                 op.packetno = p_stream->i_packet_no++;
599                 ogg_stream_packetin( &p_stream->os, &op );
600                 p_stream->pp_sout_headers[0] =
601                     OggStreamFlush( p_mux, &p_stream->os, 0 );
602                 p_stream->i_sout_headers++;
603             }
604             p_og = block_Duplicate( p_stream->pp_sout_headers[0] );
605
606             /* Get keyframe_granule_shift for theora granulepos calculation */
607             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
608             {
609                 int i_keyframe_frequency_force =
610                       1 << ((op.packet[40] << 6 >> 3) | (op.packet[41] >> 5));
611
612                 /* granule_shift = i_log( frequency_force -1 ) */
613                 p_stream->i_keyframe_granule_shift = 0;
614                 i_keyframe_frequency_force--;
615                 while( i_keyframe_frequency_force )
616                 {
617                     p_stream->i_keyframe_granule_shift++;
618                     i_keyframe_frequency_force >>= 1;
619                 }
620             }
621         }
622         else if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
623         {
624             /* flac stream marker (yeah, only that in the 1st packet) */
625             op.packet = "fLaC";
626             op.bytes  = 4;
627             op.b_o_s  = 1;
628             op.e_o_s  = 0;
629             op.granulepos = 0;
630             op.packetno = p_stream->i_packet_no++;
631             ogg_stream_packetin( &p_stream->os, &op );
632             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
633         }
634         else
635         {
636             /* ds header */
637             op.packet = (uint8_t*)&p_stream->oggds_header;
638             op.bytes  = sizeof( oggds_header_t );
639             op.b_o_s  = 1;
640             op.e_o_s  = 0;
641             op.granulepos = 0;
642             op.packetno = p_stream->i_packet_no++;
643             ogg_stream_packetin( &p_stream->os, &op );
644             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
645         }
646
647         block_ChainAppend( &p_hdr, p_og );
648     }
649
650     /* Take care of the non b_o_s headers */
651     for( i = 0; i < p_mux->i_nb_inputs; i++ )
652     {
653         ogg_stream_t *p_stream = (ogg_stream_t*)p_mux->pp_inputs[i]->p_sys;
654
655         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
656             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
657             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
658         {
659             /* Special case, headers are already there in the incoming stream.
660              * We need to gather them an mark them as headers. */
661             int j;
662             for( j = 0; j < 2; j++ )
663             {
664                 if( p_stream->i_sout_headers < j + 2 )
665                 {
666                     /* next packets in order: comments and codebooks */
667                     p_og = block_FifoGet( p_mux->pp_inputs[i]->p_fifo );
668                     op.packet = p_og->p_buffer;
669                     op.bytes  = p_og->i_buffer;
670                     op.b_o_s  = 0;
671                     op.e_o_s  = 0;
672                     op.granulepos = 0;
673                     op.packetno = p_stream->i_packet_no++;
674                     ogg_stream_packetin( &p_stream->os, &op );
675                     p_stream->pp_sout_headers[j+1] =
676                         OggStreamFlush( p_mux, &p_stream->os, 0 );
677                     p_stream->i_sout_headers++;
678                 }
679
680                 p_og = block_Duplicate( p_stream->pp_sout_headers[j+1] );
681                 block_ChainAppend( &p_hdr, p_og );
682             }
683         }
684         else if( p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
685         {
686             uint8_t com[128];
687             int     i_com;
688
689             /* comment */
690             com[0] = PACKET_TYPE_COMMENT;
691             i_com = snprintf( &com[1], 128, VERSION" stream output" ) + 1;
692             op.packet = com;
693             op.bytes  = i_com;
694             op.b_o_s  = 0;
695             op.e_o_s  = 0;
696             op.granulepos = 0;
697             op.packetno = p_stream->i_packet_no++;
698             ogg_stream_packetin( &p_stream->os, &op );
699             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
700             block_ChainAppend( &p_hdr, p_og );
701         }
702
703         /* Special case for mp4v and flac */
704         if( ( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) ||
705               p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ) &&
706             p_mux->pp_inputs[i]->p_fmt->i_extra )
707         {
708             /* Send a packet with the VOL data for mp4v
709              * or STREAMINFO for flac */
710             msg_Dbg( p_mux, "writing extra data" );
711             op.bytes  = p_mux->pp_inputs[i]->p_fmt->i_extra;
712             op.packet = p_mux->pp_inputs[i]->p_fmt->p_extra;
713             if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
714             {
715                 /* Skip the flac stream marker */
716                 op.bytes -= 4;
717                 op.packet+= 4;
718             }
719             op.b_o_s  = 0;
720             op.e_o_s  = 0;
721             op.granulepos = 0;
722             op.packetno = p_stream->i_packet_no++;
723             ogg_stream_packetin( &p_stream->os, &op );
724             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
725             block_ChainAppend( &p_hdr, p_og );
726         }
727     }
728
729     /* set HEADER flag */
730     for( p_og = p_hdr; p_og != NULL; p_og = p_og->p_next )
731     {
732         p_og->i_flags |= BLOCK_FLAG_HEADER;
733     }
734     return p_hdr;
735 }
736
737 static block_t *OggCreateFooter( sout_mux_t *p_mux, mtime_t i_dts )
738 {
739     sout_mux_sys_t *p_sys = p_mux->p_sys;
740     block_t *p_hdr = NULL;
741     block_t *p_og;
742     ogg_packet    op;
743     int i;
744
745     /* flush all remaining data */
746     for( i = 0; i < p_mux->i_nb_inputs; i++ )
747     {
748         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
749
750         /* skip newly added streams */
751         if( p_stream->b_new ) continue;
752
753         if( ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
754         {
755             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
756             sout_AccessOutWrite( p_mux->p_access, p_og );
757         }
758     }
759
760     /* Write eos packets for each stream. */
761     for( i = 0; i < p_mux->i_nb_inputs; i++ )
762     {
763         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
764
765         /* skip newly added streams */
766         if( p_stream->b_new ) continue;
767
768         op.packet = NULL;
769         op.bytes  = 0;
770         op.b_o_s  = 0;
771         op.e_o_s  = 1;
772         op.granulepos = -1;
773         op.packetno = p_stream->i_packet_no++;
774         ogg_stream_packetin( &p_stream->os, &op );
775
776         p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
777         block_ChainAppend( &p_hdr, p_og );
778         ogg_stream_clear( &p_stream->os );
779     }
780
781     for( i = 0; i < p_sys->i_del_streams; i++ )
782     {
783         op.packet = NULL;
784         op.bytes  = 0;
785         op.b_o_s  = 0;
786         op.e_o_s  = 1;
787         op.granulepos = -1;
788         op.packetno = p_sys->pp_del_streams[i]->i_packet_no++;
789         ogg_stream_packetin( &p_sys->pp_del_streams[i]->os, &op );
790
791         p_og = OggStreamFlush( p_mux, &p_sys->pp_del_streams[i]->os, 0 );
792         block_ChainAppend( &p_hdr, p_og );
793         ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
794     }
795
796     return p_hdr;
797 }
798
799 static void OggSetDate( block_t *p_og, mtime_t i_dts, mtime_t i_length )
800 {
801     int i_count;
802     block_t *p_tmp;
803     mtime_t i_delta;
804
805     for( p_tmp = p_og, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->p_next )
806     {
807         i_count++;
808     }
809     i_delta = i_length / i_count;
810
811     for( p_tmp = p_og; p_tmp != NULL; p_tmp = p_tmp->p_next )
812     {
813         p_tmp->i_dts    = i_dts;
814         p_tmp->i_length = i_delta;
815
816         i_dts += i_delta;
817     }
818 }
819
820 /*****************************************************************************
821  * Mux: multiplex available data in input fifos into the Ogg bitstream
822  *****************************************************************************/
823 static int Mux( sout_mux_t *p_mux )
824 {
825     sout_mux_sys_t *p_sys = p_mux->p_sys;
826     block_t        *p_og = NULL;
827     int            i_stream;
828     mtime_t        i_dts;
829
830     if( p_sys->i_add_streams || p_sys->i_del_streams )
831     {
832         /* Open new ogg stream */
833         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
834         {
835             msg_Dbg( p_mux, "waiting for data..." );
836             return VLC_SUCCESS;
837         }
838
839         if( p_sys->i_streams )
840         {
841             /* Close current ogg stream */
842             int i;
843
844             msg_Dbg( p_mux, "writing footer" );
845             block_ChainAppend( &p_og, OggCreateFooter( p_mux, 0 ) );
846
847             /* Remove deleted logical streams */
848             for( i = 0; i < p_sys->i_del_streams; i++ )
849             {
850                 FREE( p_sys->pp_del_streams[i] );
851             }
852             FREE( p_sys->pp_del_streams );
853             p_sys->i_streams = 0;
854         }
855
856         msg_Dbg( p_mux, "writing header" );
857         p_sys->i_start_dts = i_dts;
858         p_sys->i_streams = p_mux->i_nb_inputs;
859         p_sys->i_del_streams = 0;
860         p_sys->i_add_streams = 0;
861         block_ChainAppend( &p_og, OggCreateHeader( p_mux, i_dts ) );
862
863         /* Write header and/or footer */
864         OggSetDate( p_og, i_dts, 0 );
865         sout_AccessOutWrite( p_mux->p_access, p_og );
866         p_og = NULL;
867     }
868
869     for( ;; )
870     {
871         sout_input_t *p_input;
872         ogg_stream_t *p_stream;
873         block_t *p_data;
874         ogg_packet op;
875
876         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
877         {
878             return VLC_SUCCESS;
879         }
880
881         p_input  = p_mux->pp_inputs[i_stream];
882         p_stream = (ogg_stream_t*)p_input->p_sys;
883         p_data   = block_FifoGet( p_input->p_fifo );
884
885         if( p_stream->i_fourcc != VLC_FOURCC( 'v', 'o', 'r', 'b' ) &&
886             p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) &&
887             p_stream->i_fourcc != VLC_FOURCC( 's', 'p', 'x', ' ' ) &&
888             p_stream->i_fourcc != VLC_FOURCC( 't', 'h', 'e', 'o' ) )
889         {
890             p_data = block_Realloc( p_data, 1, p_data->i_buffer );
891             p_data->p_buffer[0] = PACKET_IS_SYNCPOINT;      // FIXME
892         }
893
894         op.packet   = p_data->p_buffer;
895         op.bytes    = p_data->i_buffer;
896         op.b_o_s    = 0;
897         op.e_o_s    = 0;
898         op.packetno = p_stream->i_packet_no++;
899
900         if( p_stream->i_cat == AUDIO_ES )
901         {
902             if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
903                 p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ||
904                 p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) )
905             {
906                 /* number of sample from begining + current packet */
907                 op.granulepos =
908                     ( i_dts - p_sys->i_start_dts + p_data->i_length ) *
909                     (mtime_t)p_input->p_fmt->audio.i_rate / I64C(1000000);
910             }
911             else
912             {
913                 /* number of sample from begining */
914                 op.granulepos = ( i_dts - p_sys->i_start_dts ) *
915                     p_stream->oggds_header.i_samples_per_unit / I64C(1000000);
916             }
917         }
918         else if( p_stream->i_cat == VIDEO_ES )
919         {
920             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
921             {
922                 /* FIXME, we assume only keyframes */
923                 op.granulepos = ( ( i_dts - p_sys->i_start_dts ) *
924                     p_input->p_fmt->video.i_frame_rate /
925                     p_input->p_fmt->video.i_frame_rate_base /
926                     I64C(1000000) ) << p_stream->i_keyframe_granule_shift;
927             }
928             else
929                 op.granulepos = ( i_dts - p_sys->i_start_dts ) * I64C(10) /
930                     p_stream->oggds_header.i_time_unit;
931         }
932         else if( p_stream->i_cat == SPU_ES )
933         {
934             /* granulepos is in milisec */
935             op.granulepos = ( i_dts - p_sys->i_start_dts ) / 1000;
936         }
937
938         ogg_stream_packetin( &p_stream->os, &op );
939
940         if( p_stream->i_cat == SPU_ES ||
941             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) )
942         {
943             /* Subtitles or Speex packets are quite small so they 
944              * need to be flushed to be sent on time */
945             p_og = OggStreamFlush( p_mux, &p_stream->os, p_data->i_dts );
946         }
947         else
948         {
949             p_og = OggStreamPageOut( p_mux, &p_stream->os, p_data->i_dts );
950         }
951
952         if( p_og )
953         {
954             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
955             p_stream->i_dts = -1;
956             p_stream->i_length = 0;
957
958             sout_AccessOutWrite( p_mux->p_access, p_og );
959         }
960         else
961         {
962             if( p_stream->i_dts < 0 )
963             {
964                 p_stream->i_dts = p_data->i_dts;
965             }
966             p_stream->i_length += p_data->i_length;
967         }
968
969         block_Release( p_data );
970     }
971
972     return VLC_SUCCESS;
973 }