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