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