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