]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
* modules/demux/ogg.c: added support for new Ogg mapping for FLAC.
[vlc] / modules / demux / ogg.c
1 /*****************************************************************************
2  * ogg.c : ogg stream demux module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
8  *          Andre Pang <Andre.Pang@csiro.au> (Annodex support)
9  *
10  * This program is free software; you can redistribute it and/or modify
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <vlc/vlc.h>
29 #include <vlc/input.h>
30
31 #include <ogg/ogg.h>
32
33 #include "codecs.h"
34 #include "vlc_bits.h"
35
36 /*****************************************************************************
37  * Module descriptor
38  *****************************************************************************/
39 static int  Open ( vlc_object_t * );
40 static void Close( vlc_object_t * );
41
42 vlc_module_begin();
43     set_description( _("Ogg stream demuxer" ) );
44     set_category( CAT_INPUT );
45     set_subcategory( SUBCAT_INPUT_DEMUX );
46     set_capability( "demux2", 50 );
47     set_callbacks( Open, Close );
48     add_shortcut( "ogg" );
49 vlc_module_end();
50
51
52 /*****************************************************************************
53  * Definitions of structures and functions used by this plugins
54  *****************************************************************************/
55 typedef struct logical_stream_s
56 {
57     ogg_stream_state os;                        /* logical stream of packets */
58
59     es_format_t      fmt;
60     es_out_id_t      *p_es;
61     double           f_rate;
62
63     int              i_serial_no;
64
65     /* the header of some logical streams (eg vorbis) contain essential
66      * data for the decoder. We back them up here in case we need to re-feed
67      * them to the decoder. */
68     int              b_force_backup;
69     int              i_packets_backup;
70     uint8_t          *p_headers;
71     int              i_headers;
72
73     /* program clock reference (in units of 90kHz) derived from the previous
74      * granulepos */
75     mtime_t          i_pcr;
76     mtime_t          i_interpolated_pcr;
77     mtime_t          i_previous_pcr;
78
79     /* Misc */
80     int b_reinit;
81     int i_theora_keyframe_granule_shift;
82
83     /* for Annodex logical bitstreams */
84     int secondary_header_packets;
85
86 } logical_stream_t;
87
88 struct demux_sys_t
89 {
90     ogg_sync_state oy;        /* sync and verify incoming physical bitstream */
91
92     int i_streams;                           /* number of logical bitstreams */
93     logical_stream_t **pp_stream;  /* pointer to an array of logical streams */
94
95     /* program clock reference (in units of 90kHz) derived from the pcr of
96      * the sub-streams */
97     mtime_t i_pcr;
98
99     /* stream state */
100     int     i_eos;
101
102     /* bitrate */
103     int     i_bitrate;
104 };
105
106 /* OggDS headers for the new header format (used in ogm files) */
107 typedef struct stream_header_video
108 {
109     ogg_int32_t width;
110     ogg_int32_t height;
111 } stream_header_video;
112
113 typedef struct stream_header_audio
114 {
115     ogg_int16_t channels;
116     ogg_int16_t blockalign;
117     ogg_int32_t avgbytespersec;
118 } stream_header_audio;
119
120 typedef struct stream_header
121 {
122     char        streamtype[8];
123     char        subtype[4];
124
125     ogg_int32_t size;                               /* size of the structure */
126
127     ogg_int64_t time_unit;                              /* in reference time */
128     ogg_int64_t samples_per_unit;
129     ogg_int32_t default_len;                                /* in media time */
130
131     ogg_int32_t buffersize;
132     ogg_int16_t bits_per_sample;
133
134     union
135     {
136         /* Video specific */
137         stream_header_video video;
138         /* Audio specific */
139         stream_header_audio audio;
140     } sh;
141 } stream_header;
142
143 #define OGG_BLOCK_SIZE 4096
144
145 /* Some defines from OggDS */
146 #define PACKET_TYPE_HEADER   0x01
147 #define PACKET_TYPE_BITS     0x07
148 #define PACKET_LEN_BITS01    0xc0
149 #define PACKET_LEN_BITS2     0x02
150 #define PACKET_IS_SYNCPOINT  0x08
151
152 /*****************************************************************************
153  * Local prototypes
154  *****************************************************************************/
155 static int  Demux  ( demux_t * );
156 static int  Control( demux_t *, int, va_list );
157
158 /* Bitstream manipulation */
159 static int  Ogg_ReadPage     ( demux_t *, ogg_page * );
160 static void Ogg_UpdatePCR    ( logical_stream_t *, ogg_packet * );
161 static void Ogg_DecodePacket ( demux_t *, logical_stream_t *, ogg_packet * );
162
163 static int Ogg_BeginningOfStream( demux_t *p_demux );
164 static int Ogg_FindLogicalStreams( demux_t *p_demux );
165 static void Ogg_EndOfStream( demux_t *p_demux );
166
167 /* Logical bitstream headers */
168 static void Ogg_ReadTheoraHeader( logical_stream_t *, ogg_packet * );
169 static void Ogg_ReadVorbisHeader( logical_stream_t *, ogg_packet * );
170 static void Ogg_ReadSpeexHeader( logical_stream_t *, ogg_packet * );
171 static void Ogg_ReadFlacHeader( demux_t *, logical_stream_t *, ogg_packet * );
172 static void Ogg_ReadAnnodexHeader( vlc_object_t *, logical_stream_t *, ogg_packet * );
173
174 /*****************************************************************************
175  * Open: initializes ogg demux structures
176  *****************************************************************************/
177 static int Open( vlc_object_t * p_this )
178 {
179     demux_t *p_demux = (demux_t *)p_this;
180     demux_sys_t    *p_sys;
181     uint8_t        *p_peek;
182
183
184     /* Check if we are dealing with an ogg stream */
185     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
186     {
187         msg_Err( p_demux, "cannot peek" );
188         return VLC_EGENERIC;
189     }
190     if( strcmp( p_demux->psz_demux, "ogg" ) && strncmp( p_peek, "OggS", 4 ) )
191     {
192         msg_Warn( p_demux, "ogg module discarded (invalid header)" );
193         return VLC_EGENERIC;
194     }
195
196     /* Set exported functions */
197     p_demux->pf_demux = Demux;
198     p_demux->pf_control = Control;
199     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
200
201     memset( p_sys, 0, sizeof( demux_sys_t ) );
202     p_sys->i_bitrate = 0;
203     p_sys->pp_stream = NULL;
204
205     /* Begnning of stream, tell the demux to look for elementary streams. */
206     p_sys->i_eos = 0;
207
208     /* Initialize the Ogg physical bitstream parser */
209     ogg_sync_init( &p_sys->oy );
210
211     return VLC_SUCCESS;
212 }
213
214 /*****************************************************************************
215  * Close: frees unused data
216  *****************************************************************************/
217 static void Close( vlc_object_t *p_this )
218 {
219     demux_t *p_demux = (demux_t *)p_this;
220     demux_sys_t *p_sys = p_demux->p_sys  ;
221
222     /* Cleanup the bitstream parser */
223     ogg_sync_clear( &p_sys->oy );
224
225     Ogg_EndOfStream( p_demux );
226
227     free( p_sys );
228 }
229
230 /*****************************************************************************
231  * Demux: reads and demuxes data packets
232  *****************************************************************************
233  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
234  *****************************************************************************/
235 static int Demux( demux_t * p_demux )
236 {
237     demux_sys_t *p_sys = p_demux->p_sys;
238     ogg_page    oggpage;
239     ogg_packet  oggpacket;
240     int         i_stream;
241
242
243     if( p_sys->i_eos == p_sys->i_streams )
244     {
245         if( p_sys->i_eos )
246         {
247             msg_Dbg( p_demux, "end of a group of logical streams" );
248             Ogg_EndOfStream( p_demux );
249         }
250
251         p_sys->i_eos = 0;
252         if( Ogg_BeginningOfStream( p_demux ) != VLC_SUCCESS ) return 0;
253
254         msg_Dbg( p_demux, "beginning of a group of logical streams" );
255         es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
256     }
257
258     /*
259      * Demux an ogg page from the stream
260      */
261     if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
262     {
263         return 0; /* EOF */
264     }
265
266     /* Test for End of Stream */
267     if( ogg_page_eos( &oggpage ) ) p_sys->i_eos++;
268
269
270     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
271     {
272         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
273
274         if( ogg_stream_pagein( &p_stream->os, &oggpage ) != 0 )
275             continue;
276
277         while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
278         {
279             /* Read info from any secondary header packets, if there are any */
280             if( p_stream->secondary_header_packets > 0 )
281             {
282                 if( p_stream->fmt.i_codec == VLC_FOURCC('t','h','e','o') &&
283                         oggpacket.bytes >= 7 &&
284                         ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
285                 {
286                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
287                     p_stream->secondary_header_packets = 0;
288                 }
289                 else if( p_stream->fmt.i_codec == VLC_FOURCC('v','o','r','b') &&
290                         oggpacket.bytes >= 7 &&
291                         ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
292                 {
293                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
294                     p_stream->secondary_header_packets = 0;
295                 }
296                 else if ( p_stream->fmt.i_codec == VLC_FOURCC('c','m','m','l') )
297                 {
298                     p_stream->secondary_header_packets = 0;
299                 }
300             }
301
302             if( p_stream->b_reinit )
303             {
304                 /* If synchro is re-initialized we need to drop all the packets
305                  * until we find a new dated one. */
306                 Ogg_UpdatePCR( p_stream, &oggpacket );
307
308                 if( p_stream->i_pcr >= 0 )
309                 {
310                     p_stream->b_reinit = 0;
311                 }
312                 else
313                 {
314                     p_stream->i_interpolated_pcr = -1;
315                     continue;
316                 }
317
318                 /* An Ogg/vorbis packet contains an end date granulepos */
319                 if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
320                     p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
321                     p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
322                 {
323                     if( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
324                     {
325                         Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
326                     }
327                     else
328                     {
329                         es_out_Control( p_demux->out, ES_OUT_SET_PCR,
330                                         p_stream->i_pcr );
331                     }
332                     continue;
333                 }
334             }
335
336             Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
337         }
338         break;
339     }
340
341     i_stream = 0; p_sys->i_pcr = -1;
342     for( ; i_stream < p_sys->i_streams; i_stream++ )
343     {
344         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
345
346         if( p_stream->fmt.i_cat == SPU_ES )
347             continue;
348         if( p_stream->i_interpolated_pcr < 0 )
349             continue;
350
351         if( p_sys->i_pcr < 0 || p_stream->i_interpolated_pcr < p_sys->i_pcr )
352             p_sys->i_pcr = p_stream->i_interpolated_pcr;
353     }
354
355     if( p_sys->i_pcr >= 0 )
356     {
357         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
358     }
359
360
361     return 1;
362 }
363
364 /*****************************************************************************
365  * Control:
366  *****************************************************************************/
367 static int Control( demux_t *p_demux, int i_query, va_list args )
368 {
369     demux_sys_t *p_sys  = p_demux->p_sys;
370     int64_t *pi64;
371     int i;
372
373     switch( i_query )
374     {
375         case DEMUX_GET_TIME:
376             pi64 = (int64_t*)va_arg( args, int64_t * );
377             *pi64 = p_sys->i_pcr;
378             return VLC_SUCCESS;
379
380         case DEMUX_SET_TIME:
381             return VLC_EGENERIC;
382
383         case DEMUX_SET_POSITION:
384             for( i = 0; i < p_sys->i_streams; i++ )
385             {
386                 logical_stream_t *p_stream = p_sys->pp_stream[i];
387
388                 /* we'll trash all the data until we find the next pcr */
389                 p_stream->b_reinit = 1;
390                 p_stream->i_pcr = -1;
391                 p_stream->i_interpolated_pcr = -1;
392                 ogg_stream_reset( &p_stream->os );
393             }
394             ogg_sync_reset( &p_sys->oy );
395
396         default:
397             return demux2_vaControlHelper( p_demux->s, 0, -1, p_sys->i_bitrate,
398                                            1, i_query, args );
399     }
400 }
401
402 /****************************************************************************
403  * Ogg_ReadPage: Read a full Ogg page from the physical bitstream.
404  ****************************************************************************
405  * Returns VLC_SUCCESS if a page has been read. An error might happen if we
406  * are at the end of stream.
407  ****************************************************************************/
408 static int Ogg_ReadPage( demux_t *p_demux, ogg_page *p_oggpage )
409 {
410     demux_sys_t *p_ogg = p_demux->p_sys  ;
411     int i_read = 0;
412     byte_t *p_buffer;
413
414     while( ogg_sync_pageout( &p_ogg->oy, p_oggpage ) != 1 )
415     {
416         p_buffer = ogg_sync_buffer( &p_ogg->oy, OGG_BLOCK_SIZE );
417
418         i_read = stream_Read( p_demux->s, p_buffer, OGG_BLOCK_SIZE );
419         if( i_read <= 0 )
420             return VLC_EGENERIC;
421
422         ogg_sync_wrote( &p_ogg->oy, i_read );
423     }
424
425     return VLC_SUCCESS;
426 }
427
428 /****************************************************************************
429  * Ogg_UpdatePCR: update the PCR (90kHz program clock reference) for the
430  *                current stream.
431  ****************************************************************************/
432 static void Ogg_UpdatePCR( logical_stream_t *p_stream,
433                            ogg_packet *p_oggpacket )
434 {
435     /* Convert the granulepos into a pcr */
436     if( p_oggpacket->granulepos >= 0 )
437     {
438         if( p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) )
439         {
440             p_stream->i_pcr = p_oggpacket->granulepos * I64C(1000000)
441                               / p_stream->f_rate;
442         }
443         else
444         {
445             ogg_int64_t iframe = p_oggpacket->granulepos >>
446               p_stream->i_theora_keyframe_granule_shift;
447             ogg_int64_t pframe = p_oggpacket->granulepos -
448               ( iframe << p_stream->i_theora_keyframe_granule_shift );
449
450             p_stream->i_pcr = ( iframe + pframe ) * I64C(1000000)
451                               / p_stream->f_rate;
452         }
453
454         p_stream->i_interpolated_pcr = p_stream->i_pcr;
455     }
456     else
457     {
458         p_stream->i_pcr = -1;
459
460         /* no granulepos available, try to interpolate the pcr.
461          * If we can't then don't touch the old value. */
462         if( p_stream->fmt.i_cat == VIDEO_ES )
463             /* 1 frame per packet */
464             p_stream->i_interpolated_pcr += (I64C(1000000) / p_stream->f_rate);
465         else if( p_stream->fmt.i_bitrate )
466             p_stream->i_interpolated_pcr +=
467                 ( p_oggpacket->bytes * I64C(1000000) /
468                   p_stream->fmt.i_bitrate / 8 );
469     }
470 }
471
472 /****************************************************************************
473  * Ogg_DecodePacket: Decode an Ogg packet.
474  ****************************************************************************/
475 static void Ogg_DecodePacket( demux_t *p_demux,
476                               logical_stream_t *p_stream,
477                               ogg_packet *p_oggpacket )
478 {
479     block_t *p_block;
480     vlc_bool_t b_selected;
481     int i_header_len = 0;
482     mtime_t i_pts = -1, i_interpolated_pts;
483
484     /* Sanity check */
485     if( !p_oggpacket->bytes )
486     {
487         msg_Dbg( p_demux, "discarding 0 sized packet" );
488         return;
489     }
490
491     if( p_oggpacket->bytes >= 7 &&
492         ! strncmp ( &p_oggpacket->packet[0], "Annodex", 7 ) )
493     {
494         /* it's an Annodex packet -- skip it (do nothing) */
495         return; 
496     }
497     else if( p_oggpacket->bytes >= 7 &&
498         ! strncmp ( &p_oggpacket->packet[0], "AnxData", 7 ) )
499     {
500         /* it's an AnxData packet -- skip it (do nothing) */
501         return; 
502     }
503
504     /* Check the ES is selected */
505     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
506                     p_stream->p_es, &b_selected );
507
508     if( p_stream->b_force_backup )
509     {
510         uint8_t *p_extra;
511         vlc_bool_t b_store_size = VLC_TRUE;
512
513         p_stream->i_packets_backup++;
514         switch( p_stream->fmt.i_codec )
515         {
516         case VLC_FOURCC( 'v','o','r','b' ):
517         case VLC_FOURCC( 's','p','x',' ' ):
518         case VLC_FOURCC( 't','h','e','o' ):
519           if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
520           break;
521
522         case VLC_FOURCC( 'f','l','a','c' ):
523           if( !p_stream->fmt.audio.i_rate && p_stream->i_packets_backup == 2 )
524           {
525               Ogg_ReadFlacHeader( p_demux, p_stream, p_oggpacket );
526               p_stream->b_force_backup = 0;
527           }
528           else if( p_stream->fmt.audio.i_rate )
529           {
530               p_stream->b_force_backup = 0;
531               p_oggpacket->packet += 9; p_oggpacket->bytes -= 9;
532           }
533           b_store_size = VLC_FALSE;
534           break;
535
536         default:
537           p_stream->b_force_backup = 0;
538           break;
539         }
540
541         /* Backup the ogg packet (likely an header packet) */
542         p_stream->p_headers =
543             realloc( p_stream->p_headers, p_stream->i_headers +
544                      p_oggpacket->bytes + (b_store_size ? 2 : 0) );
545         p_extra = p_stream->p_headers + p_stream->i_headers;
546         if( b_store_size )
547         {
548             *(p_extra++) = p_oggpacket->bytes >> 8;
549             *(p_extra++) = p_oggpacket->bytes & 0xFF;
550         }
551         memcpy( p_extra, p_oggpacket->packet, p_oggpacket->bytes );
552         p_stream->i_headers += p_oggpacket->bytes + (b_store_size ? 2 : 0);
553
554         if( !p_stream->b_force_backup )
555         {
556             /* Last header received, commit changes */
557             p_stream->fmt.i_extra = p_stream->i_headers;
558             p_stream->fmt.p_extra =
559                 realloc( p_stream->fmt.p_extra, p_stream->i_headers );
560             memcpy( p_stream->fmt.p_extra, p_stream->p_headers,
561                     p_stream->i_headers );
562             es_out_Control( p_demux->out, ES_OUT_SET_FMT,
563                             p_stream->p_es, &p_stream->fmt );
564         }
565
566         b_selected = VLC_FALSE; /* Discard the header packet */
567     }
568
569     /* Convert the pcr into a pts */
570     if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
571         p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
572         p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
573     {
574         if( p_stream->i_pcr >= 0 )
575         {
576             /* This is for streams where the granulepos of the header packets
577              * doesn't match these of the data packets (eg. ogg web radios). */
578             if( p_stream->i_previous_pcr == 0 &&
579                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
580             {
581                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
582
583                 /* Call the pace control */
584                 es_out_Control( p_demux->out, ES_OUT_SET_PCR,
585                                 p_stream->i_pcr );
586             }
587
588             p_stream->i_previous_pcr = p_stream->i_pcr;
589
590             /* The granulepos is the end date of the sample */
591             i_pts =  p_stream->i_pcr;
592         }
593     }
594
595     /* Convert the granulepos into the next pcr */
596     i_interpolated_pts = p_stream->i_interpolated_pcr;
597     Ogg_UpdatePCR( p_stream, p_oggpacket );
598
599     if( p_stream->i_pcr >= 0 )
600     {
601         /* This is for streams where the granulepos of the header packets
602          * doesn't match these of the data packets (eg. ogg web radios). */
603         if( p_stream->i_previous_pcr == 0 &&
604             p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
605         {
606             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
607
608             /* Call the pace control */
609             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_stream->i_pcr );
610         }
611     }
612
613     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
614         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
615         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
616         p_stream->i_pcr >= 0 )
617     {
618         p_stream->i_previous_pcr = p_stream->i_pcr;
619
620         /* The granulepos is the start date of the sample */
621         i_pts = p_stream->i_pcr;
622     }
623
624     if( !b_selected )
625     {
626         /* This stream isn't currently selected so we don't need to decode it,
627          * but we did need to store its pcr as it might be selected later on */
628         return;
629     }
630
631     if( !( p_block = block_New( p_demux, p_oggpacket->bytes ) ) ) return;
632
633     /* Normalize PTS */
634     if( i_pts == 0 ) i_pts = 1;
635     else if( i_pts == -1 && i_interpolated_pts == 0 ) i_pts = 1;
636     else if( i_pts == -1 ) i_pts = 0;
637
638     if( p_stream->fmt.i_cat == AUDIO_ES )
639         p_block->i_dts = p_block->i_pts = i_pts;
640     else if( p_stream->fmt.i_cat == SPU_ES )
641     {
642         p_block->i_dts = p_block->i_pts = i_pts;
643         p_block->i_length = 0;
644     }
645     else if( p_stream->fmt.i_codec == VLC_FOURCC( 't','h','e','o' ) )
646         p_block->i_dts = p_block->i_pts = i_pts;
647     else
648     {
649         p_block->i_dts = i_pts;
650         p_block->i_pts = 0;
651     }
652
653     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
654         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
655         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
656         p_stream->fmt.i_codec != VLC_FOURCC( 't','a','r','k' ) &&
657         p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) &&
658         p_stream->fmt.i_codec != VLC_FOURCC( 'c','m','m','l' ) )
659     {
660         /* We remove the header from the packet */
661         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
662         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
663
664         if( p_stream->fmt.i_codec == VLC_FOURCC( 's','u','b','t' ))
665         {
666             /* But with subtitles we need to retrieve the duration first */
667             int i, lenbytes = 0;
668         
669             if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
670             {
671                 for( i = 0, lenbytes = 0; i < i_header_len; i++ )
672                 {
673                     lenbytes = lenbytes << 8;
674                     lenbytes += *(p_oggpacket->packet + i_header_len - i);
675                 }
676             }
677             if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
678                 ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
679                   p_oggpacket->packet[i_header_len + 1] != 0 && 
680                   p_oggpacket->packet[i_header_len + 1] != '\n' &&
681                   p_oggpacket->packet[i_header_len + 1] != '\r' ) )
682             {
683                 p_block->i_length = (mtime_t)lenbytes * 1000;
684             }
685         }
686
687         i_header_len++;
688         p_block->i_buffer -= i_header_len;
689     }
690
691     if( p_stream->fmt.i_codec == VLC_FOURCC( 't','a','r','k' ) )
692     {
693         /* FIXME: the biggest hack I've ever done */
694         msg_Warn( p_demux, "tarkin pts: "I64Fd", granule: "I64Fd,
695                   p_block->i_pts, p_block->i_dts );
696         msleep(10000);
697     }
698
699     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
700             p_oggpacket->bytes - i_header_len );
701
702     es_out_Send( p_demux->out, p_stream->p_es, p_block );
703 }
704
705 /****************************************************************************
706  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
707  *                         stream and fill p_ogg.
708  *****************************************************************************
709  * The initial page of a logical stream is marked as a 'bos' page.
710  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
711  * together and all of the initial pages must appear before any data pages.
712  *
713  * On success this function returns VLC_SUCCESS.
714  ****************************************************************************/
715 static int Ogg_FindLogicalStreams( demux_t *p_demux )
716 {
717     demux_sys_t *p_ogg = p_demux->p_sys  ;
718     ogg_packet oggpacket;
719     ogg_page oggpage;
720     int i_stream;
721
722 #define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]
723
724     while( Ogg_ReadPage( p_demux, &oggpage ) == VLC_SUCCESS )
725     {
726         if( ogg_page_bos( &oggpage ) )
727         {
728
729             /* All is wonderful in our fine fine little world.
730              * We found the beginning of our first logical stream. */
731             while( ogg_page_bos( &oggpage ) )
732             {
733                 p_ogg->i_streams++;
734                 p_ogg->pp_stream =
735                     realloc( p_ogg->pp_stream, p_ogg->i_streams *
736                              sizeof(logical_stream_t *) );
737
738                 p_stream = malloc( sizeof(logical_stream_t) );
739                 memset( p_stream, 0, sizeof(logical_stream_t) );
740                 p_stream->p_headers = 0;
741                 p_stream->secondary_header_packets = 0;
742
743                 es_format_Init( &p_stream->fmt, 0, 0 );
744
745                 /* Setup the logical stream */
746                 p_stream->i_serial_no = ogg_page_serialno( &oggpage );
747                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
748
749                 /* Extract the initial header from the first page and verify
750                  * the codec type of tis Ogg bitstream */
751                 if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
752                 {
753                     /* error. stream version mismatch perhaps */
754                     msg_Err( p_demux, "error reading first page of "
755                              "Ogg bitstream data" );
756                     return VLC_EGENERIC;
757                 }
758
759                 /* FIXME: check return value */
760                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
761
762                 /* Check for Vorbis header */
763                 if( oggpacket.bytes >= 7 &&
764                     ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
765                 {
766                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
767                     msg_Dbg( p_demux, "found vorbis header" );
768                 }
769                 /* Check for Speex header */
770                 else if( oggpacket.bytes >= 7 &&
771                     ! strncmp( &oggpacket.packet[0], "Speex", 5 ) )
772                 {
773                     Ogg_ReadSpeexHeader( p_stream, &oggpacket );
774                     msg_Dbg( p_demux, "found speex header, channels: %i, "
775                              "rate: %i,  bitrate: %i",
776                              p_stream->fmt.audio.i_channels,
777                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
778                 }
779                 /* Check for Flac header (< version 1.1.1) */
780                 else if( oggpacket.bytes >= 4 &&
781                     ! strncmp( &oggpacket.packet[0], "fLaC", 4 ) )
782                 {
783                     msg_Dbg( p_demux, "found FLAC header" );
784
785                     /* Grrrr!!!! Did they really have to put all the
786                      * important info in the second header packet!!!
787                      * (STREAMINFO metadata is in the following packet) */
788                     p_stream->b_force_backup = 1;
789
790                     p_stream->fmt.i_cat = AUDIO_ES;
791                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
792                 }
793                 /* Check for Flac header (>= version 1.1.1) */
794                 else if( oggpacket.bytes >= 13 && oggpacket.packet[0] ==0x7F &&
795                     ! strncmp( &oggpacket.packet[1], "FLAC", 4 ) &&
796                     ! strncmp( &oggpacket.packet[9], "fLaC", 4 ) )
797                 {
798                     int i_packets = ((int)oggpacket.packet[7]) << 8 |
799                         oggpacket.packet[8];
800                     msg_Dbg( p_demux, "found FLAC header version %i.%i "
801                              "(%i header packets)",
802                              oggpacket.packet[5], oggpacket.packet[6],
803                              i_packets );
804
805                     p_stream->b_force_backup = 1;
806
807                     p_stream->fmt.i_cat = AUDIO_ES;
808                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
809                     oggpacket.packet += 13; oggpacket.bytes -= 13;
810                     Ogg_ReadFlacHeader( p_demux, p_stream, &oggpacket );
811                 }
812                 /* Check for Theora header */
813                 else if( oggpacket.bytes >= 7 &&
814                          ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
815                 {
816                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
817
818                     msg_Dbg( p_demux,
819                              "found theora header, bitrate: %i, rate: %f",
820                              p_stream->fmt.i_bitrate, p_stream->f_rate );
821                 }
822                 /* Check for Tarkin header */
823                 else if( oggpacket.bytes >= 7 &&
824                          ! strncmp( &oggpacket.packet[1], "tarkin", 6 ) )
825                 {
826                     oggpack_buffer opb;
827
828                     msg_Dbg( p_demux, "found tarkin header" );
829                     p_stream->fmt.i_cat = VIDEO_ES;
830                     p_stream->fmt.i_codec = VLC_FOURCC( 't','a','r','k' );
831
832                     /* Cheat and get additionnal info ;) */
833                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
834                     oggpack_adv( &opb, 88 );
835                     oggpack_adv( &opb, 104 );
836                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
837                     p_stream->f_rate = 2; /* FIXME */
838                     msg_Dbg( p_demux,
839                              "found tarkin header, bitrate: %i, rate: %f",
840                              p_stream->fmt.i_bitrate, p_stream->f_rate );
841                 }
842                 /* Check for Annodex header */
843                 else if( oggpacket.bytes >= 7 &&
844                          ! strncmp( &oggpacket.packet[0], "Annodex", 7 ) )
845                 {
846                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
847                                            &oggpacket );
848                     /* kill annodex track */
849                     free( p_stream );
850                     p_ogg->i_streams--;
851                 }
852                 /* Check for Annodex header */
853                 else if( oggpacket.bytes >= 7 &&
854                          ! strncmp( &oggpacket.packet[0], "AnxData", 7 ) )
855                 {
856                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
857                                            &oggpacket );
858                 }
859                 else if( oggpacket.bytes >= 142 &&
860                          !strncmp( &oggpacket.packet[1],
861                                    "Direct Show Samples embedded in Ogg", 35 ))
862                 {
863                     /* Old header type */
864
865                     /* Check for video header (old format) */
866                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
867                         oggpacket.bytes >= 184 )
868                     {
869                         p_stream->fmt.i_cat = VIDEO_ES;
870                         p_stream->fmt.i_codec =
871                             VLC_FOURCC( oggpacket.packet[68],
872                                         oggpacket.packet[69],
873                                         oggpacket.packet[70],
874                                         oggpacket.packet[71] );
875                         msg_Dbg( p_demux, "found video header of type: %.4s",
876                                  (char *)&p_stream->fmt.i_codec );
877
878                         p_stream->f_rate = 10000000.0 /
879                             GetQWLE((oggpacket.packet+164));
880                         p_stream->fmt.video.i_bits_per_pixel =
881                             GetWLE((oggpacket.packet+182));
882                         if( !p_stream->fmt.video.i_bits_per_pixel )
883                             /* hack, FIXME */
884                             p_stream->fmt.video.i_bits_per_pixel = 24;
885                         p_stream->fmt.video.i_width =
886                             GetDWLE((oggpacket.packet+176));
887                         p_stream->fmt.video.i_height =
888                             GetDWLE((oggpacket.packet+180));
889
890                         msg_Dbg( p_demux,
891                                  "fps: %f, width:%i; height:%i, bitcount:%i",
892                                  p_stream->f_rate,
893                                  p_stream->fmt.video.i_width,
894                                  p_stream->fmt.video.i_height,
895                                  p_stream->fmt.video.i_bits_per_pixel);
896
897                     }
898                     /* Check for audio header (old format) */
899                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
900                     {
901                         unsigned int i_extra_size;
902                         unsigned int i_format_tag;
903
904                         p_stream->fmt.i_cat = AUDIO_ES;
905
906                         i_extra_size = GetWLE((oggpacket.packet+140));
907                         if( i_extra_size )
908                         {
909                             p_stream->fmt.i_extra = i_extra_size;
910                             p_stream->fmt.p_extra = malloc( i_extra_size );
911                             memcpy( p_stream->fmt.p_extra,
912                                     oggpacket.packet + 142, i_extra_size );
913                         }
914
915                         i_format_tag = GetWLE((oggpacket.packet+124));
916                         p_stream->fmt.audio.i_channels =
917                             GetWLE((oggpacket.packet+126));
918                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
919                             GetDWLE((oggpacket.packet+128));
920                         p_stream->fmt.i_bitrate =
921                             GetDWLE((oggpacket.packet+132)) * 8;
922                         p_stream->fmt.audio.i_blockalign =
923                             GetWLE((oggpacket.packet+136));
924                         p_stream->fmt.audio.i_bitspersample =
925                             GetWLE((oggpacket.packet+138));
926
927                         wf_tag_to_fourcc( i_format_tag,
928                                           &p_stream->fmt.i_codec, 0 );
929
930                         if( p_stream->fmt.i_codec ==
931                             VLC_FOURCC('u','n','d','f') )
932                         {
933                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
934                                 ( i_format_tag >> 8 ) & 0xff,
935                                 i_format_tag & 0xff );
936                         }
937
938                         msg_Dbg( p_demux, "found audio header of type: %.4s",
939                                  (char *)&p_stream->fmt.i_codec );
940                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
941                                  "%dbits/sample %dkb/s",
942                                  i_format_tag,
943                                  p_stream->fmt.audio.i_channels,
944                                  p_stream->fmt.audio.i_rate,
945                                  p_stream->fmt.audio.i_bitspersample,
946                                  p_stream->fmt.i_bitrate / 1024 );
947
948                     }
949                     else
950                     {
951                         msg_Dbg( p_demux, "stream %d has an old header "
952                             "but is of an unknown type", p_ogg->i_streams-1 );
953                         free( p_stream );
954                         p_ogg->i_streams--;
955                     }
956                 }
957                 else if( (*oggpacket.packet & PACKET_TYPE_BITS )
958                          == PACKET_TYPE_HEADER &&
959                          oggpacket.bytes >= (int)sizeof(stream_header)+1 )
960                 {
961                     stream_header *st = (stream_header *)(oggpacket.packet+1);
962
963                     /* Check for video header (new format) */
964                     if( !strncmp( st->streamtype, "video", 5 ) )
965                     {
966                         p_stream->fmt.i_cat = VIDEO_ES;
967
968                         /* We need to get rid of the header packet */
969                         ogg_stream_packetout( &p_stream->os, &oggpacket );
970
971                         p_stream->fmt.i_codec =
972                             VLC_FOURCC( st->subtype[0], st->subtype[1],
973                                         st->subtype[2], st->subtype[3] );
974                         msg_Dbg( p_demux, "found video header of type: %.4s",
975                                  (char *)&p_stream->fmt.i_codec );
976
977                         p_stream->f_rate = 10000000.0 /
978                             GetQWLE(&st->time_unit);
979                         p_stream->fmt.video.i_bits_per_pixel =
980                             GetWLE(&st->bits_per_sample);
981                         p_stream->fmt.video.i_width =
982                             GetDWLE(&st->sh.video.width);
983                         p_stream->fmt.video.i_height =
984                             GetDWLE(&st->sh.video.height);
985
986                         msg_Dbg( p_demux,
987                                  "fps: %f, width:%i; height:%i, bitcount:%i",
988                                  p_stream->f_rate,
989                                  p_stream->fmt.video.i_width,
990                                  p_stream->fmt.video.i_height,
991                                  p_stream->fmt.video.i_bits_per_pixel );
992                     }
993                     /* Check for audio header (new format) */
994                     else if( !strncmp( st->streamtype, "audio", 5 ) )
995                     {
996                         char p_buffer[5];
997                         int i_format_tag;
998
999                         p_stream->fmt.i_cat = AUDIO_ES;
1000
1001                         /* We need to get rid of the header packet */
1002                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1003
1004                         p_stream->fmt.i_extra = GetQWLE(&st->size) -
1005                             sizeof(stream_header);
1006                         if( p_stream->fmt.i_extra )
1007                         {
1008                             p_stream->fmt.p_extra =
1009                                 malloc( p_stream->fmt.i_extra );
1010                             memcpy( p_stream->fmt.p_extra, st + 1,
1011                                     p_stream->fmt.i_extra );
1012                         }
1013
1014                         memcpy( p_buffer, st->subtype, 4 );
1015                         p_buffer[4] = '\0';
1016                         i_format_tag = strtol(p_buffer,NULL,16);
1017                         p_stream->fmt.audio.i_channels =
1018                             GetWLE(&st->sh.audio.channels);
1019                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
1020                             GetQWLE(&st->samples_per_unit);
1021                         p_stream->fmt.i_bitrate =
1022                             GetDWLE(&st->sh.audio.avgbytespersec) * 8;
1023                         p_stream->fmt.audio.i_blockalign =
1024                             GetWLE(&st->sh.audio.blockalign);
1025                         p_stream->fmt.audio.i_bitspersample =
1026                             GetWLE(&st->bits_per_sample);
1027
1028                         wf_tag_to_fourcc( i_format_tag,
1029                                           &p_stream->fmt.i_codec, 0 );
1030
1031                         if( p_stream->fmt.i_codec ==
1032                             VLC_FOURCC('u','n','d','f') )
1033                         {
1034                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1035                                 ( i_format_tag >> 8 ) & 0xff,
1036                                 i_format_tag & 0xff );
1037                         }
1038
1039                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1040                                  (char *)&p_stream->fmt.i_codec );
1041                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1042                                  "%dbits/sample %dkb/s",
1043                                  i_format_tag,
1044                                  p_stream->fmt.audio.i_channels,
1045                                  p_stream->fmt.audio.i_rate,
1046                                  p_stream->fmt.audio.i_bitspersample,
1047                                  p_stream->fmt.i_bitrate / 1024 );
1048                     }
1049                     /* Check for text (subtitles) header */
1050                     else if( !strncmp(st->streamtype, "text", 4) )
1051                     {
1052                         /* We need to get rid of the header packet */
1053                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1054
1055                         msg_Dbg( p_demux, "found text subtitles header" );
1056                         p_stream->fmt.i_cat = SPU_ES;
1057                         p_stream->fmt.i_codec = VLC_FOURCC('s','u','b','t');
1058                         p_stream->f_rate = 1000; /* granulepos is in milisec */
1059                     }
1060                     else
1061                     {
1062                         msg_Dbg( p_demux, "stream %d has a header marker "
1063                             "but is of an unknown type", p_ogg->i_streams-1 );
1064                         free( p_stream );
1065                         p_ogg->i_streams--;
1066                     }
1067                 }
1068                 else
1069                 {
1070                     msg_Dbg( p_demux, "stream %d is of unknown type",
1071                              p_ogg->i_streams-1 );
1072                     free( p_stream );
1073                     p_ogg->i_streams--;
1074                 }
1075
1076                 if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
1077                     return VLC_EGENERIC;
1078             }
1079
1080             /* This is the first data page, which means we are now finished
1081              * with the initial pages. We just need to store it in the relevant
1082              * bitstream. */
1083             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1084             {
1085                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
1086                                        &oggpage ) == 0 )
1087                 {
1088                     break;
1089                 }
1090             }
1091
1092             return VLC_SUCCESS;
1093         }
1094     }
1095 #undef p_stream
1096
1097     return VLC_EGENERIC;
1098 }
1099
1100 /****************************************************************************
1101  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1102  *                        Elementary streams.
1103  ****************************************************************************/
1104 static int Ogg_BeginningOfStream( demux_t *p_demux )
1105 {
1106     demux_sys_t *p_ogg = p_demux->p_sys  ;
1107     int i_stream;
1108
1109     /* Find the logical streams embedded in the physical stream and
1110      * initialize our p_ogg structure. */
1111     if( Ogg_FindLogicalStreams( p_demux ) != VLC_SUCCESS )
1112     {
1113         msg_Warn( p_demux, "couldn't find any ogg logical stream" );
1114         return VLC_EGENERIC;
1115     }
1116
1117     p_ogg->i_bitrate = 0;
1118
1119     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1120     {
1121 #define p_stream p_ogg->pp_stream[i_stream]
1122         p_stream->p_es = es_out_Add( p_demux->out, &p_stream->fmt );
1123
1124         if( p_stream->fmt.i_codec == VLC_FOURCC('c','m','m','l') )
1125         {
1126             /* Set the CMML stream active */
1127             es_out_Control( p_demux->out, ES_OUT_SET_ES, p_stream->p_es );
1128         }
1129
1130         p_ogg->i_bitrate += p_stream->fmt.i_bitrate;
1131
1132         p_stream->i_pcr = p_stream->i_previous_pcr =
1133             p_stream->i_interpolated_pcr = -1;
1134         p_stream->b_reinit = 0;
1135 #undef p_stream
1136     }
1137
1138     return VLC_SUCCESS;
1139 }
1140
1141 /****************************************************************************
1142  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1143  ****************************************************************************/
1144 static void Ogg_EndOfStream( demux_t *p_demux )
1145 {
1146     demux_sys_t *p_ogg = p_demux->p_sys  ;
1147     int i_stream;
1148
1149 #define p_stream p_ogg->pp_stream[i_stream]
1150     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1151     {
1152         if( p_stream->p_es )
1153             es_out_Del( p_demux->out, p_stream->p_es );
1154
1155         p_ogg->i_bitrate -= p_stream->fmt.i_bitrate;
1156
1157         ogg_stream_clear( &p_ogg->pp_stream[i_stream]->os );
1158         if( p_ogg->pp_stream[i_stream]->p_headers)
1159             free( p_ogg->pp_stream[i_stream]->p_headers );
1160
1161         es_format_Clean( &p_stream->fmt );
1162
1163         free( p_ogg->pp_stream[i_stream] );
1164     }
1165 #undef p_stream
1166
1167     /* Reinit p_ogg */
1168     if( p_ogg->pp_stream ) free( p_ogg->pp_stream );
1169     p_ogg->pp_stream = NULL;
1170     p_ogg->i_streams = 0;
1171 }
1172
1173 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
1174                                   ogg_packet *p_oggpacket )
1175 {
1176     bs_t bitstream;
1177     int i_fps_numerator;
1178     int i_fps_denominator;
1179     int i_keyframe_frequency_force;
1180
1181     p_stream->fmt.i_cat = VIDEO_ES;
1182     p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1183
1184     /* Signal that we want to keep a backup of the theora
1185      * stream headers. They will be used when switching between
1186      * audio streams. */
1187     p_stream->b_force_backup = 1;
1188
1189     /* Cheat and get additionnal info ;) */
1190     bs_init( &bitstream, p_oggpacket->packet, p_oggpacket->bytes );
1191     bs_skip( &bitstream, 56 );
1192     bs_read( &bitstream, 8 ); /* major version num */
1193     bs_read( &bitstream, 8 ); /* minor version num */
1194     bs_read( &bitstream, 8 ); /* subminor version num */
1195     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
1196     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
1197     bs_read( &bitstream, 24 ); /* frame width */
1198     bs_read( &bitstream, 24 ); /* frame height */
1199     bs_read( &bitstream, 8 ); /* x offset */
1200     bs_read( &bitstream, 8 ); /* y offset */
1201
1202     i_fps_numerator = bs_read( &bitstream, 32 );
1203     i_fps_denominator = bs_read( &bitstream, 32 );
1204     bs_read( &bitstream, 24 ); /* aspect_numerator */
1205     bs_read( &bitstream, 24 ); /* aspect_denominator */
1206
1207     bs_read( &bitstream, 8 ); /* colorspace */
1208     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
1209     bs_read( &bitstream, 6 ); /* quality */
1210
1211     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
1212
1213     /* granule_shift = i_log( frequency_force -1 ) */
1214     p_stream->i_theora_keyframe_granule_shift = 0;
1215     i_keyframe_frequency_force--;
1216     while( i_keyframe_frequency_force )
1217     {
1218         p_stream->i_theora_keyframe_granule_shift++;
1219         i_keyframe_frequency_force >>= 1;
1220     }
1221
1222     p_stream->f_rate = ((float)i_fps_numerator) / i_fps_denominator;
1223 }
1224
1225 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
1226                                   ogg_packet *p_oggpacket )
1227 {
1228     oggpack_buffer opb;
1229
1230     p_stream->fmt.i_cat = AUDIO_ES;
1231     p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1232
1233     /* Signal that we want to keep a backup of the vorbis
1234      * stream headers. They will be used when switching between
1235      * audio streams. */
1236     p_stream->b_force_backup = 1;
1237
1238     /* Cheat and get additionnal info ;) */
1239     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1240     oggpack_adv( &opb, 88 );
1241     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
1242     p_stream->f_rate = p_stream->fmt.audio.i_rate =
1243         oggpack_read( &opb, 32 );
1244     oggpack_adv( &opb, 32 );
1245     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1246 }
1247
1248 static void Ogg_ReadSpeexHeader( logical_stream_t *p_stream,
1249                                  ogg_packet *p_oggpacket )
1250 {
1251     oggpack_buffer opb;
1252
1253     p_stream->fmt.i_cat = AUDIO_ES;
1254     p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
1255
1256     /* Signal that we want to keep a backup of the speex
1257      * stream headers. They will be used when switching between
1258      * audio streams. */
1259     p_stream->b_force_backup = 1;
1260
1261     /* Cheat and get additionnal info ;) */
1262     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1263     oggpack_adv( &opb, 224 );
1264     oggpack_adv( &opb, 32 ); /* speex_version_id */
1265     oggpack_adv( &opb, 32 ); /* header_size */
1266     p_stream->f_rate = p_stream->fmt.audio.i_rate = oggpack_read( &opb, 32 );
1267     oggpack_adv( &opb, 32 ); /* mode */
1268     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
1269     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
1270     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1271 }
1272
1273 static void Ogg_ReadFlacHeader( demux_t *p_demux, logical_stream_t *p_stream,
1274                                 ogg_packet *p_oggpacket )
1275 {
1276     /* Parse the STREAMINFO metadata */
1277     bs_t s;
1278
1279     bs_init( &s, p_oggpacket->packet, p_oggpacket->bytes );
1280
1281     bs_read( &s, 1 );
1282     if( bs_read( &s, 7 ) == 0 )
1283     {
1284         if( bs_read( &s, 24 ) >= 34 /*size STREAMINFO*/ )
1285         {
1286             bs_skip( &s, 80 );
1287             p_stream->f_rate = p_stream->fmt.audio.i_rate = bs_read( &s, 20 );
1288             p_stream->fmt.audio.i_channels = bs_read( &s, 3 ) + 1;
1289
1290             msg_Dbg( p_demux, "FLAC header, channels: %i, rate: %i",
1291                      p_stream->fmt.audio.i_channels, (int)p_stream->f_rate );
1292         }
1293         else msg_Dbg( p_demux, "FLAC STREAMINFO metadata too short" );
1294
1295         /* Fake this as the last metadata block */
1296         *((uint8_t*)p_oggpacket->packet) |= 0x80;
1297     }
1298     else
1299     {
1300         /* This ain't a STREAMINFO metadata */
1301         msg_Dbg( p_demux, "Invalid FLAC STREAMINFO metadata" );
1302     }
1303 }
1304
1305 static void Ogg_ReadAnnodexHeader( vlc_object_t *p_this,
1306                                    logical_stream_t *p_stream,
1307                                    ogg_packet *p_oggpacket )
1308 {
1309     if( ! strncmp( &p_oggpacket->packet[0], "Annodex", 7 ) )
1310     {
1311         oggpack_buffer opb;
1312
1313         uint16_t major_version;
1314         uint16_t minor_version;
1315         uint64_t timebase_numerator;
1316         uint64_t timebase_denominator;
1317
1318         Ogg_ReadTheoraHeader( p_stream, p_oggpacket );
1319
1320         oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1321         oggpack_adv( &opb, 8*8 ); /* "Annodex\0" header */
1322         major_version = oggpack_read( &opb, 2*8 ); /* major version */
1323         minor_version = oggpack_read( &opb, 2*8 ); /* minor version */
1324         timebase_numerator = GetQWLE( &p_oggpacket->packet[16] );
1325         timebase_denominator = GetQWLE( &p_oggpacket->packet[24] );
1326     }
1327     else if( ! strncmp( &p_oggpacket->packet[0], "AnxData", 7 ) )
1328     {
1329         uint64_t granule_rate_numerator;
1330         uint64_t granule_rate_denominator;
1331         char content_type_string[1024];
1332
1333         /* Read in Annodex header fields */
1334
1335         granule_rate_numerator = GetQWLE( &p_oggpacket->packet[8] );
1336         granule_rate_denominator = GetQWLE( &p_oggpacket->packet[16] );
1337         p_stream->secondary_header_packets =
1338             GetDWLE( &p_oggpacket->packet[24] );
1339
1340         /* we are guaranteed that the first header field will be
1341          * the content-type (by the Annodex standard) */
1342         if( !strncasecmp( &p_oggpacket->packet[28], "Content-Type: ", 14 ) )
1343         {
1344             sscanf( &p_oggpacket->packet[42], "%1024s\r\n",
1345                     content_type_string );
1346         }
1347
1348         msg_Dbg( p_this, "AnxData packet info: "I64Fd" / "I64Fd", %d, ``%s''",
1349                  granule_rate_numerator, granule_rate_denominator,
1350                  p_stream->secondary_header_packets, content_type_string );
1351
1352         p_stream->f_rate = (float) granule_rate_numerator /
1353             (float) granule_rate_denominator;
1354
1355         /* What type of file do we have?
1356          * strcmp is safe to use here because we've extracted
1357          * content_type_string from the stream manually */
1358         if( !strncmp(content_type_string, "audio/x-wav", 11) )
1359         {
1360             /* n.b. WAVs are unsupported right now */
1361             p_stream->fmt.i_cat = UNKNOWN_ES;
1362         }
1363         else if( !strncmp(content_type_string, "audio/x-vorbis", 14) )
1364         {
1365             p_stream->fmt.i_cat = AUDIO_ES;
1366             p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1367
1368             p_stream->b_force_backup = 1;
1369         }
1370         else if( !strncmp(content_type_string, "audio/x-speex", 14) )
1371         {
1372             p_stream->fmt.i_cat = AUDIO_ES;
1373             p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
1374
1375             p_stream->b_force_backup = 1;
1376         }
1377         else if( !strncmp(content_type_string, "video/x-theora", 14) )
1378         {
1379             p_stream->fmt.i_cat = VIDEO_ES;
1380             p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1381
1382             p_stream->b_force_backup = 1;
1383         }
1384         else if( !strncmp(content_type_string, "video/x-xvid", 14) )
1385         {
1386             p_stream->fmt.i_cat = VIDEO_ES;
1387             p_stream->fmt.i_codec = VLC_FOURCC( 'x','v','i','d' );
1388
1389             p_stream->b_force_backup = 1;
1390         }
1391         else if( !strncmp(content_type_string, "video/mpeg", 14) )
1392         {
1393             /* n.b. MPEG streams are unsupported right now */
1394             p_stream->fmt.i_cat = VIDEO_ES;
1395             p_stream->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1396         }
1397         else if( !strncmp(content_type_string, "text/x-cmml", 11) )
1398         {
1399             ogg_stream_packetout( &p_stream->os, p_oggpacket );
1400             p_stream->fmt.i_cat = SPU_ES;
1401             p_stream->fmt.i_codec = VLC_FOURCC( 'c','m','m','l' );
1402         }
1403     }
1404 }