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