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