]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
Lua: Fix memory leak (cid #1100856)
[vlc] / modules / demux / ogg.c
1 /*****************************************************************************
2  * ogg.c : ogg stream demux module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2007 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
8  *          Andre Pang <Andre.Pang@csiro.au> (Annodex support)
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_demux.h>
35 #include <vlc_meta.h>
36 #include <vlc_input.h>
37
38 #include <ogg/ogg.h>
39
40 #include <vlc_codecs.h>
41 #include <vlc_bits.h>
42 #include "xiph.h"
43 #include "xiph_metadata.h"
44 #include "ogg.h"
45 #include "oggseek.h"
46
47 /*****************************************************************************
48  * Module descriptor
49  *****************************************************************************/
50 static int  Open ( vlc_object_t * );
51 static void Close( vlc_object_t * );
52
53 vlc_module_begin ()
54     set_shortname ( "OGG" )
55     set_description( N_("OGG demuxer" ) )
56     set_category( CAT_INPUT )
57     set_subcategory( SUBCAT_INPUT_DEMUX )
58     set_capability( "demux", 50 )
59     set_callbacks( Open, Close )
60     add_shortcut( "ogg" )
61 vlc_module_end ()
62
63
64 /*****************************************************************************
65  * Definitions of structures and functions used by this plugins
66  *****************************************************************************/
67
68 /* OggDS headers for the new header format (used in ogm files) */
69 typedef struct
70 {
71     ogg_int32_t width;
72     ogg_int32_t height;
73 } stream_header_video_t;
74
75 typedef struct
76 {
77     ogg_int16_t channels;
78     ogg_int16_t padding;
79     ogg_int16_t blockalign;
80     ogg_int32_t avgbytespersec;
81 } stream_header_audio_t;
82
83 typedef struct
84 {
85     char        streamtype[8];
86     char        subtype[4];
87
88     ogg_int32_t size;                               /* size of the structure */
89
90     ogg_int64_t time_unit;                              /* in reference time */
91     ogg_int64_t samples_per_unit;
92     ogg_int32_t default_len;                                /* in media time */
93
94     ogg_int32_t buffersize;
95     ogg_int16_t bits_per_sample;
96     ogg_int16_t padding;
97
98     union
99     {
100         /* Video specific */
101         stream_header_video_t video;
102         /* Audio specific */
103         stream_header_audio_t audio;
104     } sh;
105 } stream_header_t;
106
107 /*****************************************************************************
108  * Local prototypes
109  *****************************************************************************/
110 static int  Demux  ( demux_t * );
111 static int  Control( demux_t *, int, va_list );
112
113 /* Bitstream manipulation */
114 static int  Ogg_ReadPage     ( demux_t *, ogg_page * );
115 static void Ogg_UpdatePCR    ( logical_stream_t *, ogg_packet * );
116 static void Ogg_DecodePacket ( demux_t *, logical_stream_t *, ogg_packet * );
117 static int  Ogg_OpusPacketDuration( logical_stream_t *, ogg_packet * );
118
119 static int Ogg_BeginningOfStream( demux_t *p_demux );
120 static int Ogg_FindLogicalStreams( demux_t *p_demux );
121 static void Ogg_EndOfStream( demux_t *p_demux );
122
123 /* */
124 static void Ogg_LogicalStreamDelete( demux_t *p_demux, logical_stream_t *p_stream );
125 static bool Ogg_LogicalStreamResetEsFormat( demux_t *p_demux, logical_stream_t *p_stream );
126
127 /* */
128 static void Ogg_ExtractMeta( demux_t *p_demux, es_format_t *p_fmt, const uint8_t *p_headers, int i_headers );
129
130 /* Logical bitstream headers */
131 static void Ogg_ReadTheoraHeader( logical_stream_t *, ogg_packet * );
132 static void Ogg_ReadVorbisHeader( logical_stream_t *, ogg_packet * );
133 static void Ogg_ReadSpeexHeader( logical_stream_t *, ogg_packet * );
134 static void Ogg_ReadOpusHeader( logical_stream_t *, ogg_packet * );
135 static void Ogg_ReadKateHeader( logical_stream_t *, ogg_packet * );
136 static void Ogg_ReadFlacHeader( demux_t *, logical_stream_t *, ogg_packet * );
137 static void Ogg_ReadAnnodexHeader( demux_t *, logical_stream_t *, ogg_packet * );
138 static bool Ogg_ReadDiracHeader( logical_stream_t *, ogg_packet * );
139
140 static void fill_channels_info(audio_format_t *audio)
141 {
142     static const int pi_channels_map[9] =
143     {
144         0,
145         AOUT_CHAN_CENTER,
146         AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
147         AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
148         AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
149             | AOUT_CHAN_REARRIGHT,
150         AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
151             | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
152         AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
153             | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
154         AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
155             | AOUT_CHAN_REARCENTER | AOUT_CHAN_MIDDLELEFT
156             | AOUT_CHAN_MIDDLERIGHT | AOUT_CHAN_LFE,
157         AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
158             | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
159             | AOUT_CHAN_LFE,
160     };
161
162     unsigned chans = audio->i_channels;
163     if (chans < sizeof(pi_channels_map) / sizeof(pi_channels_map[0]))
164         audio->i_physical_channels =
165         audio->i_original_channels = pi_channels_map[chans];
166 }
167
168 /*****************************************************************************
169  * Open: initializes ogg demux structures
170  *****************************************************************************/
171 static int Open( vlc_object_t * p_this )
172 {
173     demux_t *p_demux = (demux_t *)p_this;
174     demux_sys_t    *p_sys;
175     const uint8_t  *p_peek;
176
177     /* Check if we are dealing with an ogg stream */
178     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
179     if( !p_demux->b_force && memcmp( p_peek, "OggS", 4 ) )
180     {
181         return VLC_EGENERIC;
182     }
183
184     /* */
185     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
186     if( !p_sys )
187         return VLC_ENOMEM;
188
189     p_sys->i_length = -1;
190
191     /* Set exported functions */
192     p_demux->pf_demux = Demux;
193     p_demux->pf_control = Control;
194
195     /* Initialize the Ogg physical bitstream parser */
196     ogg_sync_init( &p_sys->oy );
197
198     /* */
199     TAB_INIT( p_sys->i_seekpoints, p_sys->pp_seekpoints );
200
201     return VLC_SUCCESS;
202 }
203
204 /*****************************************************************************
205  * Close: frees unused data
206  *****************************************************************************/
207 static void Close( vlc_object_t *p_this )
208 {
209     demux_t *p_demux = (demux_t *)p_this;
210     demux_sys_t *p_sys = p_demux->p_sys  ;
211
212     /* Cleanup the bitstream parser */
213     ogg_sync_clear( &p_sys->oy );
214
215     Ogg_EndOfStream( p_demux );
216
217     if( p_sys->p_old_stream )
218         Ogg_LogicalStreamDelete( p_demux, p_sys->p_old_stream );
219
220     TAB_CLEAN( p_sys->i_seekpoints, p_sys->pp_seekpoints );
221
222     free( p_sys );
223 }
224
225 /*****************************************************************************
226  * Demux: reads and demuxes data packets
227  *****************************************************************************
228  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
229  *****************************************************************************/
230 static int Demux( demux_t * p_demux )
231 {
232     demux_sys_t *p_sys = p_demux->p_sys;
233     ogg_packet  oggpacket;
234     int         i_stream;
235     bool b_skipping = false;
236     bool b_canseek;
237
238
239     if( p_sys->i_eos == p_sys->i_streams )
240     {
241         if( p_sys->i_eos )
242         {
243             msg_Dbg( p_demux, "end of a group of logical streams" );
244             /* We keep the ES to try reusing it in Ogg_BeginningOfStream
245              * only 1 ES is supported (common case for ogg web radio) */
246             if( p_sys->i_streams == 1 )
247             {
248                 p_sys->p_old_stream = p_sys->pp_stream[0];
249                 TAB_CLEAN( p_sys->i_streams, p_sys->pp_stream );
250             }
251             Ogg_EndOfStream( p_demux );
252         }
253
254         p_sys->i_eos = 0;
255         if( Ogg_BeginningOfStream( p_demux ) != VLC_SUCCESS )
256             return 0;
257
258         /* Find the real duration */
259         stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_canseek );
260         if ( b_canseek )
261             Oggseek_ProbeEnd( p_demux );
262
263         msg_Dbg( p_demux, "beginning of a group of logical streams" );
264         es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 );
265     }
266
267     /*
268      * The first data page of a physical stream is stored in the relevant logical stream
269      * in Ogg_FindLogicalStreams. Therefore, we must not read a page and only update the
270      * stream it belongs to if we haven't processed this first page yet. If we do, we
271      * will only process that first page whenever we find the second page for this stream.
272      * While this is fine for Vorbis and Theora, which are continuous codecs, which means
273      * the second page will arrive real quick, this is not fine for Kate, whose second
274      * data page will typically arrive much later.
275      * This means it is now possible to seek right at the start of a stream where the last
276      * logical stream is Kate, without having to wait for the second data page to unblock
277      * the first one, which is the one that triggers the 'no more headers to backup' code.
278      * And, as we all know, seeking without having backed up all headers is bad, since the
279      * codec will fail to initialize if it's missing its headers.
280      */
281     if( !p_sys->b_page_waiting)
282     {
283         /*
284          * Demux an ogg page from the stream
285          */
286         if( Ogg_ReadPage( p_demux, &p_sys->current_page ) != VLC_SUCCESS )
287             return 0; /* EOF */
288         /* Test for End of Stream */
289         /* FIXME that eos handling is innapropriate with seeking and concatenated streams */
290         if( ogg_page_eos( &p_sys->current_page )
291             && ogg_page_granulepos( &p_sys->current_page ) != 0 ) /* skel workaround */
292             p_sys->i_eos++;
293     }
294
295     b_skipping = false;
296     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
297     {
298         b_skipping |= p_sys->pp_stream[i_stream]->i_skip_frames;
299     }
300
301     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
302     {
303         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
304
305         /* if we've just pulled page, look for the right logical stream */
306         if( !p_sys->b_page_waiting )
307         {
308             if( p_sys->i_streams == 1 &&
309                 ogg_page_serialno( &p_sys->current_page ) != p_stream->os.serialno )
310             {
311                 msg_Err( p_demux, "Broken Ogg stream (serialno) mismatch" );
312                 ogg_stream_reset_serialno( &p_stream->os, ogg_page_serialno( &p_sys->current_page ) );
313
314                 p_stream->b_reinit = true;
315                 p_stream->i_pcr = VLC_TS_0;
316                 p_stream->i_interpolated_pcr = VLC_TS_0;
317                 p_stream->i_previous_granulepos = -1;
318                 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0);
319             }
320
321             if( ogg_stream_pagein( &p_stream->os, &p_sys->current_page ) != 0 )
322             {
323                 continue;
324             }
325
326         }
327
328         DemuxDebug(
329             if ( p_stream->fmt.i_cat == VIDEO_ES )
330                 msg_Dbg(p_demux, "DEMUX READ pageno %ld g%"PRId64" (%d packets) cont %d %ld bytes eos %d ",
331                     ogg_page_pageno( &p_sys->current_page ),
332                     ogg_page_granulepos( &p_sys->current_page ),
333                     ogg_page_packets( &p_sys->current_page ),
334                     ogg_page_continued(&p_sys->current_page),
335                     p_sys->current_page.body_len, p_sys->i_eos )
336         );
337
338         while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
339         {
340             /* Read info from any secondary header packets, if there are any */
341             if( p_stream->i_secondary_header_packets > 0 )
342             {
343                 if( p_stream->fmt.i_codec == VLC_CODEC_THEORA &&
344                         oggpacket.bytes >= 7 &&
345                         ! memcmp( oggpacket.packet, "\x80theora", 7 ) )
346                 {
347                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
348                     p_stream->i_secondary_header_packets = 0;
349                 }
350                 else if( p_stream->fmt.i_codec == VLC_CODEC_VORBIS &&
351                         oggpacket.bytes >= 7 &&
352                         ! memcmp( oggpacket.packet, "\x01vorbis", 7 ) )
353                 {
354                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
355                     p_stream->i_secondary_header_packets = 0;
356                 }
357                 else if( p_stream->fmt.i_codec == VLC_CODEC_CMML )
358                 {
359                     p_stream->i_secondary_header_packets = 0;
360                 }
361
362                 /* update start of data pointer */
363                 p_stream->i_data_start = stream_Tell( p_demux->s );
364             }
365
366             /* If any streams have i_skip_frames, only decode (pre-roll)
367              *  for those streams, but don't skip headers */
368             if ( b_skipping && p_stream->i_skip_frames == 0
369                  && p_stream->i_secondary_header_packets ) continue;
370
371             if( p_stream->b_reinit )
372             {
373                 if ( Oggseek_PacketPCRFixup( p_stream, &p_sys->current_page,
374                                          &oggpacket ) )
375                 {
376                     DemuxDebug( msg_Dbg( p_demux, "PCR fixup for %"PRId64,
377                              ogg_page_granulepos( &p_sys->current_page ) ) );
378                 }
379                 else
380                 {
381                     /* If synchro is re-initialized we need to drop all the packets
382                          * until we find a new dated one. */
383                     Ogg_UpdatePCR( p_stream, &oggpacket );
384                 }
385
386                 if( p_stream->i_pcr >= 0 )
387                 {
388                     p_stream->b_reinit = false;
389                     /* For Opus, trash the first 80 ms of decoded output as
390                        well, to avoid blowing out speakers if we get unlucky.
391                        Opus predicts content from prior frames, which can go
392                        badly if we seek right where the stream goes from very
393                        quiet to very loud. It will converge after a bit. */
394                     if( p_stream->fmt.i_codec == VLC_CODEC_OPUS )
395                     {
396                         ogg_int64_t start_time;
397                         int duration;
398                         p_stream->i_skip_frames = 80*48;
399                         /* Make sure we never play audio from within the
400                            pre-skip at the beginning of the stream. */
401                         duration =
402                             Ogg_OpusPacketDuration( p_stream, &oggpacket );
403                         start_time = p_stream->i_previous_granulepos;
404                         if( duration > 0 )
405                         {
406                             start_time = start_time > duration ?
407                                 start_time - duration : 0;
408                         }
409                         if( p_stream->i_pre_skip > start_time )
410                         {
411                             p_stream->i_skip_frames +=
412                                 p_stream->i_pre_skip - start_time;
413                         }
414                     }
415                 }
416                 else
417                 {
418                     DemuxDebug(
419                         msg_Dbg(p_demux, "DEMUX DROPS PACKET (? / %d) pageno %ld granule %"PRId64,
420                             ogg_page_packets( &p_sys->current_page ),
421                             ogg_page_pageno( &p_sys->current_page ), oggpacket.granulepos );
422                     );
423
424                     p_stream->i_interpolated_pcr = -1;
425                     p_stream->i_previous_granulepos = -1;
426                     continue;
427                 }
428
429                 /* An Ogg/vorbis packet contains an end date granulepos */
430                 if( p_stream->fmt.i_codec == VLC_CODEC_VORBIS ||
431                     p_stream->fmt.i_codec == VLC_CODEC_SPEEX ||
432                     p_stream->fmt.i_codec == VLC_CODEC_OPUS ||
433                     p_stream->fmt.i_codec == VLC_CODEC_FLAC )
434                 {
435                     if( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
436                     {
437                         Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
438                     }
439                     else
440                     {
441                         es_out_Control( p_demux->out, ES_OUT_SET_PCR,
442                                         VLC_TS_0 + p_stream->i_pcr );
443                     }
444                     continue;
445                 }
446             }
447
448             DemuxDebug( if ( p_sys->b_seeked )
449             {
450                 if ( Ogg_IsKeyFrame( p_stream, &oggpacket ) )
451                      msg_Dbg(p_demux, "** DEMUX ON KEYFRAME **" );
452
453                 ogg_int64_t iframe = ogg_page_granulepos( &p_sys->current_page ) >> p_stream->i_granule_shift;
454                 ogg_int64_t pframe = ogg_page_granulepos( &p_sys->current_page ) - ( iframe << p_stream->i_granule_shift );
455
456                 msg_Dbg(p_demux, "DEMUX PACKET (size %d) IS at iframe %"PRId64" pageno %ld pframe %"PRId64" OFFSET %"PRId64" PACKET NO %"PRId64" skipleft=%d",
457                         ogg_page_packets( &p_sys->current_page ),
458                         iframe, ogg_page_pageno( &p_sys->current_page ), pframe, p_sys->i_input_position, oggpacket.packetno, p_stream->i_skip_frames );
459             })
460
461             Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
462         }
463
464         DemuxDebug( p_sys->b_seeked = false; )
465
466         if( !p_sys->b_page_waiting )
467             break;
468     }
469
470     /* if a page was waiting, it's now processed */
471     p_sys->b_page_waiting = false;
472
473     p_sys->i_pcr = -1;
474     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
475     {
476         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
477
478         if( p_stream->fmt.i_cat == SPU_ES )
479             continue;
480         if( p_stream->i_interpolated_pcr < 0 )
481             continue;
482
483         if( p_sys->i_pcr < 0 || p_stream->i_interpolated_pcr < p_sys->i_pcr )
484             p_sys->i_pcr = p_stream->i_interpolated_pcr;
485     }
486
487     if( p_sys->i_pcr >= 0 && ! b_skipping )
488         es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
489
490     return 1;
491 }
492
493 static void Ogg_ResetStreamHelper( demux_sys_t *p_sys )
494 {
495     for( int i = 0; i < p_sys->i_streams; i++ )
496     {
497         logical_stream_t *p_stream = p_sys->pp_stream[i];
498
499         /* we'll trash all the data until we find the next pcr */
500         p_stream->b_reinit = true;
501         p_stream->i_pcr = -1;
502         p_stream->i_interpolated_pcr = -1;
503         p_stream->i_previous_granulepos = -1;
504         ogg_stream_reset( &p_stream->os );
505     }
506     ogg_sync_reset( &p_sys->oy );
507 }
508
509 static logical_stream_t * Ogg_GetSelectedStream( demux_t *p_demux )
510 {
511     demux_sys_t *p_sys = p_demux->p_sys;
512     logical_stream_t *p_stream = NULL;
513     for( int i=0; i<p_sys->i_streams; i++ )
514     {
515         logical_stream_t *p_candidate = p_sys->pp_stream[i];
516
517         bool b_selected = false;
518         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
519                         p_candidate->p_es, &b_selected );
520         if ( !b_selected ) continue;
521
522         if ( !p_stream && p_candidate->fmt.i_cat == AUDIO_ES )
523         {
524             p_stream = p_candidate;
525             continue; /* Try to find video anyway */
526         }
527
528         if ( p_candidate->fmt.i_cat == VIDEO_ES )
529         {
530             p_stream = p_candidate;
531             break;
532         }
533     }
534     return p_stream;
535 }
536
537 /*****************************************************************************
538  * Control:
539  *****************************************************************************/
540 static int Control( demux_t *p_demux, int i_query, va_list args )
541 {
542     demux_sys_t *p_sys  = p_demux->p_sys;
543     vlc_meta_t *p_meta;
544     int64_t *pi64, i64;
545     double *pf, f;
546     bool *pb_bool, b;
547
548     switch( i_query )
549     {
550         case DEMUX_GET_META:
551             p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t* );
552             if( p_sys->p_meta )
553                 vlc_meta_Merge( p_meta, p_sys->p_meta );
554             return VLC_SUCCESS;
555
556         case DEMUX_HAS_UNSUPPORTED_META:
557             pb_bool = (bool*)va_arg( args, bool* );
558             *pb_bool = true;
559             return VLC_SUCCESS;
560
561         case DEMUX_GET_TIME:
562             pi64 = (int64_t*)va_arg( args, int64_t * );
563             *pi64 = p_sys->i_pcr;
564             return VLC_SUCCESS;
565
566         case DEMUX_SET_TIME:
567             return VLC_EGENERIC;
568
569         case DEMUX_GET_ATTACHMENTS:
570         {
571             input_attachment_t ***ppp_attach =
572                 (input_attachment_t***)va_arg( args, input_attachment_t*** );
573             int *pi_int = (int*)va_arg( args, int * );
574
575             if( p_sys->i_attachments <= 0 )
576                 return VLC_EGENERIC;
577
578             *pi_int = p_sys->i_attachments;
579             *ppp_attach = xmalloc( sizeof(input_attachment_t*) * p_sys->i_attachments );
580             for( int i = 0; i < p_sys->i_attachments; i++ )
581                 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachments[i] );
582             return VLC_SUCCESS;
583         }
584
585         case DEMUX_GET_POSITION:
586             pf = (double*)va_arg( args, double * );
587             if( p_sys->i_length > 0 )
588             {
589                 *pf =  (double) p_sys->i_pcr /
590                        (double) ( p_sys->i_length * (mtime_t)1000000 );
591             }
592             else if( stream_Size( p_demux->s ) > 0 )
593             {
594                 i64 = stream_Tell( p_demux->s );
595                 *pf = (double) i64 / stream_Size( p_demux->s );
596             }
597             else *pf = 0.0;
598             return VLC_SUCCESS;
599
600         case DEMUX_SET_POSITION:
601             /* forbid seeking if we haven't initialized all logical bitstreams yet;
602                if we allowed, some headers would not get backed up and decoder init
603                would fail, making that logical stream unusable */
604             if( p_sys->i_bos > 0 )
605             {
606                 return VLC_EGENERIC;
607             }
608
609             logical_stream_t *p_stream = Ogg_GetSelectedStream( p_demux );
610             if ( !p_stream )
611             {
612                 msg_Err( p_demux, "No selected seekable stream found" );
613                 return VLC_EGENERIC;
614             }
615
616             stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b );
617
618             f = (double)va_arg( args, double );
619             if ( p_sys->i_length <= 0 || !b /* || ! ACCESS_CAN_FASTSEEK */ )
620             {
621                 Ogg_ResetStreamHelper( p_sys );
622                 Oggseek_BlindSeektoPosition( p_demux, p_stream, f, b );
623                 return VLC_SUCCESS;
624             }
625
626             assert( p_sys->i_length > 0 );
627             i64 = (mtime_t)(1000000.0 * p_sys->i_length * f );
628             Ogg_ResetStreamHelper( p_sys );
629             if ( Oggseek_SeektoAbsolutetime( p_demux, p_stream, i64 ) >= 0 )
630             {
631                 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
632                                 VLC_TS_0 + i64 );
633                 return VLC_SUCCESS;
634             }
635
636             return VLC_EGENERIC;
637
638         case DEMUX_GET_LENGTH:
639             if ( p_sys->i_length < 0 )
640                 return demux_vaControlHelper( p_demux->s, 0, -1, p_sys->i_bitrate,
641                                               1, i_query, args );
642             pi64 = (int64_t*)va_arg( args, int64_t * );
643             *pi64 = p_sys->i_length * 1000000;
644             return VLC_SUCCESS;
645
646         case DEMUX_GET_TITLE_INFO:
647         {
648             input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
649             int *pi_int    = (int*)va_arg( args, int* );
650             int *pi_title_offset = (int*)va_arg( args, int* );
651             int *pi_seekpoint_offset = (int*)va_arg( args, int* );
652
653             if( p_sys->i_seekpoints > 0 )
654             {
655                 *pi_int = 1;
656                 *ppp_title = malloc( sizeof( input_title_t* ) );
657                 input_title_t *p_title = (*ppp_title)[0] = vlc_input_title_New();
658                 for( int i = 0; i < p_sys->i_seekpoints; i++ )
659                 {
660                     TAB_APPEND( p_title->i_seekpoint, p_title->seekpoint, p_sys->pp_seekpoints[i] );
661                 }
662                 *pi_title_offset = 0;
663                 *pi_seekpoint_offset = 0;
664             }
665             return VLC_SUCCESS;
666         }
667         case DEMUX_SET_TITLE:
668         {
669             const int i_title = (int)va_arg( args, int );
670             if( i_title > 1 )
671                 return VLC_EGENERIC;
672             return VLC_SUCCESS;
673         }
674         case DEMUX_SET_SEEKPOINT:
675         {
676             const int i_seekpoint = (int)va_arg( args, int );
677             if( i_seekpoint > p_sys->i_seekpoints )
678                 return VLC_EGENERIC;
679             if( p_sys->i_bos > 0 )
680             {
681                 return VLC_EGENERIC;
682             }
683
684             Ogg_ResetStreamHelper( p_sys );
685
686             if ( p_sys->i_bitrate == 0 || p_sys->b_partial_bitrate )
687             {
688                 /* we won't be able to find block by time
689                  * we'll need to bisect search from here
690                  * or use skeleton index if any (FIXME)
691                 */
692                 logical_stream_t *p_stream = Ogg_GetSelectedStream( p_demux );
693                 if ( !p_stream )
694                 {
695                     msg_Err( p_demux, "No selected seekable stream found" );
696                     return VLC_EGENERIC;
697                 }
698
699                 Oggseek_SeektoAbsolutetime( p_demux, p_stream, p_sys->pp_seekpoints[i_seekpoint]->i_time_offset );
700
701                 return VLC_SUCCESS;
702             }
703             else
704             {
705                 int64_t i_block = p_sys->pp_seekpoints[i_seekpoint]->i_time_offset * p_sys->i_bitrate / INT64_C(8000000);
706                 if( stream_Seek( p_demux->s, i_block ) )
707                     return VLC_EGENERIC;
708             }
709             p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
710             p_demux->info.i_seekpoint = i_seekpoint;
711             return VLC_SUCCESS;
712         }
713
714         default:
715             return demux_vaControlHelper( p_demux->s, 0, -1, p_sys->i_bitrate,
716                                            1, i_query, args );
717     }
718 }
719
720 /****************************************************************************
721  * Ogg_ReadPage: Read a full Ogg page from the physical bitstream.
722  ****************************************************************************
723  * Returns VLC_SUCCESS if a page has been read. An error might happen if we
724  * are at the end of stream.
725  ****************************************************************************/
726 static int Ogg_ReadPage( demux_t *p_demux, ogg_page *p_oggpage )
727 {
728     demux_sys_t *p_ogg = p_demux->p_sys  ;
729     int i_read = 0;
730     char *p_buffer;
731
732     while( ogg_sync_pageout( &p_ogg->oy, p_oggpage ) != 1 )
733     {
734         p_buffer = ogg_sync_buffer( &p_ogg->oy, OGGSEEK_BYTES_TO_READ );
735
736         i_read = stream_Read( p_demux->s, p_buffer, OGGSEEK_BYTES_TO_READ );
737         if( i_read <= 0 )
738             return VLC_EGENERIC;
739
740         ogg_sync_wrote( &p_ogg->oy, i_read );
741     }
742
743     return VLC_SUCCESS;
744 }
745
746 /****************************************************************************
747  * Ogg_UpdatePCR: update the PCR (90kHz program clock reference) for the
748  *                current stream.
749  ****************************************************************************/
750 static void Ogg_UpdatePCR( logical_stream_t *p_stream,
751                            ogg_packet *p_oggpacket )
752 {
753     p_stream->i_end_trim = 0;
754
755     /* Convert the granulepos into a pcr */
756     if( p_oggpacket->granulepos >= 0 )
757     {
758         if( p_stream->fmt.i_codec == VLC_CODEC_THEORA ||
759             p_stream->fmt.i_codec == VLC_CODEC_KATE ||
760             p_stream->fmt.i_codec == VLC_CODEC_DIRAC )
761         {
762             p_stream->i_pcr = Oggseek_GranuleToAbsTimestamp( p_stream,
763                                                 p_oggpacket->granulepos, true );
764         }
765         else
766         {
767             ogg_int64_t sample;
768             sample = p_oggpacket->granulepos;
769             if( p_oggpacket->e_o_s &&
770                 p_stream->fmt.i_codec == VLC_CODEC_OPUS &&
771                 p_stream->i_previous_granulepos >= 0 )
772             {
773                 int duration;
774                 duration = Ogg_OpusPacketDuration( p_stream, p_oggpacket );
775                 if( duration > 0 )
776                 {
777                     ogg_int64_t end_sample;
778                     end_sample = p_stream->i_previous_granulepos + duration;
779                     if( end_sample > sample )
780                         p_stream->i_end_trim = (int)(end_sample - sample);
781                 }
782             }
783             if (sample >= p_stream->i_pre_skip)
784                 sample -= p_stream->i_pre_skip;
785             else
786                 sample = 0;
787             p_stream->i_pcr = sample * INT64_C(1000000) / p_stream->f_rate;
788         }
789
790         p_stream->i_pcr += VLC_TS_0;
791         p_stream->i_interpolated_pcr = p_stream->i_pcr;
792     }
793     else
794     {
795         int duration;
796         p_stream->i_pcr = -1;
797
798         /* no granulepos available, try to interpolate the pcr.
799          * If we can't then don't touch the old value. */
800         if( p_stream->fmt.i_cat == VIDEO_ES )
801             /* 1 frame per packet */
802             p_stream->i_interpolated_pcr += (INT64_C(1000000) / p_stream->f_rate);
803         else if( p_stream->fmt.i_codec == VLC_CODEC_OPUS &&
804                  p_stream->i_previous_granulepos >= 0 &&
805                  ( duration =
806                      Ogg_OpusPacketDuration( p_stream, p_oggpacket ) ) > 0 )
807         {
808             ogg_int64_t sample;
809             p_oggpacket->granulepos =
810                 p_stream->i_previous_granulepos + duration;
811             sample = p_oggpacket->granulepos;
812             if (sample >= p_stream->i_pre_skip)
813                 sample -= p_stream->i_pre_skip;
814             else
815                 sample = 0;
816             p_stream->i_interpolated_pcr =
817                 VLC_TS_0 + sample * INT64_C(1000000) / p_stream->f_rate;
818         }
819         else if( p_stream->fmt.i_bitrate )
820         {
821             p_stream->i_interpolated_pcr +=
822                 ( p_oggpacket->bytes * INT64_C(1000000) /
823                   p_stream->fmt.i_bitrate / 8 );
824         }
825     }
826     p_stream->i_previous_granulepos = p_oggpacket->granulepos;
827 }
828
829 /****************************************************************************
830  * Ogg_DecodePacket: Decode an Ogg packet.
831  ****************************************************************************/
832 static void Ogg_DecodePacket( demux_t *p_demux,
833                               logical_stream_t *p_stream,
834                               ogg_packet *p_oggpacket )
835 {
836     block_t *p_block;
837     bool b_selected;
838     int i_header_len = 0;
839     mtime_t i_pts = -1, i_interpolated_pts;
840     demux_sys_t *p_ogg = p_demux->p_sys;
841
842     if( p_oggpacket->bytes >= 7 &&
843         ! memcmp ( p_oggpacket->packet, "Annodex", 7 ) )
844     {
845         /* it's an Annodex packet -- skip it (do nothing) */
846         return;
847     }
848     else if( p_oggpacket->bytes >= 7 &&
849         ! memcmp ( p_oggpacket->packet, "AnxData", 7 ) )
850     {
851         /* it's an AnxData packet -- skip it (do nothing) */
852         return;
853     }
854
855     if( p_stream->fmt.i_codec == VLC_CODEC_SUBT && p_oggpacket->bytes > 0 &&
856         p_oggpacket->packet[0] & PACKET_TYPE_BITS ) return;
857
858     /* Check the ES is selected */
859     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
860                     p_stream->p_es, &b_selected );
861
862     if( p_stream->b_force_backup )
863     {
864         bool b_xiph;
865         p_stream->i_packets_backup++;
866         switch( p_stream->fmt.i_codec )
867         {
868         case VLC_CODEC_VORBIS:
869         case VLC_CODEC_THEORA:
870             if( p_stream->i_packets_backup == 3 )
871                 p_stream->b_force_backup = false;
872             b_xiph = true;
873             break;
874
875         case VLC_CODEC_SPEEX:
876             if( p_stream->i_packets_backup == 2 + p_stream->i_extra_headers_packets )
877                 p_stream->b_force_backup = false;
878             b_xiph = true;
879             break;
880
881         case VLC_CODEC_OPUS:
882             if( p_stream->i_packets_backup == 2 )
883                 p_stream->b_force_backup = false;
884             b_xiph = true;
885             break;
886
887         case VLC_CODEC_FLAC:
888             if( !p_stream->fmt.audio.i_rate && p_stream->i_packets_backup == 2 )
889             {
890                 Ogg_ReadFlacHeader( p_demux, p_stream, p_oggpacket );
891                 p_stream->b_force_backup = false;
892             }
893             else if( p_stream->fmt.audio.i_rate )
894             {
895                 p_stream->b_force_backup = false;
896                 if( p_oggpacket->bytes >= 9 )
897                 {
898                     p_oggpacket->packet += 9;
899                     p_oggpacket->bytes -= 9;
900                 }
901             }
902             b_xiph = false;
903             break;
904
905         case VLC_CODEC_KATE:
906             if( p_stream->i_packets_backup == p_stream->i_kate_num_headers )
907                 p_stream->b_force_backup = false;
908             b_xiph = true;
909             break;
910
911         default:
912             p_stream->b_force_backup = false;
913             b_xiph = false;
914             break;
915         }
916
917         /* Backup the ogg packet (likely an header packet) */
918         if( !b_xiph )
919         {
920             void *p_org = p_stream->p_headers;
921             p_stream->i_headers += p_oggpacket->bytes;
922             p_stream->p_headers = realloc( p_stream->p_headers, p_stream->i_headers );
923             if( p_stream->p_headers )
924             {
925                 memcpy( (unsigned char *)p_stream->p_headers + p_stream->i_headers - p_oggpacket->bytes,
926                         p_oggpacket->packet, p_oggpacket->bytes );
927             }
928             else
929             {
930 #warning Memory leak
931                 p_stream->i_headers = 0;
932                 p_stream->p_headers = NULL;
933                 free( p_org );
934             }
935         }
936         else if( xiph_AppendHeaders( &p_stream->i_headers, &p_stream->p_headers,
937                                      p_oggpacket->bytes, p_oggpacket->packet ) )
938         {
939             p_stream->i_headers = 0;
940             p_stream->p_headers = NULL;
941         }
942         if( p_stream->i_headers > 0 )
943         {
944             if( !p_stream->b_force_backup )
945             {
946                 /* Last header received, commit changes */
947                 free( p_stream->fmt.p_extra );
948
949                 p_stream->fmt.i_extra = p_stream->i_headers;
950                 p_stream->fmt.p_extra = malloc( p_stream->i_headers );
951                 if( p_stream->fmt.p_extra )
952                     memcpy( p_stream->fmt.p_extra, p_stream->p_headers,
953                             p_stream->i_headers );
954                 else
955                     p_stream->fmt.i_extra = 0;
956
957                 if( Ogg_LogicalStreamResetEsFormat( p_demux, p_stream ) )
958                     es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
959                                     p_stream->p_es, &p_stream->fmt );
960
961                 if( p_stream->i_headers > 0 )
962                     Ogg_ExtractMeta( p_demux, & p_stream->fmt,
963                                      p_stream->p_headers, p_stream->i_headers );
964
965                 /* we're not at BOS anymore for this logical stream */
966                 p_ogg->i_bos--;
967             }
968         }
969
970         b_selected = false; /* Discard the header packet */
971     }
972
973     /* Convert the pcr into a pts */
974     if( p_stream->fmt.i_codec == VLC_CODEC_VORBIS ||
975         p_stream->fmt.i_codec == VLC_CODEC_SPEEX ||
976         p_stream->fmt.i_codec == VLC_CODEC_OPUS ||
977         p_stream->fmt.i_codec == VLC_CODEC_FLAC )
978     {
979         if( p_stream->i_pcr >= 0 )
980         {
981             /* This is for streams where the granulepos of the header packets
982              * doesn't match these of the data packets (eg. ogg web radios). */
983             if( p_stream->i_previous_pcr == 0 &&
984                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
985             {
986
987                 /* Call the pace control */
988                 es_out_Control( p_demux->out, ES_OUT_SET_PCR,
989                                 VLC_TS_0 + p_stream->i_pcr );
990             }
991
992             p_stream->i_previous_pcr = p_stream->i_pcr;
993
994             /* The granulepos is the end date of the sample */
995             i_pts = p_stream->i_pcr;
996         }
997     }
998
999     /* Convert the granulepos into the next pcr */
1000     i_interpolated_pts = p_stream->i_interpolated_pcr;
1001     Ogg_UpdatePCR( p_stream, p_oggpacket );
1002
1003     /* SPU streams are typically discontinuous, do not mind large gaps */
1004     if( p_stream->fmt.i_cat != SPU_ES )
1005     {
1006         if( p_stream->i_pcr >= 0 )
1007         {
1008             /* This is for streams where the granulepos of the header packets
1009              * doesn't match these of the data packets (eg. ogg web radios). */
1010             if( p_stream->i_previous_pcr == 0 &&
1011                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
1012             {
1013
1014                 /* Call the pace control */
1015                 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_stream->i_pcr );
1016             }
1017         }
1018     }
1019
1020     if( p_stream->fmt.i_codec != VLC_CODEC_VORBIS &&
1021         p_stream->fmt.i_codec != VLC_CODEC_SPEEX &&
1022         p_stream->fmt.i_codec != VLC_CODEC_OPUS &&
1023         p_stream->fmt.i_codec != VLC_CODEC_FLAC &&
1024         p_stream->i_pcr >= 0 )
1025     {
1026         p_stream->i_previous_pcr = p_stream->i_pcr;
1027
1028         /* The granulepos is the start date of the sample */
1029         i_pts = p_stream->i_pcr;
1030     }
1031
1032     if( !b_selected )
1033     {
1034         /* This stream isn't currently selected so we don't need to decode it,
1035          * but we did need to store its pcr as it might be selected later on */
1036         return;
1037     }
1038
1039     if( !( p_block = block_Alloc( p_oggpacket->bytes ) ) ) return;
1040
1041
1042     /* may need to preroll after a seek */
1043     if ( p_stream->i_skip_frames > 0 )
1044     {
1045         if( p_stream->fmt.i_codec == VLC_CODEC_OPUS )
1046         {
1047             int duration;
1048             duration = Ogg_OpusPacketDuration( p_stream, p_oggpacket );
1049             if( p_stream->i_skip_frames > duration )
1050             {
1051                 p_block->i_flags |= BLOCK_FLAG_PREROLL;
1052                 p_block->i_nb_samples = 0;
1053                 p_stream->i_skip_frames -= duration;
1054             }
1055             else
1056             {
1057                 p_block->i_nb_samples = duration - p_stream->i_skip_frames;
1058                 if( p_stream->i_previous_granulepos >=
1059                     p_block->i_nb_samples + p_stream->i_pre_skip )
1060                 {
1061                     i_pts = VLC_TS_0 + (p_stream->i_previous_granulepos
1062                         - p_block->i_nb_samples - p_stream->i_pre_skip) *
1063                         INT64_C(1000000) / p_stream->f_rate;
1064                 }
1065                 p_stream->i_skip_frames = 0;
1066             }
1067         }
1068         else
1069         {
1070             p_block->i_flags |= BLOCK_FLAG_PREROLL;
1071             p_stream->i_skip_frames--;
1072         }
1073     }
1074     else if( p_stream->fmt.i_codec == VLC_CODEC_OPUS )
1075         p_block->i_nb_samples = Ogg_OpusPacketDuration( p_stream, p_oggpacket );
1076
1077
1078     /* Normalize PTS */
1079     if( i_pts == VLC_TS_INVALID ) i_pts = VLC_TS_0;
1080     else if( i_pts == -1 && i_interpolated_pts == VLC_TS_INVALID )
1081         i_pts = VLC_TS_0;
1082     else if( i_pts == -1 && (p_stream->fmt.i_cat == VIDEO_ES || p_stream->fmt.i_codec == VLC_CODEC_OPUS) )
1083         i_pts = i_interpolated_pts; /* FIXME : why is this incorrect for vorbis? */
1084     else if( i_pts == -1 ) i_pts = VLC_TS_INVALID;
1085
1086     if( p_stream->fmt.i_cat == AUDIO_ES )
1087     {
1088         p_block->i_dts = p_block->i_pts = i_pts;
1089         /* Blatant abuse of the i_length field. */
1090         p_block->i_length = p_stream->i_end_trim;
1091     }
1092     else if( p_stream->fmt.i_cat == SPU_ES )
1093     {
1094         p_block->i_dts = p_block->i_pts = i_pts;
1095         p_block->i_length = 0;
1096     }
1097     else if( p_stream->fmt.i_codec == VLC_CODEC_THEORA )
1098     {
1099         p_block->i_dts = p_block->i_pts = i_pts;
1100         if( (p_oggpacket->granulepos & ((1<<p_stream->i_granule_shift)-1)) == 0 )
1101         {
1102             p_block->i_flags |= BLOCK_FLAG_TYPE_I;
1103         }
1104     }
1105     else if( p_stream->fmt.i_codec == VLC_CODEC_DIRAC )
1106     {
1107         ogg_int64_t dts = p_oggpacket->granulepos >> 31;
1108         ogg_int64_t delay = (p_oggpacket->granulepos >> 9) & 0x1fff;
1109
1110         uint64_t u_pnum = dts + delay;
1111
1112         p_block->i_dts = p_stream->i_pcr;
1113         p_block->i_pts = VLC_TS_INVALID;
1114         /* NB, OggDirac granulepos values are in units of 2*picturerate */
1115
1116         /* granulepos for dirac is possibly broken, this value should be ignored */
1117         if( -1 != p_oggpacket->granulepos )
1118             p_block->i_pts = u_pnum * INT64_C(1000000) / p_stream->f_rate / 2;
1119     }
1120     else
1121     {
1122         p_block->i_dts = i_pts;
1123         p_block->i_pts = VLC_TS_INVALID;
1124     }
1125
1126     if( p_stream->fmt.i_codec != VLC_CODEC_VORBIS &&
1127         p_stream->fmt.i_codec != VLC_CODEC_SPEEX &&
1128         p_stream->fmt.i_codec != VLC_CODEC_OPUS &&
1129         p_stream->fmt.i_codec != VLC_CODEC_FLAC &&
1130         p_stream->fmt.i_codec != VLC_CODEC_TARKIN &&
1131         p_stream->fmt.i_codec != VLC_CODEC_THEORA &&
1132         p_stream->fmt.i_codec != VLC_CODEC_CMML &&
1133         p_stream->fmt.i_codec != VLC_CODEC_DIRAC &&
1134         p_stream->fmt.i_codec != VLC_CODEC_KATE )
1135     {
1136         if( p_oggpacket->bytes <= 0 )
1137         {
1138             msg_Dbg( p_demux, "discarding 0 sized packet" );
1139             block_Release( p_block );
1140             return;
1141         }
1142         /* We remove the header from the packet */
1143         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
1144         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
1145
1146         if( p_stream->fmt.i_codec == VLC_CODEC_SUBT)
1147         {
1148             /* But with subtitles we need to retrieve the duration first */
1149             int i, lenbytes = 0;
1150
1151             if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
1152             {
1153                 for( i = 0, lenbytes = 0; i < i_header_len; i++ )
1154                 {
1155                     lenbytes = lenbytes << 8;
1156                     lenbytes += *(p_oggpacket->packet + i_header_len - i);
1157                 }
1158             }
1159             if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
1160                 ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
1161                   p_oggpacket->packet[i_header_len + 1] != 0 &&
1162                   p_oggpacket->packet[i_header_len + 1] != '\n' &&
1163                   p_oggpacket->packet[i_header_len + 1] != '\r' ) )
1164             {
1165                 p_block->i_length = (mtime_t)lenbytes * 1000;
1166             }
1167         }
1168
1169         i_header_len++;
1170         if( p_block->i_buffer >= (unsigned int)i_header_len )
1171             p_block->i_buffer -= i_header_len;
1172         else
1173             p_block->i_buffer = 0;
1174     }
1175
1176     if( p_stream->fmt.i_codec == VLC_CODEC_TARKIN )
1177     {
1178         /* FIXME: the biggest hack I've ever done */
1179         msg_Warn( p_demux, "tarkin pts: %"PRId64", granule: %"PRId64,
1180                   p_block->i_pts, p_block->i_dts );
1181         msleep(10000);
1182     }
1183
1184     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
1185             p_oggpacket->bytes - i_header_len );
1186
1187     es_out_Send( p_demux->out, p_stream->p_es, p_block );
1188 }
1189
1190 /* Re-implemented to avoid linking against libopus from the demuxer. */
1191 static int Ogg_OpusPacketDuration( logical_stream_t *p_stream,
1192                                    ogg_packet *p_oggpacket )
1193 {
1194     static const int silk_fs_div[4] = { 6000, 3000, 1500, 1000 };
1195     int toc;
1196     int nframes;
1197     int frame_size;
1198     int nsamples;
1199     int i_rate;
1200     if( p_oggpacket->bytes < 1 )
1201         return VLC_EGENERIC;
1202     toc = p_oggpacket->packet[0];
1203     switch( toc&3 )
1204     {
1205         case 0:
1206             nframes = 1;
1207             break;
1208         case 1:
1209         case 2:
1210             nframes = 2;
1211             break;
1212         default:
1213             if( p_oggpacket->bytes < 2 )
1214                 return VLC_EGENERIC;
1215             nframes = p_oggpacket->packet[1]&0x3F;
1216             break;
1217     }
1218     i_rate = (int)p_stream->fmt.audio.i_rate;
1219     if( toc&0x80 )
1220         frame_size = (i_rate << (toc >> 3 & 3)) / 400;
1221     else if( ( toc&0x60 ) == 0x60 )
1222         frame_size = i_rate/(100 >> (toc >> 3 & 1));
1223     else
1224         frame_size = i_rate*60 / silk_fs_div[toc >> 3 & 3];
1225     nsamples = nframes*frame_size;
1226     if( nsamples*25 > i_rate*3 )
1227         return VLC_EGENERIC;
1228     return nsamples;
1229 }
1230
1231 /****************************************************************************
1232  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
1233  *                         stream and fill p_ogg.
1234  *****************************************************************************
1235  * The initial page of a logical stream is marked as a 'bos' page.
1236  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
1237  * together and all of the initial pages must appear before any data pages.
1238  *
1239  * On success this function returns VLC_SUCCESS.
1240  ****************************************************************************/
1241 static int Ogg_FindLogicalStreams( demux_t *p_demux )
1242 {
1243     demux_sys_t *p_ogg = p_demux->p_sys  ;
1244     ogg_packet oggpacket;
1245     int i_stream;
1246
1247     p_ogg->i_total_length = stream_Size ( p_demux->s );
1248     msg_Dbg( p_demux, "File length is %"PRId64" bytes", p_ogg->i_total_length );
1249
1250
1251     while( Ogg_ReadPage( p_demux, &p_ogg->current_page ) == VLC_SUCCESS )
1252     {
1253
1254         if( ogg_page_bos( &p_ogg->current_page ) )
1255         {
1256
1257             /* All is wonderful in our fine fine little world.
1258              * We found the beginning of our first logical stream. */
1259             while( ogg_page_bos( &p_ogg->current_page ) )
1260             {
1261                 logical_stream_t *p_stream;
1262
1263                 p_stream = malloc( sizeof(logical_stream_t) );
1264                 if( unlikely( !p_stream ) )
1265                     return VLC_ENOMEM;
1266
1267                 TAB_APPEND( p_ogg->i_streams, p_ogg->pp_stream, p_stream );
1268
1269                 memset( p_stream, 0, sizeof(logical_stream_t) );
1270
1271                 es_format_Init( &p_stream->fmt, 0, 0 );
1272                 es_format_Init( &p_stream->fmt_old, 0, 0 );
1273
1274                 /* Setup the logical stream */
1275                 p_stream->i_serial_no = ogg_page_serialno( &p_ogg->current_page );
1276                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
1277
1278                 /* Extract the initial header from the first page and verify
1279                  * the codec type of this Ogg bitstream */
1280                 if( ogg_stream_pagein( &p_stream->os, &p_ogg->current_page ) < 0 )
1281                 {
1282                     /* error. stream version mismatch perhaps */
1283                     msg_Err( p_demux, "error reading first page of "
1284                              "Ogg bitstream data" );
1285                     return VLC_EGENERIC;
1286                 }
1287
1288                 /* FIXME: check return value */
1289                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
1290
1291                 /* Check for Vorbis header */
1292                 if( oggpacket.bytes >= 7 &&
1293                     ! memcmp( oggpacket.packet, "\x01vorbis", 7 ) )
1294                 {
1295                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
1296                     msg_Dbg( p_demux, "found vorbis header" );
1297                 }
1298                 /* Check for Speex header */
1299                 else if( oggpacket.bytes >= 5 &&
1300                     ! memcmp( oggpacket.packet, "Speex", 5 ) )
1301                 {
1302                     Ogg_ReadSpeexHeader( p_stream, &oggpacket );
1303                     msg_Dbg( p_demux, "found speex header, channels: %i, "
1304                              "rate: %i,  bitrate: %i",
1305                              p_stream->fmt.audio.i_channels,
1306                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
1307                 }
1308                 /* Check for Opus header */
1309                 else if( oggpacket.bytes >= 8 &&
1310                     ! memcmp( oggpacket.packet, "OpusHead", 8 ) )
1311                 {
1312                     Ogg_ReadOpusHeader( p_stream, &oggpacket );
1313                     msg_Dbg( p_demux, "found opus header, channels: %i, "
1314                              "pre-skip: %i",
1315                              p_stream->fmt.audio.i_channels,
1316                              (int)p_stream->i_pre_skip);
1317                     p_stream->i_skip_frames = p_stream->i_pre_skip;
1318                 }
1319                 /* Check for Flac header (< version 1.1.1) */
1320                 else if( oggpacket.bytes >= 4 &&
1321                     ! memcmp( oggpacket.packet, "fLaC", 4 ) )
1322                 {
1323                     msg_Dbg( p_demux, "found FLAC header" );
1324
1325                     /* Grrrr!!!! Did they really have to put all the
1326                      * important info in the second header packet!!!
1327                      * (STREAMINFO metadata is in the following packet) */
1328                     p_stream->b_force_backup = true;
1329
1330                     p_stream->fmt.i_cat = AUDIO_ES;
1331                     p_stream->fmt.i_codec = VLC_CODEC_FLAC;
1332                 }
1333                 /* Check for Flac header (>= version 1.1.1) */
1334                 else if( oggpacket.bytes >= 13 && oggpacket.packet[0] ==0x7F &&
1335                     ! memcmp( &oggpacket.packet[1], "FLAC", 4 ) &&
1336                     ! memcmp( &oggpacket.packet[9], "fLaC", 4 ) )
1337                 {
1338                     int i_packets = ((int)oggpacket.packet[7]) << 8 |
1339                         oggpacket.packet[8];
1340                     msg_Dbg( p_demux, "found FLAC header version %i.%i "
1341                              "(%i header packets)",
1342                              oggpacket.packet[5], oggpacket.packet[6],
1343                              i_packets );
1344
1345                     p_stream->b_force_backup = true;
1346
1347                     p_stream->fmt.i_cat = AUDIO_ES;
1348                     p_stream->fmt.i_codec = VLC_CODEC_FLAC;
1349                     oggpacket.packet += 13; oggpacket.bytes -= 13;
1350                     Ogg_ReadFlacHeader( p_demux, p_stream, &oggpacket );
1351                 }
1352                 /* Check for Theora header */
1353                 else if( oggpacket.bytes >= 7 &&
1354                          ! memcmp( oggpacket.packet, "\x80theora", 7 ) )
1355                 {
1356                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
1357
1358                     msg_Dbg( p_demux,
1359                              "found theora header, bitrate: %i, rate: %f",
1360                              p_stream->fmt.i_bitrate, p_stream->f_rate );
1361                 }
1362                 /* Check for Dirac header */
1363                 else if( ( oggpacket.bytes >= 5 &&
1364                            ! memcmp( oggpacket.packet, "BBCD\x00", 5 ) ) ||
1365                          ( oggpacket.bytes >= 9 &&
1366                            ! memcmp( oggpacket.packet, "KW-DIRAC\x00", 9 ) ) )
1367                 {
1368                     if( Ogg_ReadDiracHeader( p_stream, &oggpacket ) )
1369                         msg_Dbg( p_demux, "found dirac header" );
1370                     else
1371                     {
1372                         msg_Warn( p_demux, "found dirac header isn't decodable" );
1373                         free( p_stream );
1374                         p_ogg->i_streams--;
1375                     }
1376                 }
1377                 /* Check for Tarkin header */
1378                 else if( oggpacket.bytes >= 7 &&
1379                          ! memcmp( &oggpacket.packet[1], "tarkin", 6 ) )
1380                 {
1381                     oggpack_buffer opb;
1382
1383                     msg_Dbg( p_demux, "found tarkin header" );
1384                     p_stream->fmt.i_cat = VIDEO_ES;
1385                     p_stream->fmt.i_codec = VLC_CODEC_TARKIN;
1386
1387                     /* Cheat and get additionnal info ;) */
1388                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
1389                     oggpack_adv( &opb, 88 );
1390                     oggpack_adv( &opb, 104 );
1391                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1392                     p_stream->f_rate = 2; /* FIXME */
1393                     msg_Dbg( p_demux,
1394                              "found tarkin header, bitrate: %i, rate: %f",
1395                              p_stream->fmt.i_bitrate, p_stream->f_rate );
1396                 }
1397                 /* Check for Annodex header */
1398                 else if( oggpacket.bytes >= 7 &&
1399                          ! memcmp( oggpacket.packet, "Annodex", 7 ) )
1400                 {
1401                     Ogg_ReadAnnodexHeader( p_demux, p_stream, &oggpacket );
1402                     /* kill annodex track */
1403                     free( p_stream );
1404                     p_ogg->i_streams--;
1405                 }
1406                 /* Check for Annodex header */
1407                 else if( oggpacket.bytes >= 7 &&
1408                          ! memcmp( oggpacket.packet, "AnxData", 7 ) )
1409                 {
1410                     Ogg_ReadAnnodexHeader( p_demux, p_stream, &oggpacket );
1411                 }
1412                 /* Check for Kate header */
1413                 else if( oggpacket.bytes >= 8 &&
1414                     ! memcmp( &oggpacket.packet[1], "kate\0\0\0", 7 ) )
1415                 {
1416                     Ogg_ReadKateHeader( p_stream, &oggpacket );
1417                     msg_Dbg( p_demux, "found kate header" );
1418                 }
1419                 /* Check for OggDS */
1420                 else if( oggpacket.bytes >= 142 &&
1421                          !memcmp( &oggpacket.packet[1],
1422                                    "Direct Show Samples embedded in Ogg", 35 ))
1423                 {
1424                     /* Old header type */
1425                     p_stream->b_oggds = true;
1426                     /* Check for video header (old format) */
1427                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
1428                         oggpacket.bytes >= 184 )
1429                     {
1430                         p_stream->fmt.i_cat = VIDEO_ES;
1431                         p_stream->fmt.i_codec =
1432                             VLC_FOURCC( oggpacket.packet[68],
1433                                         oggpacket.packet[69],
1434                                         oggpacket.packet[70],
1435                                         oggpacket.packet[71] );
1436                         msg_Dbg( p_demux, "found video header of type: %.4s",
1437                                  (char *)&p_stream->fmt.i_codec );
1438
1439                         p_stream->fmt.video.i_frame_rate = 10000000;
1440                         p_stream->fmt.video.i_frame_rate_base =
1441                             GetQWLE((oggpacket.packet+164));
1442                         p_stream->f_rate = 10000000.0 /
1443                             GetQWLE((oggpacket.packet+164));
1444                         p_stream->fmt.video.i_bits_per_pixel =
1445                             GetWLE((oggpacket.packet+182));
1446                         if( !p_stream->fmt.video.i_bits_per_pixel )
1447                             /* hack, FIXME */
1448                             p_stream->fmt.video.i_bits_per_pixel = 24;
1449                         p_stream->fmt.video.i_width =
1450                             GetDWLE((oggpacket.packet+176));
1451                         p_stream->fmt.video.i_height =
1452                             GetDWLE((oggpacket.packet+180));
1453
1454                         msg_Dbg( p_demux,
1455                                  "fps: %f, width:%i; height:%i, bitcount:%i",
1456                                  p_stream->f_rate,
1457                                  p_stream->fmt.video.i_width,
1458                                  p_stream->fmt.video.i_height,
1459                                  p_stream->fmt.video.i_bits_per_pixel);
1460
1461                     }
1462                     /* Check for audio header (old format) */
1463                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
1464                     {
1465                         int i_extra_size;
1466                         unsigned int i_format_tag;
1467
1468                         p_stream->fmt.i_cat = AUDIO_ES;
1469
1470                         i_extra_size = GetWLE((oggpacket.packet+140));
1471                         if( i_extra_size > 0 && i_extra_size < oggpacket.bytes - 142 )
1472                         {
1473                             p_stream->fmt.i_extra = i_extra_size;
1474                             p_stream->fmt.p_extra = malloc( i_extra_size );
1475                             if( p_stream->fmt.p_extra )
1476                                 memcpy( p_stream->fmt.p_extra,
1477                                         oggpacket.packet + 142, i_extra_size );
1478                             else
1479                                 p_stream->fmt.i_extra = 0;
1480                         }
1481
1482                         i_format_tag = GetWLE((oggpacket.packet+124));
1483                         p_stream->fmt.audio.i_channels =
1484                             GetWLE((oggpacket.packet+126));
1485                         fill_channels_info(&p_stream->fmt.audio);
1486                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
1487                             GetDWLE((oggpacket.packet+128));
1488                         p_stream->fmt.i_bitrate =
1489                             GetDWLE((oggpacket.packet+132)) * 8;
1490                         p_stream->fmt.audio.i_blockalign =
1491                             GetWLE((oggpacket.packet+136));
1492                         p_stream->fmt.audio.i_bitspersample =
1493                             GetWLE((oggpacket.packet+138));
1494
1495                         wf_tag_to_fourcc( i_format_tag,
1496                                           &p_stream->fmt.i_codec, 0 );
1497
1498                         if( p_stream->fmt.i_codec ==
1499                             VLC_FOURCC('u','n','d','f') )
1500                         {
1501                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1502                                 ( i_format_tag >> 8 ) & 0xff,
1503                                 i_format_tag & 0xff );
1504                         }
1505
1506                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1507                                  (char *)&p_stream->fmt.i_codec );
1508                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1509                                  "%dbits/sample %dkb/s",
1510                                  i_format_tag,
1511                                  p_stream->fmt.audio.i_channels,
1512                                  p_stream->fmt.audio.i_rate,
1513                                  p_stream->fmt.audio.i_bitspersample,
1514                                  p_stream->fmt.i_bitrate / 1024 );
1515
1516                     }
1517                     else
1518                     {
1519                         msg_Dbg( p_demux, "stream %d has an old header "
1520                             "but is of an unknown type", p_ogg->i_streams-1 );
1521                         free( p_stream );
1522                         p_ogg->i_streams--;
1523                     }
1524                 }
1525                 /* Check for OggDS */
1526                 else if( oggpacket.bytes >= 44+1 &&
1527                          (*oggpacket.packet & PACKET_TYPE_BITS ) == PACKET_TYPE_HEADER )
1528                 {
1529                     stream_header_t tmp;
1530                     stream_header_t *st = &tmp;
1531
1532                     p_stream->b_oggds = true;
1533
1534                     memcpy( st->streamtype, &oggpacket.packet[1+0], 8 );
1535                     memcpy( st->subtype, &oggpacket.packet[1+8], 4 );
1536                     st->size = GetDWLE( &oggpacket.packet[1+12] );
1537                     st->time_unit = GetQWLE( &oggpacket.packet[1+16] );
1538                     st->samples_per_unit = GetQWLE( &oggpacket.packet[1+24] );
1539                     st->default_len = GetDWLE( &oggpacket.packet[1+32] );
1540                     st->buffersize = GetDWLE( &oggpacket.packet[1+36] );
1541                     st->bits_per_sample = GetWLE( &oggpacket.packet[1+40] ); // (padding 2)
1542
1543                     /* Check for video header (new format) */
1544                     if( !strncmp( st->streamtype, "video", 5 ) &&
1545                         oggpacket.bytes >= 52+1 )
1546                     {
1547                         st->sh.video.width = GetDWLE( &oggpacket.packet[1+44] );
1548                         st->sh.video.height = GetDWLE( &oggpacket.packet[1+48] );
1549
1550                         p_stream->fmt.i_cat = VIDEO_ES;
1551
1552                         /* We need to get rid of the header packet */
1553                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1554
1555                         p_stream->fmt.i_codec =
1556                             VLC_FOURCC( st->subtype[0], st->subtype[1],
1557                                         st->subtype[2], st->subtype[3] );
1558                         msg_Dbg( p_demux, "found video header of type: %.4s",
1559                                  (char *)&p_stream->fmt.i_codec );
1560
1561                         p_stream->fmt.video.i_frame_rate = 10000000;
1562                         p_stream->fmt.video.i_frame_rate_base = st->time_unit;
1563                         if( st->time_unit <= 0 )
1564                             st->time_unit = 400000;
1565                         p_stream->f_rate = 10000000.0 / st->time_unit;
1566                         p_stream->fmt.video.i_bits_per_pixel = st->bits_per_sample;
1567                         p_stream->fmt.video.i_width = st->sh.video.width;
1568                         p_stream->fmt.video.i_height = st->sh.video.height;
1569
1570                         msg_Dbg( p_demux,
1571                                  "fps: %f, width:%i; height:%i, bitcount:%i",
1572                                  p_stream->f_rate,
1573                                  p_stream->fmt.video.i_width,
1574                                  p_stream->fmt.video.i_height,
1575                                  p_stream->fmt.video.i_bits_per_pixel );
1576                     }
1577                     /* Check for audio header (new format) */
1578                     else if( !strncmp( st->streamtype, "audio", 5 ) &&
1579                              oggpacket.bytes >= 56+1 )
1580                     {
1581                         char p_buffer[5];
1582                         int i_extra_size;
1583                         int i_format_tag;
1584
1585                         st->sh.audio.channels = GetWLE( &oggpacket.packet[1+44] );
1586                         st->sh.audio.blockalign = GetWLE( &oggpacket.packet[1+48] );
1587                         st->sh.audio.avgbytespersec = GetDWLE( &oggpacket.packet[1+52] );
1588
1589                         p_stream->fmt.i_cat = AUDIO_ES;
1590
1591                         /* We need to get rid of the header packet */
1592                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1593
1594                         i_extra_size = st->size - 56;
1595
1596                         if( i_extra_size > 0 &&
1597                             i_extra_size < oggpacket.bytes - 1 - 56 )
1598                         {
1599                             p_stream->fmt.i_extra = i_extra_size;
1600                             p_stream->fmt.p_extra = malloc( p_stream->fmt.i_extra );
1601                             if( p_stream->fmt.p_extra )
1602                                 memcpy( p_stream->fmt.p_extra, st + 1,
1603                                         p_stream->fmt.i_extra );
1604                             else
1605                                 p_stream->fmt.i_extra = 0;
1606                         }
1607
1608                         memcpy( p_buffer, st->subtype, 4 );
1609                         p_buffer[4] = '\0';
1610                         i_format_tag = strtol(p_buffer,NULL,16);
1611                         p_stream->fmt.audio.i_channels = st->sh.audio.channels;
1612                         fill_channels_info(&p_stream->fmt.audio);
1613                         if( st->time_unit <= 0 )
1614                             st->time_unit = 10000000;
1615                         p_stream->f_rate = p_stream->fmt.audio.i_rate = st->samples_per_unit * 10000000 / st->time_unit;
1616                         p_stream->fmt.i_bitrate = st->sh.audio.avgbytespersec * 8;
1617                         p_stream->fmt.audio.i_blockalign = st->sh.audio.blockalign;
1618                         p_stream->fmt.audio.i_bitspersample = st->bits_per_sample;
1619
1620                         wf_tag_to_fourcc( i_format_tag,
1621                                           &p_stream->fmt.i_codec, 0 );
1622
1623                         if( p_stream->fmt.i_codec ==
1624                             VLC_FOURCC('u','n','d','f') )
1625                         {
1626                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1627                                 ( i_format_tag >> 8 ) & 0xff,
1628                                 i_format_tag & 0xff );
1629                         }
1630
1631                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1632                                  (char *)&p_stream->fmt.i_codec );
1633                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1634                                  "%dbits/sample %dkb/s",
1635                                  i_format_tag,
1636                                  p_stream->fmt.audio.i_channels,
1637                                  p_stream->fmt.audio.i_rate,
1638                                  p_stream->fmt.audio.i_bitspersample,
1639                                  p_stream->fmt.i_bitrate / 1024 );
1640                     }
1641                     /* Check for text (subtitles) header */
1642                     else if( !strncmp(st->streamtype, "text", 4) )
1643                     {
1644                         /* We need to get rid of the header packet */
1645                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1646
1647                         msg_Dbg( p_demux, "found text subtitle header" );
1648                         p_stream->fmt.i_cat = SPU_ES;
1649                         p_stream->fmt.i_codec = VLC_CODEC_SUBT;
1650                         p_stream->f_rate = 1000; /* granulepos is in millisec */
1651                     }
1652                     else
1653                     {
1654                         msg_Dbg( p_demux, "stream %d has a header marker "
1655                             "but is of an unknown type", p_ogg->i_streams-1 );
1656                         free( p_stream );
1657                         p_ogg->i_streams--;
1658                     }
1659                 }
1660                 else if( oggpacket.bytes >= 7 &&
1661                              ! memcmp( oggpacket.packet, "fishead", 7 ) )
1662
1663                 {
1664                     /* Skeleton */
1665                     msg_Dbg( p_demux, "stream %d is a skeleton",
1666                                 p_ogg->i_streams-1 );
1667                     /* FIXME: https://trac.videolan.org/vlc/ticket/1412 */
1668                 }
1669                 else
1670                 {
1671                     msg_Dbg( p_demux, "stream %d is of unknown type",
1672                              p_ogg->i_streams-1 );
1673                     free( p_stream );
1674                     p_ogg->i_streams--;
1675                 }
1676
1677                 if( Ogg_ReadPage( p_demux, &p_ogg->current_page ) != VLC_SUCCESS )
1678                     return VLC_EGENERIC;
1679             }
1680
1681             /* we'll need to get all headers for all of those streams
1682                that we have to backup headers for */
1683             p_ogg->i_bos = 0;
1684             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1685             {
1686                 if( p_ogg->pp_stream[i_stream]->b_force_backup )
1687                     p_ogg->i_bos++;
1688             }
1689
1690
1691             /* This is the first data page, which means we are now finished
1692              * with the initial pages. We just need to store it in the relevant
1693              * bitstream. */
1694             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1695             {
1696                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
1697                                        &p_ogg->current_page ) == 0 )
1698                 {
1699                     p_ogg->b_page_waiting = true;
1700                     break;
1701                 }
1702             }
1703
1704             return VLC_SUCCESS;
1705         }
1706     }
1707
1708     return VLC_EGENERIC;
1709 }
1710
1711 /****************************************************************************
1712  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1713  *                        Elementary streams.
1714  ****************************************************************************/
1715 static int Ogg_BeginningOfStream( demux_t *p_demux )
1716 {
1717     demux_sys_t *p_ogg = p_demux->p_sys  ;
1718     logical_stream_t *p_old_stream = p_ogg->p_old_stream;
1719     int i_stream;
1720
1721     /* Find the logical streams embedded in the physical stream and
1722      * initialize our p_ogg structure. */
1723     if( Ogg_FindLogicalStreams( p_demux ) != VLC_SUCCESS )
1724     {
1725         msg_Warn( p_demux, "couldn't find any ogg logical stream" );
1726         return VLC_EGENERIC;
1727     }
1728
1729     p_ogg->i_bitrate = 0;
1730
1731     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1732     {
1733         logical_stream_t *p_stream = p_ogg->pp_stream[i_stream];
1734
1735         p_stream->p_es = NULL;
1736
1737         /* initialise kframe index */
1738         p_stream->idx=NULL;
1739
1740         /* Try first to reuse an old ES */
1741         if( p_old_stream &&
1742             p_old_stream->fmt.i_cat == p_stream->fmt.i_cat &&
1743             p_old_stream->fmt.i_codec == p_stream->fmt.i_codec )
1744         {
1745             msg_Dbg( p_demux, "will reuse old stream to avoid glitch" );
1746
1747             p_stream->p_es = p_old_stream->p_es;
1748             es_format_Copy( &p_stream->fmt_old, &p_old_stream->fmt );
1749
1750             p_old_stream->p_es = NULL;
1751             p_old_stream = NULL;
1752         }
1753
1754         if( !p_stream->p_es )
1755         {
1756             /* Better be safe than sorry when possible with ogm */
1757             if( p_stream->fmt.i_codec == VLC_CODEC_MPGA ||
1758                 p_stream->fmt.i_codec == VLC_CODEC_A52 )
1759                 p_stream->fmt.b_packetized = false;
1760
1761             p_stream->p_es = es_out_Add( p_demux->out, &p_stream->fmt );
1762         }
1763
1764         // TODO: something to do here ?
1765         if( p_stream->fmt.i_codec == VLC_CODEC_CMML )
1766         {
1767             /* Set the CMML stream active */
1768             es_out_Control( p_demux->out, ES_OUT_SET_ES, p_stream->p_es );
1769         }
1770
1771         if ( p_stream->fmt.i_bitrate == 0  &&
1772              ( p_stream->fmt.i_cat == VIDEO_ES ||
1773                p_stream->fmt.i_cat == AUDIO_ES ) )
1774             p_ogg->b_partial_bitrate = true;
1775         else
1776             p_ogg->i_bitrate += p_stream->fmt.i_bitrate;
1777
1778         p_stream->i_pcr = p_stream->i_previous_pcr =
1779             p_stream->i_interpolated_pcr = -1;
1780         p_stream->b_reinit = false;
1781     }
1782
1783     if( p_ogg->p_old_stream )
1784     {
1785         if( p_ogg->p_old_stream->p_es )
1786             msg_Dbg( p_demux, "old stream not reused" );
1787         Ogg_LogicalStreamDelete( p_demux, p_ogg->p_old_stream );
1788         p_ogg->p_old_stream = NULL;
1789     }
1790
1791
1792     /* get total frame count for video stream; we will need this for seeking */
1793     p_ogg->i_total_frames = 0;
1794
1795     return VLC_SUCCESS;
1796 }
1797
1798 /****************************************************************************
1799  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1800  ****************************************************************************/
1801 static void Ogg_EndOfStream( demux_t *p_demux )
1802 {
1803     demux_sys_t *p_ogg = p_demux->p_sys  ;
1804     int i_stream;
1805
1806     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1807         Ogg_LogicalStreamDelete( p_demux, p_ogg->pp_stream[i_stream] );
1808     free( p_ogg->pp_stream );
1809
1810     /* Reinit p_ogg */
1811     p_ogg->i_bitrate = 0;
1812     p_ogg->i_streams = 0;
1813     p_ogg->pp_stream = NULL;
1814
1815     /* */
1816     if( p_ogg->p_meta )
1817         vlc_meta_Delete( p_ogg->p_meta );
1818     p_ogg->p_meta = NULL;
1819 }
1820
1821 /**
1822  * This function delete and release all data associated to a logical_stream_t
1823  */
1824 static void Ogg_LogicalStreamDelete( demux_t *p_demux, logical_stream_t *p_stream )
1825 {
1826     if( p_stream->p_es )
1827         es_out_Del( p_demux->out, p_stream->p_es );
1828
1829     ogg_stream_clear( &p_stream->os );
1830     free( p_stream->p_headers );
1831
1832     es_format_Clean( &p_stream->fmt_old );
1833     es_format_Clean( &p_stream->fmt );
1834
1835     if ( p_stream->idx != NULL)
1836     {
1837         oggseek_index_entries_free( p_stream->idx );
1838     }
1839
1840     free( p_stream );
1841 }
1842 /**
1843  * This function check if a we need to reset a decoder in case we are
1844  * reusing an old ES
1845  */
1846 static bool Ogg_IsVorbisFormatCompatible( const es_format_t *p_new, const es_format_t *p_old )
1847 {
1848     unsigned pi_new_size[XIPH_MAX_HEADER_COUNT];
1849     void     *pp_new_data[XIPH_MAX_HEADER_COUNT];
1850     unsigned i_new_count;
1851     if( xiph_SplitHeaders(pi_new_size, pp_new_data, &i_new_count, p_new->i_extra, p_new->p_extra ) )
1852         i_new_count = 0;
1853
1854     unsigned pi_old_size[XIPH_MAX_HEADER_COUNT];
1855     void     *pp_old_data[XIPH_MAX_HEADER_COUNT];
1856     unsigned i_old_count;
1857     if( xiph_SplitHeaders(pi_old_size, pp_old_data, &i_old_count, p_old->i_extra, p_old->p_extra ) )
1858         i_old_count = 0;
1859
1860     bool b_match = i_new_count == i_old_count;
1861     for( unsigned i = 0; i < i_new_count && b_match; i++ )
1862     {
1863         /* Ignore vorbis comment */
1864         if( i == 1 )
1865             continue;
1866         if( pi_new_size[i] != pi_old_size[i] ||
1867             memcmp( pp_new_data[i], pp_old_data[i], pi_new_size[i] ) )
1868             b_match = false;
1869     }
1870
1871     for( unsigned i = 0; i < i_new_count; i++ )
1872         free( pp_new_data[i] );
1873     for( unsigned i = 0; i < i_old_count; i++ )
1874         free( pp_old_data[i] );
1875     return b_match;
1876 }
1877
1878 static bool Ogg_IsOpusFormatCompatible( const es_format_t *p_new,
1879                                         const es_format_t *p_old )
1880 {
1881     unsigned pi_new_size[XIPH_MAX_HEADER_COUNT];
1882     void     *pp_new_data[XIPH_MAX_HEADER_COUNT];
1883     unsigned i_new_count;
1884     if( xiph_SplitHeaders(pi_new_size, pp_new_data, &i_new_count, p_new->i_extra, p_new->p_extra ) )
1885         i_new_count = 0;
1886     unsigned pi_old_size[XIPH_MAX_HEADER_COUNT];
1887     void     *pp_old_data[XIPH_MAX_HEADER_COUNT];
1888     unsigned i_old_count;
1889     if( xiph_SplitHeaders(pi_old_size, pp_old_data, &i_old_count, p_old->i_extra, p_old->p_extra ) )
1890         i_old_count = 0;
1891     bool b_match = false;
1892     if( i_new_count == i_old_count && i_new_count > 0 )
1893     {
1894         static const unsigned char default_map[2] = { 0, 1 };
1895         unsigned char *p_old_head;
1896         unsigned char *p_new_head;
1897         const unsigned char *p_old_map;
1898         const unsigned char *p_new_map;
1899         int i_old_channel_count;
1900         int i_new_channel_count;
1901         int i_old_stream_count;
1902         int i_new_stream_count;
1903         int i_old_coupled_count;
1904         int i_new_coupled_count;
1905         p_old_head = (unsigned char *)pp_old_data[0];
1906         i_old_channel_count = i_old_stream_count = i_old_coupled_count = 0;
1907         p_old_map = default_map;
1908         if( pi_old_size[0] >= 19 && p_old_head[8] <= 15 )
1909         {
1910             i_old_channel_count = p_old_head[9];
1911             switch( p_old_head[18] )
1912             {
1913                 case 0:
1914                     i_old_stream_count = 1;
1915                     i_old_coupled_count = i_old_channel_count - 1;
1916                     break;
1917                 case 1:
1918                     if( pi_old_size[0] >= 21U + i_old_channel_count )
1919                     {
1920                         i_old_stream_count = p_old_head[19];
1921                         i_old_coupled_count = p_old_head[20];
1922                         p_old_map = p_old_head + 21;
1923                     }
1924                     break;
1925             }
1926         }
1927         p_new_head = (unsigned char *)pp_new_data[0];
1928         i_new_channel_count = i_new_stream_count = i_new_coupled_count = 0;
1929         p_new_map = default_map;
1930         if( pi_new_size[0] >= 19 && p_new_head[8] <= 15 )
1931         {
1932             i_new_channel_count = p_new_head[9];
1933             switch( p_new_head[18] )
1934             {
1935                 case 0:
1936                     i_new_stream_count = 1;
1937                     i_new_coupled_count = i_new_channel_count - 1;
1938                     break;
1939                 case 1:
1940                     if( pi_new_size[0] >= 21U + i_new_channel_count )
1941                     {
1942                         i_new_stream_count = p_new_head[19];
1943                         i_new_coupled_count = p_new_head[20];
1944                         p_new_map = p_new_head+21;
1945                     }
1946                     break;
1947             }
1948         }
1949         b_match = i_old_channel_count == i_new_channel_count &&
1950                   i_old_stream_count == i_new_stream_count &&
1951                   i_old_coupled_count == i_new_coupled_count &&
1952                   memcmp(p_old_map, p_new_map,
1953                       i_new_channel_count*sizeof(*p_new_map)) == 0;
1954     }
1955     for( unsigned i = 0; i < i_new_count; i++ )
1956         free( pp_new_data[i] );
1957     for( unsigned i = 0; i < i_old_count; i++ )
1958         free( pp_old_data[i] );
1959     return b_match;
1960 }
1961
1962 static bool Ogg_LogicalStreamResetEsFormat( demux_t *p_demux, logical_stream_t *p_stream )
1963 {
1964     bool b_compatible = false;
1965     if( !p_stream->fmt_old.i_cat || !p_stream->fmt_old.i_codec )
1966         return true;
1967
1968     /* Only Vorbis and Opus are supported. */
1969     if( p_stream->fmt.i_codec == VLC_CODEC_VORBIS )
1970         b_compatible = Ogg_IsVorbisFormatCompatible( &p_stream->fmt, &p_stream->fmt_old );
1971     else if( p_stream->fmt.i_codec == VLC_CODEC_OPUS )
1972         b_compatible = Ogg_IsOpusFormatCompatible( &p_stream->fmt, &p_stream->fmt_old );
1973
1974     if( !b_compatible )
1975         msg_Warn( p_demux, "cannot reuse old stream, resetting the decoder" );
1976
1977     return !b_compatible;
1978 }
1979 static void Ogg_ExtractXiphMeta( demux_t *p_demux, es_format_t *p_fmt,
1980                                  const void *p_headers, unsigned i_headers, unsigned i_skip )
1981 {
1982     demux_sys_t *p_ogg = p_demux->p_sys;
1983
1984     unsigned pi_size[XIPH_MAX_HEADER_COUNT];
1985     void     *pp_data[XIPH_MAX_HEADER_COUNT];
1986     unsigned i_count;
1987     if( xiph_SplitHeaders( pi_size, pp_data, &i_count, i_headers, p_headers ) )
1988         return;
1989
1990     /* TODO how to handle multiple comments properly ? */
1991     if( i_count >= 2 && pi_size[1] > i_skip )
1992     {
1993         int i_cover_score = 0;
1994         int i_cover_idx = 0;
1995         float pf_replay_gain[AUDIO_REPLAY_GAIN_MAX];
1996         float pf_replay_peak[AUDIO_REPLAY_GAIN_MAX];
1997         for(int i=0; i< AUDIO_REPLAY_GAIN_MAX; i++ )
1998         {
1999             pf_replay_gain[i] = 0;
2000             pf_replay_peak[i] = 0;
2001         }
2002         vorbis_ParseComment( &p_ogg->p_meta, (uint8_t*)pp_data[1] + i_skip, pi_size[1] - i_skip,
2003                              &p_ogg->i_attachments, &p_ogg->attachments,
2004                              &i_cover_score, &i_cover_idx,
2005                              &p_ogg->i_seekpoints, &p_ogg->pp_seekpoints,
2006                              &pf_replay_gain, &pf_replay_peak );
2007         if( p_ogg->p_meta != NULL && i_cover_idx < p_ogg->i_attachments )
2008         {
2009             char psz_url[128];
2010             snprintf( psz_url, sizeof(psz_url), "attachment://%s",
2011                 p_ogg->attachments[i_cover_idx]->psz_name );
2012             vlc_meta_Set( p_ogg->p_meta, vlc_meta_ArtworkURL, psz_url );
2013         }
2014
2015         for ( int i=0; i<AUDIO_REPLAY_GAIN_MAX;i++ )
2016         {
2017             if ( pf_replay_gain[i] != 0 )
2018             {
2019                 p_fmt->audio_replay_gain.pb_gain[i] = true;
2020                 p_fmt->audio_replay_gain.pf_gain[i] = pf_replay_gain[i];
2021                 msg_Dbg( p_demux, "setting replay gain %d to %f", i, pf_replay_gain[i] );
2022             }
2023             if ( pf_replay_peak[i] != 0 )
2024             {
2025                 p_fmt->audio_replay_gain.pb_peak[i] = true;
2026                 p_fmt->audio_replay_gain.pf_peak[i] = pf_replay_peak[i];
2027                 msg_Dbg( p_demux, "setting replay peak %d to %f", i, pf_replay_gain[i] );
2028             }
2029         }
2030     }
2031
2032     if( p_ogg->i_seekpoints > 1 )
2033     {
2034         p_demux->info.i_update |= INPUT_UPDATE_TITLE_LIST;
2035     }
2036
2037     for( unsigned i = 0; i < i_count; i++ )
2038         free( pp_data[i] );
2039 }
2040 static void Ogg_ExtractMeta( demux_t *p_demux, es_format_t *p_fmt, const uint8_t *p_headers, int i_headers )
2041 {
2042     demux_sys_t *p_ogg = p_demux->p_sys;
2043
2044     switch( p_fmt->i_codec )
2045     {
2046     /* 3 headers with the 2° one being the comments */
2047     case VLC_CODEC_VORBIS:
2048     case VLC_CODEC_THEORA:
2049         Ogg_ExtractXiphMeta( p_demux, p_fmt, p_headers, i_headers, 1+6 );
2050         break;
2051     case VLC_CODEC_OPUS:
2052         Ogg_ExtractXiphMeta( p_demux, p_fmt, p_headers, i_headers, 8 );
2053         break;
2054     case VLC_CODEC_SPEEX:
2055         Ogg_ExtractXiphMeta( p_demux, p_fmt, p_headers, i_headers, 0 );
2056         break;
2057
2058     /* N headers with the 2° one being the comments */
2059     case VLC_CODEC_KATE:
2060         /* 1 byte for header type, 7 bytes for magic, 1 reserved zero byte */
2061         Ogg_ExtractXiphMeta( p_demux, p_fmt, p_headers, i_headers, 1+7+1 );
2062         break;
2063
2064     /* TODO */
2065     case VLC_CODEC_FLAC:
2066         msg_Warn( p_demux, "Ogg_ExtractMeta does not support %4.4s", (const char*)&p_fmt->i_codec );
2067         break;
2068
2069     /* No meta data */
2070     case VLC_CODEC_CMML: /* CMML is XML text, doesn't have Vorbis comments */
2071     case VLC_CODEC_DIRAC:
2072     default:
2073         break;
2074     }
2075     if( p_ogg->p_meta )
2076         p_demux->info.i_update |= INPUT_UPDATE_META;
2077 }
2078
2079 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
2080                                   ogg_packet *p_oggpacket )
2081 {
2082     bs_t bitstream;
2083     int i_fps_numerator;
2084     int i_fps_denominator;
2085     int i_keyframe_frequency_force;
2086     int i_major;
2087     int i_minor;
2088     int i_subminor;
2089     int i_version;
2090
2091     p_stream->fmt.i_cat = VIDEO_ES;
2092     p_stream->fmt.i_codec = VLC_CODEC_THEORA;
2093
2094     /* Signal that we want to keep a backup of the theora
2095      * stream headers. They will be used when switching between
2096      * audio streams. */
2097     p_stream->b_force_backup = true;
2098
2099     /* Cheat and get additionnal info ;) */
2100     bs_init( &bitstream, p_oggpacket->packet, p_oggpacket->bytes );
2101     bs_skip( &bitstream, 56 );
2102
2103     i_major = bs_read( &bitstream, 8 ); /* major version num */
2104     i_minor = bs_read( &bitstream, 8 ); /* minor version num */
2105     i_subminor = bs_read( &bitstream, 8 ); /* subminor version num */
2106
2107     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
2108     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
2109     bs_read( &bitstream, 24 ); /* frame width */
2110     bs_read( &bitstream, 24 ); /* frame height */
2111     bs_read( &bitstream, 8 ); /* x offset */
2112     bs_read( &bitstream, 8 ); /* y offset */
2113
2114     i_fps_numerator = bs_read( &bitstream, 32 );
2115     i_fps_denominator = bs_read( &bitstream, 32 );
2116     bs_read( &bitstream, 24 ); /* aspect_numerator */
2117     bs_read( &bitstream, 24 ); /* aspect_denominator */
2118
2119     p_stream->fmt.video.i_frame_rate = i_fps_numerator;
2120     p_stream->fmt.video.i_frame_rate_base = i_fps_denominator;
2121
2122     bs_read( &bitstream, 8 ); /* colorspace */
2123     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
2124     bs_read( &bitstream, 6 ); /* quality */
2125
2126     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
2127
2128     /* granule_shift = i_log( frequency_force -1 ) */
2129     p_stream->i_granule_shift = 0;
2130     i_keyframe_frequency_force--;
2131     while( i_keyframe_frequency_force )
2132     {
2133         p_stream->i_granule_shift++;
2134         i_keyframe_frequency_force >>= 1;
2135     }
2136
2137     i_version = i_major * 1000000 + i_minor * 1000 + i_subminor;
2138     p_stream->i_keyframe_offset = 0;
2139     p_stream->f_rate = ((float)i_fps_numerator) / i_fps_denominator;
2140
2141     if ( i_version >= 3002001 )
2142     {
2143         p_stream->i_keyframe_offset = 1;
2144     }
2145 }
2146
2147 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
2148                                   ogg_packet *p_oggpacket )
2149 {
2150     oggpack_buffer opb;
2151
2152     p_stream->fmt.i_cat = AUDIO_ES;
2153     p_stream->fmt.i_codec = VLC_CODEC_VORBIS;
2154
2155     /* Signal that we want to keep a backup of the vorbis
2156      * stream headers. They will be used when switching between
2157      * audio streams. */
2158     p_stream->b_force_backup = true;
2159
2160     /* Cheat and get additionnal info ;) */
2161     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
2162     oggpack_adv( &opb, 88 );
2163     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
2164     fill_channels_info(&p_stream->fmt.audio);
2165     p_stream->f_rate = p_stream->fmt.audio.i_rate =
2166         oggpack_read( &opb, 32 );
2167     oggpack_adv( &opb, 32 );
2168     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
2169 }
2170
2171 static void Ogg_ReadSpeexHeader( logical_stream_t *p_stream,
2172                                  ogg_packet *p_oggpacket )
2173 {
2174     oggpack_buffer opb;
2175
2176     p_stream->fmt.i_cat = AUDIO_ES;
2177     p_stream->fmt.i_codec = VLC_CODEC_SPEEX;
2178
2179     /* Signal that we want to keep a backup of the speex
2180      * stream headers. They will be used when switching between
2181      * audio streams. */
2182     p_stream->b_force_backup = true;
2183
2184     /* Cheat and get additionnal info ;) */
2185     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
2186     oggpack_adv( &opb, 224 );
2187     oggpack_adv( &opb, 32 ); /* speex_version_id */
2188     oggpack_adv( &opb, 32 ); /* header_size */
2189     p_stream->f_rate = p_stream->fmt.audio.i_rate = oggpack_read( &opb, 32 );
2190     oggpack_adv( &opb, 32 ); /* mode */
2191     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
2192     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
2193     fill_channels_info(&p_stream->fmt.audio);
2194     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
2195     oggpack_adv( &opb, 32 ); /* frame_size */
2196     oggpack_adv( &opb, 32 ); /* vbr */
2197     oggpack_adv( &opb, 32 ); /* frames_per_packet */
2198     p_stream->i_extra_headers_packets = oggpack_read( &opb, 32 ); /* extra_headers */
2199 }
2200
2201 static void Ogg_ReadOpusHeader( logical_stream_t *p_stream,
2202                                 ogg_packet *p_oggpacket )
2203 {
2204     oggpack_buffer opb;
2205
2206     p_stream->fmt.i_cat = AUDIO_ES;
2207     p_stream->fmt.i_codec = VLC_CODEC_OPUS;
2208
2209     /* Signal that we want to keep a backup of the opus
2210      * stream headers. They will be used when switching between
2211      * audio streams. */
2212     p_stream->b_force_backup = true;
2213
2214     /* All OggOpus streams are timestamped at 48kHz and
2215      * can be played at 48kHz. */
2216     p_stream->f_rate = p_stream->fmt.audio.i_rate = 48000;
2217     p_stream->fmt.i_bitrate = 0;
2218
2219     /* Cheat and get additional info ;) */
2220     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
2221     oggpack_adv( &opb, 64 );
2222     oggpack_adv( &opb, 8 ); /* version_id */
2223     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
2224     fill_channels_info(&p_stream->fmt.audio);
2225     p_stream->i_pre_skip = oggpack_read( &opb, 16 );
2226 }
2227
2228 static void Ogg_ReadFlacHeader( demux_t *p_demux, logical_stream_t *p_stream,
2229                                 ogg_packet *p_oggpacket )
2230 {
2231     /* Parse the STREAMINFO metadata */
2232     bs_t s;
2233
2234     bs_init( &s, p_oggpacket->packet, p_oggpacket->bytes );
2235
2236     bs_read( &s, 1 );
2237     if( p_oggpacket->bytes > 0 && bs_read( &s, 7 ) != 0 )
2238     {
2239         msg_Dbg( p_demux, "Invalid FLAC STREAMINFO metadata" );
2240         return;
2241     }
2242
2243     if( bs_read( &s, 24 ) >= 34 /*size STREAMINFO*/ )
2244     {
2245         bs_skip( &s, 80 );
2246         p_stream->f_rate = p_stream->fmt.audio.i_rate = bs_read( &s, 20 );
2247         p_stream->fmt.audio.i_channels = bs_read( &s, 3 ) + 1;
2248         fill_channels_info(&p_stream->fmt.audio);
2249
2250         msg_Dbg( p_demux, "FLAC header, channels: %i, rate: %i",
2251                  p_stream->fmt.audio.i_channels, (int)p_stream->f_rate );
2252     }
2253     else
2254     {
2255         msg_Dbg( p_demux, "FLAC STREAMINFO metadata too short" );
2256     }
2257
2258     /* Fake this as the last metadata block */
2259     *((uint8_t*)p_oggpacket->packet) |= 0x80;
2260 }
2261
2262 static void Ogg_ReadKateHeader( logical_stream_t *p_stream,
2263                                 ogg_packet *p_oggpacket )
2264 {
2265     oggpack_buffer opb;
2266     int32_t gnum;
2267     int32_t gden;
2268     int n;
2269     char *psz_desc;
2270
2271     p_stream->fmt.i_cat = SPU_ES;
2272     p_stream->fmt.i_codec = VLC_CODEC_KATE;
2273
2274     /* Signal that we want to keep a backup of the kate
2275      * stream headers. They will be used when switching between
2276      * kate streams. */
2277     p_stream->b_force_backup = true;
2278
2279     /* Cheat and get additionnal info ;) */
2280     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
2281     oggpack_adv( &opb, 11*8 ); /* packet type, kate magic, version */
2282     p_stream->i_kate_num_headers = oggpack_read( &opb, 8 );
2283     oggpack_adv( &opb, 3*8 );
2284     p_stream->i_granule_shift = oggpack_read( &opb, 8 );
2285     oggpack_adv( &opb, 8*8 ); /* reserved */
2286     gnum = oggpack_read( &opb, 32 );
2287     gden = oggpack_read( &opb, 32 );
2288     p_stream->f_rate = (double)gnum/gden;
2289
2290     p_stream->fmt.psz_language = malloc(16);
2291     if( p_stream->fmt.psz_language )
2292     {
2293         for( n = 0; n < 16; n++ )
2294             p_stream->fmt.psz_language[n] = oggpack_read(&opb,8);
2295         p_stream->fmt.psz_language[15] = 0; /* just in case */
2296     }
2297     else
2298     {
2299         for( n = 0; n < 16; n++ )
2300             oggpack_read(&opb,8);
2301     }
2302     p_stream->fmt.psz_description = malloc(16);
2303     if( p_stream->fmt.psz_description )
2304     {
2305         for( n = 0; n < 16; n++ )
2306             p_stream->fmt.psz_description[n] = oggpack_read(&opb,8);
2307         p_stream->fmt.psz_description[15] = 0; /* just in case */
2308
2309         /* Now find a localized user readable description for this category */
2310         psz_desc = strdup(FindKateCategoryName(p_stream->fmt.psz_description));
2311         if( psz_desc )
2312         {
2313             free( p_stream->fmt.psz_description );
2314             p_stream->fmt.psz_description = psz_desc;
2315         }
2316     }
2317     else
2318     {
2319         for( n = 0; n < 16; n++ )
2320             oggpack_read(&opb,8);
2321     }
2322 }
2323
2324 static void Ogg_ReadAnnodexHeader( demux_t *p_demux,
2325                                    logical_stream_t *p_stream,
2326                                    ogg_packet *p_oggpacket )
2327 {
2328     if( p_oggpacket->bytes >= 28 &&
2329         !memcmp( p_oggpacket->packet, "Annodex", 7 ) )
2330     {
2331         oggpack_buffer opb;
2332
2333         uint16_t major_version;
2334         uint16_t minor_version;
2335         uint64_t timebase_numerator;
2336         uint64_t timebase_denominator;
2337
2338         Ogg_ReadTheoraHeader( p_stream, p_oggpacket );
2339
2340         oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
2341         oggpack_adv( &opb, 8*8 ); /* "Annodex\0" header */
2342         major_version = oggpack_read( &opb, 2*8 ); /* major version */
2343         minor_version = oggpack_read( &opb, 2*8 ); /* minor version */
2344         timebase_numerator = GetQWLE( &p_oggpacket->packet[16] );
2345         timebase_denominator = GetQWLE( &p_oggpacket->packet[24] );
2346
2347         msg_Dbg( p_demux, "Annodex info: version %"PRIu16".%"PRIu16" "
2348                           "Timebase  %"PRId64" / %"PRId64,
2349                           major_version, minor_version,
2350                           timebase_numerator, timebase_denominator );
2351     }
2352     else if( p_oggpacket->bytes >= 42 &&
2353              !memcmp( p_oggpacket->packet, "AnxData", 7 ) )
2354     {
2355         uint64_t granule_rate_numerator;
2356         uint64_t granule_rate_denominator;
2357         char content_type_string[1024];
2358
2359         /* Read in Annodex header fields */
2360
2361         granule_rate_numerator = GetQWLE( &p_oggpacket->packet[8] );
2362         granule_rate_denominator = GetQWLE( &p_oggpacket->packet[16] );
2363         p_stream->i_secondary_header_packets =
2364             GetDWLE( &p_oggpacket->packet[24] );
2365
2366         /* we are guaranteed that the first header field will be
2367          * the content-type (by the Annodex standard) */
2368         content_type_string[0] = '\0';
2369         if( !strncasecmp( (char*)(&p_oggpacket->packet[28]), "Content-Type: ", 14 ) )
2370         {
2371             uint8_t *p = memchr( &p_oggpacket->packet[42], '\r',
2372                                  p_oggpacket->bytes - 1 );
2373             if( p && p[0] == '\r' && p[1] == '\n' )
2374                 sscanf( (char*)(&p_oggpacket->packet[42]), "%1023s\r\n",
2375                         content_type_string );
2376         }
2377
2378         msg_Dbg( p_demux, "AnxData packet info: %"PRId64" / %"PRId64", %d, ``%s''",
2379                  granule_rate_numerator, granule_rate_denominator,
2380                  p_stream->i_secondary_header_packets, content_type_string );
2381
2382         p_stream->f_rate = (float) granule_rate_numerator /
2383             (float) granule_rate_denominator;
2384
2385         /* What type of file do we have?
2386          * strcmp is safe to use here because we've extracted
2387          * content_type_string from the stream manually */
2388         if( !strncmp(content_type_string, "audio/x-wav", 11) )
2389         {
2390             /* n.b. WAVs are unsupported right now */
2391             p_stream->fmt.i_cat = UNKNOWN_ES;
2392         }
2393         else if( !strncmp(content_type_string, "audio/x-vorbis", 14) )
2394         {
2395             p_stream->fmt.i_cat = AUDIO_ES;
2396             p_stream->fmt.i_codec = VLC_CODEC_VORBIS;
2397
2398             p_stream->b_force_backup = true;
2399         }
2400         else if( !strncmp(content_type_string, "audio/x-speex", 13) )
2401         {
2402             p_stream->fmt.i_cat = AUDIO_ES;
2403             p_stream->fmt.i_codec = VLC_CODEC_SPEEX;
2404
2405             p_stream->b_force_backup = true;
2406         }
2407         else if( !strncmp(content_type_string, "video/x-theora", 14) )
2408         {
2409             p_stream->fmt.i_cat = VIDEO_ES;
2410             p_stream->fmt.i_codec = VLC_CODEC_THEORA;
2411
2412             p_stream->b_force_backup = true;
2413         }
2414         else if( !strncmp(content_type_string, "video/x-xvid", 12) )
2415         {
2416             p_stream->fmt.i_cat = VIDEO_ES;
2417             p_stream->fmt.i_codec = VLC_FOURCC( 'x','v','i','d' );
2418
2419             p_stream->b_force_backup = true;
2420         }
2421         else if( !strncmp(content_type_string, "video/mpeg", 10) )
2422         {
2423             /* n.b. MPEG streams are unsupported right now */
2424             p_stream->fmt.i_cat = VIDEO_ES;
2425             p_stream->fmt.i_codec = VLC_CODEC_MPGV;
2426         }
2427         else if( !strncmp(content_type_string, "text/x-cmml", 11) )
2428         {
2429             ogg_stream_packetout( &p_stream->os, p_oggpacket );
2430             p_stream->fmt.i_cat = SPU_ES;
2431             p_stream->fmt.i_codec = VLC_CODEC_CMML;
2432         }
2433     }
2434 }
2435
2436 static uint32_t dirac_uint( bs_t *p_bs )
2437 {
2438     uint32_t u_count = 0, u_value = 0;
2439
2440     while( !bs_eof( p_bs ) && !bs_read( p_bs, 1 ) )
2441     {
2442         u_count++;
2443         u_value <<= 1;
2444         u_value |= bs_read( p_bs, 1 );
2445     }
2446
2447     return (1<<u_count) - 1 + u_value;
2448 }
2449
2450 static int dirac_bool( bs_t *p_bs )
2451 {
2452     return bs_read( p_bs, 1 );
2453 }
2454
2455 static bool Ogg_ReadDiracHeader( logical_stream_t *p_stream,
2456                                  ogg_packet *p_oggpacket )
2457 {
2458     static const struct {
2459         uint32_t u_n /* numerator */, u_d /* denominator */;
2460     } p_dirac_frate_tbl[] = { /* table 10.3 */
2461         {1,1}, /* this first value is never used */
2462         {24000,1001}, {24,1}, {25,1}, {30000,1001}, {30,1},
2463         {50,1}, {60000,1001}, {60,1}, {15000,1001}, {25,2},
2464     };
2465     static const size_t u_dirac_frate_tbl = sizeof(p_dirac_frate_tbl)/sizeof(*p_dirac_frate_tbl);
2466
2467     static const uint32_t pu_dirac_vidfmt_frate[] = { /* table C.1 */
2468         1, 9, 10, 9, 10, 9, 10, 4, 3, 7, 6, 4, 3, 7, 6, 2, 2, 7, 6, 7, 6,
2469     };
2470     static const size_t u_dirac_vidfmt_frate = sizeof(pu_dirac_vidfmt_frate)/sizeof(*pu_dirac_vidfmt_frate);
2471
2472     bs_t bs;
2473
2474     p_stream->i_granule_shift = 22; /* not 32 */
2475
2476     /* Backing up stream headers is not required -- seqhdrs are repeated
2477      * thoughout the stream at suitable decoding start points */
2478     p_stream->b_force_backup = false;
2479
2480     /* read in useful bits from sequence header */
2481     bs_init( &bs, p_oggpacket->packet, p_oggpacket->bytes );
2482     bs_skip( &bs, 13*8); /* parse_info_header */
2483     dirac_uint( &bs ); /* major_version */
2484     dirac_uint( &bs ); /* minor_version */
2485     dirac_uint( &bs ); /* profile */
2486     dirac_uint( &bs ); /* level */
2487
2488     uint32_t u_video_format = dirac_uint( &bs ); /* index */
2489     if( u_video_format >= u_dirac_vidfmt_frate )
2490     {
2491         /* don't know how to parse this ogg dirac stream */
2492         return false;
2493     }
2494
2495     if( dirac_bool( &bs ) )
2496     {
2497         dirac_uint( &bs ); /* frame_width */
2498         dirac_uint( &bs ); /* frame_height */
2499     }
2500
2501     if( dirac_bool( &bs ) )
2502     {
2503         dirac_uint( &bs ); /* chroma_format */
2504     }
2505
2506     if( dirac_bool( &bs ) )
2507     {
2508         dirac_uint( &bs ); /* scan_format */
2509     }
2510
2511     uint32_t u_n = p_dirac_frate_tbl[pu_dirac_vidfmt_frate[u_video_format]].u_n;
2512     uint32_t u_d = p_dirac_frate_tbl[pu_dirac_vidfmt_frate[u_video_format]].u_d;
2513     if( dirac_bool( &bs ) )
2514     {
2515         uint32_t u_frame_rate_index = dirac_uint( &bs );
2516         if( u_frame_rate_index >= u_dirac_frate_tbl )
2517         {
2518             /* something is wrong with this stream */
2519             return false;
2520         }
2521         u_n = p_dirac_frate_tbl[u_frame_rate_index].u_n;
2522         u_d = p_dirac_frate_tbl[u_frame_rate_index].u_d;
2523         if( u_frame_rate_index == 0 )
2524         {
2525             u_n = dirac_uint( &bs ); /* frame_rate_numerator */
2526             u_d = dirac_uint( &bs ); /* frame_rate_denominator */
2527         }
2528     }
2529     p_stream->f_rate = (float) u_n / u_d;
2530
2531     /* probably is an ogg dirac es */
2532     p_stream->fmt.i_cat = VIDEO_ES;
2533     p_stream->fmt.i_codec = VLC_CODEC_DIRAC;
2534
2535     return true;
2536 }