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