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