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