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