]> git.sesse.net Git - vlc/blob - modules/mux/ogg.c
mux/ogg: Enable OggDirac support
[vlc] / modules / mux / ogg.c
1 /*****************************************************************************
2  * ogg.c: ogg muxer module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001, 2002, 2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_TIME_H
30 #   include <time.h>
31 #endif
32
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36
37 #include <vlc_common.h>
38 #include <vlc_plugin.h>
39 #include <vlc_sout.h>
40 #include <vlc_block.h>
41 #include <vlc_codecs.h>
42
43 #include <ogg/ogg.h>
44
45 /*****************************************************************************
46  * Module descriptor
47  *****************************************************************************/
48 static int  Open   ( vlc_object_t * );
49 static void Close  ( vlc_object_t * );
50
51 vlc_module_begin ()
52     set_description( N_("Ogg/OGM muxer") )
53     set_capability( "sout mux", 10 )
54     set_category( CAT_SOUT )
55     set_subcategory( SUBCAT_SOUT_MUX )
56     add_shortcut( "ogg" )
57     add_shortcut( "ogm" )
58     set_callbacks( Open, Close )
59 vlc_module_end ()
60
61
62 /*****************************************************************************
63  * Exported prototypes
64  *****************************************************************************/
65 static int Control  ( sout_mux_t *, int, va_list );
66 static int AddStream( sout_mux_t *, sout_input_t * );
67 static int DelStream( sout_mux_t *, sout_input_t * );
68 static int Mux      ( sout_mux_t * );
69 static int MuxBlock ( sout_mux_t *, sout_input_t * );
70
71 static block_t *OggCreateHeader( sout_mux_t * );
72 static block_t *OggCreateFooter( sout_mux_t * );
73
74 /*****************************************************************************
75  * Misc declarations
76  *****************************************************************************/
77
78 /* Structures used for OggDS headers used in ogm files */
79
80 #define PACKET_TYPE_HEADER   0x01
81 #define PACKET_TYPE_COMMENT  0x03
82 #define PACKET_IS_SYNCPOINT  0x08
83
84 typedef struct
85 #ifdef HAVE_ATTRIBUTE_PACKED
86     __attribute__((__packed__))
87 #endif
88 {
89     int32_t i_width;
90     int32_t i_height;
91 } oggds_header_video_t;
92
93 typedef struct
94 #ifdef HAVE_ATTRIBUTE_PACKED
95     __attribute__((__packed__))
96 #endif
97 {
98     int16_t i_channels;
99     int16_t i_block_align;
100     int32_t i_avgbytespersec;
101 } oggds_header_audio_t;
102
103 typedef struct
104 #ifdef HAVE_ATTRIBUTE_PACKED
105     __attribute__((__packed__))
106 #endif
107 {
108     uint8_t i_packet_type;
109
110     char stream_type[8];
111     char sub_type[4];
112
113     int32_t i_size;
114
115     int64_t i_time_unit;
116     int64_t i_samples_per_unit;
117     int32_t i_default_len;
118
119     int32_t i_buffer_size;
120     int16_t i_bits_per_sample;
121
122     int16_t i_padding_0; /* Because the original is using MSVC packing style */
123
124     union
125     {
126         oggds_header_video_t video;
127         oggds_header_audio_t audio;
128     } header;
129
130     int32_t i_padding_1; /* Because the original is using MSVC packing style */
131
132 } oggds_header_t;
133
134 /*
135  * TODO  move this function to src/stream_output.c (used by nearly all muxers)
136  */
137 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
138 {
139     mtime_t i_dts;
140     int     i_stream, i;
141
142     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
143     {
144         block_fifo_t  *p_fifo;
145
146         p_fifo = p_mux->pp_inputs[i]->p_fifo;
147
148         /* We don't really need to have anything in the SPU fifo */
149         if( p_mux->pp_inputs[i]->p_fmt->i_cat == SPU_ES &&
150             block_FifoCount( p_fifo ) == 0 ) continue;
151
152         if( block_FifoCount( p_fifo ) )
153         {
154             block_t *p_buf;
155
156             p_buf = block_FifoShow( p_fifo );
157             if( i_stream < 0 || p_buf->i_dts < i_dts )
158             {
159                 i_dts = p_buf->i_dts;
160                 i_stream = i;
161             }
162         }
163         else return -1;
164
165     }
166     if( pi_stream ) *pi_stream = i_stream;
167     if( pi_dts ) *pi_dts = i_dts;
168     return i_stream;
169 }
170
171 /*****************************************************************************
172  * Definitions of structures and functions used by this plugins
173  *****************************************************************************/
174 typedef struct
175 {
176     int i_cat;
177     int i_fourcc;
178
179     int b_new;
180
181     mtime_t i_dts;
182     mtime_t i_length;
183     int     i_packet_no;
184     int     i_serial_no;
185     int     i_keyframe_granule_shift; /* Theora only */
186     int     i_last_keyframe; /* dirac and eventually theora */
187     ogg_stream_state os;
188
189     oggds_header_t *p_oggds_header;
190
191 } ogg_stream_t;
192
193 struct sout_mux_sys_t
194 {
195     int     i_streams;
196
197     mtime_t i_start_dts;
198     int     i_next_serial_no;
199
200     /* number of logical streams pending to be added */
201     int i_add_streams;
202
203     /* logical streams pending to be deleted */
204     int i_del_streams;
205     ogg_stream_t **pp_del_streams;
206 };
207
208 static void OggSetDate( block_t *, mtime_t , mtime_t  );
209 static block_t *OggStreamFlush( sout_mux_t *, ogg_stream_state *, mtime_t );
210
211 /*****************************************************************************
212  * Open: Open muxer
213  *****************************************************************************/
214 static int Open( vlc_object_t *p_this )
215 {
216     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
217     sout_mux_sys_t  *p_sys;
218
219     msg_Info( p_mux, "Open" );
220
221     p_sys                 = malloc( sizeof( sout_mux_sys_t ) );
222     if( !p_sys )
223         return VLC_ENOMEM;
224     p_sys->i_streams      = 0;
225     p_sys->i_add_streams  = 0;
226     p_sys->i_del_streams  = 0;
227     p_sys->pp_del_streams = 0;
228
229     p_mux->p_sys        = p_sys;
230     p_mux->pf_control   = Control;
231     p_mux->pf_addstream = AddStream;
232     p_mux->pf_delstream = DelStream;
233     p_mux->pf_mux       = Mux;
234
235     /* First serial number is random.
236      * (Done like this because on win32 you need to seed the random number
237      *  generator once per thread). */
238     srand( (unsigned int)time( NULL ) );
239     p_sys->i_next_serial_no = rand();
240
241     return VLC_SUCCESS;
242 }
243
244 /*****************************************************************************
245  * Close: Finalize ogg bitstream and close muxer
246  *****************************************************************************/
247 static void Close( vlc_object_t * p_this )
248 {
249     sout_mux_t     *p_mux = (sout_mux_t*)p_this;
250     sout_mux_sys_t *p_sys = p_mux->p_sys;
251
252     msg_Info( p_mux, "Close" );
253
254     if( p_sys->i_del_streams )
255     {
256         block_t *p_og = NULL;
257         mtime_t i_dts = -1;
258         int i;
259
260         /* Close the current ogg stream */
261         msg_Dbg( p_mux, "writing footer" );
262         block_ChainAppend( &p_og, OggCreateFooter( p_mux ) );
263
264         /* Remove deleted logical streams */
265         for( i = 0; i < p_sys->i_del_streams; i++ )
266         {
267             i_dts = p_sys->pp_del_streams[i]->i_dts;
268             ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
269             FREENULL( p_sys->pp_del_streams[i]->p_oggds_header );
270             FREENULL( p_sys->pp_del_streams[i] );
271         }
272         FREENULL( p_sys->pp_del_streams );
273         p_sys->i_streams -= p_sys->i_del_streams;
274
275         /* Write footer */
276         OggSetDate( p_og, i_dts, 0 );
277         sout_AccessOutWrite( p_mux->p_access, p_og );
278     }
279
280     free( p_sys );
281 }
282
283 /*****************************************************************************
284  * Control:
285  *****************************************************************************/
286 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
287 {
288     VLC_UNUSED(p_mux);
289     bool *pb_bool;
290     char **ppsz;
291
292    switch( i_query )
293    {
294        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
295            pb_bool = (bool*)va_arg( args, bool * );
296            *pb_bool = true;
297            return VLC_SUCCESS;
298
299        case MUX_GET_ADD_STREAM_WAIT:
300            pb_bool = (bool*)va_arg( args, bool * );
301            *pb_bool = true;
302            return VLC_SUCCESS;
303
304        case MUX_GET_MIME:
305            ppsz = (char**)va_arg( args, char ** );
306            *ppsz = strdup( "application/ogg" );
307            return VLC_SUCCESS;
308
309         default:
310             return VLC_EGENERIC;
311    }
312 }
313 /*****************************************************************************
314  * AddStream: Add an elementary stream to the muxed stream
315  *****************************************************************************/
316 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
317 {
318     sout_mux_sys_t *p_sys = p_mux->p_sys;
319     ogg_stream_t   *p_stream;
320     uint16_t i_tag;
321
322     msg_Dbg( p_mux, "adding input" );
323
324     p_input->p_sys = p_stream = calloc( 1, sizeof( ogg_stream_t ) );
325     if( !p_stream )
326         return VLC_ENOMEM;
327
328     p_stream->i_cat       = p_input->p_fmt->i_cat;
329     p_stream->i_fourcc    = p_input->p_fmt->i_codec;
330     p_stream->i_serial_no = p_sys->i_next_serial_no++;
331     p_stream->i_packet_no = 0;
332
333     p_stream->p_oggds_header = 0;
334
335     switch( p_input->p_fmt->i_cat )
336     {
337     case VIDEO_ES:
338         if( !p_input->p_fmt->video.i_frame_rate ||
339             !p_input->p_fmt->video.i_frame_rate_base )
340         {
341             msg_Warn( p_mux, "Missing frame rate, assuming 25fps" );
342             p_input->p_fmt->video.i_frame_rate = 25;
343             p_input->p_fmt->video.i_frame_rate_base = 1;
344         }
345
346         switch( p_stream->i_fourcc )
347         {
348         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
349         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
350         case VLC_FOURCC( 'D', 'I', 'V', '3' ):
351         case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
352         case VLC_FOURCC( 'W', 'M', 'V', '1' ):
353         case VLC_FOURCC( 'W', 'M', 'V', '2' ):
354         case VLC_FOURCC( 'W', 'M', 'V', '3' ):
355         case VLC_FOURCC( 'S', 'N', 'O', 'W' ):
356             p_stream->p_oggds_header = malloc( sizeof(oggds_header_t) );
357             if( !p_stream->p_oggds_header )
358             {
359                 free( p_stream );
360                 return VLC_ENOMEM;
361             }
362             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
363             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
364
365             memcpy( p_stream->p_oggds_header->stream_type, "video", 5 );
366             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) )
367             {
368                 memcpy( p_stream->p_oggds_header->sub_type, "XVID", 4 );
369             }
370             else if( p_stream->i_fourcc == VLC_FOURCC( 'D', 'I', 'V', '3' ) )
371             {
372                 memcpy( p_stream->p_oggds_header->sub_type, "DIV3", 4 );
373             }
374             else
375             {
376                 memcpy( p_stream->p_oggds_header->sub_type,
377                         &p_stream->i_fourcc, 4 );
378             }
379             SetDWLE( &p_stream->p_oggds_header->i_size,
380                      sizeof( oggds_header_t ) - 1 );
381             SetQWLE( &p_stream->p_oggds_header->i_time_unit,
382                      INT64_C(10000000) * p_input->p_fmt->video.i_frame_rate_base /
383                      (int64_t)p_input->p_fmt->video.i_frame_rate );
384             SetQWLE( &p_stream->p_oggds_header->i_samples_per_unit, 1 );
385             SetDWLE( &p_stream->p_oggds_header->i_default_len, 1 ); /* ??? */
386             SetDWLE( &p_stream->p_oggds_header->i_buffer_size, 1024*1024 );
387             SetWLE( &p_stream->p_oggds_header->i_bits_per_sample, 0 );
388             SetDWLE( &p_stream->p_oggds_header->header.video.i_width,
389                      p_input->p_fmt->video.i_width );
390             SetDWLE( &p_stream->p_oggds_header->header.video.i_height,
391                      p_input->p_fmt->video.i_height );
392             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
393             break;
394
395         case VLC_FOURCC( 'd', 'r', 'a', 'c' ):
396             msg_Dbg( p_mux, "dirac stream" );
397             break;
398
399         case VLC_FOURCC( 't', 'h', 'e', 'o' ):
400             msg_Dbg( p_mux, "theora stream" );
401             break;
402
403         default:
404             FREENULL( p_input->p_sys );
405             return VLC_EGENERIC;
406         }
407         break;
408
409     case AUDIO_ES:
410         switch( p_stream->i_fourcc )
411         {
412         case VLC_FOURCC( 'v', 'o', 'r', 'b' ):
413             msg_Dbg( p_mux, "vorbis stream" );
414             break;
415
416         case VLC_FOURCC( 's', 'p', 'x', ' ' ):
417             msg_Dbg( p_mux, "speex stream" );
418             break;
419
420         case VLC_FOURCC( 'f', 'l', 'a', 'c' ):
421             msg_Dbg( p_mux, "flac stream" );
422             break;
423
424         default:
425             fourcc_to_wf_tag( p_stream->i_fourcc, &i_tag );
426             if( i_tag == WAVE_FORMAT_UNKNOWN )
427             {
428                 FREENULL( p_input->p_sys );
429                 return VLC_EGENERIC;
430             }
431
432             p_stream->p_oggds_header =
433                 malloc( sizeof(oggds_header_t) + p_input->p_fmt->i_extra );
434             if( !p_stream->p_oggds_header )
435             {
436                 free( p_stream );
437                 return VLC_ENOMEM;
438             }
439             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
440             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
441
442             SetDWLE( &p_stream->p_oggds_header->i_size,
443                      sizeof( oggds_header_t ) - 1 + p_input->p_fmt->i_extra );
444
445             if( p_input->p_fmt->i_extra )
446             {
447                 memcpy( &p_stream->p_oggds_header[1],
448                         p_input->p_fmt->p_extra, p_input->p_fmt->i_extra );
449             }
450
451             memcpy( p_stream->p_oggds_header->stream_type, "audio", 5 );
452
453             memset( p_stream->p_oggds_header->sub_type, 0, 4 );
454             sprintf( p_stream->p_oggds_header->sub_type, "%-x", i_tag );
455
456             SetQWLE( &p_stream->p_oggds_header->i_time_unit, INT64_C(10000000) );
457             SetDWLE( &p_stream->p_oggds_header->i_default_len, 1 );
458             SetDWLE( &p_stream->p_oggds_header->i_buffer_size, 30*1024 );
459             SetQWLE( &p_stream->p_oggds_header->i_samples_per_unit,
460                      p_input->p_fmt->audio.i_rate );
461             SetWLE( &p_stream->p_oggds_header->i_bits_per_sample,
462                     p_input->p_fmt->audio.i_bitspersample );
463             SetDWLE( &p_stream->p_oggds_header->header.audio.i_channels,
464                      p_input->p_fmt->audio.i_channels );
465             SetDWLE( &p_stream->p_oggds_header->header.audio.i_block_align,
466                      p_input->p_fmt->audio.i_blockalign );
467             SetDWLE( &p_stream->p_oggds_header->header.audio.i_avgbytespersec,
468                      p_input->p_fmt->i_bitrate / 8);
469             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
470             break;
471         }
472         break;
473
474     case SPU_ES:
475         switch( p_stream->i_fourcc )
476         {
477         case VLC_FOURCC( 's', 'u','b', 't' ):
478             p_stream->p_oggds_header = malloc( sizeof(oggds_header_t) );
479             if( !p_stream->p_oggds_header )
480             {
481                 free( p_stream );
482                 return VLC_ENOMEM;
483             }
484             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
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( i = 0; i < p_mux->i_nb_inputs; i++ )
623     {
624         sout_input_t *p_input = p_mux->pp_inputs[i];
625         ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
626         p_stream->b_new = false;
627
628         msg_Dbg( p_mux, "creating header for %4.4s",
629                  (char *)&p_stream->i_fourcc );
630
631         ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
632         p_stream->i_packet_no = 0;
633
634         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
635             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
636             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
637         {
638             /* First packet in order: vorbis/speex/theora info */
639             p_extra = p_input->p_fmt->p_extra;
640             i_extra = p_input->p_fmt->i_extra;
641
642             op.bytes = *(p_extra++) << 8;
643             op.bytes |= (*(p_extra++) & 0xFF);
644             op.packet = p_extra;
645             i_extra -= (op.bytes + 2);
646             if( i_extra < 0 )
647             {
648                 msg_Err( p_mux, "header data corrupted");
649                 op.bytes += i_extra;
650             }
651
652             op.b_o_s  = 1;
653             op.e_o_s  = 0;
654             op.granulepos = 0;
655             op.packetno = p_stream->i_packet_no++;
656             ogg_stream_packetin( &p_stream->os, &op );
657             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
658
659             /* Get keyframe_granule_shift for theora granulepos calculation */
660             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
661             {
662                 int i_keyframe_frequency_force =
663                       1 << ((op.packet[40] << 6 >> 3) | (op.packet[41] >> 5));
664
665                 /* granule_shift = i_log( frequency_force -1 ) */
666                 p_stream->i_keyframe_granule_shift = 0;
667                 i_keyframe_frequency_force--;
668                 while( i_keyframe_frequency_force )
669                 {
670                     p_stream->i_keyframe_granule_shift++;
671                     i_keyframe_frequency_force >>= 1;
672                 }
673             }
674         }
675         else if( p_stream->i_fourcc == VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
676         {
677             op.packet = p_input->p_fmt->p_extra;
678             op.bytes  = p_input->p_fmt->i_extra;
679             op.b_o_s  = 1;
680             op.e_o_s  = 0;
681             op.granulepos = ~0;
682             op.packetno = p_stream->i_packet_no++;
683             ogg_stream_packetin( &p_stream->os, &op );
684             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
685         }
686         else if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
687         {
688             /* flac stream marker (yeah, only that in the 1st packet) */
689             op.packet = (unsigned char *)"fLaC";
690             op.bytes  = 4;
691             op.b_o_s  = 1;
692             op.e_o_s  = 0;
693             op.granulepos = 0;
694             op.packetno = p_stream->i_packet_no++;
695             ogg_stream_packetin( &p_stream->os, &op );
696             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
697         }
698         else if( p_stream->p_oggds_header )
699         {
700             /* ds header */
701             op.packet = (uint8_t*)p_stream->p_oggds_header;
702             op.bytes  = p_stream->p_oggds_header->i_size + 1;
703             op.b_o_s  = 1;
704             op.e_o_s  = 0;
705             op.granulepos = 0;
706             op.packetno = p_stream->i_packet_no++;
707             ogg_stream_packetin( &p_stream->os, &op );
708             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
709         }
710
711         block_ChainAppend( &p_hdr, p_og );
712     }
713
714     /* Take care of the non b_o_s headers */
715     for( i = 0; i < p_mux->i_nb_inputs; i++ )
716     {
717         sout_input_t *p_input = p_mux->pp_inputs[i];
718         ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
719
720         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
721             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
722             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
723         {
724             /* Special case, headers are already there in the incoming stream.
725              * We need to gather them an mark them as headers. */
726             int j = 2;
727
728             if( p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ) j = 1;
729
730             p_extra = p_input->p_fmt->p_extra;
731             i_extra = p_input->p_fmt->i_extra;
732
733             /* Skip 1 header */
734             op.bytes = *(p_extra++) << 8;
735             op.bytes |= (*(p_extra++) & 0xFF);
736             op.packet = p_extra;
737             p_extra += op.bytes;
738             i_extra -= (op.bytes + 2);
739
740             while( j-- )
741             {
742                 op.bytes = *(p_extra++) << 8;
743                 op.bytes |= (*(p_extra++) & 0xFF);
744                 op.packet = p_extra;
745                 p_extra += op.bytes;
746                 i_extra -= (op.bytes + 2);
747                 if( i_extra < 0 )
748                 {
749                     msg_Err( p_mux, "header data corrupted");
750                     op.bytes += i_extra;
751                 }
752
753                 op.b_o_s  = 0;
754                 op.e_o_s  = 0;
755                 op.granulepos = 0;
756                 op.packetno = p_stream->i_packet_no++;
757                 ogg_stream_packetin( &p_stream->os, &op );
758
759                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
760                 block_ChainAppend( &p_hdr, p_og );
761             }
762         }
763         else if( p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) &&
764                  p_stream->i_fourcc != VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
765         {
766             uint8_t com[128];
767             int     i_com;
768
769             /* comment */
770             com[0] = PACKET_TYPE_COMMENT;
771             i_com = snprintf( (char *)(com+1), 127,
772                               PACKAGE_VERSION" stream output" )
773                      + 1;
774             op.packet = com;
775             op.bytes  = i_com;
776             op.b_o_s  = 0;
777             op.e_o_s  = 0;
778             op.granulepos = 0;
779             op.packetno = p_stream->i_packet_no++;
780             ogg_stream_packetin( &p_stream->os, &op );
781             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
782             block_ChainAppend( &p_hdr, p_og );
783         }
784
785         /* Special case for mp4v and flac */
786         if( ( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) ||
787               p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ) &&
788             p_input->p_fmt->i_extra )
789         {
790             /* Send a packet with the VOL data for mp4v
791              * or STREAMINFO for flac */
792             msg_Dbg( p_mux, "writing extra data" );
793             op.bytes  = p_input->p_fmt->i_extra;
794             op.packet = p_input->p_fmt->p_extra;
795             if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
796             {
797                 /* Skip the flac stream marker */
798                 op.bytes -= 4;
799                 op.packet+= 4;
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 = -1;
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 = -1;
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     int            i_stream;
913     mtime_t        i_dts;
914
915     if( p_sys->i_add_streams || p_sys->i_del_streams )
916     {
917         /* Open new ogg stream */
918         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
919         {
920             msg_Dbg( p_mux, "waiting for data..." );
921             return VLC_SUCCESS;
922         }
923
924         if( p_sys->i_streams )
925         {
926             /* Close current ogg stream */
927             int i;
928
929             msg_Dbg( p_mux, "writing footer" );
930             block_ChainAppend( &p_og, OggCreateFooter( p_mux ) );
931
932             /* Remove deleted logical streams */
933             for( i = 0; i < p_sys->i_del_streams; i++ )
934             {
935                 FREENULL( p_sys->pp_del_streams[i]->p_oggds_header );
936                 FREENULL( p_sys->pp_del_streams[i] );
937             }
938             FREENULL( p_sys->pp_del_streams );
939             p_sys->i_streams = 0;
940         }
941
942         msg_Dbg( p_mux, "writing header" );
943         p_sys->i_start_dts = i_dts;
944         p_sys->i_streams = p_mux->i_nb_inputs;
945         p_sys->i_del_streams = 0;
946         p_sys->i_add_streams = 0;
947         block_ChainAppend( &p_og, OggCreateHeader( p_mux ) );
948
949         /* Write header and/or footer */
950         OggSetDate( p_og, i_dts, 0 );
951         sout_AccessOutWrite( p_mux->p_access, p_og );
952         p_og = NULL;
953     }
954
955     for( ;; )
956     {
957         if( MuxGetStream( p_mux, &i_stream, 0 ) < 0 ) return VLC_SUCCESS;
958         MuxBlock( p_mux, p_mux->pp_inputs[i_stream] );
959     }
960
961     return VLC_SUCCESS;
962 }
963
964 static int MuxBlock( sout_mux_t *p_mux, sout_input_t *p_input )
965 {
966     sout_mux_sys_t *p_sys = p_mux->p_sys;
967     ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
968     block_t *p_data = block_FifoGet( p_input->p_fifo );
969     block_t *p_og = NULL;
970     ogg_packet op;
971
972     if( p_stream->i_fourcc != VLC_FOURCC( 'v', 'o', 'r', 'b' ) &&
973         p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) &&
974         p_stream->i_fourcc != VLC_FOURCC( 's', 'p', 'x', ' ' ) &&
975         p_stream->i_fourcc != VLC_FOURCC( 't', 'h', 'e', 'o' ) &&
976         p_stream->i_fourcc != VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
977     {
978         p_data = block_Realloc( p_data, 1, p_data->i_buffer );
979         p_data->p_buffer[0] = PACKET_IS_SYNCPOINT;      // FIXME
980     }
981
982     op.packet   = p_data->p_buffer;
983     op.bytes    = p_data->i_buffer;
984     op.b_o_s    = 0;
985     op.e_o_s    = 0;
986     op.packetno = p_stream->i_packet_no++;
987
988     if( p_stream->i_cat == AUDIO_ES )
989     {
990         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
991             p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ||
992             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) )
993         {
994             /* number of sample from begining + current packet */
995             op.granulepos =
996                 ( p_data->i_dts - p_sys->i_start_dts + p_data->i_length ) *
997                 (mtime_t)p_input->p_fmt->audio.i_rate / INT64_C(1000000);
998         }
999         else if( p_stream->p_oggds_header )
1000         {
1001             /* number of sample from begining */
1002             op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) *
1003                 p_stream->p_oggds_header->i_samples_per_unit / INT64_C(1000000);
1004         }
1005     }
1006     else if( p_stream->i_cat == VIDEO_ES )
1007     {
1008         if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
1009         {
1010             /* FIXME, we assume only keyframes */
1011             op.granulepos = ( ( p_data->i_dts - p_sys->i_start_dts ) *
1012                 p_input->p_fmt->video.i_frame_rate /
1013                 p_input->p_fmt->video.i_frame_rate_base /
1014                 INT64_C(1000000) ) << p_stream->i_keyframe_granule_shift;
1015         }
1016         else if( p_stream->i_fourcc == VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
1017         {
1018             mtime_t dt = (p_data->i_dts - p_sys->i_start_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             mtime_t delay = (p_data->i_pts - p_data->i_dts + 1)
1023                           * p_input->p_fmt->video.i_frame_rate *2
1024                           / p_input->p_fmt->video.i_frame_rate_base
1025                           / INT64_C(1000000);
1026             if( p_data->i_flags & BLOCK_FLAG_TYPE_I )
1027                 p_stream->i_last_keyframe = dt;
1028             mtime_t dist = dt - p_stream->i_last_keyframe;
1029             op.granulepos = dt << 31 | (dist&0xff00) << 14
1030                           | (delay&0x1fff) << 9 | (dist&0xff);
1031         }
1032         else if( p_stream->p_oggds_header )
1033             op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) * INT64_C(10) /
1034                 p_stream->p_oggds_header->i_time_unit;
1035     }
1036     else if( p_stream->i_cat == SPU_ES )
1037     {
1038         /* granulepos is in millisec */
1039         op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) / 1000;
1040     }
1041
1042     ogg_stream_packetin( &p_stream->os, &op );
1043
1044     if( p_stream->i_cat == SPU_ES ||
1045         p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
1046         p_stream->i_fourcc == VLC_FOURCC( 'd', 'r', 'a', 'c' ) )
1047     {
1048         /* Subtitles or Speex packets are quite small so they
1049          * need to be flushed to be sent on time */
1050         /* The OggDirac mapping suggests ever so strongly that a
1051          * page flush occurs after each OggDirac packet, so to make
1052          * the timestamps unambiguous */
1053         p_og = OggStreamFlush( p_mux, &p_stream->os, p_data->i_dts );
1054     }
1055     else
1056     {
1057         p_og = OggStreamPageOut( p_mux, &p_stream->os, p_data->i_dts );
1058     }
1059
1060     if( p_og )
1061     {
1062         OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
1063         p_stream->i_dts = -1;
1064         p_stream->i_length = 0;
1065
1066         sout_AccessOutWrite( p_mux->p_access, p_og );
1067     }
1068     else
1069     {
1070         if( p_stream->i_dts < 0 )
1071         {
1072             p_stream->i_dts = p_data->i_dts;
1073         }
1074         p_stream->i_length += p_data->i_length;
1075     }
1076
1077     block_Release( p_data );
1078     return VLC_SUCCESS;
1079 }