]> git.sesse.net Git - vlc/blob - modules/mux/ogg.c
* modules/codec/flac.c: added a FLAC encoder.
[vlc] / modules / mux / ogg.c
1 /*****************************************************************************
2  * ogg.c: ogg muxer module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VideoLAN
5  * $Id: ogg.c,v 1.22 2003/11/21 20:49:14 gbazin Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@netcourrier.com>
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>
29 #include <string.h>
30
31 #ifdef HAVE_TIME_H
32 #   include <time.h>
33 #endif
34
35 #include <vlc/vlc.h>
36 #include <vlc/input.h>
37 #include <vlc/sout.h>
38
39 #include "codecs.h"
40
41 #include <ogg/ogg.h>
42
43 /*****************************************************************************
44  * Exported prototypes
45  *****************************************************************************/
46 static int  Open   ( vlc_object_t * );
47 static void Close  ( vlc_object_t * );
48
49 static int Capability(sout_mux_t *, int, void *, void * );
50 static int AddStream( sout_mux_t *, sout_input_t * );
51 static int DelStream( sout_mux_t *, sout_input_t * );
52 static int Mux      ( sout_mux_t * );
53
54 static sout_buffer_t *OggCreateHeader( sout_mux_t *, mtime_t );
55 static sout_buffer_t *OggCreateFooter( sout_mux_t *, mtime_t );
56
57 /*****************************************************************************
58  * Module descriptor
59  *****************************************************************************/
60 vlc_module_begin();
61     set_description( _("Ogg/ogm muxer") );
62     set_capability( "sout mux", 10 );
63     add_shortcut( "ogg" );
64     add_shortcut( "ogm" );
65     set_callbacks( Open, Close );
66 vlc_module_end();
67
68 /*****************************************************************************
69  * Misc declarations
70  *****************************************************************************/
71 #define FREE( p ) if( p ) { free( p ); (p) = NULL; }
72
73 /* Structures used for OggDS headers used in ogm files */
74
75 #define PACKET_TYPE_HEADER   0x01
76 #define PACKET_TYPE_COMMENT  0x03
77 #define PACKET_IS_SYNCPOINT  0x08
78
79 typedef struct
80 #ifdef HAVE_ATTRIBUTE_PACKED
81     __attribute__((__packed__))
82 #endif
83 {
84     int32_t i_width;
85     int32_t i_height;
86 } oggds_header_video_t;
87
88 typedef struct
89 #ifdef HAVE_ATTRIBUTE_PACKED
90     __attribute__((__packed__))
91 #endif
92 {
93     int16_t i_channels;
94     int16_t i_block_align;
95     int32_t i_avgbytespersec;
96 } oggds_header_audio_t;
97
98 typedef struct
99 #ifdef HAVE_ATTRIBUTE_PACKED
100     __attribute__((__packed__))
101 #endif
102 {
103     uint8_t i_packet_type;
104
105     char stream_type[8];
106     char sub_type[4];
107
108     int32_t i_size;
109
110     int64_t i_time_unit;
111     int64_t i_samples_per_unit;
112     int32_t i_default_len;
113
114     int32_t i_buffer_size;
115     int16_t i_bits_per_sample;
116
117     int16_t i_padding_0; /* Because the original is using MSVC packing style */
118
119     union
120     {
121         oggds_header_video_t video;
122         oggds_header_audio_t audio;
123     } header;
124
125     int32_t i_padding_1; /* Because the original is using MSVC packing style */
126
127 } oggds_header_t;
128
129 /* Helper writer functions */
130
131 #define SetWLE( p, v ) _SetWLE( (uint8_t*)p, v)
132 static void _SetWLE( uint8_t *p, uint16_t i_dw )
133 {
134     p[1] = ( i_dw >>  8 )&0xff;
135     p[0] = ( i_dw       )&0xff;
136 }
137
138 #define SetDWLE( p, v ) _SetDWLE( (uint8_t*)p, v)
139 static void _SetDWLE( uint8_t *p, uint32_t i_dw )
140 {
141     p[3] = ( i_dw >> 24 )&0xff;
142     p[2] = ( i_dw >> 16 )&0xff;
143     p[1] = ( i_dw >>  8 )&0xff;
144     p[0] = ( i_dw       )&0xff;
145 }
146 #define SetQWLE( p, v ) _SetQWLE( (uint8_t*)p, v)
147 static void _SetQWLE( uint8_t *p, uint64_t i_qw )
148 {
149     SetDWLE( p,   i_qw&0xffffffff );
150     SetDWLE( p+4, ( i_qw >> 32)&0xffffffff );
151 }
152
153 /*
154  * TODO  move this function to src/stream_output.c (used by nearly all muxers)
155  */
156 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
157 {
158     mtime_t i_dts;
159     int     i_stream;
160     int     i;
161
162     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
163     {
164         sout_fifo_t  *p_fifo;
165
166         p_fifo = p_mux->pp_inputs[i]->p_fifo;
167
168         /* We don't really need to have anything in the SPU fifo */
169         if( p_mux->pp_inputs[i]->p_fmt->i_cat == SPU_ES &&
170             p_fifo->i_depth == 0 ) continue;
171
172         if( p_fifo->i_depth > 2 ||
173             /* Special case for SPUs */
174             ( p_mux->pp_inputs[i]->p_fmt->i_cat == SPU_ES &&
175               p_fifo->i_depth > 0 ) )
176         {
177             sout_buffer_t *p_buf;
178
179             p_buf = sout_FifoShow( p_fifo );
180             if( i_stream < 0 || p_buf->i_dts < i_dts )
181             {
182                 i_dts = p_buf->i_dts;
183                 i_stream = i;
184             }
185         }
186         else
187         {
188             // wait that all fifo have at least 3 packets (3 vorbis headers)
189             return( -1 );
190         }
191     }
192     if( pi_stream )
193     {
194         *pi_stream = i_stream;
195     }
196     if( pi_dts )
197     {
198         *pi_dts = i_dts;
199     }
200     return( i_stream );
201 }
202
203 /*****************************************************************************
204  * Definitions of structures and functions used by this plugins 
205  *****************************************************************************/
206 typedef struct
207 {
208     int i_cat;
209     int i_fourcc;
210
211     int b_new;
212
213     mtime_t i_dts;
214     mtime_t i_length;
215     int     i_packet_no;
216     int     i_serial_no;
217     int     i_keyframe_granule_shift; /* Theora only */
218     ogg_stream_state os;
219
220     oggds_header_t oggds_header;
221
222     sout_buffer_t *pp_sout_headers[3];
223     int           i_sout_headers;
224
225 } ogg_stream_t;
226
227 struct sout_mux_sys_t
228 {
229     int     i_streams;
230
231     mtime_t i_start_dts;
232     int     i_next_serial_no;
233
234     /* number of logical streams pending to be added */
235     int i_add_streams;
236
237     /* logical streams pending to be deleted */
238     int i_del_streams;
239     ogg_stream_t **pp_del_streams;
240 };
241
242 static void OggSetDate( sout_buffer_t *, mtime_t , mtime_t  );
243 static sout_buffer_t *OggStreamFlush( sout_mux_t *, ogg_stream_state *,
244                                       mtime_t );
245
246 /*****************************************************************************
247  * Open: Open muxer
248  *****************************************************************************/
249 static int Open( vlc_object_t *p_this )
250 {
251     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
252     sout_mux_sys_t  *p_sys;
253
254     msg_Info( p_mux, "Open" );
255
256     p_sys                 = malloc( sizeof( sout_mux_sys_t ) );
257     p_sys->i_streams      = 0;
258     p_sys->i_add_streams  = 0;
259     p_sys->i_del_streams  = 0;
260     p_sys->pp_del_streams = 0;
261
262     p_mux->p_sys        = p_sys;
263     p_mux->pf_capacity  = Capability;
264     p_mux->pf_addstream = AddStream;
265     p_mux->pf_delstream = DelStream;
266     p_mux->pf_mux       = Mux;
267     p_mux->i_preheader  = 1;
268
269     /* First serial number is random.
270      * (Done like this because on win32 you need to seed the random number
271      *  generator once per thread). */
272     srand( (unsigned int)time( NULL ) );
273     p_sys->i_next_serial_no = rand();
274
275     return VLC_SUCCESS;
276 }
277
278 /*****************************************************************************
279  * Close: Finalize ogg bitstream and close muxer
280  *****************************************************************************/
281 static void Close( vlc_object_t * p_this )
282 {
283     sout_mux_t     *p_mux = (sout_mux_t*)p_this;
284     sout_mux_sys_t *p_sys = p_mux->p_sys;
285
286     msg_Info( p_mux, "Close" );
287
288     if( p_sys->i_del_streams )
289     {
290         sout_buffer_t *p_og = NULL;
291         mtime_t i_dts = -1;
292         int i;
293
294         /* Close the current ogg stream */
295         msg_Dbg( p_mux, "writing footer" );
296         sout_BufferChain( &p_og, OggCreateFooter( p_mux, 0 ) );
297
298         /* Remove deleted logical streams */
299         for( i = 0; i < p_sys->i_del_streams; i++ )
300         {
301             i_dts = p_sys->pp_del_streams[i]->i_dts;
302             ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
303             FREE( p_sys->pp_del_streams[i] );
304         }
305         FREE( p_sys->pp_del_streams );
306         p_sys->i_streams -= p_sys->i_del_streams;
307
308         /* Write footer */
309         OggSetDate( p_og, i_dts, 0 );
310         sout_AccessOutWrite( p_mux->p_access, p_og );
311     }
312
313     free( p_sys );
314 }
315
316 static int Capability( sout_mux_t *p_mux, int i_query, void *p_args,
317                        void *p_answer )
318 {
319    switch( i_query )
320    {
321         case SOUT_MUX_CAP_GET_ADD_STREAM_ANY_TIME:
322             *(vlc_bool_t*)p_answer = VLC_TRUE;
323             return( SOUT_MUX_CAP_ERR_OK );
324         default:
325             return( SOUT_MUX_CAP_ERR_UNIMPLEMENTED );
326    }
327 }
328
329 /*****************************************************************************
330  * AddStream: Add an elementary stream to the muxed stream
331  *****************************************************************************/
332 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
333 {
334     sout_mux_sys_t *p_sys = p_mux->p_sys;
335     ogg_stream_t   *p_stream;
336
337     msg_Dbg( p_mux, "adding input" );
338
339     p_input->p_sys = (void *)p_stream = malloc( sizeof( ogg_stream_t ) );
340
341     p_stream->i_cat       = p_input->p_fmt->i_cat;
342     p_stream->i_fourcc    = p_input->p_fmt->i_codec;
343     p_stream->i_serial_no = p_sys->i_next_serial_no++;
344     p_stream->i_packet_no = 0;
345
346     p_stream->i_sout_headers = 0;
347
348     memset( &p_stream->oggds_header, 0, sizeof(p_stream->oggds_header) );
349     p_stream->oggds_header.i_packet_type = PACKET_TYPE_HEADER;
350     switch( p_input->p_fmt->i_cat )
351     {
352     case VIDEO_ES:
353         switch( p_stream->i_fourcc )
354         {
355         case VLC_FOURCC( 'm', 'p','4', 'v' ):
356         case VLC_FOURCC( 'D', 'I','V', '3' ):
357             memcpy( p_stream->oggds_header.stream_type, "video", 5 );
358             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p','4', 'v' ) )
359             {
360                 memcpy( p_stream->oggds_header.sub_type, "XVID", 4 );
361             }
362             else if( p_stream->i_fourcc == VLC_FOURCC( 'D', 'I','V', '3' ) )
363             {
364                 memcpy( p_stream->oggds_header.sub_type, "DIV3", 4 );
365             }
366             SetDWLE( &p_stream->oggds_header.i_size,
367                      sizeof( oggds_header_t ) - 1);
368             SetQWLE( &p_stream->oggds_header.i_time_unit,
369                      I64C(10000000)/(int64_t)25 );  // FIXME (25fps)
370             SetQWLE( &p_stream->oggds_header.i_samples_per_unit, 1 );
371             SetDWLE( &p_stream->oggds_header.i_default_len, 1 ); /* ??? */
372             SetDWLE( &p_stream->oggds_header.i_buffer_size, 1024*1024 );
373             SetWLE( &p_stream->oggds_header.i_bits_per_sample, 0 );
374             SetDWLE( &p_stream->oggds_header.header.video.i_width,
375                      p_input->p_fmt->video.i_width );
376             SetDWLE( &p_stream->oggds_header.header.video.i_height,
377                      p_input->p_fmt->video.i_height );
378             msg_Dbg( p_mux, "mp4v/div3 stream" );
379             break;
380
381         case VLC_FOURCC( 't', 'h', 'e', 'o' ):
382             msg_Dbg( p_mux, "theora stream" );
383             break;
384
385         default:
386             FREE( p_input->p_sys );
387             return( VLC_EGENERIC );
388         }
389         break;
390
391     case AUDIO_ES:
392         switch( p_stream->i_fourcc )
393         {
394         case VLC_FOURCC( 'm', 'p','g', 'a' ):
395         case VLC_FOURCC( 'a', '5','2', ' ' ):
396             memcpy( p_stream->oggds_header.stream_type, "audio", 5 );
397             if( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p','g', 'a' ) )
398             {
399                 memcpy( p_stream->oggds_header.sub_type, "55  ", 4 );
400             }
401             else if( p_stream->i_fourcc == VLC_FOURCC( 'a', '5','2', ' ' ) )
402             {
403                 memcpy( p_stream->oggds_header.sub_type, "2000", 4 );
404             }
405             SetDWLE( &p_stream->oggds_header.i_size,
406                      sizeof( oggds_header_t ) - 1);
407             SetQWLE( &p_stream->oggds_header.i_time_unit, 0 /* not used */ );
408             SetDWLE( &p_stream->oggds_header.i_default_len, 1 );
409             SetDWLE( &p_stream->oggds_header.i_buffer_size, 30*1024 );
410             SetQWLE( &p_stream->oggds_header.i_samples_per_unit,
411                      p_input->p_fmt->audio.i_rate );
412             SetWLE( &p_stream->oggds_header.i_bits_per_sample, 0 );
413             SetDWLE( &p_stream->oggds_header.header.audio.i_channels,
414                      p_input->p_fmt->audio.i_channels );
415             SetDWLE( &p_stream->oggds_header.header.audio.i_block_align,
416                      p_input->p_fmt->audio.i_blockalign );
417             SetDWLE( &p_stream->oggds_header.header.audio.i_avgbytespersec, 0);
418             msg_Dbg( p_mux, "mpga/a52 stream" );
419             break;
420
421         case VLC_FOURCC( 'v', 'o', 'r', 'b' ):
422             msg_Dbg( p_mux, "vorbis stream" );
423             break;
424
425         case VLC_FOURCC( 's', 'p', 'x', ' ' ):
426             msg_Dbg( p_mux, "speex stream" );
427             break;
428
429         case VLC_FOURCC( 'f', 'l', 'a', 'c' ):
430             msg_Dbg( p_mux, "flac stream" );
431             break;
432
433         default:
434             FREE( p_input->p_sys );
435             return( VLC_EGENERIC );
436         }
437         break;
438
439     case SPU_ES:
440         switch( p_stream->i_fourcc )
441         {
442         case VLC_FOURCC( 's', 'u','b', 't' ):
443             memcpy( p_stream->oggds_header.stream_type, "text", 4 );
444             msg_Dbg( p_mux, "subtitles stream" );
445             break;
446
447         default:
448             FREE( p_input->p_sys );
449             return( VLC_EGENERIC );
450         }
451         break;
452     default:
453         FREE( p_input->p_sys );
454         return( VLC_EGENERIC );
455     }
456
457     p_stream->b_new = VLC_TRUE;
458
459     p_sys->i_add_streams++;
460
461     return( VLC_SUCCESS );
462 }
463
464 /*****************************************************************************
465  * DelStream: Delete an elementary stream from the muxed stream
466  *****************************************************************************/
467 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
468 {
469     sout_mux_sys_t *p_sys  = p_mux->p_sys;
470     ogg_stream_t   *p_stream = (ogg_stream_t*)p_input->p_sys;
471     sout_buffer_t  *p_og;
472
473     msg_Dbg( p_mux, "removing input" );
474
475     /* flush all remaining data */
476     if( p_input->p_sys )
477     {
478         int i;
479
480         if( ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
481         {
482             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
483             sout_AccessOutWrite( p_mux->p_access, p_og );
484         }
485
486         for( i = 0; i < p_stream->i_sout_headers; i++ )
487         {
488             sout_BufferDelete( p_mux->p_sout, p_stream->pp_sout_headers[i] );
489             p_stream->i_sout_headers = 0;
490         }
491
492         /* move input in delete queue */
493         if( !p_stream->b_new )
494         {
495             p_sys->pp_del_streams = realloc( p_sys->pp_del_streams,
496                                              (p_sys->i_del_streams + 1) *
497                                              sizeof(ogg_stream_t *) );
498             p_sys->pp_del_streams[p_sys->i_del_streams++] = p_stream;
499         }
500         else
501         {
502             /* Wasn't already added so get rid of it */
503             ogg_stream_clear( &p_stream->os );
504             FREE( p_stream );
505             p_sys->i_add_streams--;
506         }
507     }
508
509     p_input->p_sys = NULL;
510
511     return( 0 );
512 }
513
514 /*****************************************************************************
515  * Ogg bitstream manipulation routines
516  *****************************************************************************/
517 static sout_buffer_t *OggStreamFlush( sout_mux_t *p_mux,
518                                       ogg_stream_state *p_os, mtime_t i_pts )
519 {
520     sout_buffer_t *p_og, *p_og_first = NULL;
521     ogg_page      og;
522
523     for( ;; )
524     {
525         /* flush all data */
526         int i_result;
527         int i_size;
528         if( ( i_result = ogg_stream_flush( p_os, &og ) ) == 0 )
529         {
530             break;
531         }
532
533         i_size = og.header_len + og.body_len;
534         p_og = sout_BufferNew( p_mux->p_sout, i_size);
535
536         memcpy( p_og->p_buffer, og.header, og.header_len );
537         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
538         p_og->i_size    = i_size;
539         p_og->i_dts     = 0;
540         p_og->i_pts     = i_pts;
541         p_og->i_length  = 0;
542
543         i_pts   = 0; // write it only once
544
545         sout_BufferChain( &p_og_first, p_og );
546     }
547
548     return( p_og_first );
549 }
550
551 static sout_buffer_t *OggStreamPageOut( sout_mux_t *p_mux,
552                                         ogg_stream_state *p_os, mtime_t i_pts )
553 {
554     sout_buffer_t *p_og, *p_og_first = NULL;
555     ogg_page      og;
556
557     for( ;; )
558     {
559         /* flush all data */
560         int i_result;
561         int i_size;
562         if( ( i_result = ogg_stream_pageout( p_os, &og ) ) == 0 )
563         {
564             break;
565         }
566
567         i_size = og.header_len + og.body_len;
568         p_og = sout_BufferNew( p_mux->p_sout, i_size);
569
570         memcpy( p_og->p_buffer, og.header, og.header_len );
571         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
572         p_og->i_size    = i_size;
573         p_og->i_dts     = 0;
574         p_og->i_pts     = i_pts;
575         p_og->i_length  = 0;
576
577         i_pts   = 0; // write them only once
578
579         sout_BufferChain( &p_og_first, p_og );
580     }
581
582     return( p_og_first );
583 }
584
585 static sout_buffer_t *OggCreateHeader( sout_mux_t *p_mux, mtime_t i_dts )
586 {
587     sout_buffer_t *p_hdr = NULL;
588     sout_buffer_t *p_og;
589     ogg_packet    op;
590     int i;
591
592     /* Write header for each stream. All b_o_s (beginning of stream) packets
593      * must appear first in the ogg stream so we take care of them first. */
594     for( i = 0; i < p_mux->i_nb_inputs; i++ )
595     {
596         ogg_stream_t *p_stream = (ogg_stream_t*)p_mux->pp_inputs[i]->p_sys;
597         p_stream->b_new = VLC_FALSE;
598
599         msg_Dbg( p_mux, "creating header for %4.4s",
600                  (char *)&p_stream->i_fourcc );
601
602         ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
603         p_stream->i_packet_no = 0;
604
605         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
606             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
607             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
608         {
609             /* Special case, headers are already there in the
610              * incoming stream or we backed them up earlier */
611
612             /* first packet in order: vorbis/speex/theora info */
613             if( !p_stream->i_sout_headers )
614             {
615                 p_og = sout_FifoGet( p_mux->pp_inputs[i]->p_fifo );
616                 op.packet = p_og->p_buffer;
617                 op.bytes  = p_og->i_size;
618                 op.b_o_s  = 1;
619                 op.e_o_s  = 0;
620                 op.granulepos = 0;
621                 op.packetno = p_stream->i_packet_no++;
622                 ogg_stream_packetin( &p_stream->os, &op );
623                 p_stream->pp_sout_headers[0] =
624                     OggStreamFlush( p_mux, &p_stream->os, 0 );
625                 p_stream->i_sout_headers++;
626             }
627             p_og = sout_BufferDuplicate( p_mux->p_sout,
628                                          p_stream->pp_sout_headers[0] );
629
630             /* Get keyframe_granule_shift for theora granulepos calculation */
631             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
632             {
633                 int i_keyframe_frequency_force = 1 << (op.packet[36] >> 3);
634
635                 /* granule_shift = i_log( frequency_force -1 ) */
636                 p_stream->i_keyframe_granule_shift = 0;
637                 i_keyframe_frequency_force--;
638                 while( i_keyframe_frequency_force )
639                 {
640                     p_stream->i_keyframe_granule_shift++;
641                     i_keyframe_frequency_force >>= 1;
642                 }
643             }
644         }
645         else if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
646         {
647             /* flac stream marker (yeah, only that in the 1st packet) */
648             op.packet = "fLaC";
649             op.bytes  = 4;
650             op.b_o_s  = 1;
651             op.e_o_s  = 0;
652             op.granulepos = 0;
653             op.packetno = p_stream->i_packet_no++;
654             ogg_stream_packetin( &p_stream->os, &op );
655             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
656         }
657         else
658         {
659             /* ds header */
660             op.packet = (uint8_t*)&p_stream->oggds_header;
661             op.bytes  = sizeof( oggds_header_t );
662             op.b_o_s  = 1;
663             op.e_o_s  = 0;
664             op.granulepos = 0;
665             op.packetno = p_stream->i_packet_no++;
666             ogg_stream_packetin( &p_stream->os, &op );
667             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
668         }
669
670         sout_BufferChain( &p_hdr, p_og );
671     }
672
673     /* Take care of the non b_o_s headers */
674     for( i = 0; i < p_mux->i_nb_inputs; i++ )
675     {
676         ogg_stream_t *p_stream = (ogg_stream_t*)p_mux->pp_inputs[i]->p_sys;
677
678         if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
679             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) ||
680             p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
681         {
682             /* Special case, headers are already there in the incoming stream.
683              * We need to gather them an mark them as headers. */
684             int j;
685             for( j = 0; j < 2; j++ )
686             {
687                 if( p_stream->i_sout_headers < j + 2 )
688                 {
689                     /* next packets in order: comments and codebooks */
690                     p_og = sout_FifoGet( p_mux->pp_inputs[i]->p_fifo );
691                     op.packet = p_og->p_buffer;
692                     op.bytes  = p_og->i_size;
693                     op.b_o_s  = 0;
694                     op.e_o_s  = 0;
695                     op.granulepos = 0;
696                     op.packetno = p_stream->i_packet_no++;
697                     ogg_stream_packetin( &p_stream->os, &op );
698                     p_stream->pp_sout_headers[j+1] =
699                         OggStreamFlush( p_mux, &p_stream->os, 0 );
700                     p_stream->i_sout_headers++;
701                 }
702
703                 p_og = sout_BufferDuplicate( p_mux->p_sout,
704                                              p_stream->pp_sout_headers[j+1] );
705                 sout_BufferChain( &p_hdr, p_og );
706             }
707         }
708         else if( p_stream->i_fourcc != VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
709         {
710             uint8_t com[128];
711             int     i_com;
712
713             /* comment */
714             com[0] = PACKET_TYPE_COMMENT;
715             i_com = snprintf( &com[1], 128, VERSION" stream output" ) + 1;
716             op.packet = com;
717             op.bytes  = i_com;
718             op.b_o_s  = 0;
719             op.e_o_s  = 0;
720             op.granulepos = 0;
721             op.packetno = p_stream->i_packet_no++;
722             ogg_stream_packetin( &p_stream->os, &op );
723             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
724             sout_BufferChain( &p_hdr, p_og );
725         }
726
727         /* Special case for mp4v and flac */
728         if( ( p_stream->i_fourcc == VLC_FOURCC( 'm', 'p', '4', 'v' ) ||
729               p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) ) &&
730             p_mux->pp_inputs[i]->p_fmt->i_extra )
731         {
732             /* Send a packet with the VOL data for mp4v
733              * or STREAMINFO for flac */
734             msg_Dbg( p_mux, "writing extra data" );
735             op.bytes  = p_mux->pp_inputs[i]->p_fmt->i_extra;
736             op.packet = p_mux->pp_inputs[i]->p_fmt->p_extra;
737             if( p_stream->i_fourcc == VLC_FOURCC( 'f', 'l', 'a', 'c' ) )
738             {
739                 /* Skip the flac stream marker */
740                 ((uint8_t *)op.bytes) -= 4;
741                 ((uint8_t *)op.packet) += 4;
742             }
743             op.b_o_s  = 0;
744             op.e_o_s  = 0;
745             op.granulepos = 0;
746             op.packetno = p_stream->i_packet_no++;
747             ogg_stream_packetin( &p_stream->os, &op );
748             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
749             sout_BufferChain( &p_hdr, p_og );
750         }
751     }
752
753     /* set HEADER flag */
754     for( p_og = p_hdr; p_og != NULL; p_og = p_og->p_next )
755     {
756         p_og->i_flags |= SOUT_BUFFER_FLAGS_HEADER;
757     }
758     return( p_hdr );
759 }
760
761 static sout_buffer_t *OggCreateFooter( sout_mux_t *p_mux, mtime_t i_dts )
762 {
763     sout_mux_sys_t *p_sys = p_mux->p_sys;
764     sout_buffer_t *p_hdr = NULL;
765     sout_buffer_t *p_og;
766     ogg_packet    op;
767     int i;
768
769     /* flush all remaining data */
770     for( i = 0; i < p_mux->i_nb_inputs; i++ )
771     {
772         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
773
774         /* skip newly added streams */
775         if( p_stream->b_new ) continue;
776
777         if( ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
778         {
779             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
780             sout_AccessOutWrite( p_mux->p_access, p_og );
781         }
782     }
783
784     /* Write eos packets for each stream. */
785     for( i = 0; i < p_mux->i_nb_inputs; i++ )
786     {
787         ogg_stream_t *p_stream = p_mux->pp_inputs[i]->p_sys;
788
789         /* skip newly added streams */
790         if( p_stream->b_new ) continue;
791
792         op.packet = NULL;
793         op.bytes  = 0;
794         op.b_o_s  = 0;
795         op.e_o_s  = 1;
796         op.granulepos = -1;
797         op.packetno = p_stream->i_packet_no++;
798         ogg_stream_packetin( &p_stream->os, &op );
799
800         p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
801         sout_BufferChain( &p_hdr, p_og );
802         ogg_stream_clear( &p_stream->os );
803     }
804
805     for( i = 0; i < p_sys->i_del_streams; i++ )
806     {
807         op.packet = NULL;
808         op.bytes  = 0;
809         op.b_o_s  = 0;
810         op.e_o_s  = 1;
811         op.granulepos = -1;
812         op.packetno = p_sys->pp_del_streams[i]->i_packet_no++;
813         ogg_stream_packetin( &p_sys->pp_del_streams[i]->os, &op );
814
815         p_og = OggStreamFlush( p_mux, &p_sys->pp_del_streams[i]->os, 0 );
816         sout_BufferChain( &p_hdr, p_og );
817         ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
818     }
819
820     return( p_hdr );
821 }
822
823 static void OggSetDate( sout_buffer_t *p_og, mtime_t i_dts, mtime_t i_length )
824 {
825     int i_count;
826     sout_buffer_t *p_tmp;
827     mtime_t i_delta;
828
829     for( p_tmp = p_og, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->p_next )
830     {
831         i_count++;
832     }
833     i_delta = i_length / i_count;
834
835     for( p_tmp = p_og; p_tmp != NULL; p_tmp = p_tmp->p_next )
836     {
837         p_tmp->i_dts    = i_dts;
838         p_tmp->i_length = i_delta;
839
840         i_dts += i_delta;
841     }
842 }
843
844 /*****************************************************************************
845  * Mux: multiplex available data in input fifos into the Ogg bitstream
846  *****************************************************************************/
847 static int Mux( sout_mux_t *p_mux )
848 {
849     sout_mux_sys_t *p_sys = p_mux->p_sys;
850     sout_buffer_t  *p_og = NULL;
851     int            i_stream;
852     mtime_t        i_dts;
853
854     if( p_sys->i_add_streams || p_sys->i_del_streams )
855     {
856         /* Open new ogg stream */
857         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
858         {
859             msg_Dbg( p_mux, "waiting for data..." );
860             return( VLC_SUCCESS );
861         }
862
863         if( p_sys->i_streams )
864         {
865             /* Close current ogg stream */
866             int i;
867
868             msg_Dbg( p_mux, "writing footer" );
869             sout_BufferChain( &p_og, OggCreateFooter( p_mux, 0 ) );
870
871             /* Remove deleted logical streams */
872             for( i = 0; i < p_sys->i_del_streams; i++ )
873             {
874                 FREE( p_sys->pp_del_streams[i] );
875             }
876             FREE( p_sys->pp_del_streams );
877             p_sys->i_streams = 0;
878         }
879
880         msg_Dbg( p_mux, "writing header" );
881         p_sys->i_start_dts = i_dts;
882         p_sys->i_streams = p_mux->i_nb_inputs;
883         p_sys->i_del_streams = 0;
884         p_sys->i_add_streams = 0;
885         sout_BufferChain( &p_og, OggCreateHeader( p_mux, i_dts ) );
886
887         /* Write header and/or footer */
888         OggSetDate( p_og, i_dts, 0 );
889         sout_AccessOutWrite( p_mux->p_access, p_og );
890         p_og = NULL;
891     }
892
893     for( ;; )
894     {
895         sout_input_t  *p_input;
896         ogg_stream_t  *p_stream;
897         sout_buffer_t *p_data;
898         ogg_packet    op;
899
900         if( MuxGetStream( p_mux, &i_stream, &i_dts) < 0 )
901         {
902             return( VLC_SUCCESS );
903         }
904
905         p_input  = p_mux->pp_inputs[i_stream];
906         p_stream = (ogg_stream_t*)p_input->p_sys;
907         p_data   = sout_FifoGet( p_input->p_fifo );
908
909         if( p_stream->i_fourcc != VLC_FOURCC( 'v', 'o', 'r', 'b' ) &&
910             p_stream->i_fourcc != VLC_FOURCC( 's', 'p', 'x', ' ' ) &&
911             p_stream->i_fourcc != VLC_FOURCC( 't', 'h', 'e', 'o' ) )
912         {
913             sout_BufferReallocFromPreHeader( p_mux->p_sout, p_data, 1 );
914             p_data->p_buffer[0] = PACKET_IS_SYNCPOINT;      // FIXME
915         }
916
917         op.packet   = p_data->p_buffer;
918         op.bytes    = p_data->i_size;
919         op.b_o_s    = 0;
920         op.e_o_s    = 0;
921         op.packetno = p_stream->i_packet_no++;
922
923         if( p_stream->i_cat == AUDIO_ES )
924         {
925             if( p_stream->i_fourcc == VLC_FOURCC( 'v', 'o', 'r', 'b' ) ||
926                 p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) )
927             {
928                 /* number of sample from begining + current packet */
929                 op.granulepos =
930                     ( i_dts + p_data->i_length - p_sys->i_start_dts ) *
931                     p_input->p_fmt->audio.i_rate / I64C(1000000);
932             }
933             else
934             {
935                 /* number of sample from begining */
936                 op.granulepos = ( i_dts - p_sys->i_start_dts ) *
937                     p_stream->oggds_header.i_samples_per_unit / I64C(1000000);
938             }
939         }
940         else if( p_stream->i_cat == VIDEO_ES )
941         {
942             if( p_stream->i_fourcc == VLC_FOURCC( 't', 'h', 'e', 'o' ) )
943             {
944                 /* FIXME, we assume only keyframes and 25fps */
945                 op.granulepos = ( ( i_dts - p_sys->i_start_dts ) * I64C(25)
946                     / I64C(1000000) ) << p_stream->i_keyframe_granule_shift;
947             }
948             else
949                 op.granulepos = ( i_dts - p_sys->i_start_dts ) * I64C(10) /
950                     p_stream->oggds_header.i_time_unit;
951         }
952         else if( p_stream->i_cat == SPU_ES )
953         {
954             /* granulepos is in milisec */
955             op.granulepos = ( i_dts - p_sys->i_start_dts ) / 1000;
956         }
957
958         ogg_stream_packetin( &p_stream->os, &op );
959
960         if( p_stream->i_cat == SPU_ES ||
961             p_stream->i_fourcc == VLC_FOURCC( 's', 'p', 'x', ' ' ) )
962         {
963             /* Subtitles or Speex packets are quite small so they 
964              * need to be flushed to be sent on time */
965             sout_BufferChain( &p_og, OggStreamFlush( p_mux, &p_stream->os,
966                                                      p_data->i_dts ) );
967         }
968         else
969         {
970             sout_BufferChain( &p_og, OggStreamPageOut( p_mux, &p_stream->os,
971                                                        p_data->i_dts ) );
972         }
973
974         if( p_og )
975         {
976             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
977             p_stream->i_dts = -1;
978             p_stream->i_length = 0;
979
980             sout_AccessOutWrite( p_mux->p_access, p_og );
981
982             p_og = NULL;
983         }
984         else
985         {
986             if( p_stream->i_dts < 0 )
987             {
988                 p_stream->i_dts = p_data->i_dts;
989             }
990             p_stream->i_length += p_data->i_length;
991         }
992
993         sout_BufferDelete( p_mux->p_sout, p_data );
994     }
995
996     return( VLC_SUCCESS );
997 }