]> git.sesse.net Git - vlc/blob - modules/mux/ogg.c
mux: ogg: rewrite steam creation and ordering (fix #9731, fix #9732)
[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 *OggCreateHeaders( sout_mux_t * );
70
71 /*****************************************************************************
72  * Misc declarations
73  *****************************************************************************/
74
75 /* Skeleton */
76 #define FISBONE_BASE_SIZE 52
77 #define FISBONE_BASE_OFFSET 44
78
79 /* Structures used for OggDS headers used in ogm files */
80
81 #define PACKET_TYPE_HEADER   0x01
82 #define PACKET_TYPE_COMMENT  0x03
83 #define PACKET_IS_SYNCPOINT  0x08
84
85 typedef struct
86 {
87     int32_t i_width;
88     int32_t i_height;
89 } oggds_header_video_t;
90
91 typedef struct
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 {
100     uint8_t i_packet_type;
101
102     char stream_type[8];
103     char sub_type[4];
104
105     int32_t i_size;
106
107     int64_t i_time_unit;
108     int64_t i_samples_per_unit;
109     int32_t i_default_len;
110
111     int32_t i_buffer_size;
112     int16_t i_bits_per_sample;
113
114     int16_t i_padding_0; /* Because the original is using MSVC packing style */
115
116     union
117     {
118         oggds_header_video_t video;
119         oggds_header_audio_t audio;
120     } header;
121
122     int32_t i_padding_1; /* Because the original is using MSVC packing style */
123
124 } oggds_header_t;
125
126 /*****************************************************************************
127  * Definitions of structures and functions used by this plugins
128  *****************************************************************************/
129 typedef struct
130 {
131     int i_cat;
132     vlc_fourcc_t i_fourcc;
133
134     int b_new;
135
136     mtime_t i_dts;
137     mtime_t i_length;
138     int     i_packet_no;
139     int     i_serial_no;
140     int     i_keyframe_granule_shift; /* Theora only */
141     int     i_last_keyframe; /* dirac and theora */
142     int     i_num_frames; /* Theora only */
143     uint64_t u_last_granulepos; /* Used for correct EOS page */
144     int64_t i_num_keyframes;
145     ogg_stream_state os;
146
147     oggds_header_t *p_oggds_header;
148     bool b_fisbone_done;
149     bool b_started;
150     bool b_finished;
151
152 } ogg_stream_t;
153
154 struct sout_mux_sys_t
155 {
156     int     i_streams;
157
158     mtime_t i_start_dts;
159     int     i_next_serial_no;
160
161     /* number of logical streams pending to be added */
162     int i_add_streams;
163     bool b_can_add_streams;
164
165     /* logical streams pending to be deleted */
166     int i_del_streams;
167     ogg_stream_t **pp_del_streams;
168
169     /* Skeleton */
170     struct
171     {
172         bool b_create;
173         int i_serial_no;
174         int i_packet_no;
175         ogg_stream_state os;
176         bool b_head_done;
177     } skeleton;
178 };
179
180 static void OggSetDate( block_t *, mtime_t , mtime_t  );
181 static block_t *OggStreamFlush( sout_mux_t *, ogg_stream_state *, mtime_t );
182 static block_t *OggCreateStreamFooter( sout_mux_t *p_mux, ogg_stream_t *p_stream );
183
184 /*****************************************************************************
185  * Open: Open muxer
186  *****************************************************************************/
187 static int Open( vlc_object_t *p_this )
188 {
189     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
190     sout_mux_sys_t  *p_sys;
191
192     msg_Info( p_mux, "Open" );
193
194     p_sys                 = malloc( sizeof( sout_mux_sys_t ) );
195     if( !p_sys )
196         return VLC_ENOMEM;
197     p_sys->i_streams      = 0;
198     p_sys->i_add_streams  = 0;
199     p_sys->b_can_add_streams = true;
200     p_sys->i_del_streams  = 0;
201     p_sys->pp_del_streams = 0;
202
203     p_mux->p_sys        = p_sys;
204     p_mux->pf_control   = Control;
205     p_mux->pf_addstream = AddStream;
206     p_mux->pf_delstream = DelStream;
207     p_mux->pf_mux       = Mux;
208
209     /* First serial number is random.
210      * (Done like this because on win32 you need to seed the random number
211      *  generator once per thread). */
212     uint32_t r;
213     vlc_rand_bytes(&r, sizeof(r));
214     p_sys->i_next_serial_no = r & INT_MAX;
215
216     return VLC_SUCCESS;
217 }
218
219 /*****************************************************************************
220  * Close: Finalize ogg bitstream and close muxer
221  *****************************************************************************/
222 static void Close( vlc_object_t * p_this )
223 {
224     sout_mux_t     *p_mux = (sout_mux_t*)p_this;
225     sout_mux_sys_t *p_sys = p_mux->p_sys;
226
227     msg_Info( p_mux, "Close" );
228
229     if( p_sys->i_del_streams )
230     {
231         block_t *p_og = NULL;
232         mtime_t i_dts = p_sys->pp_del_streams[p_sys->i_del_streams - 1]->i_dts;
233
234         /* Close the current ogg stream */
235         msg_Dbg( p_mux, "writing footer" );
236
237         for(int i = 0; i < p_mux->i_nb_inputs; i++ )
238         {
239             block_ChainAppend( &p_og, OggCreateStreamFooter( p_mux, (ogg_stream_t *) p_mux->pp_inputs[i]->p_sys ) );
240         }
241
242         /* Remove deleted logical streams */
243         for(int i = 0; i < p_sys->i_del_streams; i++ )
244         {
245             block_ChainAppend( &p_og, OggCreateStreamFooter( p_mux, p_sys->pp_del_streams[i] ) );
246             ogg_stream_clear( &p_sys->pp_del_streams[i]->os );
247             FREENULL( p_sys->pp_del_streams[i]->p_oggds_header );
248             FREENULL( p_sys->pp_del_streams[i] );
249         }
250         FREENULL( p_sys->pp_del_streams );
251         p_sys->i_streams -= p_sys->i_del_streams;
252
253         /* Write footer */
254         OggSetDate( p_og, i_dts, 0 );
255         sout_AccessOutWrite( p_mux->p_access, p_og );
256     }
257
258     free( p_sys );
259 }
260
261 /*****************************************************************************
262  * Control:
263  *****************************************************************************/
264 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
265 {
266     VLC_UNUSED(p_mux);
267     bool *pb_bool;
268     char **ppsz;
269
270    switch( i_query )
271    {
272        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
273            pb_bool = (bool*)va_arg( args, bool * );
274            *pb_bool = true;
275            return VLC_SUCCESS;
276
277        case MUX_GET_ADD_STREAM_WAIT:
278            pb_bool = (bool*)va_arg( args, bool * );
279            *pb_bool = true;
280            return VLC_SUCCESS;
281
282        case MUX_GET_MIME:
283            ppsz = (char**)va_arg( args, char ** );
284            *ppsz = strdup( "application/ogg" );
285            return VLC_SUCCESS;
286
287         default:
288             return VLC_EGENERIC;
289    }
290 }
291 /*****************************************************************************
292  * AddStream: Add an elementary stream to the muxed stream
293  *****************************************************************************/
294 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
295 {
296     sout_mux_sys_t *p_sys = p_mux->p_sys;
297     ogg_stream_t   *p_stream;
298     uint16_t i_tag;
299
300     msg_Dbg( p_mux, "adding input" );
301
302     p_input->p_sys = p_stream = calloc( 1, sizeof( ogg_stream_t ) );
303     if( !p_stream )
304         return VLC_ENOMEM;
305
306     p_stream->i_cat       = p_input->p_fmt->i_cat;
307     p_stream->i_fourcc    = p_input->p_fmt->i_codec;
308     p_stream->i_serial_no = p_sys->i_next_serial_no++;
309     p_stream->i_packet_no = 0;
310     p_stream->i_last_keyframe = 0;
311     p_stream->i_num_keyframes = 0;
312     p_stream->i_num_frames = 0;
313
314     p_stream->p_oggds_header = 0;
315
316     /* FIXME: https://trac.videolan.org/vlc/ticket/1412 */
317     switch( p_input->p_fmt->i_cat )
318     {
319     case VIDEO_ES:
320         if( !p_input->p_fmt->video.i_frame_rate ||
321             !p_input->p_fmt->video.i_frame_rate_base )
322         {
323             msg_Warn( p_mux, "Missing frame rate, assuming 25fps" );
324             p_input->p_fmt->video.i_frame_rate = 25;
325             p_input->p_fmt->video.i_frame_rate_base = 1;
326         }
327
328         switch( p_stream->i_fourcc )
329         {
330         case VLC_CODEC_MP4V:
331         case VLC_CODEC_MPGV:
332         case VLC_CODEC_DIV3:
333         case VLC_CODEC_MJPG:
334         case VLC_CODEC_WMV1:
335         case VLC_CODEC_WMV2:
336         case VLC_CODEC_WMV3:
337             p_stream->p_oggds_header = calloc( 1, sizeof(oggds_header_t) );
338             if( !p_stream->p_oggds_header )
339             {
340                 free( p_stream );
341                 return VLC_ENOMEM;
342             }
343             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
344
345             memcpy( p_stream->p_oggds_header->stream_type, "video", 5 );
346             if( p_stream->i_fourcc == VLC_CODEC_MP4V )
347             {
348                 memcpy( p_stream->p_oggds_header->sub_type, "XVID", 4 );
349             }
350             else if( p_stream->i_fourcc == VLC_CODEC_DIV3 )
351             {
352                 memcpy( p_stream->p_oggds_header->sub_type, "DIV3", 4 );
353             }
354             else
355             {
356                 memcpy( p_stream->p_oggds_header->sub_type,
357                         &p_stream->i_fourcc, 4 );
358             }
359             p_stream->p_oggds_header->i_size = 0 ;
360             p_stream->p_oggds_header->i_time_unit =
361                      INT64_C(10000000) * p_input->p_fmt->video.i_frame_rate_base /
362                      (int64_t)p_input->p_fmt->video.i_frame_rate;
363             p_stream->p_oggds_header->i_samples_per_unit = 1;
364             p_stream->p_oggds_header->i_default_len = 1 ; /* ??? */
365             p_stream->p_oggds_header->i_buffer_size = 1024*1024;
366             p_stream->p_oggds_header->i_bits_per_sample = 0;
367             p_stream->p_oggds_header->header.video.i_width = p_input->p_fmt->video.i_width;
368             p_stream->p_oggds_header->header.video.i_height = p_input->p_fmt->video.i_height;
369             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
370             break;
371
372         case VLC_CODEC_DIRAC:
373             msg_Dbg( p_mux, "dirac stream" );
374             break;
375
376         case VLC_CODEC_THEORA:
377             msg_Dbg( p_mux, "theora stream" );
378             break;
379
380         default:
381             FREENULL( p_input->p_sys );
382             return VLC_EGENERIC;
383         }
384         break;
385
386     case AUDIO_ES:
387         switch( p_stream->i_fourcc )
388         {
389         case VLC_CODEC_OPUS:
390             msg_Dbg( p_mux, "opus stream" );
391             break;
392
393         case VLC_CODEC_VORBIS:
394             msg_Dbg( p_mux, "vorbis stream" );
395             break;
396
397         case VLC_CODEC_SPEEX:
398             msg_Dbg( p_mux, "speex stream" );
399             break;
400
401         case VLC_CODEC_FLAC:
402             msg_Dbg( p_mux, "flac stream" );
403             break;
404
405         default:
406             fourcc_to_wf_tag( p_stream->i_fourcc, &i_tag );
407             if( i_tag == WAVE_FORMAT_UNKNOWN )
408             {
409                 FREENULL( p_input->p_sys );
410                 return VLC_EGENERIC;
411             }
412
413             p_stream->p_oggds_header =
414                 malloc( sizeof(oggds_header_t) + p_input->p_fmt->i_extra );
415             if( !p_stream->p_oggds_header )
416             {
417                 free( p_stream );
418                 return VLC_ENOMEM;
419             }
420             memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
421             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
422
423             p_stream->p_oggds_header->i_size = p_input->p_fmt->i_extra;
424
425             if( p_input->p_fmt->i_extra )
426             {
427                 memcpy( &p_stream->p_oggds_header[1],
428                         p_input->p_fmt->p_extra, p_input->p_fmt->i_extra );
429             }
430
431             memcpy( p_stream->p_oggds_header->stream_type, "audio", 5 );
432
433             memset( p_stream->p_oggds_header->sub_type, 0, 4 );
434             char buf[5];
435             snprintf( buf, sizeof(buf), "%"PRIx16, i_tag );
436             strncpy( p_stream->p_oggds_header->sub_type, buf, 4 );
437
438             p_stream->p_oggds_header->i_time_unit = INT64_C(10000000);
439             p_stream->p_oggds_header->i_default_len = 1;
440             p_stream->p_oggds_header->i_buffer_size = 30*1024 ;
441             p_stream->p_oggds_header->i_samples_per_unit = p_input->p_fmt->audio.i_rate;
442             p_stream->p_oggds_header->i_bits_per_sample = p_input->p_fmt->audio.i_bitspersample;
443             p_stream->p_oggds_header->header.audio.i_channels = p_input->p_fmt->audio.i_channels;
444             p_stream->p_oggds_header->header.audio.i_block_align =  p_input->p_fmt->audio.i_blockalign;
445             p_stream->p_oggds_header->header.audio.i_avgbytespersec =  p_input->p_fmt->i_bitrate / 8;
446             msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
447             break;
448         }
449         break;
450
451     case SPU_ES:
452         switch( p_stream->i_fourcc )
453         {
454         case VLC_CODEC_SUBT:
455             p_stream->p_oggds_header = calloc( 1, sizeof(oggds_header_t) );
456             if( !p_stream->p_oggds_header )
457             {
458                 free( p_stream );
459                 return VLC_ENOMEM;
460             }
461             p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;
462
463             memcpy( p_stream->p_oggds_header->stream_type, "text", 4 );
464             msg_Dbg( p_mux, "subtitles stream" );
465             break;
466
467         default:
468             FREENULL( p_input->p_sys );
469             return VLC_EGENERIC;
470         }
471         break;
472     default:
473         FREENULL( p_input->p_sys );
474         return VLC_EGENERIC;
475     }
476
477     p_stream->b_new = true;
478
479     p_sys->i_add_streams++;
480
481     return VLC_SUCCESS;
482 }
483
484 /*****************************************************************************
485  * DelStream: Delete an elementary stream from the muxed stream
486  *****************************************************************************/
487 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
488 {
489     sout_mux_sys_t *p_sys  = p_mux->p_sys;
490     ogg_stream_t   *p_stream = (ogg_stream_t*)p_input->p_sys;
491     block_t *p_og;
492
493     msg_Dbg( p_mux, "removing input" );
494
495     /* flush all remaining data */
496     if( p_input->p_sys )
497     {
498         if( !p_stream->b_new )
499         {
500             while( block_FifoCount( p_input->p_fifo ) )
501                 MuxBlock( p_mux, p_input );
502         }
503
504         if( !p_stream->b_new &&
505             ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
506         {
507             OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
508             sout_AccessOutWrite( p_mux->p_access, p_og );
509         }
510
511         /* move input in delete queue */
512         if( !p_stream->b_new )
513         {
514             p_sys->pp_del_streams = xrealloc( p_sys->pp_del_streams,
515                         (p_sys->i_del_streams + 1) * sizeof(ogg_stream_t *) );
516             p_sys->pp_del_streams[p_sys->i_del_streams++] = p_stream;
517         }
518         else
519         {
520             /* wasn't already added so get rid of it */
521             FREENULL( p_stream->p_oggds_header );
522             FREENULL( p_stream );
523             p_sys->i_add_streams--;
524         }
525     }
526
527     p_input->p_sys = NULL;
528
529     return 0;
530 }
531
532 /*****************************************************************************
533  * Ogg bitstream manipulation routines
534  *****************************************************************************/
535 static block_t *OggStreamGetPage( sout_mux_t *p_mux,
536                                   ogg_stream_state *p_os, mtime_t i_pts,
537                                   bool flush )
538 {
539     (void)p_mux;
540     block_t *p_og, *p_og_first = NULL;
541     ogg_page og;
542     int (*pager)( ogg_stream_state*, ogg_page* ) = flush ? ogg_stream_flush : ogg_stream_pageout;
543
544     while( pager( p_os, &og ) )
545     {
546         /* Flush all data */
547         p_og = block_Alloc( og.header_len + og.body_len );
548
549         memcpy( p_og->p_buffer, og.header, og.header_len );
550         memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
551         p_og->i_dts     = 0;
552         p_og->i_pts     = i_pts;
553         p_og->i_length  = 0;
554
555         i_pts = 0; // write it only once
556
557         block_ChainAppend( &p_og_first, p_og );
558     }
559
560     return p_og_first;
561 }
562
563 static block_t *OggStreamFlush( sout_mux_t *p_mux,
564                                 ogg_stream_state *p_os, mtime_t i_pts )
565 {
566     return OggStreamGetPage( p_mux, p_os, i_pts, true );
567 }
568
569 static block_t *OggStreamPageOut( sout_mux_t *p_mux,
570                                   ogg_stream_state *p_os, mtime_t i_pts )
571 {
572     return OggStreamGetPage( p_mux, p_os, i_pts, false );
573 }
574
575 static void OggGetSkeletonFisbone( uint8_t **pp_buffer, long *pi_size,
576                                    sout_input_t *p_input, sout_mux_t *p_mux )
577 {
578     uint8_t *psz_header;
579     uint8_t *p_buffer;
580     const char *psz_value = NULL;
581     ogg_stream_t *p_stream = (ogg_stream_t *) p_input->p_sys;
582     struct
583     {
584         char *psz_content_type;
585         char *psz_role;
586         long int i_size;
587         unsigned int i_count;
588     } headers = { NULL, NULL, 0, 0 };
589     *pi_size = 0;
590
591     switch( p_stream->i_fourcc )
592     {
593         case VLC_CODEC_VORBIS:
594             psz_value = "audio/vorbis";
595             break;
596         case VLC_CODEC_THEORA:
597             psz_value = "video/theora";
598             break;
599         case VLC_CODEC_SPEEX:
600             psz_value = "audio/speex";
601             break;
602         case VLC_CODEC_FLAC:
603             psz_value = "audio/flac";
604             break;
605         case VLC_CODEC_CMML:
606             psz_value = "text/cmml";
607             break;
608         case VLC_CODEC_KATE:
609             psz_value = "application/kate";
610             break;
611         default:
612             psz_value = "application/octet-stream";
613             msg_Warn( p_mux, "Unkown fourcc for stream %s, setting Content-Type to %s",
614                   vlc_fourcc_GetDescription( p_stream->i_cat, p_stream->i_fourcc ),
615                   psz_value );
616     }
617
618     /* Content Type Header */
619     if ( asprintf( &headers.psz_content_type, "Content-Type: %s\r\n", psz_value ) != -1 )
620     {
621         headers.i_size += strlen( headers.psz_content_type );
622         headers.i_count++;
623     }
624
625     /* Set Role Header */
626     if ( p_input->p_fmt->i_priority > ES_PRIORITY_NOT_SELECTABLE )
627     {
628         int i_max_prio = ES_PRIORITY_MIN;
629         for ( int i=0; i< p_mux->i_nb_inputs; i++ )
630         {
631             if ( p_mux->pp_inputs[i]->p_fmt->i_cat != p_input->p_fmt->i_cat ) continue;
632             i_max_prio = __MAX( p_mux->pp_inputs[i]->p_fmt->i_priority, i_max_prio );
633         }
634
635         psz_value = NULL;
636         if ( p_input->p_fmt->i_cat == AUDIO_ES || p_input->p_fmt->i_cat == VIDEO_ES )
637         {
638             if ( p_input->p_fmt->i_priority == i_max_prio && i_max_prio >= ES_PRIORITY_SELECTABLE_MIN )
639                 psz_value = ( p_input->p_fmt->i_cat == VIDEO_ES ) ?
640                             "video/main" : "audio/main";
641             else
642                 psz_value = ( p_input->p_fmt->i_cat == VIDEO_ES ) ?
643                             "video/alternate" : "audio/alternate";
644         }
645         else if ( p_input->p_fmt->i_cat == SPU_ES )
646         {
647             psz_value = ( p_input->p_fmt->i_codec == VLC_CODEC_KATE ) ?
648                         "text/karaoke" : "text/subtitle";
649         }
650
651         if ( psz_value && asprintf( &headers.psz_role, "Role: %s\r\n", psz_value ) != -1 )
652         {
653             headers.i_size += strlen( headers.psz_role );
654             headers.i_count++;
655         }
656     }
657
658     *pp_buffer = calloc( FISBONE_BASE_SIZE + headers.i_size, sizeof(uint8_t) );
659     if ( !*pp_buffer ) return;
660     p_buffer = *pp_buffer;
661
662     memcpy( p_buffer, "fisbone", 8 );
663     SetDWLE( &p_buffer[8], FISBONE_BASE_OFFSET ); /* offset to message headers */
664     SetDWLE( &p_buffer[12], p_stream->i_serial_no );
665     SetDWLE( &p_buffer[16], headers.i_count );
666
667     /* granulerate den */
668     switch ( p_input->p_fmt->i_cat )
669     {
670         case VIDEO_ES:
671             SetQWLE( &(*pp_buffer)[20], p_input->p_fmt->video.i_frame_rate );
672             SetQWLE( &(*pp_buffer)[28], p_input->p_fmt->video.i_frame_rate_base );
673         break;
674         case AUDIO_ES:
675             SetQWLE( &(*pp_buffer)[20], p_input->p_fmt->audio.i_rate );
676             SetQWLE( &(*pp_buffer)[28], 1 );
677         break;
678         default:
679             SetQWLE( &(*pp_buffer)[20], 1000 );
680             SetQWLE( &(*pp_buffer)[28], 1 );
681     }
682
683     /* preroll */
684     if ( p_input->p_fmt->p_extra )
685         SetDWLE( &(*pp_buffer)[44], xiph_CountHeaders( p_input->p_fmt->p_extra ) );
686
687     psz_header = *pp_buffer + FISBONE_BASE_SIZE;
688     memcpy( psz_header, headers.psz_content_type, strlen( headers.psz_content_type ) );
689     psz_header += strlen( headers.psz_content_type );
690     if ( headers.psz_role )
691         memcpy( psz_header, headers.psz_role, strlen( headers.psz_role ) );
692
693     *pi_size = FISBONE_BASE_SIZE + headers.i_size;
694
695     free( headers.psz_content_type );
696     free( headers.psz_role );
697 }
698
699 static void OggFillSkeletonFishead( uint8_t *p_buffer, sout_mux_t *p_mux )
700 {
701     VLC_UNUSED( p_mux );
702     memcpy( p_buffer, "fishead", 8 );
703     SetWLE( &p_buffer[8], 4 );
704     SetWLE( &p_buffer[10], 0 );
705     SetQWLE( &p_buffer[20], 1000 );
706     SetQWLE( &p_buffer[36], 1000 );
707     SetQWLE( &p_buffer[64], 0 );
708     SetQWLE( &p_buffer[72], 0 );
709 }
710
711 static int32_t OggFillDsHeader( uint8_t *p_buffer, oggds_header_t *p_oggds_header, int i_cat )
712 {
713     int index = 0;
714     p_buffer[index] = p_oggds_header->i_packet_type;
715     index++;
716     memcpy( &p_buffer[index], p_oggds_header->stream_type, sizeof(p_oggds_header->stream_type) );
717     index += sizeof(p_oggds_header->stream_type);
718     memcpy(&p_buffer[index], p_oggds_header->sub_type, sizeof(p_oggds_header->sub_type) );
719     index += sizeof(p_oggds_header->sub_type);
720
721     /* The size is filled at the end */
722     uint8_t *p_isize = &p_buffer[index];
723     index += 4;
724
725     SetQWLE( &p_buffer[index], p_oggds_header->i_time_unit );
726     index += 8;
727     SetQWLE( &p_buffer[index], p_oggds_header->i_samples_per_unit );
728     index += 8;
729     SetDWLE( &p_buffer[index], p_oggds_header->i_default_len );
730     index += 4;
731     SetDWLE( &p_buffer[index], p_oggds_header->i_buffer_size );
732     index += 4;
733     SetWLE( &p_buffer[index], p_oggds_header->i_bits_per_sample );
734     index += 2;
735     SetWLE( &p_buffer[index], p_oggds_header->i_padding_0 );
736     index += 2;
737     /* audio or video */
738     switch( i_cat )
739     {
740     case VIDEO_ES:
741         SetDWLE( &p_buffer[index], p_oggds_header->header.video.i_width );
742         SetDWLE( &p_buffer[index+4], p_oggds_header->header.video.i_height );
743         break;
744     case AUDIO_ES:
745         SetWLE( &p_buffer[index], p_oggds_header->header.audio.i_channels );
746         SetWLE( &p_buffer[index+2], p_oggds_header->header.audio.i_block_align );
747         SetDWLE( &p_buffer[index+4], p_oggds_header->header.audio.i_avgbytespersec );
748         break;
749     }
750     index += 8;
751     SetDWLE( &p_buffer[index], p_oggds_header->i_padding_1 );
752     index += 4;
753
754     /* extra header */
755     if( p_oggds_header->i_size > 0 )
756     {
757         memcpy( &p_buffer[index], p_oggds_header + sizeof(*p_oggds_header), p_oggds_header->i_size );
758         index += p_oggds_header->i_size;
759     }
760
761     SetDWLE( p_isize, index-1 );
762     return index;
763 }
764
765 static block_t *OggCreateHeaders( sout_mux_t *p_mux )
766 {
767     block_t *p_hdr = NULL;
768     block_t *p_og = NULL;
769     ogg_packet op;
770     ogg_stream_t *p_stream;
771     sout_mux_sys_t *p_sys = p_mux->p_sys;
772     int i;
773     p_sys->skeleton.b_create = !! p_mux->i_nb_inputs;
774
775     /* no skeleton for solo vorbis/speex/opus tracks */
776     if ( p_mux->i_nb_inputs == 1 && p_mux->pp_inputs[0]->p_fmt->i_cat == AUDIO_ES )
777     {
778         p_sys->skeleton.b_create = false;
779     }
780     else
781     {
782         for ( int i=0; i< p_mux->i_nb_inputs; i++ )
783         {
784             p_stream = (ogg_stream_t*) p_mux->pp_inputs[i]->p_sys;
785             if ( p_stream->p_oggds_header )
786             {
787                 /* We don't want skeleton for OggDS */
788                 p_sys->skeleton.b_create = false;
789                 break;
790             }
791         }
792     }
793
794     /* Skeleton's Fishead must be the first page of the stream */
795     if ( p_sys->skeleton.b_create && !p_sys->skeleton.b_head_done )
796     {
797         msg_Dbg( p_mux, "creating header for skeleton" );
798         p_sys->skeleton.i_serial_no = p_sys->i_next_serial_no++;
799         ogg_stream_init( &p_sys->skeleton.os, p_sys->skeleton.i_serial_no );
800         op.bytes = 80;
801         op.packet = calloc( 1, op.bytes );
802         if ( op.packet == NULL ) return NULL;
803         op.b_o_s = 1;
804         op.e_o_s = 0;
805         op.granulepos = 0;
806         op.packetno = 0;
807         OggFillSkeletonFishead( op.packet, p_mux );
808         ogg_stream_packetin( &p_sys->skeleton.os, &op );
809         p_og = OggStreamFlush( p_mux, &p_sys->skeleton.os, 0 );
810         block_ChainAppend( &p_hdr, p_og );
811         p_sys->skeleton.b_head_done = true;
812     }
813
814     /* Write header for each stream. All b_o_s (beginning of stream) packets
815      * must appear first in the ogg stream so we take care of them first. */
816     for( int pass = 0; pass < 2; pass++ )
817     {
818         for( i = 0; i < p_mux->i_nb_inputs; i++ )
819         {
820             sout_input_t *p_input = p_mux->pp_inputs[i];
821             p_stream = (ogg_stream_t*)p_input->p_sys;
822
823             bool video = ( p_stream->i_fourcc == VLC_CODEC_THEORA || p_stream->i_fourcc == VLC_CODEC_DIRAC );
824             if( ( ( pass == 0 && !video ) || ( pass == 1 && video ) ) )
825                 continue;
826
827             msg_Dbg( p_mux, "creating header for %4.4s",
828                      (char *)&p_stream->i_fourcc );
829
830             ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
831             p_stream->b_new = false;
832             p_stream->i_packet_no = 0;
833             p_stream->b_started = true;
834
835             if( p_stream->i_fourcc == VLC_CODEC_VORBIS ||
836                 p_stream->i_fourcc == VLC_CODEC_SPEEX ||
837                 p_stream->i_fourcc == VLC_CODEC_OPUS ||
838                 p_stream->i_fourcc == VLC_CODEC_THEORA )
839             {
840                 /* First packet in order: vorbis/speex/theora info */
841                 unsigned pi_size[XIPH_MAX_HEADER_COUNT];
842                 void     *pp_data[XIPH_MAX_HEADER_COUNT];
843                 unsigned i_count;
844                 if( xiph_SplitHeaders( pi_size, pp_data, &i_count,
845                                        p_input->p_fmt->i_extra, p_input->p_fmt->p_extra ) )
846                 {
847                     i_count = 0;
848                     pi_size[0] = 0;
849                     pp_data[0] = NULL;
850                 }
851
852                 op.bytes  = pi_size[0];
853                 op.packet = pp_data[0];
854                 if( pi_size[0] <= 0 )
855                     msg_Err( p_mux, "header data corrupted");
856
857                 op.b_o_s  = 1;
858                 op.e_o_s  = 0;
859                 op.granulepos = 0;
860                 op.packetno = p_stream->i_packet_no++;
861                 ogg_stream_packetin( &p_stream->os, &op );
862                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
863
864                 /* Get keyframe_granule_shift for theora granulepos calculation */
865                 if( p_stream->i_fourcc == VLC_CODEC_THEORA )
866                 {
867                     p_stream->i_keyframe_granule_shift =
868                         ( (op.packet[40] & 0x03) << 3 ) | ( (op.packet[41] & 0xe0) >> 5 );
869                 }
870             }
871             else if( p_stream->i_fourcc == VLC_CODEC_DIRAC )
872             {
873                 op.packet = p_input->p_fmt->p_extra;
874                 op.bytes  = p_input->p_fmt->i_extra;
875                 op.b_o_s  = 1;
876                 op.e_o_s  = 0;
877                 op.granulepos = ~0;
878                 op.packetno = p_stream->i_packet_no++;
879                 ogg_stream_packetin( &p_stream->os, &op );
880                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
881             }
882             else if( p_stream->i_fourcc == VLC_CODEC_FLAC )
883             {
884                 /* flac stream marker (yeah, only that in the 1st packet) */
885                 op.packet = (unsigned char *)"fLaC";
886                 op.bytes  = 4;
887                 op.b_o_s  = 1;
888                 op.e_o_s  = 0;
889                 op.granulepos = 0;
890                 op.packetno = p_stream->i_packet_no++;
891                 ogg_stream_packetin( &p_stream->os, &op );
892                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
893             }
894             else if( p_stream->p_oggds_header )
895             {
896                 /* ds header */
897                 op.packet = malloc( sizeof(*p_stream->p_oggds_header) + p_stream->p_oggds_header->i_size );
898                 if( !op.packet )
899                     return NULL;
900                 op.bytes  = OggFillDsHeader( op.packet, p_stream->p_oggds_header, p_stream->i_cat );
901                 op.b_o_s  = 1;
902                 op.e_o_s  = 0;
903                 op.granulepos = 0;
904                 op.packetno = p_stream->i_packet_no++;
905                 ogg_stream_packetin( &p_stream->os, &op );
906                 p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
907                 free( op.packet );
908             }
909
910             block_ChainAppend( &p_hdr, p_og );
911         }
912     }
913
914     /* Create fisbones if any */
915     if ( p_sys->skeleton.b_create )
916     {
917         for( i = 0; i < p_mux->i_nb_inputs; i++ )
918         {
919             sout_input_t *p_input = p_mux->pp_inputs[i];
920             ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
921             if ( p_stream->b_fisbone_done ) continue;
922             OggGetSkeletonFisbone( &op.packet, &op.bytes, p_input, p_mux );
923             if ( op.packet == NULL ) return NULL;
924             op.b_o_s = 0;
925             op.e_o_s = 0;
926             op.granulepos = 0;
927             op.packetno = p_sys->skeleton.i_packet_no++;
928             ogg_stream_packetin( &p_sys->skeleton.os, &op );
929             p_og = OggStreamFlush( p_mux, &p_sys->skeleton.os, 0 );
930             block_ChainAppend( &p_hdr, p_og );
931             p_stream->b_fisbone_done = true;
932         }
933     }
934
935     /* Take care of the non b_o_s headers */
936     for( i = 0; i < p_mux->i_nb_inputs; i++ )
937     {
938         sout_input_t *p_input = p_mux->pp_inputs[i];
939         ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
940
941         if( p_stream->i_fourcc == VLC_CODEC_VORBIS ||
942             p_stream->i_fourcc == VLC_CODEC_SPEEX ||
943             p_stream->i_fourcc == VLC_CODEC_OPUS ||
944             p_stream->i_fourcc == VLC_CODEC_THEORA )
945         {
946             unsigned pi_size[XIPH_MAX_HEADER_COUNT];
947             void     *pp_data[XIPH_MAX_HEADER_COUNT];
948             unsigned i_count;
949             if( xiph_SplitHeaders( pi_size, pp_data, &i_count,
950                                    p_input->p_fmt->i_extra, p_input->p_fmt->p_extra ) )
951                 i_count = 0;
952
953             /* Special case, headers are already there in the incoming stream.
954              * We need to gather them an mark them as headers. */
955             for( unsigned i = 1; i < i_count; i++ )
956             {
957                 op.bytes  = pi_size[i];
958                 op.packet = pp_data[i];
959                 if( pi_size[i] <= 0 )
960                     msg_Err( p_mux, "header data corrupted");
961
962                 op.b_o_s  = 0;
963                 op.e_o_s  = 0;
964                 op.granulepos = 0;
965                 op.packetno = p_stream->i_packet_no++;
966                 ogg_stream_packetin( &p_stream->os, &op );
967                 msg_Dbg( p_mux, "adding non bos, secondary header" );
968                 if( i == i_count - 1 )
969                     p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
970                 else
971                     p_og = OggStreamPageOut( p_mux, &p_stream->os, 0 );
972                 if( p_og )
973                     block_ChainAppend( &p_hdr, p_og );
974             }
975         }
976         else if( p_stream->i_fourcc != VLC_CODEC_FLAC &&
977                  p_stream->i_fourcc != VLC_CODEC_DIRAC )
978         {
979             uint8_t com[128];
980             int     i_com;
981
982             /* comment */
983             com[0] = PACKET_TYPE_COMMENT;
984             i_com = snprintf( (char *)(com+1), 127,
985                               PACKAGE_VERSION" stream output" )
986                      + 1;
987             op.packet = com;
988             op.bytes  = i_com;
989             op.b_o_s  = 0;
990             op.e_o_s  = 0;
991             op.granulepos = 0;
992             op.packetno = p_stream->i_packet_no++;
993             ogg_stream_packetin( &p_stream->os, &op );
994             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
995             block_ChainAppend( &p_hdr, p_og );
996         }
997
998         /* Special case for mp4v and flac */
999         if( ( p_stream->i_fourcc == VLC_CODEC_MP4V ||
1000               p_stream->i_fourcc == VLC_CODEC_FLAC ) &&
1001             p_input->p_fmt->i_extra )
1002         {
1003             /* Send a packet with the VOL data for mp4v
1004              * or STREAMINFO for flac */
1005             msg_Dbg( p_mux, "writing extra data" );
1006             op.bytes  = p_input->p_fmt->i_extra;
1007             op.packet = p_input->p_fmt->p_extra;
1008             uint8_t flac_streaminfo[34 + 4];
1009             if( p_stream->i_fourcc == VLC_CODEC_FLAC )
1010             {
1011                 if (op.bytes == 42 && !memcmp(op.packet, "fLaC", 4)) {
1012                     op.bytes -= 4;
1013                     memcpy(flac_streaminfo, op.packet + 4, 38);
1014                     op.packet = flac_streaminfo;
1015                 } else if (op.bytes == 34) {
1016                     op.bytes += 4;
1017                     memcpy(flac_streaminfo + 4, op.packet, 34);
1018                     flac_streaminfo[0] = 0x80; /* last block, streaminfo */
1019                     flac_streaminfo[1] = 0;
1020                     flac_streaminfo[2] = 0;
1021                     flac_streaminfo[3] = 34; /* block size */
1022                     op.packet = flac_streaminfo;
1023                 } else {
1024                     msg_Err(p_mux, "Invalid FLAC streaminfo (%ld bytes)",
1025                             op.bytes);
1026                 }
1027             }
1028             op.b_o_s  = 0;
1029             op.e_o_s  = 0;
1030             op.granulepos = 0;
1031             op.packetno = p_stream->i_packet_no++;
1032             ogg_stream_packetin( &p_stream->os, &op );
1033             p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
1034             block_ChainAppend( &p_hdr, p_og );
1035         }
1036     }
1037
1038     if ( p_sys->skeleton.b_create )
1039     {
1040         msg_Dbg( p_mux, "ending skeleton" );
1041         op.packet = NULL;
1042         op.bytes = 0;
1043         op.b_o_s = 0;
1044         op.e_o_s = 1;
1045         op.granulepos = 0;
1046         op.packetno = p_sys->skeleton.i_packet_no++;
1047         ogg_stream_packetin( &p_sys->skeleton.os, &op );
1048         p_og = OggStreamFlush( p_mux, &p_sys->skeleton.os, 0 );
1049         block_ChainAppend( &p_hdr, p_og );
1050     }
1051
1052     /* set HEADER flag */
1053     for( p_og = p_hdr; p_og != NULL; p_og = p_og->p_next )
1054     {
1055         p_og->i_flags |= BLOCK_FLAG_HEADER;
1056     }
1057     return p_hdr;
1058 }
1059
1060 static block_t *OggCreateStreamFooter( sout_mux_t *p_mux, ogg_stream_t *p_stream )
1061 {
1062     block_t *p_og, *p_hdr = NULL;
1063     ogg_packet op;
1064
1065     p_stream->b_fisbone_done = false;
1066
1067     /* Write eos packet for stream. */
1068     op.packet = NULL;
1069     op.bytes  = 0;
1070     op.b_o_s  = 0;
1071     op.e_o_s  = 1;
1072     op.granulepos = p_stream->u_last_granulepos;
1073     op.packetno = p_stream->i_packet_no++;
1074     ogg_stream_packetin( &p_stream->os, &op );
1075
1076     /* flush it with all remaining data */
1077     if( ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
1078     {
1079         OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
1080         block_ChainAppend( &p_hdr, p_og );
1081     }
1082
1083     ogg_stream_clear( &p_stream->os );
1084
1085     return p_hdr;
1086 }
1087
1088 static void OggSetDate( block_t *p_og, mtime_t i_dts, mtime_t i_length )
1089 {
1090     int i_count;
1091     block_t *p_tmp;
1092     mtime_t i_delta;
1093
1094     for( p_tmp = p_og, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->p_next )
1095     {
1096         i_count++;
1097     }
1098
1099     if( i_count == 0 ) return; /* ignore. */
1100
1101     i_delta = i_length / i_count;
1102
1103     for( p_tmp = p_og; p_tmp != NULL; p_tmp = p_tmp->p_next )
1104     {
1105         p_tmp->i_dts    = i_dts;
1106         p_tmp->i_length = i_delta;
1107
1108         i_dts += i_delta;
1109     }
1110 }
1111
1112 /*****************************************************************************
1113  * Mux: multiplex available data in input fifos into the Ogg bitstream
1114  *****************************************************************************/
1115 static int Mux( sout_mux_t *p_mux )
1116 {
1117     sout_mux_sys_t *p_sys = p_mux->p_sys;
1118     block_t        *p_og = NULL;
1119     mtime_t        i_dts;
1120
1121     /* End any stream that ends in that group */
1122     if ( p_sys->i_del_streams )
1123     {
1124         /* Remove deleted logical streams */
1125         for( int i = 0; i < p_sys->i_del_streams; i++ )
1126         {
1127             block_ChainAppend( &p_og, OggCreateStreamFooter( p_mux, p_sys->pp_del_streams[i] ) );
1128             FREENULL( p_sys->pp_del_streams[i]->p_oggds_header );
1129             FREENULL( p_sys->pp_del_streams[i] );
1130         }
1131         FREENULL( p_sys->pp_del_streams );
1132     }
1133
1134     if ( p_sys->i_streams == 0 )
1135     {
1136         /* All streams have been deleted, or none have ever been created
1137            From this point, we are allowed to start a new group of logical streams */
1138         p_sys->skeleton.b_head_done = false;
1139         p_sys->b_can_add_streams = true;
1140     }
1141
1142     if ( p_sys->i_add_streams )
1143     {
1144         if ( !p_sys->b_can_add_streams )
1145         {
1146             msg_Warn( p_mux, "Can't add new stream: Considerer increasing sout-mux-caching variable");
1147             msg_Warn( p_mux, "Resetting and setting new identity to current streams");
1148             p_sys->skeleton.b_head_done = false;
1149             /* resetting all active streams */
1150             for ( int i=0; i < p_mux->p_sys->i_streams; i++ )
1151             {
1152                 ogg_stream_t * p_stream = (ogg_stream_t *) p_mux->pp_inputs[i]->p_sys;
1153                 if ( p_stream->b_finished || !p_stream->b_started ) continue;
1154                 block_ChainAppend( &p_og, OggCreateStreamFooter( p_mux, p_stream ) );
1155                 p_stream->i_serial_no = p_sys->i_next_serial_no++;
1156                 p_stream->i_packet_no = 0;
1157                 p_stream->b_finished = true;
1158             }
1159             p_sys->b_can_add_streams = true;
1160             sout_AccessOutWrite( p_mux->p_access, p_og );
1161             p_og = NULL;
1162         }
1163
1164         /* Open new ogg stream */
1165         if( sout_MuxGetStream( p_mux, 1, &i_dts) < 0 )
1166         {
1167             msg_Dbg( p_mux, "waiting for data..." );
1168             return VLC_SUCCESS;
1169         }
1170         msg_Dbg( p_mux, "writing streams headers" );
1171         p_sys->i_start_dts = i_dts;
1172         p_sys->i_streams = p_mux->i_nb_inputs;
1173         p_sys->i_del_streams = 0;
1174         p_sys->i_add_streams = 0;
1175         block_t *p_header = OggCreateHeaders( p_mux );
1176         if( !p_header )
1177             return VLC_ENOMEM;
1178         block_ChainAppend( &p_og, p_header );
1179
1180         /* Since we started sending secondaryheader or data pages,
1181              * we're no longer allowed to create new streams, until all streams end */
1182         p_sys->b_can_add_streams = false;
1183
1184         /* Write header */
1185         OggSetDate( p_og, i_dts, 0 );
1186         sout_AccessOutWrite( p_mux->p_access, p_og );
1187         p_og = NULL;
1188     }
1189
1190     /* Do the regular data mux thing */
1191     for( ;; )
1192     {
1193         int i_stream = sout_MuxGetStream( p_mux, 1, NULL );
1194         if( i_stream < 0 )
1195             return VLC_SUCCESS;
1196         MuxBlock( p_mux, p_mux->pp_inputs[i_stream] );
1197     }
1198
1199     return VLC_SUCCESS;
1200 }
1201
1202 static int MuxBlock( sout_mux_t *p_mux, sout_input_t *p_input )
1203 {
1204     sout_mux_sys_t *p_sys = p_mux->p_sys;
1205     ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
1206     block_t *p_data = block_FifoGet( p_input->p_fifo );
1207     block_t *p_og = NULL;
1208     ogg_packet op;
1209
1210     if( p_stream->i_fourcc != VLC_CODEC_VORBIS &&
1211         p_stream->i_fourcc != VLC_CODEC_FLAC &&
1212         p_stream->i_fourcc != VLC_CODEC_SPEEX &&
1213         p_stream->i_fourcc != VLC_CODEC_OPUS &&
1214         p_stream->i_fourcc != VLC_CODEC_THEORA &&
1215         p_stream->i_fourcc != VLC_CODEC_DIRAC )
1216     {
1217         p_data = block_Realloc( p_data, 1, p_data->i_buffer );
1218         p_data->p_buffer[0] = PACKET_IS_SYNCPOINT;      // FIXME
1219     }
1220
1221     op.packet   = p_data->p_buffer;
1222     op.bytes    = p_data->i_buffer;
1223     op.b_o_s    = 0;
1224     op.e_o_s    = 0;
1225     op.packetno = p_stream->i_packet_no++;
1226     op.granulepos = -1;
1227
1228     if( p_stream->i_cat == AUDIO_ES )
1229     {
1230         if( p_stream->i_fourcc == VLC_CODEC_VORBIS ||
1231             p_stream->i_fourcc == VLC_CODEC_FLAC ||
1232             p_stream->i_fourcc == VLC_CODEC_OPUS ||
1233             p_stream->i_fourcc == VLC_CODEC_SPEEX )
1234         {
1235             /* number of sample from begining + current packet */
1236             op.granulepos =
1237                 ( p_data->i_dts - p_sys->i_start_dts + p_data->i_length ) *
1238                 (mtime_t)p_input->p_fmt->audio.i_rate / INT64_C(1000000);
1239         }
1240         else if( p_stream->p_oggds_header )
1241         {
1242             /* number of sample from begining */
1243             op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) *
1244                 p_stream->p_oggds_header->i_samples_per_unit / INT64_C(1000000);
1245         }
1246     }
1247     else if( p_stream->i_cat == VIDEO_ES )
1248     {
1249         if( p_stream->i_fourcc == VLC_CODEC_THEORA )
1250         {
1251             p_stream->i_num_frames++;
1252             if( p_data->i_flags & BLOCK_FLAG_TYPE_I )
1253             {
1254                 p_stream->i_num_keyframes++;
1255                 p_stream->i_last_keyframe = p_stream->i_num_frames;
1256             }
1257
1258             op.granulepos = (p_stream->i_last_keyframe << p_stream->i_keyframe_granule_shift )
1259                           | (p_stream->i_num_frames-p_stream->i_last_keyframe);
1260         }
1261         else if( p_stream->i_fourcc == VLC_CODEC_DIRAC )
1262         {
1263             mtime_t dt = (p_data->i_dts - p_sys->i_start_dts + 1)
1264                        * p_input->p_fmt->video.i_frame_rate *2
1265                        / p_input->p_fmt->video.i_frame_rate_base
1266                        / INT64_C(1000000);
1267             mtime_t delay = (p_data->i_pts - p_data->i_dts + 1)
1268                           * p_input->p_fmt->video.i_frame_rate *2
1269                           / p_input->p_fmt->video.i_frame_rate_base
1270                           / INT64_C(1000000);
1271             if( p_data->i_flags & BLOCK_FLAG_TYPE_I )
1272                 p_stream->i_last_keyframe = dt;
1273             mtime_t dist = dt - p_stream->i_last_keyframe;
1274             op.granulepos = dt << 31 | (dist&0xff00) << 14
1275                           | (delay&0x1fff) << 9 | (dist&0xff);
1276         }
1277         else if( p_stream->p_oggds_header )
1278             op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) * INT64_C(10) /
1279                 p_stream->p_oggds_header->i_time_unit;
1280     }
1281     else if( p_stream->i_cat == SPU_ES )
1282     {
1283         /* granulepos is in millisec */
1284         op.granulepos = ( p_data->i_dts - p_sys->i_start_dts ) / 1000;
1285     }
1286     else
1287         return VLC_EGENERIC;
1288
1289     p_stream->u_last_granulepos = op.granulepos;
1290     ogg_stream_packetin( &p_stream->os, &op );
1291
1292     if( p_stream->i_cat == SPU_ES ||
1293         p_stream->i_fourcc == VLC_CODEC_SPEEX ||
1294         p_stream->i_fourcc == VLC_CODEC_DIRAC )
1295     {
1296         /* Subtitles or Speex packets are quite small so they
1297          * need to be flushed to be sent on time */
1298         /* The OggDirac mapping suggests ever so strongly that a
1299          * page flush occurs after each OggDirac packet, so to make
1300          * the timestamps unambiguous */
1301         p_og = OggStreamFlush( p_mux, &p_stream->os, p_data->i_dts );
1302     }
1303     else
1304     {
1305         p_og = OggStreamPageOut( p_mux, &p_stream->os, p_data->i_dts );
1306     }
1307
1308     if( p_og )
1309     {
1310         OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
1311         p_stream->i_dts = -1;
1312         p_stream->i_length = 0;
1313
1314         sout_AccessOutWrite( p_mux->p_access, p_og );
1315     }
1316     else
1317     {
1318         if( p_stream->i_dts < 0 )
1319         {
1320             p_stream->i_dts = p_data->i_dts;
1321         }
1322         p_stream->i_length += p_data->i_length;
1323     }
1324
1325     block_Release( p_data );
1326     return VLC_SUCCESS;
1327 }