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