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