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