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