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