]> git.sesse.net Git - vlc/blob - modules/mux/ogg.c
2f2310681d65cab9c44ad1c8dd750b782b40c28d
[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_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.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( N_("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 * );
68 static block_t *OggCreateFooter( sout_mux_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 = 0;
136     int     i_stream = -1;
137
138     for( int i = 0; 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             block_FifoCount( p_fifo ) == 0 ) continue;
147
148         if( block_FifoCount( p_fifo ) )
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     int     i_last_keyframe; /* dirac and theora */
183     int     i_num_frames; /* Theora only */
184     uint64_t u_last_granulepos; /* Used for correct EOS page */
185     int64_t i_num_keyframes;
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     if( !p_sys )
222         return VLC_ENOMEM;
223     p_sys->i_streams      = 0;
224     p_sys->i_add_streams  = 0;
225     p_sys->i_del_streams  = 0;
226     p_sys->pp_del_streams = 0;
227
228     p_mux->p_sys        = p_sys;
229     p_mux->pf_control   = Control;
230     p_mux->pf_addstream = AddStream;
231     p_mux->pf_delstream = DelStream;
232     p_mux->pf_mux       = Mux;
233
234     /* First serial number is random.
235      * (Done like this because on win32 you need to seed the random number
236      *  generator once per thread). */
237     srand( (unsigned int)time( NULL ) );
238     p_sys->i_next_serial_no = rand();
239
240     return VLC_SUCCESS;
241 }
242
243 /*****************************************************************************
244  * Close: Finalize ogg bitstream and close muxer
245  *****************************************************************************/
246 static void Close( vlc_object_t * p_this )
247 {
248     sout_mux_t     *p_mux = (sout_mux_t*)p_this;
249     sout_mux_sys_t *p_sys = p_mux->p_sys;
250
251     msg_Info( p_mux, "Close" );
252
253     if( p_sys->i_del_streams )
254     {
255         block_t *p_og = NULL;
256         mtime_t i_dts = p_sys->pp_del_streams[p_sys->i_del_streams - 1]->i_dts;
257
258         /* Close the current ogg stream */
259         msg_Dbg( p_mux, "writing footer" );
260         block_ChainAppend( &p_og, OggCreateFooter( p_mux ) );
261
262         /* Remove deleted logical streams */
263         for(int i = 0; i < p_sys->i_del_streams; i++ )
264         {
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 = calloc( 1, sizeof( ogg_stream_t ) );
322     if( !p_stream )
323         return VLC_ENOMEM;
324
325     p_stream->i_cat       = p_input->p_fmt->i_cat;
326     p_stream->i_fourcc    = p_input->p_fmt->i_codec;
327     p_stream->i_serial_no = p_sys->i_next_serial_no++;
328     p_stream->i_packet_no = 0;
329     p_stream->i_last_keyframe = 0;
330     p_stream->i_num_keyframes = 0;
331     p_stream->i_num_frames = 0;
332
333     p_stream->p_oggds_header = 0;
334
335     switch( p_input->p_fmt->i_cat )
336     {
337     case VIDEO_ES:
338         if( !p_input->p_fmt->video.i_frame_rate ||
339             !p_input->p_fmt->video.i_frame_rate_base )
340         {
341             msg_Warn( p_mux, "Missing frame rate, assuming 25fps" );
342             p_input->p_fmt->video.i_frame_rate = 25;
343             p_input->p_fmt->video.i_frame_rate_base = 1;
344         }
345
346         switch( p_stream->i_fourcc )
347         {
348         case VLC_CODEC_MP4V:
349         case VLC_CODEC_MPGV:
350         case VLC_CODEC_DIV3:
351         case VLC_CODEC_MJPG:
352         case VLC_CODEC_WMV1:
353         case VLC_CODEC_WMV2:
354         case VLC_CODEC_WMV3:
355         case VLC_CODEC_SNOW:
356             p_stream->p_oggds_header = calloc( 1, sizeof(oggds_header_t) );
357             if( !p_stream->p_oggds_header )
358             {
359                 free( p_stream );
360                 return VLC_ENOMEM;
361             }
362             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
363
364             memcpy( p_stream->p_oggds_header->stream_type, "video", 5 );
365             if( p_stream->i_fourcc == VLC_CODEC_MP4V )
366             {
367                 memcpy( p_stream->p_oggds_header->sub_type, "XVID", 4 );
368             }
369             else if( p_stream->i_fourcc == VLC_CODEC_DIV3 )
370             {
371                 memcpy( p_stream->p_oggds_header->sub_type, "DIV3", 4 );
372             }
373             else
374             {
375                 memcpy( p_stream->p_oggds_header->sub_type,
376                         &p_stream->i_fourcc, 4 );
377             }
378             SetDWLE( &p_stream->p_oggds_header->i_size,
379                      sizeof( oggds_header_t ) - 1 );
380             SetQWLE( &p_stream->p_oggds_header->i_time_unit,
381                      INT64_C(10000000) * p_input->p_fmt->video.i_frame_rate_base /
382                      (int64_t)p_input->p_fmt->video.i_frame_rate );
383             SetQWLE( &p_stream->p_oggds_header->i_samples_per_unit, 1 );
384             SetDWLE( &p_stream->p_oggds_header->i_default_len, 1 ); /* ??? */
385             SetDWLE( &p_stream->p_oggds_header->i_buffer_size, 1024*1024 );
386             SetWLE( &p_stream->p_oggds_header->i_bits_per_sample, 0 );
387             SetDWLE( &p_stream->p_oggds_header->header.video.i_width,
388                      p_input->p_fmt->video.i_width );
389             SetDWLE( &p_stream->p_oggds_header->header.video.i_height,
390                      p_input->p_fmt->video.i_height );
391             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
392             break;
393
394         case VLC_CODEC_DIRAC:
395             msg_Dbg( p_mux, "dirac stream" );
396             break;
397
398         case VLC_CODEC_THEORA:
399             msg_Dbg( p_mux, "theora stream" );
400             break;
401
402         default:
403             FREENULL( p_input->p_sys );
404             return VLC_EGENERIC;
405         }
406         break;
407
408     case AUDIO_ES:
409         switch( p_stream->i_fourcc )
410         {
411         case VLC_CODEC_VORBIS:
412             msg_Dbg( p_mux, "vorbis stream" );
413             break;
414
415         case VLC_CODEC_SPEEX:
416             msg_Dbg( p_mux, "speex stream" );
417             break;
418
419         case VLC_CODEC_FLAC:
420             msg_Dbg( p_mux, "flac stream" );
421             break;
422
423         default:
424             fourcc_to_wf_tag( p_stream->i_fourcc, &i_tag );
425             if( i_tag == WAVE_FORMAT_UNKNOWN )
426             {
427                 FREENULL( p_input->p_sys );
428                 return VLC_EGENERIC;
429             }
430
431             p_stream->p_oggds_header =
432                 malloc( sizeof(oggds_header_t) + p_input->p_fmt->i_extra );
433             if( !p_stream->p_oggds_header )
434             {
435                 free( p_stream );
436                 return VLC_ENOMEM;
437             }
438             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
439             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
440
441             SetDWLE( &p_stream->p_oggds_header->i_size,
442                      sizeof( oggds_header_t ) - 1 + p_input->p_fmt->i_extra );
443
444             if( p_input->p_fmt->i_extra )
445             {
446                 memcpy( &p_stream->p_oggds_header[1],
447                         p_input->p_fmt->p_extra, p_input->p_fmt->i_extra );
448             }
449
450             memcpy( p_stream->p_oggds_header->stream_type, "audio", 5 );
451
452             memset( p_stream->p_oggds_header->sub_type, 0, 4 );
453             sprintf( p_stream->p_oggds_header->sub_type, "%-x", i_tag );
454
455             SetQWLE( &p_stream->p_oggds_header->i_time_unit, INT64_C(10000000) );
456             SetDWLE( &p_stream->p_oggds_header->i_default_len, 1 );
457             SetDWLE( &p_stream->p_oggds_header->i_buffer_size, 30*1024 );
458             SetQWLE( &p_stream->p_oggds_header->i_samples_per_unit,
459                      p_input->p_fmt->audio.i_rate );
460             SetWLE( &p_stream->p_oggds_header->i_bits_per_sample,
461                     p_input->p_fmt->audio.i_bitspersample );
462             SetDWLE( &p_stream->p_oggds_header->header.audio.i_channels,
463                      p_input->p_fmt->audio.i_channels );
464             SetDWLE( &p_stream->p_oggds_header->header.audio.i_block_align,
465                      p_input->p_fmt->audio.i_blockalign );
466             SetDWLE( &p_stream->p_oggds_header->header.audio.i_avgbytespersec,
467                      p_input->p_fmt->i_bitrate / 8);
468             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
469             break;
470         }
471         break;
472
473     case SPU_ES:
474         switch( p_stream->i_fourcc )
475         {
476         case VLC_CODEC_SUBT:
477             p_stream->p_oggds_header = calloc( 1, sizeof(oggds_header_t) );
478             if( !p_stream->p_oggds_header )
479             {
480                 free( p_stream );
481                 return VLC_ENOMEM;
482             }
483             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
484
485             memcpy( p_stream->p_oggds_header->stream_type, "text", 4 );
486             msg_Dbg( p_mux, "subtitles stream" );
487             break;
488
489         default:
490             FREENULL( p_input->p_sys );
491             return VLC_EGENERIC;
492         }
493         break;
494     default:
495         FREENULL( p_input->p_sys );
496         return VLC_EGENERIC;
497     }
498
499     p_stream->b_new = true;
500
501     p_sys->i_add_streams++;
502
503     return VLC_SUCCESS;
504 }
505
506 /*****************************************************************************
507  * DelStream: Delete an elementary stream from the muxed stream
508  *****************************************************************************/
509 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
510 {
511     sout_mux_sys_t *p_sys  = p_mux->p_sys;
512     ogg_stream_t   *p_stream = (ogg_stream_t*)p_input->p_sys;
513     block_t *p_og;
514
515     msg_Dbg( p_mux, "removing input" );
516
517     /* flush all remaining data */
518     if( p_input->p_sys )
519     {
520         if( !p_stream->b_new )
521         {
522             while( block_FifoCount( p_input->p_fifo ) )
523                 MuxBlock( p_mux, p_input );
524         }
525
526         if( !p_stream->b_new &&
527             ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
528         {
529             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
530             sout_AccessOutWrite( p_mux->p_access, p_og );
531         }
532
533         /* move input in delete queue */
534         if( !p_stream->b_new )
535         {
536             p_sys->pp_del_streams = xrealloc( p_sys->pp_del_streams,
537                         (p_sys->i_del_streams + 1) * sizeof(ogg_stream_t *) );
538             p_sys->pp_del_streams[p_sys->i_del_streams++] = p_stream;
539         }
540         else
541         {
542             /* wasn't already added so get rid of it */
543             FREENULL( p_stream->p_oggds_header );
544             FREENULL( p_stream );
545             p_sys->i_add_streams--;
546         }
547     }
548
549     p_input->p_sys = NULL;
550
551     return 0;
552 }
553
554 /*****************************************************************************
555  * Ogg bitstream manipulation routines
556  *****************************************************************************/
557 static block_t *OggStreamGetPage( sout_mux_t *p_mux,
558                                   ogg_stream_state *p_os, mtime_t i_pts,
559                                   bool flush )
560 {
561     (void)p_mux;
562     block_t *p_og, *p_og_first = NULL;
563     ogg_page og;
564     int (*pager)( ogg_stream_state*, ogg_page* ) = flush ? ogg_stream_flush : ogg_stream_pageout;
565
566     while( pager( p_os, &og ) )
567     {
568         /* Flush all data */
569         p_og = block_New( p_mux, og.header_len + og.body_len );
570
571         memcpy( p_og->p_buffer, og.header, og.header_len );
572         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
573         p_og->i_dts     = 0;
574         p_og->i_pts     = i_pts;
575         p_og->i_length  = 0;
576
577         i_pts = 0; // write it only once
578
579         block_ChainAppend( &p_og_first, p_og );
580     }
581
582     return p_og_first;
583 }
584
585 static block_t *OggStreamFlush( sout_mux_t *p_mux,
586                                 ogg_stream_state *p_os, mtime_t i_pts )
587 {
588     return OggStreamGetPage( p_mux, p_os, i_pts, true );
589 }
590
591 static block_t *OggStreamPageOut( sout_mux_t *p_mux,
592                                   ogg_stream_state *p_os, mtime_t i_pts )
593 {
594     return OggStreamGetPage( p_mux, p_os, i_pts, false );
595 }
596
597 static block_t *OggCreateHeader( sout_mux_t *p_mux )
598 {
599     block_t *p_hdr = NULL;
600     block_t *p_og = NULL;
601     ogg_packet op;
602     uint8_t *p_extra;
603     int i, i_extra;
604
605     /* Write header for each stream. All b_o_s (beginning of stream) packets
606      * must appear first in the ogg stream so we take care of them first. */
607     for( int pass = 0; pass < 2; pass++ )
608     {
609         for( i = 0; i < p_mux->i_nb_inputs; i++ )
610         {
611             sout_input_t *p_input = p_mux->pp_inputs[i];
612             ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
613
614             bool video = ( p_stream->i_fourcc == VLC_CODEC_THEORA || p_stream->i_fourcc == VLC_CODEC_DIRAC );
615             if( ( ( pass == 0 && !video ) || ( pass == 1 && video ) ) )
616                 continue;
617
618             msg_Dbg( p_mux, "creating header for %4.4s",
619                      (char *)&p_stream->i_fourcc );
620
621             ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
622             p_stream->b_new = false;
623             p_stream->i_packet_no = 0;
624
625             if( p_stream->i_fourcc == VLC_CODEC_VORBIS ||
626                 p_stream->i_fourcc == VLC_CODEC_SPEEX ||
627                 p_stream->i_fourcc == VLC_CODEC_THEORA )
628             {
629                 /* First packet in order: vorbis/speex/theora info */
630                 p_extra = p_input->p_fmt->p_extra;
631                 i_extra = p_input->p_fmt->i_extra;
632
633                 op.bytes = *(p_extra++) << 8;
634                 op.bytes |= (*(p_extra++) & 0xFF);
635                 op.packet = p_extra;
636                 i_extra -= (op.bytes + 2);
637                 if( i_extra < 0 )
638                 {
639                     msg_Err( p_mux, "header data corrupted");
640                     op.bytes += i_extra;
641                 }
642
643                 op.b_o_s  = 1;
644                 op.e_o_s  = 0;
645                 op.granulepos = 0;
646                 op.packetno = p_stream->i_packet_no++;
647                 ogg_stream_packetin( &p_stream->os, &op );
648                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
649
650                 /* Get keyframe_granule_shift for theora granulepos calculation */
651                 if( p_stream->i_fourcc == VLC_CODEC_THEORA )
652                 {
653                     p_stream->i_keyframe_granule_shift =
654                         ( (op.packet[40] & 0x03) << 3 ) | ( (op.packet[41] & 0xe0) >> 5 );
655                 }
656             }
657             else if( p_stream->i_fourcc == VLC_CODEC_DIRAC )
658             {
659                 op.packet = p_input->p_fmt->p_extra;
660                 op.bytes  = p_input->p_fmt->i_extra;
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             else if( p_stream->i_fourcc == VLC_CODEC_FLAC )
669             {
670                 /* flac stream marker (yeah, only that in the 1st packet) */
671                 op.packet = (unsigned char *)"fLaC";
672                 op.bytes  = 4;
673                 op.b_o_s  = 1;
674                 op.e_o_s  = 0;
675                 op.granulepos = 0;
676                 op.packetno = p_stream->i_packet_no++;
677                 ogg_stream_packetin( &p_stream->os, &op );
678                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
679             }
680             else if( p_stream->p_oggds_header )
681             {
682                 /* ds header */
683                 op.packet = (uint8_t*)p_stream->p_oggds_header;
684                 op.bytes  = p_stream->p_oggds_header->i_size + 1;
685                 op.b_o_s  = 1;
686                 op.e_o_s  = 0;
687                 op.granulepos = 0;
688                 op.packetno = p_stream->i_packet_no++;
689                 ogg_stream_packetin( &p_stream->os, &op );
690                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
691             }
692
693             block_ChainAppend( &p_hdr, p_og );
694         }
695     }
696
697     /* Take care of the non b_o_s headers */
698     for( i = 0; i < p_mux->i_nb_inputs; i++ )
699     {
700         sout_input_t *p_input = p_mux->pp_inputs[i];
701         ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
702
703         if( p_stream->i_fourcc == VLC_CODEC_VORBIS ||
704             p_stream->i_fourcc == VLC_CODEC_SPEEX ||
705             p_stream->i_fourcc == VLC_CODEC_THEORA )
706         {
707             /* Special case, headers are already there in the incoming stream.
708              * We need to gather them an mark them as headers. */
709             int j = 2;
710
711             if( p_stream->i_fourcc == VLC_CODEC_SPEEX ) j = 1;
712
713             p_extra = p_input->p_fmt->p_extra;
714             i_extra = p_input->p_fmt->i_extra;
715
716             /* Skip 1 header */
717             op.bytes = *(p_extra++) << 8;
718             op.bytes |= (*(p_extra++) & 0xFF);
719             op.packet = p_extra;
720             p_extra += op.bytes;
721             i_extra -= (op.bytes + 2);
722
723             while( j-- )
724             {
725                 op.bytes = *(p_extra++) << 8;
726                 op.bytes |= (*(p_extra++) & 0xFF);
727                 op.packet = p_extra;
728                 p_extra += op.bytes;
729                 i_extra -= (op.bytes + 2);
730                 if( i_extra < 0 )
731                 {
732                     msg_Err( p_mux, "header data corrupted");
733                     op.bytes += i_extra;
734                 }
735
736                 op.b_o_s  = 0;
737                 op.e_o_s  = 0;
738                 op.granulepos = 0;
739                 op.packetno = p_stream->i_packet_no++;
740                 ogg_stream_packetin( &p_stream->os, &op );
741
742                 if( j == 0 )
743                     p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
744                 else
745                     p_og = OggStreamPageOut( p_mux, &p_stream->os, 0 );
746                 if( p_og )
747                     block_ChainAppend( &p_hdr, p_og );
748             }
749         }
750         else if( p_stream->i_fourcc != VLC_CODEC_FLAC &&
751                  p_stream->i_fourcc != VLC_CODEC_DIRAC )
752         {
753             uint8_t com[128];
754             int     i_com;
755
756             /* comment */
757             com[0] = PACKET_TYPE_COMMENT;
758             i_com = snprintf( (char *)(com+1), 127,
759                               PACKAGE_VERSION" stream output" )
760                      + 1;
761             op.packet = com;
762             op.bytes  = i_com;
763             op.b_o_s  = 0;
764             op.e_o_s  = 0;
765             op.granulepos = 0;
766             op.packetno = p_stream->i_packet_no++;
767             ogg_stream_packetin( &p_stream->os, &op );
768             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
769             block_ChainAppend( &p_hdr, p_og );
770         }
771
772         /* Special case for mp4v and flac */
773         if( ( p_stream->i_fourcc == VLC_CODEC_MP4V ||
774               p_stream->i_fourcc == VLC_CODEC_FLAC ) &&
775             p_input->p_fmt->i_extra )
776         {
777             /* Send a packet with the VOL data for mp4v
778              * or STREAMINFO for flac */
779             msg_Dbg( p_mux, "writing extra data" );
780             op.bytes  = p_input->p_fmt->i_extra;
781             op.packet = p_input->p_fmt->p_extra;
782             if( p_stream->i_fourcc == VLC_CODEC_FLAC )
783             {
784                 /* Skip the flac stream marker */
785                 op.bytes -= 4;
786                 op.packet+= 4;
787             }
788             op.b_o_s  = 0;
789             op.e_o_s  = 0;
790             op.granulepos = 0;
791             op.packetno = p_stream->i_packet_no++;
792             ogg_stream_packetin( &p_stream->os, &op );
793             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
794             block_ChainAppend( &p_hdr, p_og );
795         }
796     }
797
798     /* set HEADER flag */
799     for( p_og = p_hdr; p_og != NULL; p_og = p_og->p_next )
800     {
801         p_og->i_flags |= BLOCK_FLAG_HEADER;
802     }
803     return p_hdr;
804 }
805
806 static block_t *OggCreateFooter( sout_mux_t *p_mux )
807 {
808     sout_mux_sys_t *p_sys = p_mux->p_sys;
809     block_t *p_hdr = NULL;
810     block_t *p_og;
811     ogg_packet    op;
812     int     i;
813
814     /* flush all remaining data */
815     for( i = 0; i < p_mux->i_nb_inputs; i++ )
816     {
817         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
818
819         /* skip newly added streams */
820         if( p_stream->b_new ) continue;
821
822         if( ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
823         {
824             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
825             sout_AccessOutWrite( p_mux->p_access, p_og );
826         }
827     }
828
829     /* Write eos packets for each stream. */
830     for( i = 0; i < p_mux->i_nb_inputs; i++ )
831     {
832         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
833
834         /* skip newly added streams */
835         if( p_stream->b_new ) continue;
836
837         op.packet = NULL;
838         op.bytes  = 0;
839         op.b_o_s  = 0;
840         op.e_o_s  = 1;
841         op.granulepos = p_stream->u_last_granulepos;
842         op.packetno = p_stream->i_packet_no++;
843         ogg_stream_packetin( &p_stream->os, &op );
844
845         p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
846         block_ChainAppend( &p_hdr, p_og );
847         ogg_stream_clear( &p_stream->os );
848     }
849
850     for( i = 0; i < p_sys->i_del_streams; i++ )
851     {
852         op.packet = NULL;
853         op.bytes  = 0;
854         op.b_o_s  = 0;
855         op.e_o_s  = 1;
856         op.granulepos = p_sys->pp_del_streams[i]->u_last_granulepos;
857         op.packetno = p_sys->pp_del_streams[i]->i_packet_no++;
858         ogg_stream_packetin( &p_sys->pp_del_streams[i]->os, &op );
859
860         p_og = OggStreamFlush( p_mux, &p_sys->pp_del_streams[i]->os, 0 );
861         block_ChainAppend( &p_hdr, p_og );
862         ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
863     }
864
865     return p_hdr;
866 }
867
868 static void OggSetDate( block_t *p_og, mtime_t i_dts, mtime_t i_length )
869 {
870     int i_count;
871     block_t *p_tmp;
872     mtime_t i_delta;
873
874     for( p_tmp = p_og, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->p_next )
875     {
876         i_count++;
877     }
878
879     if( i_count == 0 ) return; /* ignore. */
880
881     i_delta = i_length / i_count;
882
883     for( p_tmp = p_og; p_tmp != NULL; p_tmp = p_tmp->p_next )
884     {
885         p_tmp->i_dts    = i_dts;
886         p_tmp->i_length = i_delta;
887
888         i_dts += i_delta;
889     }
890 }
891
892 /*****************************************************************************
893  * Mux: multiplex available data in input fifos into the Ogg bitstream
894  *****************************************************************************/
895 static int Mux( sout_mux_t *p_mux )
896 {
897     sout_mux_sys_t *p_sys = p_mux->p_sys;
898     block_t        *p_og = NULL;
899     int            i_stream;
900     mtime_t        i_dts;
901
902     if( p_sys->i_add_streams || p_sys->i_del_streams )
903     {
904         /* Open new ogg stream */
905         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
906         {
907             msg_Dbg( p_mux, "waiting for data..." );
908             return VLC_SUCCESS;
909         }
910
911         if( p_sys->i_streams )
912         {
913             /* Close current ogg stream */
914             int i;
915
916             msg_Dbg( p_mux, "writing footer" );
917             block_ChainAppend( &p_og, OggCreateFooter( p_mux ) );
918
919             /* Remove deleted logical streams */
920             for( i = 0; i < p_sys->i_del_streams; i++ )
921             {
922                 FREENULL( p_sys->pp_del_streams[i]->p_oggds_header );
923                 FREENULL( p_sys->pp_del_streams[i] );
924             }
925             FREENULL( p_sys->pp_del_streams );
926             p_sys->i_streams = 0;
927         }
928
929         msg_Dbg( p_mux, "writing header" );
930         p_sys->i_start_dts = i_dts;
931         p_sys->i_streams = p_mux->i_nb_inputs;
932         p_sys->i_del_streams = 0;
933         p_sys->i_add_streams = 0;
934         block_ChainAppend( &p_og, OggCreateHeader( p_mux ) );
935
936         /* Write header and/or footer */
937         OggSetDate( p_og, i_dts, 0 );
938         sout_AccessOutWrite( p_mux->p_access, p_og );
939         p_og = NULL;
940     }
941
942     for( ;; )
943     {
944         if( MuxGetStream( p_mux, &i_stream, 0 ) < 0 ) return VLC_SUCCESS;
945         MuxBlock( p_mux, p_mux->pp_inputs[i_stream] );
946     }
947
948     return VLC_SUCCESS;
949 }
950
951 static int MuxBlock( sout_mux_t *p_mux, sout_input_t *p_input )
952 {
953     sout_mux_sys_t *p_sys = p_mux->p_sys;
954     ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
955     block_t *p_data = block_FifoGet( p_input->p_fifo );
956     block_t *p_og = NULL;
957     ogg_packet op;
958
959     if( p_stream->i_fourcc != VLC_CODEC_VORBIS &&
960         p_stream->i_fourcc != VLC_CODEC_FLAC &&
961         p_stream->i_fourcc != VLC_CODEC_SPEEX &&
962         p_stream->i_fourcc != VLC_CODEC_THEORA &&
963         p_stream->i_fourcc != VLC_CODEC_DIRAC )
964     {
965         p_data = block_Realloc( p_data, 1, p_data->i_buffer );
966         p_data->p_buffer[0] = PACKET_IS_SYNCPOINT;      // FIXME
967     }
968
969     op.packet   = p_data->p_buffer;
970     op.bytes    = p_data->i_buffer;
971     op.b_o_s    = 0;
972     op.e_o_s    = 0;
973     op.packetno = p_stream->i_packet_no++;
974
975     if( p_stream->i_cat == AUDIO_ES )
976     {
977         if( p_stream->i_fourcc == VLC_CODEC_VORBIS ||
978             p_stream->i_fourcc == VLC_CODEC_FLAC ||
979             p_stream->i_fourcc == VLC_CODEC_SPEEX )
980         {
981             /* number of sample from begining + current packet */
982             op.granulepos =
983                 ( p_data->i_dts - p_sys->i_start_dts + p_data->i_length ) *
984                 (mtime_t)p_input->p_fmt->audio.i_rate / INT64_C(1000000);
985         }
986         else if( p_stream->p_oggds_header )
987         {
988             /* number of sample from begining */
989             op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) *
990                 p_stream->p_oggds_header->i_samples_per_unit / INT64_C(1000000);
991         }
992     }
993     else if( p_stream->i_cat == VIDEO_ES )
994     {
995         if( p_stream->i_fourcc == VLC_CODEC_THEORA )
996         {
997             p_stream->i_num_frames++;
998             if( p_data->i_flags & BLOCK_FLAG_TYPE_I )
999             {
1000                 p_stream->i_num_keyframes++;
1001                 p_stream->i_last_keyframe = p_stream->i_num_frames;
1002             }
1003
1004             op.granulepos = (p_stream->i_last_keyframe << p_stream->i_keyframe_granule_shift )
1005                           | (p_stream->i_num_frames-p_stream->i_last_keyframe);
1006         }
1007         else if( p_stream->i_fourcc == VLC_CODEC_DIRAC )
1008         {
1009             mtime_t dt = (p_data->i_dts - p_sys->i_start_dts + 1)
1010                        * p_input->p_fmt->video.i_frame_rate *2
1011                        / p_input->p_fmt->video.i_frame_rate_base
1012                        / INT64_C(1000000);
1013             mtime_t delay = (p_data->i_pts - p_data->i_dts + 1)
1014                           * p_input->p_fmt->video.i_frame_rate *2
1015                           / p_input->p_fmt->video.i_frame_rate_base
1016                           / INT64_C(1000000);
1017             if( p_data->i_flags & BLOCK_FLAG_TYPE_I )
1018                 p_stream->i_last_keyframe = dt;
1019             mtime_t dist = dt - p_stream->i_last_keyframe;
1020             op.granulepos = dt << 31 | (dist&0xff00) << 14
1021                           | (delay&0x1fff) << 9 | (dist&0xff);
1022         }
1023         else if( p_stream->p_oggds_header )
1024             op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) * INT64_C(10) /
1025                 p_stream->p_oggds_header->i_time_unit;
1026     }
1027     else if( p_stream->i_cat == SPU_ES )
1028     {
1029         /* granulepos is in millisec */
1030         op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) / 1000;
1031     }
1032
1033     p_stream->u_last_granulepos = op.granulepos;
1034     ogg_stream_packetin( &p_stream->os, &op );
1035
1036     if( p_stream->i_cat == SPU_ES ||
1037         p_stream->i_fourcc == VLC_CODEC_SPEEX ||
1038         p_stream->i_fourcc == VLC_CODEC_DIRAC )
1039     {
1040         /* Subtitles or Speex packets are quite small so they
1041          * need to be flushed to be sent on time */
1042         /* The OggDirac mapping suggests ever so strongly that a
1043          * page flush occurs after each OggDirac packet, so to make
1044          * the timestamps unambiguous */
1045         p_og = OggStreamFlush( p_mux, &p_stream->os, p_data->i_dts );
1046     }
1047     else
1048     {
1049         p_og = OggStreamPageOut( p_mux, &p_stream->os, p_data->i_dts );
1050     }
1051
1052     if( p_og )
1053     {
1054         OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
1055         p_stream->i_dts = -1;
1056         p_stream->i_length = 0;
1057
1058         sout_AccessOutWrite( p_mux->p_access, p_og );
1059     }
1060     else
1061     {
1062         if( p_stream->i_dts < 0 )
1063         {
1064             p_stream->i_dts = p_data->i_dts;
1065         }
1066         p_stream->i_length += p_data->i_length;
1067     }
1068
1069     block_Release( p_data );
1070     return VLC_SUCCESS;
1071 }