]> git.sesse.net Git - vlc/blob - modules/mux/ogg.c
Fix duplicate definitions of FREE
[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 #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
76 /* Structures used for OggDS headers used in ogm files */
77
78 #define PACKET_TYPE_HEADER   0x01
79 #define PACKET_TYPE_COMMENT  0x03
80 #define PACKET_IS_SYNCPOINT  0x08
81
82 typedef struct
83 #ifdef HAVE_ATTRIBUTE_PACKED
84     __attribute__((__packed__))
85 #endif
86 {
87     int32_t i_width;
88     int32_t i_height;
89 } oggds_header_video_t;
90
91 typedef struct
92 #ifdef HAVE_ATTRIBUTE_PACKED
93     __attribute__((__packed__))
94 #endif
95 {
96     int16_t i_channels;
97     int16_t i_block_align;
98     int32_t i_avgbytespersec;
99 } oggds_header_audio_t;
100
101 typedef struct
102 #ifdef HAVE_ATTRIBUTE_PACKED
103     __attribute__((__packed__))
104 #endif
105 {
106     uint8_t i_packet_type;
107
108     char stream_type[8];
109     char sub_type[4];
110
111     int32_t i_size;
112
113     int64_t i_time_unit;
114     int64_t i_samples_per_unit;
115     int32_t i_default_len;
116
117     int32_t i_buffer_size;
118     int16_t i_bits_per_sample;
119
120     int16_t i_padding_0; /* Because the original is using MSVC packing style */
121
122     union
123     {
124         oggds_header_video_t video;
125         oggds_header_audio_t audio;
126     } header;
127
128     int32_t i_padding_1; /* Because the original is using MSVC packing style */
129
130 } oggds_header_t;
131
132 /*
133  * TODO  move this function to src/stream_output.c (used by nearly all muxers)
134  */
135 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
136 {
137     mtime_t i_dts;
138     int     i_stream;
139     int     i;
140
141     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
142     {
143         block_fifo_t  *p_fifo;
144
145         p_fifo = p_mux->pp_inputs[i]->p_fifo;
146
147         /* We don't really need to have anything in the SPU fifo */
148         if( p_mux->pp_inputs[i]->p_fmt->i_cat == SPU_ES &&
149             p_fifo->i_depth == 0 ) continue;
150
151         if( p_fifo->i_depth )
152         {
153             block_t *p_buf;
154
155             p_buf = block_FifoShow( p_fifo );
156             if( i_stream < 0 || p_buf->i_dts < i_dts )
157             {
158                 i_dts = p_buf->i_dts;
159                 i_stream = i;
160             }
161         }
162         else return -1;
163
164     }
165     if( pi_stream ) *pi_stream = i_stream;
166     if( pi_dts ) *pi_dts = i_dts;
167     return i_stream;
168 }
169
170 /*****************************************************************************
171  * Definitions of structures and functions used by this plugins 
172  *****************************************************************************/
173 typedef struct
174 {
175     int i_cat;
176     int i_fourcc;
177
178     int b_new;
179
180     mtime_t i_dts;
181     mtime_t i_length;
182     int     i_packet_no;
183     int     i_serial_no;
184     int     i_keyframe_granule_shift; /* Theora only */
185     ogg_stream_state os;
186
187     oggds_header_t *p_oggds_header;
188
189 } ogg_stream_t;
190
191 struct sout_mux_sys_t
192 {
193     int     i_streams;
194
195     mtime_t i_start_dts;
196     int     i_next_serial_no;
197
198     /* number of logical streams pending to be added */
199     int i_add_streams;
200
201     /* logical streams pending to be deleted */
202     int i_del_streams;
203     ogg_stream_t **pp_del_streams;
204 };
205
206 static void OggSetDate( block_t *, mtime_t , mtime_t  );
207 static block_t *OggStreamFlush( sout_mux_t *, ogg_stream_state *, mtime_t );
208
209 /*****************************************************************************
210  * Open: Open muxer
211  *****************************************************************************/
212 static int Open( vlc_object_t *p_this )
213 {
214     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
215     sout_mux_sys_t  *p_sys;
216
217     msg_Info( p_mux, "Open" );
218
219     p_sys                 = malloc( sizeof( sout_mux_sys_t ) );
220     p_sys->i_streams      = 0;
221     p_sys->i_add_streams  = 0;
222     p_sys->i_del_streams  = 0;
223     p_sys->pp_del_streams = 0;
224
225     p_mux->p_sys        = p_sys;
226     p_mux->pf_control   = Control;
227     p_mux->pf_addstream = AddStream;
228     p_mux->pf_delstream = DelStream;
229     p_mux->pf_mux       = Mux;
230
231     /* First serial number is random.
232      * (Done like this because on win32 you need to seed the random number
233      *  generator once per thread). */
234     srand( (unsigned int)time( NULL ) );
235     p_sys->i_next_serial_no = rand();
236
237     return VLC_SUCCESS;
238 }
239
240 /*****************************************************************************
241  * Close: Finalize ogg bitstream and close muxer
242  *****************************************************************************/
243 static void Close( vlc_object_t * p_this )
244 {
245     sout_mux_t     *p_mux = (sout_mux_t*)p_this;
246     sout_mux_sys_t *p_sys = p_mux->p_sys;
247
248     msg_Info( p_mux, "Close" );
249
250     if( p_sys->i_del_streams )
251     {
252         block_t *p_og = NULL;
253         mtime_t i_dts = -1;
254         int i;
255
256         /* Close the current ogg stream */
257         msg_Dbg( p_mux, "writing footer" );
258         block_ChainAppend( &p_og, OggCreateFooter( p_mux, 0 ) );
259
260         /* Remove deleted logical streams */
261         for( i = 0; i < p_sys->i_del_streams; i++ )
262         {
263             i_dts = p_sys->pp_del_streams[i]->i_dts;
264             ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
265             FREENULL( p_sys->pp_del_streams[i]->p_oggds_header );
266             FREENULL( p_sys->pp_del_streams[i] );
267         }
268         FREENULL( p_sys->pp_del_streams );
269         p_sys->i_streams -= p_sys->i_del_streams;
270
271         /* Write footer */
272         OggSetDate( p_og, i_dts, 0 );
273         sout_AccessOutWrite( p_mux->p_access, p_og );
274     }
275
276     free( p_sys );
277 }
278
279 /*****************************************************************************
280  * Control:
281  *****************************************************************************/
282 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
283 {
284     vlc_bool_t *pb_bool;
285     char **ppsz;
286
287    switch( i_query )
288    {
289        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
290            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
291            *pb_bool = VLC_TRUE;
292            return VLC_SUCCESS;
293
294        case MUX_GET_ADD_STREAM_WAIT:
295            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
296            *pb_bool = VLC_TRUE;
297            return VLC_SUCCESS;
298
299        case MUX_GET_MIME:
300            ppsz = (char**)va_arg( args, char ** );
301            *ppsz = strdup( "application/ogg" );
302            return VLC_SUCCESS;
303
304         default:
305             return VLC_EGENERIC;
306    }
307 }
308 /*****************************************************************************
309  * AddStream: Add an elementary stream to the muxed stream
310  *****************************************************************************/
311 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
312 {
313     sout_mux_sys_t *p_sys = p_mux->p_sys;
314     ogg_stream_t   *p_stream;
315     uint16_t i_tag;
316
317     msg_Dbg( p_mux, "adding input" );
318
319     p_input->p_sys = p_stream = malloc( sizeof( ogg_stream_t ) );
320
321     p_stream->i_cat       = p_input->p_fmt->i_cat;
322     p_stream->i_fourcc    = p_input->p_fmt->i_codec;
323     p_stream->i_serial_no = p_sys->i_next_serial_no++;
324     p_stream->i_packet_no = 0;
325
326     p_stream->p_oggds_header = 0;
327
328     switch( p_input->p_fmt->i_cat )
329     {
330     case VIDEO_ES:
331         if( !p_input->p_fmt->video.i_frame_rate ||
332             !p_input->p_fmt->video.i_frame_rate_base )
333         {
334             msg_Warn( p_mux, "Missing frame rate, assuming 25fps" );
335             p_input->p_fmt->video.i_frame_rate = 25;
336             p_input->p_fmt->video.i_frame_rate_base = 1;
337         }
338
339         switch( p_stream->i_fourcc )
340         {
341         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
342         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
343         case VLC_FOURCC( 'D', 'I', 'V', '3' ):
344         case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
345         case VLC_FOURCC( 'W', 'M', 'V', '1' ):
346         case VLC_FOURCC( 'W', 'M', 'V', '2' ):
347         case VLC_FOURCC( 'W', 'M', 'V', '3' ):
348         case VLC_FOURCC( 'S', 'N', 'O', 'W' ):
349         case VLC_FOURCC( 'd', 'r', 'a', 'c' ):
350             p_stream->p_oggds_header = malloc( sizeof(oggds_header_t) );
351             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
352             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
353
354             memcpy( p_stream->p_oggds_header->stream_type, "video", 5 );
355             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) )
356             {
357                 memcpy( p_stream->p_oggds_header->sub_type, "XVID", 4 );
358             }
359             else if( p_stream->i_fourcc == VLC_FOURCC( 'D', 'I', 'V', '3' ) )
360             {
361                 memcpy( p_stream->p_oggds_header->sub_type, "DIV3", 4 );
362             }
363             else
364             {
365                 memcpy( p_stream->p_oggds_header->sub_type,
366                         &p_stream->i_fourcc, 4 );
367             }
368             SetDWLE( &p_stream->p_oggds_header->i_size,
369                      sizeof( oggds_header_t ) - 1 );
370             SetQWLE( &p_stream->p_oggds_header->i_time_unit,
371                      I64C(10000000) * p_input->p_fmt->video.i_frame_rate_base /
372                      (int64_t)p_input->p_fmt->video.i_frame_rate );
373             SetQWLE( &p_stream->p_oggds_header->i_samples_per_unit, 1 );
374             SetDWLE( &p_stream->p_oggds_header->i_default_len, 1 ); /* ??? */
375             SetDWLE( &p_stream->p_oggds_header->i_buffer_size, 1024*1024 );
376             SetWLE( &p_stream->p_oggds_header->i_bits_per_sample, 0 );
377             SetDWLE( &p_stream->p_oggds_header->header.video.i_width,
378                      p_input->p_fmt->video.i_width );
379             SetDWLE( &p_stream->p_oggds_header->header.video.i_height,
380                      p_input->p_fmt->video.i_height );
381             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
382             break;
383
384         case VLC_FOURCC( 't', 'h', 'e', 'o' ):
385             msg_Dbg( p_mux, "theora stream" );
386             break;
387
388         default:
389             FREENULL( p_input->p_sys );
390             return VLC_EGENERIC;
391         }
392         break;
393
394     case AUDIO_ES:
395         switch( p_stream->i_fourcc )
396         {
397         case VLC_FOURCC( 'v', 'o', 'r', 'b' ):
398             msg_Dbg( p_mux, "vorbis stream" );
399             break;
400
401         case VLC_FOURCC( 's', 'p', 'x', ' ' ):
402             msg_Dbg( p_mux, "speex stream" );
403             break;
404
405         case VLC_FOURCC( 'f', 'l', 'a', 'c' ):
406             msg_Dbg( p_mux, "flac stream" );
407             break;
408
409         default:
410             fourcc_to_wf_tag( p_stream->i_fourcc, &i_tag );
411             if( i_tag == WAVE_FORMAT_UNKNOWN )
412             {
413                 FREENULL( p_input->p_sys );
414                 return VLC_EGENERIC;
415             }
416
417             p_stream->p_oggds_header =
418                 malloc( sizeof(oggds_header_t) + p_input->p_fmt->i_extra );
419             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
420             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
421
422             SetDWLE( &p_stream->p_oggds_header->i_size,
423                      sizeof( oggds_header_t ) - 1 + p_input->p_fmt->i_extra );
424
425             if( p_input->p_fmt->i_extra )
426             {
427                 memcpy( &p_stream->p_oggds_header[1],
428                         p_input->p_fmt->p_extra, p_input->p_fmt->i_extra );
429             }
430
431             memcpy( p_stream->p_oggds_header->stream_type, "audio", 5 );
432
433             memset( p_stream->p_oggds_header->sub_type, 0, 4 );
434             sprintf( p_stream->p_oggds_header->sub_type, "%-x", i_tag );
435
436             SetQWLE( &p_stream->p_oggds_header->i_time_unit, I64C(10000000) );
437             SetDWLE( &p_stream->p_oggds_header->i_default_len, 1 );
438             SetDWLE( &p_stream->p_oggds_header->i_buffer_size, 30*1024 );
439             SetQWLE( &p_stream->p_oggds_header->i_samples_per_unit,
440                      p_input->p_fmt->audio.i_rate );
441             SetWLE( &p_stream->p_oggds_header->i_bits_per_sample,
442                     p_input->p_fmt->audio.i_bitspersample );
443             SetDWLE( &p_stream->p_oggds_header->header.audio.i_channels,
444                      p_input->p_fmt->audio.i_channels );
445             SetDWLE( &p_stream->p_oggds_header->header.audio.i_block_align,
446                      p_input->p_fmt->audio.i_blockalign );
447             SetDWLE( &p_stream->p_oggds_header->header.audio.i_avgbytespersec,
448                      p_input->p_fmt->i_bitrate / 8);
449             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
450             break;
451         }
452         break;
453
454     case SPU_ES:
455         switch( p_stream->i_fourcc )
456         {
457         case VLC_FOURCC( 's', 'u','b', 't' ):
458             p_stream->p_oggds_header = malloc( sizeof(oggds_header_t) );
459             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
460             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
461
462             memcpy( p_stream->p_oggds_header->stream_type, "text", 4 );
463             msg_Dbg( p_mux, "subtitles stream" );
464             break;
465
466         default:
467             FREENULL( p_input->p_sys );
468             return VLC_EGENERIC;
469         }
470         break;
471     default:
472         FREENULL( p_input->p_sys );
473         return VLC_EGENERIC;
474     }
475
476     p_stream->b_new = VLC_TRUE;
477
478     p_sys->i_add_streams++;
479
480     return VLC_SUCCESS;
481 }
482
483 /*****************************************************************************
484  * DelStream: Delete an elementary stream from the muxed stream
485  *****************************************************************************/
486 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
487 {
488     sout_mux_sys_t *p_sys  = p_mux->p_sys;
489     ogg_stream_t   *p_stream = (ogg_stream_t*)p_input->p_sys;
490     block_t *p_og;
491
492     msg_Dbg( p_mux, "removing input" );
493
494     /* flush all remaining data */
495     if( p_input->p_sys )
496     {
497         if( !p_stream->b_new )
498         {
499             while( p_input->p_fifo->i_depth ) MuxBlock( p_mux, p_input );
500         }
501
502         if( !p_stream->b_new &&
503             ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
504         {
505             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
506             sout_AccessOutWrite( p_mux->p_access, p_og );
507         }
508
509         /* move input in delete queue */
510         if( !p_stream->b_new )
511         {
512             p_sys->pp_del_streams = realloc( p_sys->pp_del_streams,
513                                              (p_sys->i_del_streams + 1) *
514                                              sizeof(ogg_stream_t *) );
515             p_sys->pp_del_streams[p_sys->i_del_streams++] = p_stream;
516         }
517         else
518         {
519             /* wasn't already added so get rid of it */
520             FREENULL( p_stream->p_oggds_header );
521             FREENULL( p_stream );
522             p_sys->i_add_streams--;
523         }
524     }
525
526     p_input->p_sys = NULL;
527
528     return 0;
529 }
530
531 /*****************************************************************************
532  * Ogg bitstream manipulation routines
533  *****************************************************************************/
534 static block_t *OggStreamFlush( sout_mux_t *p_mux,
535                                 ogg_stream_state *p_os, mtime_t i_pts )
536 {
537     block_t *p_og, *p_og_first = NULL;
538     ogg_page og;
539
540     while( ogg_stream_flush( p_os, &og ) )
541     {
542         /* Flush all data */
543         p_og = block_New( p_mux, og.header_len + og.body_len );
544
545         memcpy( p_og->p_buffer, og.header, og.header_len );
546         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
547         p_og->i_dts     = 0;
548         p_og->i_pts     = i_pts;
549         p_og->i_length  = 0;
550
551         i_pts = 0; // write it only once
552
553         block_ChainAppend( &p_og_first, p_og );
554     }
555
556     return p_og_first;
557 }
558
559 static block_t *OggStreamPageOut( sout_mux_t *p_mux,
560                                   ogg_stream_state *p_os, mtime_t i_pts )
561 {
562     block_t *p_og, *p_og_first = NULL;
563     ogg_page og;
564
565     while( ogg_stream_pageout( p_os, &og ) )
566     {
567         /* Flush all data */
568         p_og = block_New( p_mux, og.header_len + og.body_len );
569
570         memcpy( p_og->p_buffer, og.header, og.header_len );
571         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
572         p_og->i_dts     = 0;
573         p_og->i_pts     = i_pts;
574         p_og->i_length  = 0;
575
576         i_pts = 0; // write them only once
577
578         block_ChainAppend( &p_og_first, p_og );
579     }
580
581     return p_og_first;
582 }
583
584 static block_t *OggCreateHeader( sout_mux_t *p_mux, mtime_t i_dts )
585 {
586     block_t *p_hdr = NULL;
587     block_t *p_og = NULL;
588     ogg_packet op;
589     uint8_t *p_extra;
590     int i, i_extra;
591
592     /* Write header for each stream. All b_o_s (beginning of stream) packets
593      * must appear first in the ogg stream so we take care of them first. */
594     for( i = 0; i < p_mux->i_nb_inputs; i++ )
595     {
596         sout_input_t *p_input = p_mux->pp_inputs[i];
597         ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
598         p_stream->b_new = VLC_FALSE;
599
600         msg_Dbg( p_mux, "creating header for %4.4s",
601                  (char *)&p_stream->i_fourcc );
602
603         ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
604         p_stream->i_packet_no = 0;
605
606         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
607             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
608             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
609         {
610             /* First packet in order: vorbis/speex/theora info */
611             p_extra = p_input->p_fmt->p_extra;
612             i_extra = p_input->p_fmt->i_extra;
613
614             op.bytes = *(p_extra++) << 8;
615             op.bytes |= (*(p_extra++) & 0xFF);
616             op.packet = p_extra;
617             i_extra -= (op.bytes + 2);
618             if( i_extra < 0 )
619             {
620                 msg_Err( p_mux, "header data corrupted");
621                 op.bytes += i_extra;
622             }
623
624             op.b_o_s  = 1;
625             op.e_o_s  = 0;
626             op.granulepos = 0;
627             op.packetno = p_stream->i_packet_no++;
628             ogg_stream_packetin( &p_stream->os, &op );
629             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
630
631             /* Get keyframe_granule_shift for theora granulepos calculation */
632             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
633             {
634                 int i_keyframe_frequency_force =
635                       1 << ((op.packet[40] << 6 >> 3) | (op.packet[41] >> 5));
636
637                 /* granule_shift = i_log( frequency_force -1 ) */
638                 p_stream->i_keyframe_granule_shift = 0;
639                 i_keyframe_frequency_force--;
640                 while( i_keyframe_frequency_force )
641                 {
642                     p_stream->i_keyframe_granule_shift++;
643                     i_keyframe_frequency_force >>= 1;
644                 }
645             }
646         }
647         else if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
648         {
649             /* flac stream marker (yeah, only that in the 1st packet) */
650             op.packet = (unsigned char *)"fLaC";
651             op.bytes  = 4;
652             op.b_o_s  = 1;
653             op.e_o_s  = 0;
654             op.granulepos = 0;
655             op.packetno = p_stream->i_packet_no++;
656             ogg_stream_packetin( &p_stream->os, &op );
657             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
658         }
659         else if( p_stream->p_oggds_header )
660         {
661             /* ds header */
662             op.packet = (uint8_t*)p_stream->p_oggds_header;
663             op.bytes  = p_stream->p_oggds_header->i_size + 1;
664             op.b_o_s  = 1;
665             op.e_o_s  = 0;
666             op.granulepos = 0;
667             op.packetno = p_stream->i_packet_no++;
668             ogg_stream_packetin( &p_stream->os, &op );
669             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
670         }
671
672         block_ChainAppend( &p_hdr, p_og );
673     }
674
675     /* Take care of the non b_o_s headers */
676     for( i = 0; i < p_mux->i_nb_inputs; i++ )
677     {
678         sout_input_t *p_input = p_mux->pp_inputs[i];
679         ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
680
681         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
682             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
683             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
684         {
685             /* Special case, headers are already there in the incoming stream.
686              * We need to gather them an mark them as headers. */
687             int j = 2;
688
689             if( p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ) j = 1;
690
691             p_extra = p_input->p_fmt->p_extra;
692             i_extra = p_input->p_fmt->i_extra;
693
694             /* Skip 1 header */
695             op.bytes = *(p_extra++) << 8;
696             op.bytes |= (*(p_extra++) & 0xFF);
697             op.packet = p_extra;
698             p_extra += op.bytes;
699             i_extra -= (op.bytes + 2);
700
701             while( j-- )
702             {
703                 op.bytes = *(p_extra++) << 8;
704                 op.bytes |= (*(p_extra++) & 0xFF);
705                 op.packet = p_extra;
706                 p_extra += op.bytes;
707                 i_extra -= (op.bytes + 2);
708                 if( i_extra < 0 )
709                 {
710                     msg_Err( p_mux, "header data corrupted");
711                     op.bytes += i_extra;
712                 }
713
714                 op.b_o_s  = 0;
715                 op.e_o_s  = 0;
716                 op.granulepos = 0;
717                 op.packetno = p_stream->i_packet_no++;
718                 ogg_stream_packetin( &p_stream->os, &op );
719
720                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
721                 block_ChainAppend( &p_hdr, p_og );
722             }
723         }
724         else if( p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
725         {
726             uint8_t com[128];
727             int     i_com;
728
729             /* comment */
730             com[0] = PACKET_TYPE_COMMENT;
731             i_com = snprintf( (char *)(com+1), 127,
732                               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                 FREENULL( p_sys->pp_del_streams[i]->p_oggds_header );
893                 FREENULL( p_sys->pp_del_streams[i] );
894             }
895             FREENULL( 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 }