]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
Copyright fixes
[vlc] / modules / demux / ogg.c
1 /*****************************************************************************
2  * ogg.c : ogg stream demux module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN (Centrale Réseaux) and its contributors
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" ) && strncmp( 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                         ! strncmp( &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                         ! strncmp( &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     byte_t *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         ! strncmp ( &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         ! strncmp ( &p_oggpacket->packet[0], "AnxData", 7 ) )
494     {
495         /* it's an AnxData packet -- skip it (do nothing) */
496         return; 
497     }
498
499     /* Check the ES is selected */
500     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
501                     p_stream->p_es, &b_selected );
502
503     if( p_stream->b_force_backup )
504     {
505         uint8_t *p_extra;
506         vlc_bool_t b_store_size = VLC_TRUE;
507
508         p_stream->i_packets_backup++;
509         switch( p_stream->fmt.i_codec )
510         {
511         case VLC_FOURCC( 'v','o','r','b' ):
512         case VLC_FOURCC( 's','p','x',' ' ):
513         case VLC_FOURCC( 't','h','e','o' ):
514           if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
515           break;
516
517         case VLC_FOURCC( 'f','l','a','c' ):
518           if( !p_stream->fmt.audio.i_rate && p_stream->i_packets_backup == 2 )
519           {
520               Ogg_ReadFlacHeader( p_demux, p_stream, p_oggpacket );
521               p_stream->b_force_backup = 0;
522           }
523           else if( p_stream->fmt.audio.i_rate )
524           {
525               p_stream->b_force_backup = 0;
526               p_oggpacket->packet += 9; p_oggpacket->bytes -= 9;
527           }
528           b_store_size = VLC_FALSE;
529           break;
530
531         default:
532           p_stream->b_force_backup = 0;
533           break;
534         }
535
536         /* Backup the ogg packet (likely an header packet) */
537         p_stream->p_headers =
538             realloc( p_stream->p_headers, p_stream->i_headers +
539                      p_oggpacket->bytes + (b_store_size ? 2 : 0) );
540         p_extra = p_stream->p_headers + p_stream->i_headers;
541         if( b_store_size )
542         {
543             *(p_extra++) = p_oggpacket->bytes >> 8;
544             *(p_extra++) = p_oggpacket->bytes & 0xFF;
545         }
546         memcpy( p_extra, p_oggpacket->packet, p_oggpacket->bytes );
547         p_stream->i_headers += p_oggpacket->bytes + (b_store_size ? 2 : 0);
548
549         if( !p_stream->b_force_backup )
550         {
551             /* Last header received, commit changes */
552             p_stream->fmt.i_extra = p_stream->i_headers;
553             p_stream->fmt.p_extra =
554                 realloc( p_stream->fmt.p_extra, p_stream->i_headers );
555             memcpy( p_stream->fmt.p_extra, p_stream->p_headers,
556                     p_stream->i_headers );
557             es_out_Control( p_demux->out, ES_OUT_SET_FMT,
558                             p_stream->p_es, &p_stream->fmt );
559         }
560
561         b_selected = VLC_FALSE; /* Discard the header packet */
562     }
563
564     /* Convert the pcr into a pts */
565     if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
566         p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
567         p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
568     {
569         if( p_stream->i_pcr >= 0 )
570         {
571             /* This is for streams where the granulepos of the header packets
572              * doesn't match these of the data packets (eg. ogg web radios). */
573             if( p_stream->i_previous_pcr == 0 &&
574                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
575             {
576                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
577
578                 /* Call the pace control */
579                 es_out_Control( p_demux->out, ES_OUT_SET_PCR,
580                                 p_stream->i_pcr );
581             }
582
583             p_stream->i_previous_pcr = p_stream->i_pcr;
584
585             /* The granulepos is the end date of the sample */
586             i_pts =  p_stream->i_pcr;
587         }
588     }
589
590     /* Convert the granulepos into the next pcr */
591     i_interpolated_pts = p_stream->i_interpolated_pcr;
592     Ogg_UpdatePCR( p_stream, p_oggpacket );
593
594     if( p_stream->i_pcr >= 0 )
595     {
596         /* This is for streams where the granulepos of the header packets
597          * doesn't match these of the data packets (eg. ogg web radios). */
598         if( p_stream->i_previous_pcr == 0 &&
599             p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
600         {
601             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
602
603             /* Call the pace control */
604             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_stream->i_pcr );
605         }
606     }
607
608     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
609         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
610         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
611         p_stream->i_pcr >= 0 )
612     {
613         p_stream->i_previous_pcr = p_stream->i_pcr;
614
615         /* The granulepos is the start date of the sample */
616         i_pts = p_stream->i_pcr;
617     }
618
619     if( !b_selected )
620     {
621         /* This stream isn't currently selected so we don't need to decode it,
622          * but we did need to store its pcr as it might be selected later on */
623         return;
624     }
625
626     if( !( p_block = block_New( p_demux, p_oggpacket->bytes ) ) ) return;
627
628     /* Normalize PTS */
629     if( i_pts == 0 ) i_pts = 1;
630     else if( i_pts == -1 && i_interpolated_pts == 0 ) i_pts = 1;
631     else if( i_pts == -1 ) i_pts = 0;
632
633     if( p_stream->fmt.i_cat == AUDIO_ES )
634         p_block->i_dts = p_block->i_pts = i_pts;
635     else if( p_stream->fmt.i_cat == SPU_ES )
636     {
637         p_block->i_dts = p_block->i_pts = i_pts;
638         p_block->i_length = 0;
639     }
640     else if( p_stream->fmt.i_codec == VLC_FOURCC( 't','h','e','o' ) )
641         p_block->i_dts = p_block->i_pts = i_pts;
642     else
643     {
644         p_block->i_dts = i_pts;
645         p_block->i_pts = 0;
646     }
647
648     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
649         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
650         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
651         p_stream->fmt.i_codec != VLC_FOURCC( 't','a','r','k' ) &&
652         p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) &&
653         p_stream->fmt.i_codec != VLC_FOURCC( 'c','m','m','l' ) )
654     {
655         /* We remove the header from the packet */
656         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
657         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
658
659         if( p_stream->fmt.i_codec == VLC_FOURCC( 's','u','b','t' ))
660         {
661             /* But with subtitles we need to retrieve the duration first */
662             int i, lenbytes = 0;
663         
664             if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
665             {
666                 for( i = 0, lenbytes = 0; i < i_header_len; i++ )
667                 {
668                     lenbytes = lenbytes << 8;
669                     lenbytes += *(p_oggpacket->packet + i_header_len - i);
670                 }
671             }
672             if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
673                 ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
674                   p_oggpacket->packet[i_header_len + 1] != 0 && 
675                   p_oggpacket->packet[i_header_len + 1] != '\n' &&
676                   p_oggpacket->packet[i_header_len + 1] != '\r' ) )
677             {
678                 p_block->i_length = (mtime_t)lenbytes * 1000;
679             }
680         }
681
682         i_header_len++;
683         p_block->i_buffer -= i_header_len;
684     }
685
686     if( p_stream->fmt.i_codec == VLC_FOURCC( 't','a','r','k' ) )
687     {
688         /* FIXME: the biggest hack I've ever done */
689         msg_Warn( p_demux, "tarkin pts: "I64Fd", granule: "I64Fd,
690                   p_block->i_pts, p_block->i_dts );
691         msleep(10000);
692     }
693
694     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
695             p_oggpacket->bytes - i_header_len );
696
697     es_out_Send( p_demux->out, p_stream->p_es, p_block );
698 }
699
700 /****************************************************************************
701  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
702  *                         stream and fill p_ogg.
703  *****************************************************************************
704  * The initial page of a logical stream is marked as a 'bos' page.
705  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
706  * together and all of the initial pages must appear before any data pages.
707  *
708  * On success this function returns VLC_SUCCESS.
709  ****************************************************************************/
710 static int Ogg_FindLogicalStreams( demux_t *p_demux )
711 {
712     demux_sys_t *p_ogg = p_demux->p_sys  ;
713     ogg_packet oggpacket;
714     ogg_page oggpage;
715     int i_stream;
716
717 #define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]
718
719     while( Ogg_ReadPage( p_demux, &oggpage ) == VLC_SUCCESS )
720     {
721         if( ogg_page_bos( &oggpage ) )
722         {
723
724             /* All is wonderful in our fine fine little world.
725              * We found the beginning of our first logical stream. */
726             while( ogg_page_bos( &oggpage ) )
727             {
728                 p_ogg->i_streams++;
729                 p_ogg->pp_stream =
730                     realloc( p_ogg->pp_stream, p_ogg->i_streams *
731                              sizeof(logical_stream_t *) );
732
733                 p_stream = malloc( sizeof(logical_stream_t) );
734                 memset( p_stream, 0, sizeof(logical_stream_t) );
735                 p_stream->p_headers = 0;
736                 p_stream->secondary_header_packets = 0;
737
738                 es_format_Init( &p_stream->fmt, 0, 0 );
739
740                 /* Setup the logical stream */
741                 p_stream->i_serial_no = ogg_page_serialno( &oggpage );
742                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
743
744                 /* Extract the initial header from the first page and verify
745                  * the codec type of tis Ogg bitstream */
746                 if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
747                 {
748                     /* error. stream version mismatch perhaps */
749                     msg_Err( p_demux, "error reading first page of "
750                              "Ogg bitstream data" );
751                     return VLC_EGENERIC;
752                 }
753
754                 /* FIXME: check return value */
755                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
756
757                 /* Check for Vorbis header */
758                 if( oggpacket.bytes >= 7 &&
759                     ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
760                 {
761                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
762                     msg_Dbg( p_demux, "found vorbis header" );
763                 }
764                 /* Check for Speex header */
765                 else if( oggpacket.bytes >= 7 &&
766                     ! strncmp( &oggpacket.packet[0], "Speex", 5 ) )
767                 {
768                     Ogg_ReadSpeexHeader( p_stream, &oggpacket );
769                     msg_Dbg( p_demux, "found speex header, channels: %i, "
770                              "rate: %i,  bitrate: %i",
771                              p_stream->fmt.audio.i_channels,
772                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
773                 }
774                 /* Check for Flac header (< version 1.1.1) */
775                 else if( oggpacket.bytes >= 4 &&
776                     ! strncmp( &oggpacket.packet[0], "fLaC", 4 ) )
777                 {
778                     msg_Dbg( p_demux, "found FLAC header" );
779
780                     /* Grrrr!!!! Did they really have to put all the
781                      * important info in the second header packet!!!
782                      * (STREAMINFO metadata is in the following packet) */
783                     p_stream->b_force_backup = 1;
784
785                     p_stream->fmt.i_cat = AUDIO_ES;
786                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
787                 }
788                 /* Check for Flac header (>= version 1.1.1) */
789                 else if( oggpacket.bytes >= 13 && oggpacket.packet[0] ==0x7F &&
790                     ! strncmp( &oggpacket.packet[1], "FLAC", 4 ) &&
791                     ! strncmp( &oggpacket.packet[9], "fLaC", 4 ) )
792                 {
793                     int i_packets = ((int)oggpacket.packet[7]) << 8 |
794                         oggpacket.packet[8];
795                     msg_Dbg( p_demux, "found FLAC header version %i.%i "
796                              "(%i header packets)",
797                              oggpacket.packet[5], oggpacket.packet[6],
798                              i_packets );
799
800                     p_stream->b_force_backup = 1;
801
802                     p_stream->fmt.i_cat = AUDIO_ES;
803                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
804                     oggpacket.packet += 13; oggpacket.bytes -= 13;
805                     Ogg_ReadFlacHeader( p_demux, p_stream, &oggpacket );
806                 }
807                 /* Check for Theora header */
808                 else if( oggpacket.bytes >= 7 &&
809                          ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
810                 {
811                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
812
813                     msg_Dbg( p_demux,
814                              "found theora header, bitrate: %i, rate: %f",
815                              p_stream->fmt.i_bitrate, p_stream->f_rate );
816                 }
817                 /* Check for Tarkin header */
818                 else if( oggpacket.bytes >= 7 &&
819                          ! strncmp( &oggpacket.packet[1], "tarkin", 6 ) )
820                 {
821                     oggpack_buffer opb;
822
823                     msg_Dbg( p_demux, "found tarkin header" );
824                     p_stream->fmt.i_cat = VIDEO_ES;
825                     p_stream->fmt.i_codec = VLC_FOURCC( 't','a','r','k' );
826
827                     /* Cheat and get additionnal info ;) */
828                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
829                     oggpack_adv( &opb, 88 );
830                     oggpack_adv( &opb, 104 );
831                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
832                     p_stream->f_rate = 2; /* FIXME */
833                     msg_Dbg( p_demux,
834                              "found tarkin header, bitrate: %i, rate: %f",
835                              p_stream->fmt.i_bitrate, p_stream->f_rate );
836                 }
837                 /* Check for Annodex header */
838                 else if( oggpacket.bytes >= 7 &&
839                          ! strncmp( &oggpacket.packet[0], "Annodex", 7 ) )
840                 {
841                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
842                                            &oggpacket );
843                     /* kill annodex track */
844                     free( p_stream );
845                     p_ogg->i_streams--;
846                 }
847                 /* Check for Annodex header */
848                 else if( oggpacket.bytes >= 7 &&
849                          ! strncmp( &oggpacket.packet[0], "AnxData", 7 ) )
850                 {
851                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
852                                            &oggpacket );
853                 }
854                 else if( oggpacket.bytes >= 142 &&
855                          !strncmp( &oggpacket.packet[1],
856                                    "Direct Show Samples embedded in Ogg", 35 ))
857                 {
858                     /* Old header type */
859
860                     /* Check for video header (old format) */
861                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
862                         oggpacket.bytes >= 184 )
863                     {
864                         p_stream->fmt.i_cat = VIDEO_ES;
865                         p_stream->fmt.i_codec =
866                             VLC_FOURCC( oggpacket.packet[68],
867                                         oggpacket.packet[69],
868                                         oggpacket.packet[70],
869                                         oggpacket.packet[71] );
870                         msg_Dbg( p_demux, "found video header of type: %.4s",
871                                  (char *)&p_stream->fmt.i_codec );
872
873                         p_stream->fmt.video.i_frame_rate = 10000000;
874                         p_stream->fmt.video.i_frame_rate_base =
875                             GetQWLE((oggpacket.packet+164));
876                         p_stream->f_rate = 10000000.0 /
877                             GetQWLE((oggpacket.packet+164));
878                         p_stream->fmt.video.i_bits_per_pixel =
879                             GetWLE((oggpacket.packet+182));
880                         if( !p_stream->fmt.video.i_bits_per_pixel )
881                             /* hack, FIXME */
882                             p_stream->fmt.video.i_bits_per_pixel = 24;
883                         p_stream->fmt.video.i_width =
884                             GetDWLE((oggpacket.packet+176));
885                         p_stream->fmt.video.i_height =
886                             GetDWLE((oggpacket.packet+180));
887
888                         msg_Dbg( p_demux,
889                                  "fps: %f, width:%i; height:%i, bitcount:%i",
890                                  p_stream->f_rate,
891                                  p_stream->fmt.video.i_width,
892                                  p_stream->fmt.video.i_height,
893                                  p_stream->fmt.video.i_bits_per_pixel);
894
895                     }
896                     /* Check for audio header (old format) */
897                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
898                     {
899                         unsigned int i_extra_size;
900                         unsigned int i_format_tag;
901
902                         p_stream->fmt.i_cat = AUDIO_ES;
903
904                         i_extra_size = GetWLE((oggpacket.packet+140));
905                         if( i_extra_size )
906                         {
907                             p_stream->fmt.i_extra = i_extra_size;
908                             p_stream->fmt.p_extra = malloc( i_extra_size );
909                             memcpy( p_stream->fmt.p_extra,
910                                     oggpacket.packet + 142, i_extra_size );
911                         }
912
913                         i_format_tag = GetWLE((oggpacket.packet+124));
914                         p_stream->fmt.audio.i_channels =
915                             GetWLE((oggpacket.packet+126));
916                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
917                             GetDWLE((oggpacket.packet+128));
918                         p_stream->fmt.i_bitrate =
919                             GetDWLE((oggpacket.packet+132)) * 8;
920                         p_stream->fmt.audio.i_blockalign =
921                             GetWLE((oggpacket.packet+136));
922                         p_stream->fmt.audio.i_bitspersample =
923                             GetWLE((oggpacket.packet+138));
924
925                         wf_tag_to_fourcc( i_format_tag,
926                                           &p_stream->fmt.i_codec, 0 );
927
928                         if( p_stream->fmt.i_codec ==
929                             VLC_FOURCC('u','n','d','f') )
930                         {
931                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
932                                 ( i_format_tag >> 8 ) & 0xff,
933                                 i_format_tag & 0xff );
934                         }
935
936                         msg_Dbg( p_demux, "found audio header of type: %.4s",
937                                  (char *)&p_stream->fmt.i_codec );
938                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
939                                  "%dbits/sample %dkb/s",
940                                  i_format_tag,
941                                  p_stream->fmt.audio.i_channels,
942                                  p_stream->fmt.audio.i_rate,
943                                  p_stream->fmt.audio.i_bitspersample,
944                                  p_stream->fmt.i_bitrate / 1024 );
945
946                     }
947                     else
948                     {
949                         msg_Dbg( p_demux, "stream %d has an old header "
950                             "but is of an unknown type", p_ogg->i_streams-1 );
951                         free( p_stream );
952                         p_ogg->i_streams--;
953                     }
954                 }
955                 else if( (*oggpacket.packet & PACKET_TYPE_BITS )
956                          == PACKET_TYPE_HEADER &&
957                          oggpacket.bytes >= (int)sizeof(stream_header)+1 )
958                 {
959                     stream_header *st = (stream_header *)(oggpacket.packet+1);
960
961                     /* Check for video header (new format) */
962                     if( !strncmp( st->streamtype, "video", 5 ) )
963                     {
964                         p_stream->fmt.i_cat = VIDEO_ES;
965
966                         /* We need to get rid of the header packet */
967                         ogg_stream_packetout( &p_stream->os, &oggpacket );
968
969                         p_stream->fmt.i_codec =
970                             VLC_FOURCC( st->subtype[0], st->subtype[1],
971                                         st->subtype[2], st->subtype[3] );
972                         msg_Dbg( p_demux, "found video header of type: %.4s",
973                                  (char *)&p_stream->fmt.i_codec );
974
975                         p_stream->fmt.video.i_frame_rate = 10000000;
976                         p_stream->fmt.video.i_frame_rate_base =
977                             GetQWLE(&st->time_unit);
978                         p_stream->f_rate = 10000000.0 /
979                             GetQWLE(&st->time_unit);
980                         p_stream->fmt.video.i_bits_per_pixel =
981                             GetWLE(&st->bits_per_sample);
982                         p_stream->fmt.video.i_width =
983                             GetDWLE(&st->sh.video.width);
984                         p_stream->fmt.video.i_height =
985                             GetDWLE(&st->sh.video.height);
986
987                         msg_Dbg( p_demux,
988                                  "fps: %f, width:%i; height:%i, bitcount:%i",
989                                  p_stream->f_rate,
990                                  p_stream->fmt.video.i_width,
991                                  p_stream->fmt.video.i_height,
992                                  p_stream->fmt.video.i_bits_per_pixel );
993                     }
994                     /* Check for audio header (new format) */
995                     else if( !strncmp( st->streamtype, "audio", 5 ) )
996                     {
997                         char p_buffer[5];
998                         int i_format_tag;
999
1000                         p_stream->fmt.i_cat = AUDIO_ES;
1001
1002                         /* We need to get rid of the header packet */
1003                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1004
1005                         p_stream->fmt.i_extra = GetQWLE(&st->size) -
1006                             sizeof(stream_header);
1007                         if( p_stream->fmt.i_extra )
1008                         {
1009                             p_stream->fmt.p_extra =
1010                                 malloc( p_stream->fmt.i_extra );
1011                             memcpy( p_stream->fmt.p_extra, st + 1,
1012                                     p_stream->fmt.i_extra );
1013                         }
1014
1015                         memcpy( p_buffer, st->subtype, 4 );
1016                         p_buffer[4] = '\0';
1017                         i_format_tag = strtol(p_buffer,NULL,16);
1018                         p_stream->fmt.audio.i_channels =
1019                             GetWLE(&st->sh.audio.channels);
1020                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
1021                             GetQWLE(&st->samples_per_unit);
1022                         p_stream->fmt.i_bitrate =
1023                             GetDWLE(&st->sh.audio.avgbytespersec) * 8;
1024                         p_stream->fmt.audio.i_blockalign =
1025                             GetWLE(&st->sh.audio.blockalign);
1026                         p_stream->fmt.audio.i_bitspersample =
1027                             GetWLE(&st->bits_per_sample);
1028
1029                         wf_tag_to_fourcc( i_format_tag,
1030                                           &p_stream->fmt.i_codec, 0 );
1031
1032                         if( p_stream->fmt.i_codec ==
1033                             VLC_FOURCC('u','n','d','f') )
1034                         {
1035                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1036                                 ( i_format_tag >> 8 ) & 0xff,
1037                                 i_format_tag & 0xff );
1038                         }
1039
1040                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1041                                  (char *)&p_stream->fmt.i_codec );
1042                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1043                                  "%dbits/sample %dkb/s",
1044                                  i_format_tag,
1045                                  p_stream->fmt.audio.i_channels,
1046                                  p_stream->fmt.audio.i_rate,
1047                                  p_stream->fmt.audio.i_bitspersample,
1048                                  p_stream->fmt.i_bitrate / 1024 );
1049                     }
1050                     /* Check for text (subtitles) header */
1051                     else if( !strncmp(st->streamtype, "text", 4) )
1052                     {
1053                         /* We need to get rid of the header packet */
1054                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1055
1056                         msg_Dbg( p_demux, "found text subtitles header" );
1057                         p_stream->fmt.i_cat = SPU_ES;
1058                         p_stream->fmt.i_codec = VLC_FOURCC('s','u','b','t');
1059                         p_stream->f_rate = 1000; /* granulepos is in milisec */
1060                     }
1061                     else
1062                     {
1063                         msg_Dbg( p_demux, "stream %d has a header marker "
1064                             "but is of an unknown type", p_ogg->i_streams-1 );
1065                         free( p_stream );
1066                         p_ogg->i_streams--;
1067                     }
1068                 }
1069                 else
1070                 {
1071                     msg_Dbg( p_demux, "stream %d is of unknown type",
1072                              p_ogg->i_streams-1 );
1073                     free( p_stream );
1074                     p_ogg->i_streams--;
1075                 }
1076
1077                 if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
1078                     return VLC_EGENERIC;
1079             }
1080
1081             /* This is the first data page, which means we are now finished
1082              * with the initial pages. We just need to store it in the relevant
1083              * bitstream. */
1084             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1085             {
1086                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
1087                                        &oggpage ) == 0 )
1088                 {
1089                     break;
1090                 }
1091             }
1092
1093             return VLC_SUCCESS;
1094         }
1095     }
1096 #undef p_stream
1097
1098     return VLC_EGENERIC;
1099 }
1100
1101 /****************************************************************************
1102  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1103  *                        Elementary streams.
1104  ****************************************************************************/
1105 static int Ogg_BeginningOfStream( demux_t *p_demux )
1106 {
1107     demux_sys_t *p_ogg = p_demux->p_sys  ;
1108     int i_stream;
1109
1110     /* Find the logical streams embedded in the physical stream and
1111      * initialize our p_ogg structure. */
1112     if( Ogg_FindLogicalStreams( p_demux ) != VLC_SUCCESS )
1113     {
1114         msg_Warn( p_demux, "couldn't find any ogg logical stream" );
1115         return VLC_EGENERIC;
1116     }
1117
1118     p_ogg->i_bitrate = 0;
1119
1120     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1121     {
1122 #define p_stream p_ogg->pp_stream[i_stream]
1123         p_stream->p_es = es_out_Add( p_demux->out, &p_stream->fmt );
1124
1125         if( p_stream->fmt.i_codec == VLC_FOURCC('c','m','m','l') )
1126         {
1127             /* Set the CMML stream active */
1128             es_out_Control( p_demux->out, ES_OUT_SET_ES, p_stream->p_es );
1129         }
1130
1131         p_ogg->i_bitrate += p_stream->fmt.i_bitrate;
1132
1133         p_stream->i_pcr = p_stream->i_previous_pcr =
1134             p_stream->i_interpolated_pcr = -1;
1135         p_stream->b_reinit = 0;
1136 #undef p_stream
1137     }
1138
1139     return VLC_SUCCESS;
1140 }
1141
1142 /****************************************************************************
1143  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1144  ****************************************************************************/
1145 static void Ogg_EndOfStream( demux_t *p_demux )
1146 {
1147     demux_sys_t *p_ogg = p_demux->p_sys  ;
1148     int i_stream;
1149
1150 #define p_stream p_ogg->pp_stream[i_stream]
1151     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1152     {
1153         if( p_stream->p_es )
1154             es_out_Del( p_demux->out, p_stream->p_es );
1155
1156         p_ogg->i_bitrate -= p_stream->fmt.i_bitrate;
1157
1158         ogg_stream_clear( &p_ogg->pp_stream[i_stream]->os );
1159         if( p_ogg->pp_stream[i_stream]->p_headers)
1160             free( p_ogg->pp_stream[i_stream]->p_headers );
1161
1162         es_format_Clean( &p_stream->fmt );
1163
1164         free( p_ogg->pp_stream[i_stream] );
1165     }
1166 #undef p_stream
1167
1168     /* Reinit p_ogg */
1169     if( p_ogg->pp_stream ) free( p_ogg->pp_stream );
1170     p_ogg->pp_stream = NULL;
1171     p_ogg->i_streams = 0;
1172 }
1173
1174 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
1175                                   ogg_packet *p_oggpacket )
1176 {
1177     bs_t bitstream;
1178     int i_fps_numerator;
1179     int i_fps_denominator;
1180     int i_keyframe_frequency_force;
1181
1182     p_stream->fmt.i_cat = VIDEO_ES;
1183     p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1184
1185     /* Signal that we want to keep a backup of the theora
1186      * stream headers. They will be used when switching between
1187      * audio streams. */
1188     p_stream->b_force_backup = 1;
1189
1190     /* Cheat and get additionnal info ;) */
1191     bs_init( &bitstream, p_oggpacket->packet, p_oggpacket->bytes );
1192     bs_skip( &bitstream, 56 );
1193     bs_read( &bitstream, 8 ); /* major version num */
1194     bs_read( &bitstream, 8 ); /* minor version num */
1195     bs_read( &bitstream, 8 ); /* subminor version num */
1196     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
1197     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
1198     bs_read( &bitstream, 24 ); /* frame width */
1199     bs_read( &bitstream, 24 ); /* frame height */
1200     bs_read( &bitstream, 8 ); /* x offset */
1201     bs_read( &bitstream, 8 ); /* y offset */
1202
1203     i_fps_numerator = bs_read( &bitstream, 32 );
1204     i_fps_denominator = bs_read( &bitstream, 32 );
1205     bs_read( &bitstream, 24 ); /* aspect_numerator */
1206     bs_read( &bitstream, 24 ); /* aspect_denominator */
1207
1208     p_stream->fmt.video.i_frame_rate = i_fps_numerator;
1209     p_stream->fmt.video.i_frame_rate_base = i_fps_denominator;
1210
1211     bs_read( &bitstream, 8 ); /* colorspace */
1212     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
1213     bs_read( &bitstream, 6 ); /* quality */
1214
1215     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
1216
1217     /* granule_shift = i_log( frequency_force -1 ) */
1218     p_stream->i_theora_keyframe_granule_shift = 0;
1219     i_keyframe_frequency_force--;
1220     while( i_keyframe_frequency_force )
1221     {
1222         p_stream->i_theora_keyframe_granule_shift++;
1223         i_keyframe_frequency_force >>= 1;
1224     }
1225
1226     p_stream->f_rate = ((float)i_fps_numerator) / i_fps_denominator;
1227 }
1228
1229 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
1230                                   ogg_packet *p_oggpacket )
1231 {
1232     oggpack_buffer opb;
1233
1234     p_stream->fmt.i_cat = AUDIO_ES;
1235     p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1236
1237     /* Signal that we want to keep a backup of the vorbis
1238      * stream headers. They will be used when switching between
1239      * audio streams. */
1240     p_stream->b_force_backup = 1;
1241
1242     /* Cheat and get additionnal info ;) */
1243     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1244     oggpack_adv( &opb, 88 );
1245     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
1246     p_stream->f_rate = p_stream->fmt.audio.i_rate =
1247         oggpack_read( &opb, 32 );
1248     oggpack_adv( &opb, 32 );
1249     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1250 }
1251
1252 static void Ogg_ReadSpeexHeader( logical_stream_t *p_stream,
1253                                  ogg_packet *p_oggpacket )
1254 {
1255     oggpack_buffer opb;
1256
1257     p_stream->fmt.i_cat = AUDIO_ES;
1258     p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
1259
1260     /* Signal that we want to keep a backup of the speex
1261      * stream headers. They will be used when switching between
1262      * audio streams. */
1263     p_stream->b_force_backup = 1;
1264
1265     /* Cheat and get additionnal info ;) */
1266     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1267     oggpack_adv( &opb, 224 );
1268     oggpack_adv( &opb, 32 ); /* speex_version_id */
1269     oggpack_adv( &opb, 32 ); /* header_size */
1270     p_stream->f_rate = p_stream->fmt.audio.i_rate = oggpack_read( &opb, 32 );
1271     oggpack_adv( &opb, 32 ); /* mode */
1272     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
1273     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
1274     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1275 }
1276
1277 static void Ogg_ReadFlacHeader( demux_t *p_demux, logical_stream_t *p_stream,
1278                                 ogg_packet *p_oggpacket )
1279 {
1280     /* Parse the STREAMINFO metadata */
1281     bs_t s;
1282
1283     bs_init( &s, p_oggpacket->packet, p_oggpacket->bytes );
1284
1285     bs_read( &s, 1 );
1286     if( bs_read( &s, 7 ) == 0 )
1287     {
1288         if( bs_read( &s, 24 ) >= 34 /*size STREAMINFO*/ )
1289         {
1290             bs_skip( &s, 80 );
1291             p_stream->f_rate = p_stream->fmt.audio.i_rate = bs_read( &s, 20 );
1292             p_stream->fmt.audio.i_channels = bs_read( &s, 3 ) + 1;
1293
1294             msg_Dbg( p_demux, "FLAC header, channels: %i, rate: %i",
1295                      p_stream->fmt.audio.i_channels, (int)p_stream->f_rate );
1296         }
1297         else msg_Dbg( p_demux, "FLAC STREAMINFO metadata too short" );
1298
1299         /* Fake this as the last metadata block */
1300         *((uint8_t*)p_oggpacket->packet) |= 0x80;
1301     }
1302     else
1303     {
1304         /* This ain't a STREAMINFO metadata */
1305         msg_Dbg( p_demux, "Invalid FLAC STREAMINFO metadata" );
1306     }
1307 }
1308
1309 static void Ogg_ReadAnnodexHeader( vlc_object_t *p_this,
1310                                    logical_stream_t *p_stream,
1311                                    ogg_packet *p_oggpacket )
1312 {
1313     if( ! strncmp( &p_oggpacket->packet[0], "Annodex", 7 ) )
1314     {
1315         oggpack_buffer opb;
1316
1317         uint16_t major_version;
1318         uint16_t minor_version;
1319         uint64_t timebase_numerator;
1320         uint64_t timebase_denominator;
1321
1322         Ogg_ReadTheoraHeader( p_stream, p_oggpacket );
1323
1324         oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1325         oggpack_adv( &opb, 8*8 ); /* "Annodex\0" header */
1326         major_version = oggpack_read( &opb, 2*8 ); /* major version */
1327         minor_version = oggpack_read( &opb, 2*8 ); /* minor version */
1328         timebase_numerator = GetQWLE( &p_oggpacket->packet[16] );
1329         timebase_denominator = GetQWLE( &p_oggpacket->packet[24] );
1330     }
1331     else if( ! strncmp( &p_oggpacket->packet[0], "AnxData", 7 ) )
1332     {
1333         uint64_t granule_rate_numerator;
1334         uint64_t granule_rate_denominator;
1335         char content_type_string[1024];
1336
1337         /* Read in Annodex header fields */
1338
1339         granule_rate_numerator = GetQWLE( &p_oggpacket->packet[8] );
1340         granule_rate_denominator = GetQWLE( &p_oggpacket->packet[16] );
1341         p_stream->secondary_header_packets =
1342             GetDWLE( &p_oggpacket->packet[24] );
1343
1344         /* we are guaranteed that the first header field will be
1345          * the content-type (by the Annodex standard) */
1346         if( !strncasecmp( &p_oggpacket->packet[28], "Content-Type: ", 14 ) )
1347         {
1348             sscanf( &p_oggpacket->packet[42], "%1024s\r\n",
1349                     content_type_string );
1350         }
1351
1352         msg_Dbg( p_this, "AnxData packet info: "I64Fd" / "I64Fd", %d, ``%s''",
1353                  granule_rate_numerator, granule_rate_denominator,
1354                  p_stream->secondary_header_packets, content_type_string );
1355
1356         p_stream->f_rate = (float) granule_rate_numerator /
1357             (float) granule_rate_denominator;
1358
1359         /* What type of file do we have?
1360          * strcmp is safe to use here because we've extracted
1361          * content_type_string from the stream manually */
1362         if( !strncmp(content_type_string, "audio/x-wav", 11) )
1363         {
1364             /* n.b. WAVs are unsupported right now */
1365             p_stream->fmt.i_cat = UNKNOWN_ES;
1366         }
1367         else if( !strncmp(content_type_string, "audio/x-vorbis", 14) )
1368         {
1369             p_stream->fmt.i_cat = AUDIO_ES;
1370             p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1371
1372             p_stream->b_force_backup = 1;
1373         }
1374         else if( !strncmp(content_type_string, "audio/x-speex", 14) )
1375         {
1376             p_stream->fmt.i_cat = AUDIO_ES;
1377             p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
1378
1379             p_stream->b_force_backup = 1;
1380         }
1381         else if( !strncmp(content_type_string, "video/x-theora", 14) )
1382         {
1383             p_stream->fmt.i_cat = VIDEO_ES;
1384             p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1385
1386             p_stream->b_force_backup = 1;
1387         }
1388         else if( !strncmp(content_type_string, "video/x-xvid", 14) )
1389         {
1390             p_stream->fmt.i_cat = VIDEO_ES;
1391             p_stream->fmt.i_codec = VLC_FOURCC( 'x','v','i','d' );
1392
1393             p_stream->b_force_backup = 1;
1394         }
1395         else if( !strncmp(content_type_string, "video/mpeg", 14) )
1396         {
1397             /* n.b. MPEG streams are unsupported right now */
1398             p_stream->fmt.i_cat = VIDEO_ES;
1399             p_stream->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1400         }
1401         else if( !strncmp(content_type_string, "text/x-cmml", 11) )
1402         {
1403             ogg_stream_packetout( &p_stream->os, p_oggpacket );
1404             p_stream->fmt.i_cat = SPU_ES;
1405             p_stream->fmt.i_codec = VLC_FOURCC( 'c','m','m','l' );
1406         }
1407     }
1408 }