]> git.sesse.net Git - vlc/blob - modules/mux/ogg.c
26ddeee4ca78e988d8e89e2634a857415052ff17
[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 = malloc( sizeof(oggds_header_t) );
358             if( !p_stream->p_oggds_header )
359             {
360                 free( p_stream );
361                 return VLC_ENOMEM;
362             }
363             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
364             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
365
366             memcpy( p_stream->p_oggds_header->stream_type, "video", 5 );
367             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) )
368             {
369                 memcpy( p_stream->p_oggds_header->sub_type, "XVID", 4 );
370             }
371             else if( p_stream->i_fourcc == VLC_FOURCC( 'D', 'I', 'V', '3' ) )
372             {
373                 memcpy( p_stream->p_oggds_header->sub_type, "DIV3", 4 );
374             }
375             else
376             {
377                 memcpy( p_stream->p_oggds_header->sub_type,
378                         &p_stream->i_fourcc, 4 );
379             }
380             SetDWLE( &p_stream->p_oggds_header->i_size,
381                      sizeof( oggds_header_t ) - 1 );
382             SetQWLE( &p_stream->p_oggds_header->i_time_unit,
383                      INT64_C(10000000) * p_input->p_fmt->video.i_frame_rate_base /
384                      (int64_t)p_input->p_fmt->video.i_frame_rate );
385             SetQWLE( &p_stream->p_oggds_header->i_samples_per_unit, 1 );
386             SetDWLE( &p_stream->p_oggds_header->i_default_len, 1 ); /* ??? */
387             SetDWLE( &p_stream->p_oggds_header->i_buffer_size, 1024*1024 );
388             SetWLE( &p_stream->p_oggds_header->i_bits_per_sample, 0 );
389             SetDWLE( &p_stream->p_oggds_header->header.video.i_width,
390                      p_input->p_fmt->video.i_width );
391             SetDWLE( &p_stream->p_oggds_header->header.video.i_height,
392                      p_input->p_fmt->video.i_height );
393             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
394             break;
395
396         case VLC_FOURCC( 'd', 'r', 'a', 'c' ):
397             msg_Dbg( p_mux, "dirac stream" );
398             break;
399
400         case VLC_FOURCC( 't', 'h', 'e', 'o' ):
401             msg_Dbg( p_mux, "theora stream" );
402             break;
403
404         default:
405             FREENULL( p_input->p_sys );
406             return VLC_EGENERIC;
407         }
408         break;
409
410     case AUDIO_ES:
411         switch( p_stream->i_fourcc )
412         {
413         case VLC_FOURCC( 'v', 'o', 'r', 'b' ):
414             msg_Dbg( p_mux, "vorbis stream" );
415             break;
416
417         case VLC_FOURCC( 's', 'p', 'x', ' ' ):
418             msg_Dbg( p_mux, "speex stream" );
419             break;
420
421         case VLC_FOURCC( 'f', 'l', 'a', 'c' ):
422             msg_Dbg( p_mux, "flac stream" );
423             break;
424
425         default:
426             fourcc_to_wf_tag( p_stream->i_fourcc, &i_tag );
427             if( i_tag == WAVE_FORMAT_UNKNOWN )
428             {
429                 FREENULL( p_input->p_sys );
430                 return VLC_EGENERIC;
431             }
432
433             p_stream->p_oggds_header =
434                 malloc( sizeof(oggds_header_t) + p_input->p_fmt->i_extra );
435             if( !p_stream->p_oggds_header )
436             {
437                 free( p_stream );
438                 return VLC_ENOMEM;
439             }
440             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
441             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
442
443             SetDWLE( &p_stream->p_oggds_header->i_size,
444                      sizeof( oggds_header_t ) - 1 + p_input->p_fmt->i_extra );
445
446             if( p_input->p_fmt->i_extra )
447             {
448                 memcpy( &p_stream->p_oggds_header[1],
449                         p_input->p_fmt->p_extra, p_input->p_fmt->i_extra );
450             }
451
452             memcpy( p_stream->p_oggds_header->stream_type, "audio", 5 );
453
454             memset( p_stream->p_oggds_header->sub_type, 0, 4 );
455             sprintf( p_stream->p_oggds_header->sub_type, "%-x", i_tag );
456
457             SetQWLE( &p_stream->p_oggds_header->i_time_unit, INT64_C(10000000) );
458             SetDWLE( &p_stream->p_oggds_header->i_default_len, 1 );
459             SetDWLE( &p_stream->p_oggds_header->i_buffer_size, 30*1024 );
460             SetQWLE( &p_stream->p_oggds_header->i_samples_per_unit,
461                      p_input->p_fmt->audio.i_rate );
462             SetWLE( &p_stream->p_oggds_header->i_bits_per_sample,
463                     p_input->p_fmt->audio.i_bitspersample );
464             SetDWLE( &p_stream->p_oggds_header->header.audio.i_channels,
465                      p_input->p_fmt->audio.i_channels );
466             SetDWLE( &p_stream->p_oggds_header->header.audio.i_block_align,
467                      p_input->p_fmt->audio.i_blockalign );
468             SetDWLE( &p_stream->p_oggds_header->header.audio.i_avgbytespersec,
469                      p_input->p_fmt->i_bitrate / 8);
470             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
471             break;
472         }
473         break;
474
475     case SPU_ES:
476         switch( p_stream->i_fourcc )
477         {
478         case VLC_FOURCC( 's', 'u','b', 't' ):
479             p_stream->p_oggds_header = malloc( sizeof(oggds_header_t) );
480             if( !p_stream->p_oggds_header )
481             {
482                 free( p_stream );
483                 return VLC_ENOMEM;
484             }
485             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
486             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
487
488             memcpy( p_stream->p_oggds_header->stream_type, "text", 4 );
489             msg_Dbg( p_mux, "subtitles stream" );
490             break;
491
492         default:
493             FREENULL( p_input->p_sys );
494             return VLC_EGENERIC;
495         }
496         break;
497     default:
498         FREENULL( p_input->p_sys );
499         return VLC_EGENERIC;
500     }
501
502     p_stream->b_new = true;
503
504     p_sys->i_add_streams++;
505
506     return VLC_SUCCESS;
507 }
508
509 /*****************************************************************************
510  * DelStream: Delete an elementary stream from the muxed stream
511  *****************************************************************************/
512 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
513 {
514     sout_mux_sys_t *p_sys  = p_mux->p_sys;
515     ogg_stream_t   *p_stream = (ogg_stream_t*)p_input->p_sys;
516     block_t *p_og;
517
518     msg_Dbg( p_mux, "removing input" );
519
520     /* flush all remaining data */
521     if( p_input->p_sys )
522     {
523         if( !p_stream->b_new )
524         {
525             while( block_FifoCount( p_input->p_fifo ) )
526                 MuxBlock( p_mux, p_input );
527         }
528
529         if( !p_stream->b_new &&
530             ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
531         {
532             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
533             sout_AccessOutWrite( p_mux->p_access, p_og );
534         }
535
536         /* move input in delete queue */
537         if( !p_stream->b_new )
538         {
539             p_sys->pp_del_streams = realloc( p_sys->pp_del_streams,
540                                              (p_sys->i_del_streams + 1) *
541                                              sizeof(ogg_stream_t *) );
542             p_sys->pp_del_streams[p_sys->i_del_streams++] = p_stream;
543         }
544         else
545         {
546             /* wasn't already added so get rid of it */
547             FREENULL( p_stream->p_oggds_header );
548             FREENULL( p_stream );
549             p_sys->i_add_streams--;
550         }
551     }
552
553     p_input->p_sys = NULL;
554
555     return 0;
556 }
557
558 /*****************************************************************************
559  * Ogg bitstream manipulation routines
560  *****************************************************************************/
561 static block_t *OggStreamFlush( sout_mux_t *p_mux,
562                                 ogg_stream_state *p_os, mtime_t i_pts )
563 {
564     (void)p_mux;
565     block_t *p_og, *p_og_first = NULL;
566     ogg_page og;
567
568     while( ogg_stream_flush( p_os, &og ) )
569     {
570         /* Flush all data */
571         p_og = block_New( p_mux, og.header_len + og.body_len );
572
573         memcpy( p_og->p_buffer, og.header, og.header_len );
574         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
575         p_og->i_dts     = 0;
576         p_og->i_pts     = i_pts;
577         p_og->i_length  = 0;
578
579         i_pts = 0; // write it only once
580
581         block_ChainAppend( &p_og_first, p_og );
582     }
583
584     return p_og_first;
585 }
586
587 static block_t *OggStreamPageOut( sout_mux_t *p_mux,
588                                   ogg_stream_state *p_os, mtime_t i_pts )
589 {
590     (void)p_mux;
591     block_t *p_og, *p_og_first = NULL;
592     ogg_page og;
593
594     while( ogg_stream_pageout( p_os, &og ) )
595     {
596         /* Flush all data */
597         p_og = block_New( p_mux, og.header_len + og.body_len );
598
599         memcpy( p_og->p_buffer, og.header, og.header_len );
600         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
601         p_og->i_dts     = 0;
602         p_og->i_pts     = i_pts;
603         p_og->i_length  = 0;
604
605         i_pts = 0; // write them only once
606
607         block_ChainAppend( &p_og_first, p_og );
608     }
609
610     return p_og_first;
611 }
612
613 static block_t *OggCreateHeader( sout_mux_t *p_mux )
614 {
615     block_t *p_hdr = NULL;
616     block_t *p_og = NULL;
617     ogg_packet op;
618     uint8_t *p_extra;
619     int i, i_extra;
620
621     /* Write header for each stream. All b_o_s (beginning of stream) packets
622      * must appear first in the ogg stream so we take care of them first. */
623     for( i = 0; i < p_mux->i_nb_inputs; i++ )
624     {
625         sout_input_t *p_input = p_mux->pp_inputs[i];
626         ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
627         p_stream->b_new = false;
628
629         msg_Dbg( p_mux, "creating header for %4.4s",
630                  (char *)&p_stream->i_fourcc );
631
632         ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
633         p_stream->i_packet_no = 0;
634
635         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
636             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
637             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
638         {
639             /* First packet in order: vorbis/speex/theora info */
640             p_extra = p_input->p_fmt->p_extra;
641             i_extra = p_input->p_fmt->i_extra;
642
643             op.bytes = *(p_extra++) << 8;
644             op.bytes |= (*(p_extra++) & 0xFF);
645             op.packet = p_extra;
646             i_extra -= (op.bytes + 2);
647             if( i_extra < 0 )
648             {
649                 msg_Err( p_mux, "header data corrupted");
650                 op.bytes += i_extra;
651             }
652
653             op.b_o_s  = 1;
654             op.e_o_s  = 0;
655             op.granulepos = 0;
656             op.packetno = p_stream->i_packet_no++;
657             ogg_stream_packetin( &p_stream->os, &op );
658             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
659
660             /* Get keyframe_granule_shift for theora granulepos calculation */
661             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
662             {
663                 int i_keyframe_frequency_force =
664                       1 << ((op.packet[40] << 6 >> 3) | (op.packet[41] >> 5));
665
666                 /* granule_shift = i_log( frequency_force -1 ) */
667                 p_stream->i_keyframe_granule_shift = 0;
668                 i_keyframe_frequency_force--;
669                 while( i_keyframe_frequency_force )
670                 {
671                     p_stream->i_keyframe_granule_shift++;
672                     i_keyframe_frequency_force >>= 1;
673                 }
674             }
675         }
676         else if( p_stream->i_fourcc == VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
677         {
678             op.packet = p_input->p_fmt->p_extra;
679             op.bytes  = p_input->p_fmt->i_extra;
680             op.b_o_s  = 1;
681             op.e_o_s  = 0;
682             op.granulepos = ~0;
683             op.packetno = p_stream->i_packet_no++;
684             ogg_stream_packetin( &p_stream->os, &op );
685             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
686         }
687         else if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
688         {
689             /* flac stream marker (yeah, only that in the 1st packet) */
690             op.packet = (unsigned char *)"fLaC";
691             op.bytes  = 4;
692             op.b_o_s  = 1;
693             op.e_o_s  = 0;
694             op.granulepos = 0;
695             op.packetno = p_stream->i_packet_no++;
696             ogg_stream_packetin( &p_stream->os, &op );
697             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
698         }
699         else if( p_stream->p_oggds_header )
700         {
701             /* ds header */
702             op.packet = (uint8_t*)p_stream->p_oggds_header;
703             op.bytes  = p_stream->p_oggds_header->i_size + 1;
704             op.b_o_s  = 1;
705             op.e_o_s  = 0;
706             op.granulepos = 0;
707             op.packetno = p_stream->i_packet_no++;
708             ogg_stream_packetin( &p_stream->os, &op );
709             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
710         }
711
712         block_ChainAppend( &p_hdr, p_og );
713     }
714
715     /* Take care of the non b_o_s headers */
716     for( i = 0; i < p_mux->i_nb_inputs; i++ )
717     {
718         sout_input_t *p_input = p_mux->pp_inputs[i];
719         ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
720
721         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
722             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
723             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
724         {
725             /* Special case, headers are already there in the incoming stream.
726              * We need to gather them an mark them as headers. */
727             int j = 2;
728
729             if( p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ) j = 1;
730
731             p_extra = p_input->p_fmt->p_extra;
732             i_extra = p_input->p_fmt->i_extra;
733
734             /* Skip 1 header */
735             op.bytes = *(p_extra++) << 8;
736             op.bytes |= (*(p_extra++) & 0xFF);
737             op.packet = p_extra;
738             p_extra += op.bytes;
739             i_extra -= (op.bytes + 2);
740
741             while( j-- )
742             {
743                 op.bytes = *(p_extra++) << 8;
744                 op.bytes |= (*(p_extra++) & 0xFF);
745                 op.packet = p_extra;
746                 p_extra += op.bytes;
747                 i_extra -= (op.bytes + 2);
748                 if( i_extra < 0 )
749                 {
750                     msg_Err( p_mux, "header data corrupted");
751                     op.bytes += i_extra;
752                 }
753
754                 op.b_o_s  = 0;
755                 op.e_o_s  = 0;
756                 op.granulepos = 0;
757                 op.packetno = p_stream->i_packet_no++;
758                 ogg_stream_packetin( &p_stream->os, &op );
759
760                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
761                 block_ChainAppend( &p_hdr, p_og );
762             }
763         }
764         else if( p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) &&
765                  p_stream->i_fourcc != VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
766         {
767             uint8_t com[128];
768             int     i_com;
769
770             /* comment */
771             com[0] = PACKET_TYPE_COMMENT;
772             i_com = snprintf( (char *)(com+1), 127,
773                               PACKAGE_VERSION" stream output" )
774                      + 1;
775             op.packet = com;
776             op.bytes  = i_com;
777             op.b_o_s  = 0;
778             op.e_o_s  = 0;
779             op.granulepos = 0;
780             op.packetno = p_stream->i_packet_no++;
781             ogg_stream_packetin( &p_stream->os, &op );
782             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
783             block_ChainAppend( &p_hdr, p_og );
784         }
785
786         /* Special case for mp4v and flac */
787         if( ( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) ||
788               p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ) &&
789             p_input->p_fmt->i_extra )
790         {
791             /* Send a packet with the VOL data for mp4v
792              * or STREAMINFO for flac */
793             msg_Dbg( p_mux, "writing extra data" );
794             op.bytes  = p_input->p_fmt->i_extra;
795             op.packet = p_input->p_fmt->p_extra;
796             if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
797             {
798                 /* Skip the flac stream marker */
799                 op.bytes -= 4;
800                 op.packet+= 4;
801             }
802             op.b_o_s  = 0;
803             op.e_o_s  = 0;
804             op.granulepos = 0;
805             op.packetno = p_stream->i_packet_no++;
806             ogg_stream_packetin( &p_stream->os, &op );
807             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
808             block_ChainAppend( &p_hdr, p_og );
809         }
810     }
811
812     /* set HEADER flag */
813     for( p_og = p_hdr; p_og != NULL; p_og = p_og->p_next )
814     {
815         p_og->i_flags |= BLOCK_FLAG_HEADER;
816     }
817     return p_hdr;
818 }
819
820 static block_t *OggCreateFooter( sout_mux_t *p_mux )
821 {
822     sout_mux_sys_t *p_sys = p_mux->p_sys;
823     block_t *p_hdr = NULL;
824     block_t *p_og;
825     ogg_packet    op;
826     int     i;
827
828     /* flush all remaining data */
829     for( i = 0; i < p_mux->i_nb_inputs; i++ )
830     {
831         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
832
833         /* skip newly added streams */
834         if( p_stream->b_new ) continue;
835
836         if( ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
837         {
838             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
839             sout_AccessOutWrite( p_mux->p_access, p_og );
840         }
841     }
842
843     /* Write eos packets for each stream. */
844     for( i = 0; i < p_mux->i_nb_inputs; i++ )
845     {
846         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
847
848         /* skip newly added streams */
849         if( p_stream->b_new ) continue;
850
851         op.packet = NULL;
852         op.bytes  = 0;
853         op.b_o_s  = 0;
854         op.e_o_s  = 1;
855         op.granulepos = p_stream->u_last_granulepos;
856         op.packetno = p_stream->i_packet_no++;
857         ogg_stream_packetin( &p_stream->os, &op );
858
859         p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
860         block_ChainAppend( &p_hdr, p_og );
861         ogg_stream_clear( &p_stream->os );
862     }
863
864     for( i = 0; i < p_sys->i_del_streams; i++ )
865     {
866         op.packet = NULL;
867         op.bytes  = 0;
868         op.b_o_s  = 0;
869         op.e_o_s  = 1;
870         op.granulepos = p_sys->pp_del_streams[i]->u_last_granulepos;
871         op.packetno = p_sys->pp_del_streams[i]->i_packet_no++;
872         ogg_stream_packetin( &p_sys->pp_del_streams[i]->os, &op );
873
874         p_og = OggStreamFlush( p_mux, &p_sys->pp_del_streams[i]->os, 0 );
875         block_ChainAppend( &p_hdr, p_og );
876         ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
877     }
878
879     return p_hdr;
880 }
881
882 static void OggSetDate( block_t *p_og, mtime_t i_dts, mtime_t i_length )
883 {
884     int i_count;
885     block_t *p_tmp;
886     mtime_t i_delta;
887
888     for( p_tmp = p_og, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->p_next )
889     {
890         i_count++;
891     }
892
893     if( i_count == 0 ) return; /* ignore. */
894
895     i_delta = i_length / i_count;
896
897     for( p_tmp = p_og; p_tmp != NULL; p_tmp = p_tmp->p_next )
898     {
899         p_tmp->i_dts    = i_dts;
900         p_tmp->i_length = i_delta;
901
902         i_dts += i_delta;
903     }
904 }
905
906 /*****************************************************************************
907  * Mux: multiplex available data in input fifos into the Ogg bitstream
908  *****************************************************************************/
909 static int Mux( sout_mux_t *p_mux )
910 {
911     sout_mux_sys_t *p_sys = p_mux->p_sys;
912     block_t        *p_og = NULL;
913     int            i_stream;
914     mtime_t        i_dts;
915
916     if( p_sys->i_add_streams || p_sys->i_del_streams )
917     {
918         /* Open new ogg stream */
919         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
920         {
921             msg_Dbg( p_mux, "waiting for data..." );
922             return VLC_SUCCESS;
923         }
924
925         if( p_sys->i_streams )
926         {
927             /* Close current ogg stream */
928             int i;
929
930             msg_Dbg( p_mux, "writing footer" );
931             block_ChainAppend( &p_og, OggCreateFooter( p_mux ) );
932
933             /* Remove deleted logical streams */
934             for( i = 0; i < p_sys->i_del_streams; i++ )
935             {
936                 FREENULL( p_sys->pp_del_streams[i]->p_oggds_header );
937                 FREENULL( p_sys->pp_del_streams[i] );
938             }
939             FREENULL( p_sys->pp_del_streams );
940             p_sys->i_streams = 0;
941         }
942
943         msg_Dbg( p_mux, "writing header" );
944         p_sys->i_start_dts = i_dts;
945         p_sys->i_streams = p_mux->i_nb_inputs;
946         p_sys->i_del_streams = 0;
947         p_sys->i_add_streams = 0;
948         block_ChainAppend( &p_og, OggCreateHeader( p_mux ) );
949
950         /* Write header and/or footer */
951         OggSetDate( p_og, i_dts, 0 );
952         sout_AccessOutWrite( p_mux->p_access, p_og );
953         p_og = NULL;
954     }
955
956     for( ;; )
957     {
958         if( MuxGetStream( p_mux, &i_stream, 0 ) < 0 ) return VLC_SUCCESS;
959         MuxBlock( p_mux, p_mux->pp_inputs[i_stream] );
960     }
961
962     return VLC_SUCCESS;
963 }
964
965 static int MuxBlock( sout_mux_t *p_mux, sout_input_t *p_input )
966 {
967     sout_mux_sys_t *p_sys = p_mux->p_sys;
968     ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
969     block_t *p_data = block_FifoGet( p_input->p_fifo );
970     block_t *p_og = NULL;
971     ogg_packet op;
972
973     if( p_stream->i_fourcc != VLC_FOURCC( 'v', 'o', 'r', 'b' ) &&
974         p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) &&
975         p_stream->i_fourcc != VLC_FOURCC( 's', 'p', 'x', ' ' ) &&
976         p_stream->i_fourcc != VLC_FOURCC( 't', 'h', 'e', 'o' ) &&
977         p_stream->i_fourcc != VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
978     {
979         p_data = block_Realloc( p_data, 1, p_data->i_buffer );
980         p_data->p_buffer[0] = PACKET_IS_SYNCPOINT;      // FIXME
981     }
982
983     op.packet   = p_data->p_buffer;
984     op.bytes    = p_data->i_buffer;
985     op.b_o_s    = 0;
986     op.e_o_s    = 0;
987     op.packetno = p_stream->i_packet_no++;
988
989     if( p_stream->i_cat == AUDIO_ES )
990     {
991         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
992             p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ||
993             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) )
994         {
995             /* number of sample from begining + current packet */
996             op.granulepos =
997                 ( p_data->i_dts - p_sys->i_start_dts + p_data->i_length ) *
998                 (mtime_t)p_input->p_fmt->audio.i_rate / INT64_C(1000000);
999         }
1000         else if( p_stream->p_oggds_header )
1001         {
1002             /* number of sample from begining */
1003             op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) *
1004                 p_stream->p_oggds_header->i_samples_per_unit / INT64_C(1000000);
1005         }
1006     }
1007     else if( p_stream->i_cat == VIDEO_ES )
1008     {
1009         if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
1010         {
1011             /* FIXME, we assume only keyframes */
1012             op.granulepos = ( ( p_data->i_dts - p_sys->i_start_dts ) *
1013                 p_input->p_fmt->video.i_frame_rate /
1014                 p_input->p_fmt->video.i_frame_rate_base /
1015                 INT64_C(1000000) ) << p_stream->i_keyframe_granule_shift;
1016         }
1017         else if( p_stream->i_fourcc == VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
1018         {
1019             mtime_t dt = (p_data->i_dts - p_sys->i_start_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             mtime_t delay = (p_data->i_pts - p_data->i_dts + 1)
1024                           * p_input->p_fmt->video.i_frame_rate *2
1025                           / p_input->p_fmt->video.i_frame_rate_base
1026                           / INT64_C(1000000);
1027             if( p_data->i_flags & BLOCK_FLAG_TYPE_I )
1028                 p_stream->i_last_keyframe = dt;
1029             mtime_t dist = dt - p_stream->i_last_keyframe;
1030             op.granulepos = dt << 31 | (dist&0xff00) << 14
1031                           | (delay&0x1fff) << 9 | (dist&0xff);
1032         }
1033         else if( p_stream->p_oggds_header )
1034             op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) * INT64_C(10) /
1035                 p_stream->p_oggds_header->i_time_unit;
1036     }
1037     else if( p_stream->i_cat == SPU_ES )
1038     {
1039         /* granulepos is in millisec */
1040         op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) / 1000;
1041     }
1042
1043     p_stream->u_last_granulepos = op.granulepos;
1044     ogg_stream_packetin( &p_stream->os, &op );
1045
1046     if( p_stream->i_cat == SPU_ES ||
1047         p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
1048         p_stream->i_fourcc == VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
1049     {
1050         /* Subtitles or Speex packets are quite small so they
1051          * need to be flushed to be sent on time */
1052         /* The OggDirac mapping suggests ever so strongly that a
1053          * page flush occurs after each OggDirac packet, so to make
1054          * the timestamps unambiguous */
1055         p_og = OggStreamFlush( p_mux, &p_stream->os, p_data->i_dts );
1056     }
1057     else
1058     {
1059         p_og = OggStreamPageOut( p_mux, &p_stream->os, p_data->i_dts );
1060     }
1061
1062     if( p_og )
1063     {
1064         OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
1065         p_stream->i_dts = -1;
1066         p_stream->i_length = 0;
1067
1068         sout_AccessOutWrite( p_mux->p_access, p_og );
1069     }
1070     else
1071     {
1072         if( p_stream->i_dts < 0 )
1073         {
1074             p_stream->i_dts = p_data->i_dts;
1075         }
1076         p_stream->i_length += p_data->i_length;
1077     }
1078
1079     block_Release( p_data );
1080     return VLC_SUCCESS;
1081 }