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