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