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