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