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