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