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