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