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