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