]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
* modules/demux/ogg.c: provide some file info. Tested with the tarzan.ogm
[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.16 2002/12/19 23:23:24 sigmunau 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
98     mtime_t i_length;
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 demux" ) );
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           if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
385           break;
386
387         default:
388           p_stream->b_force_backup = 0;
389           break;
390         }
391     }
392
393     vlc_mutex_lock( &p_input->stream.control.control_lock );
394     if( p_stream->i_cat == AUDIO_ES && p_input->stream.control.b_mute )
395     {
396         b_trash = VLC_TRUE;
397     }
398     vlc_mutex_unlock( &p_input->stream.control.control_lock );
399
400     if( !p_stream->p_es->p_decoder_fifo || b_trash )
401     {
402         /* This stream isn't currently selected so we don't need to decode it,
403          * but we do need to store its pcr as it might be selected later on. */
404         Ogg_UpdatePCR( p_stream, p_oggpacket );
405
406         return;
407     }
408
409     if( !( p_pes = input_NewPES( p_input->p_method_data ) ) )
410     {
411         return;
412     }
413     if( !( p_data = input_NewPacket( p_input->p_method_data,
414                                      p_oggpacket->bytes ) ) )
415     {
416         input_DeletePES( p_input->p_method_data, p_pes );
417         return;
418     }
419
420     /* Convert the pcr into a pts */
421     if( p_stream->i_cat != SPU_ES )
422     {
423         p_pes->i_pts = ( p_stream->i_pcr < 0 ) ? 0 :
424             input_ClockGetTS( p_input, p_input->stream.p_selected_program,
425                               p_stream->i_pcr );
426     }
427     else
428     {
429         /* Of course subtitles had to be different! */
430         p_pes->i_pts = ( p_oggpacket->granulepos < 0 ) ? 0 :
431             input_ClockGetTS( p_input, p_input->stream.p_selected_program,
432                               p_oggpacket->granulepos * 90000 /
433                               p_stream->f_rate );
434     }
435
436     /* Convert the next granulepos into a pcr */
437     Ogg_UpdatePCR( p_stream, p_oggpacket );
438
439     p_pes->i_nb_data = 1;
440     p_pes->i_dts = p_oggpacket->granulepos;
441     p_pes->p_first = p_pes->p_last = p_data;
442     p_pes->i_pes_size = p_oggpacket->bytes;
443
444     if( p_stream->i_fourcc != VLC_FOURCC( 'v','o','r','b' ) &&
445         p_stream->i_fourcc != VLC_FOURCC( 't','a','r','k' ) &&
446         p_stream->i_fourcc != VLC_FOURCC( 't','h','e','o' ) &&
447         p_stream->i_fourcc != VLC_FOURCC( 'o','f','l','c') )
448     {
449         /* Remove the header from the packet */
450         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
451         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
452         i_header_len++;
453
454         p_pes->i_pes_size -= i_header_len;
455         p_pes->i_dts = 0;
456     }
457
458     if( p_stream->i_fourcc == VLC_FOURCC( 't','a','r','k' ) )
459     {
460         /* FIXME: the biggest hack I've ever done */
461         msg_Warn( p_input, "tark pts: "I64Fd", granule: "I64Fd,
462                   p_pes->i_pts, p_pes->i_dts );
463         msleep(10000);
464     }
465
466     memcpy( p_data->p_payload_start,
467             p_oggpacket->packet + i_header_len,
468             p_oggpacket->bytes - i_header_len );
469
470     p_data->p_payload_end = p_data->p_payload_start + p_pes->i_pes_size;
471     p_data->b_discard_payload = 0;
472
473     input_DecodePES( p_stream->p_es->p_decoder_fifo, p_pes );
474 }
475
476 /****************************************************************************
477  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
478  *                         stream and fill p_ogg.
479  *****************************************************************************
480  * The initial page of a logical stream is marked as a 'bos' page.
481  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
482  * together and all of the initial pages must appear before any data pages.
483  *
484  * On success this function returns VLC_SUCCESS.
485  ****************************************************************************/
486 static int Ogg_FindLogicalStreams( input_thread_t *p_input, demux_sys_t *p_ogg)
487 {
488     ogg_packet oggpacket;
489     ogg_page oggpage;
490     int i_stream;
491
492     while( Ogg_ReadPage( p_input, p_ogg, &oggpage ) == VLC_SUCCESS )
493     {
494         if( ogg_page_bos( &oggpage ) )
495         {
496
497             /* All is wonderful in our fine fine little world.
498              * We found the beginning of our first logical stream. */
499             while( ogg_page_bos( &oggpage ) )
500             {
501                 p_ogg->i_streams++;
502                 p_ogg->pp_stream =
503                     realloc( p_ogg->pp_stream, p_ogg->i_streams *
504                              sizeof(logical_stream_t *) );
505
506 #define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]
507
508                 p_stream = malloc( sizeof(logical_stream_t) );
509                 memset( p_stream, 0, sizeof(logical_stream_t) );
510
511                 /* Setup the logical stream */
512                 p_stream->i_serial_no = ogg_page_serialno( &oggpage );
513                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
514
515                 /* Extract the initial header from the first page and verify
516                  * the codec type of tis Ogg bitstream */
517                 if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
518                 {
519                     /* error. stream version mismatch perhaps */
520                     msg_Err( p_input, "Error reading first page of "
521                              "Ogg bitstream data" );
522                     return VLC_EGENERIC;
523                 }
524
525                 /* FIXME: check return value */
526                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
527
528                 msg_Dbg( p_input, "found string: %s", strndup( &oggpacket.packet[0], 6 ) );
529                 msg_Dbg( p_input, "oggpacket.bytes is %d", oggpacket.bytes );
530                 if( oggpacket.bytes >= 4 &&
531                     ! strncmp( &oggpacket.packet[0], "fLaC", 4 ) )
532                 {
533                     oggpack_buffer opb;
534
535                     msg_Dbg( p_input, "found flac header" );
536                     p_stream->i_cat = AUDIO_ES;
537                     p_stream->i_fourcc = VLC_FOURCC( 'o','f','l','c' );
538 #if 0
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 #endif
551                 }
552
553                 /* Check for Vorbis header */
554                 else if( oggpacket.bytes >= 7 &&
555                     ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
556                 {
557                     oggpack_buffer opb;
558
559                     msg_Dbg( p_input, "found vorbis header" );
560                     p_stream->i_cat = AUDIO_ES;
561                     p_stream->i_fourcc = VLC_FOURCC( 'v','o','r','b' );
562
563                     /* Signal that we want to keep a backup of the vorbis
564                      * stream headers. They will be used when switching between
565                      * audio streams. */
566                     p_stream->b_force_backup = 1;
567
568                     /* Cheat and get additionnal info ;) */
569                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
570                     oggpack_adv( &opb, 96 );
571                     p_stream->f_rate = oggpack_read( &opb, 32 );
572                     oggpack_adv( &opb, 32 );
573                     p_stream->i_bitrate = oggpack_read( &opb, 32 );
574                     {
575                         char title[sizeof("Stream") + 10];
576                         input_info_category_t *p_cat;
577                         sprintf( title, "Stream %d", p_ogg->i_streams );
578                         p_cat = input_InfoCategory( p_input, title );
579                         input_AddInfo( p_cat, "Type", "Audio" );
580                         input_AddInfo( p_cat, "Codec", "vorbis" );
581                         input_AddInfo( p_cat, "Sample Rate", "%f",
582                                        p_stream->f_rate );
583                         input_AddInfo( p_cat, "Bit Rate", "%d",
584                                        p_stream->i_bitrate );
585                     }
586                 }
587                 /* Check for Theora header */
588                 else if( oggpacket.bytes >= 7 &&
589                          ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
590                 {
591 #ifdef HAVE_OGGPACKB
592                     oggpack_buffer opb;
593                     int i_fps_numerator;
594                     int i_fps_denominator;
595                     int i_keyframe_frequency_force;
596 #endif
597
598                     msg_Dbg( p_input, "found theora header" );
599 #ifdef HAVE_OGGPACKB
600                     p_stream->i_cat = VIDEO_ES;
601                     p_stream->i_fourcc = VLC_FOURCC( 't','h','e','o' );
602
603                     /* Cheat and get additionnal info ;) */
604                     oggpackB_readinit(&opb, oggpacket.packet, oggpacket.bytes);
605                     oggpackB_adv( &opb, 56 );
606                     oggpackB_read( &opb, 8 ); /* major version num */
607                     oggpackB_read( &opb, 8 ); /* minor version num */
608                     oggpackB_read( &opb, 8 ); /* subminor version num */
609                     oggpackB_read( &opb, 16 ) /*<< 4*/; /* width */
610                     oggpackB_read( &opb, 16 ) /*<< 4*/; /* height */
611                     i_fps_numerator = oggpackB_read( &opb, 32 );
612                     i_fps_denominator = oggpackB_read( &opb, 32 );
613                     oggpackB_read( &opb, 24 ); /* aspect_numerator */
614                     oggpackB_read( &opb, 24 ); /* aspect_denominator */
615                     i_keyframe_frequency_force = 1 << oggpackB_read( &opb, 5 );
616                     p_stream->i_bitrate = oggpackB_read( &opb, 24 );
617                     oggpackB_read(&opb,6); /* quality */
618
619                     /* granule_shift = i_log( frequency_force -1 ) */
620                     p_stream->i_theora_keyframe_granule_shift = 0;
621                     i_keyframe_frequency_force--;
622                     while( i_keyframe_frequency_force )
623                     {
624                         p_stream->i_theora_keyframe_granule_shift++;
625                         i_keyframe_frequency_force >>= 1;
626                     }
627
628                     p_stream->f_rate = (float)i_fps_numerator /
629                                                 i_fps_denominator;
630                     msg_Dbg( p_input,
631                              "found theora header, bitrate: %i, rate: %f",
632                              p_stream->i_bitrate, p_stream->f_rate );
633                     {
634                         char title[sizeof("Stream") + 10];
635                         input_info_category_t *p_cat;
636                         sprintf( title, "Stream %d", p_ogg->i_streams );
637                         p_cat = input_InfoCategory( p_input, title );
638                         input_AddInfo( p_cat, "Type", "Video" );
639                         input_AddInfo( p_cat, "Codec", "theora" );
640                         input_AddInfo( p_cat, "Frame Rate", "%f",
641                                        p_stream->f_rate );
642                         input_AddInfo( p_cat, "Bit Rate", "%d",
643                                        p_stream->i_bitrate );
644                     }
645 #else /* HAVE_OGGPACKB */
646                     msg_Dbg( p_input, "the ogg demuxer has been compiled "
647                              "without support for the oggpackB extension."
648                              "The theora stream won't be decoded." );
649                     free( p_stream );
650                     p_ogg->i_streams--;
651                     continue;
652 #endif /* HAVE_OGGPACKB */
653                 }
654                 /* Check for Tarkin header */
655                 else if( oggpacket.bytes >= 7 &&
656                          ! strncmp( &oggpacket.packet[1], "tarkin", 6 ) )
657                 {
658                     oggpack_buffer opb;
659
660                     msg_Dbg( p_input, "found tarkin header" );
661                     p_stream->i_cat = VIDEO_ES;
662                     p_stream->i_fourcc = VLC_FOURCC( 't','a','r','k' );
663
664                     /* Cheat and get additionnal info ;) */
665                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
666                     oggpack_adv( &opb, 88 );
667                     oggpack_adv( &opb, 104 );
668                     p_stream->i_bitrate = oggpack_read( &opb, 32 );
669                     p_stream->f_rate = 2; /* FIXME */
670                     msg_Dbg( p_input,
671                              "found tarkin header, bitrate: %i, rate: %f",
672                              p_stream->i_bitrate, p_stream->f_rate );
673                                         {
674                         char title[sizeof("Stream") + 10];
675                         input_info_category_t *p_cat;
676                         sprintf( title, "Stream %d", p_ogg->i_streams );
677                         p_cat = input_InfoCategory( p_input, title );
678                         input_AddInfo( p_cat, "Type", "Video" );
679                         input_AddInfo( p_cat, "Codec", "tarkin" );
680                         input_AddInfo( p_cat, "Sample Rate", "%f",
681                                        p_stream->f_rate );
682                         input_AddInfo( p_cat, "Bit Rate", "%d",
683                                        p_stream->i_bitrate );
684                     }
685
686                 }
687                 else if( oggpacket.bytes >= 142 &&
688                          !strncmp( &oggpacket.packet[1],
689                                    "Direct Show Samples embedded in Ogg", 35 ))
690                 {
691                     /* Old header type */
692
693                     /* Check for video header (old format) */
694                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
695                         oggpacket.bytes >= 184 )
696                     {
697                         p_stream->i_cat = VIDEO_ES;
698
699                         p_stream->p_bih = (BITMAPINFOHEADER *)
700                             malloc( sizeof(BITMAPINFOHEADER) );
701                         if( !p_stream->p_bih )
702                         {
703                             /* Mem allocation error, just ignore the stream */
704                             free( p_stream );
705                             p_ogg->i_streams--;
706                             continue;
707                         }
708                         p_stream->p_bih->biSize = sizeof(BITMAPINFOHEADER);
709                         p_stream->p_bih->biCompression= p_stream->i_fourcc =
710                             VLC_FOURCC( oggpacket.packet[68],
711                                         oggpacket.packet[69],
712                                         oggpacket.packet[70],
713                                         oggpacket.packet[71] );
714                         msg_Dbg( p_input, "found video header of type: %.4s",
715                                  (char *)&p_stream->i_fourcc );
716
717                         p_stream->f_rate = 10000000.0 /
718                             GetQWLE((oggpacket.packet+164));
719                         p_stream->p_bih->biBitCount =
720                             GetWLE((oggpacket.packet+182));
721                         if( !p_stream->p_bih->biBitCount )
722                             p_stream->p_bih->biBitCount=24; // hack, FIXME
723                         p_stream->p_bih->biWidth =
724                             GetDWLE((oggpacket.packet+176));
725                         p_stream->p_bih->biHeight =
726                             GetDWLE((oggpacket.packet+180));
727                         p_stream->p_bih->biPlanes= 1 ;
728                         p_stream->p_bih->biSizeImage =
729                             (p_stream->p_bih->biBitCount >> 3) *
730                             p_stream->p_bih->biWidth *
731                             p_stream->p_bih->biHeight;
732
733                         msg_Dbg( p_input,
734                              "fps: %f, width:%i; height:%i, bitcount:%i",
735                             p_stream->f_rate, p_stream->p_bih->biWidth,
736                             p_stream->p_bih->biHeight,
737                             p_stream->p_bih->biBitCount);
738                         {
739                             char title[sizeof("Stream") + 10];
740                             input_info_category_t *p_cat;
741                             sprintf( title, "Stream %d", p_ogg->i_streams );
742                             p_cat = input_InfoCategory( p_input, title );
743                             input_AddInfo( p_cat, "Type", "Video" );
744                             input_AddInfo( p_cat, "Codec", "%.4s",
745                                            (char *)&p_stream->i_fourcc );
746                             input_AddInfo( p_cat, "Frame Rate", "%f",
747                                            p_stream->f_rate );
748                             input_AddInfo( p_cat, "Bit Count", "%d",
749                                            p_stream->p_bih->biBitCount );
750                             input_AddInfo( p_cat, "Width", "%d",
751                                            p_stream->p_bih->biWidth );
752                             input_AddInfo( p_cat, "Height", "%d",
753                                            p_stream->p_bih->biHeight );
754                         }
755                         p_stream->i_bitrate = 0;
756                     }
757                     /* Check for audio header (old format) */
758                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
759                     {
760                         unsigned int i_extra_size;
761
762                         p_stream->i_cat = AUDIO_ES;
763
764                         i_extra_size = GetWLE((oggpacket.packet+140));
765
766                         p_stream->p_wf = (WAVEFORMATEX *)
767                             malloc( sizeof(WAVEFORMATEX) + i_extra_size );
768                         if( !p_stream->p_wf )
769                         {
770                             /* Mem allocation error, just ignore the stream */
771                             free( p_stream );
772                             p_ogg->i_streams--;
773                             continue;
774                         }
775
776                         p_stream->p_wf->wFormatTag =
777                             GetWLE((oggpacket.packet+124));
778                         p_stream->p_wf->nChannels =
779                             GetWLE((oggpacket.packet+126));
780                         p_stream->f_rate = p_stream->p_wf->nSamplesPerSec =
781                             GetDWLE((oggpacket.packet+128));
782                         p_stream->i_bitrate = p_stream->p_wf->nAvgBytesPerSec =
783                             GetDWLE((oggpacket.packet+132));
784                         p_stream->i_bitrate *= 8;
785                         p_stream->p_wf->nBlockAlign =
786                             GetWLE((oggpacket.packet+136));
787                         p_stream->p_wf->wBitsPerSample =
788                             GetWLE((oggpacket.packet+138));
789                         p_stream->p_wf->cbSize = i_extra_size;
790
791                         if( i_extra_size > 0 )
792                             memcpy( p_stream->p_wf+sizeof(WAVEFORMATEX),
793                                     oggpacket.packet+142, i_extra_size );
794
795                         switch( p_stream->p_wf->wFormatTag )
796                         {
797                         case WAVE_FORMAT_PCM:
798                             p_stream->i_fourcc =
799                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
800                             break;
801                         case WAVE_FORMAT_MPEG:
802                         case WAVE_FORMAT_MPEGLAYER3:
803                             p_stream->i_fourcc =
804                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
805                             break;
806                         case WAVE_FORMAT_A52:
807                             p_stream->i_fourcc =
808                                 VLC_FOURCC( 'a', '5', '2', ' ' );
809                             break;
810                         case WAVE_FORMAT_WMA1:
811                             p_stream->i_fourcc =
812                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
813                             break;
814                         case WAVE_FORMAT_WMA2:
815                             p_stream->i_fourcc =
816                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
817                             break;
818                         default:
819                             p_stream->i_fourcc = VLC_FOURCC( 'm', 's',
820                                 ( p_stream->p_wf->wFormatTag >> 8 ) & 0xff,
821                                 p_stream->p_wf->wFormatTag & 0xff );
822                         }
823
824                         msg_Dbg( p_input, "found audio header of type: %.4s",
825                                  (char *)&p_stream->i_fourcc );
826                         msg_Dbg( p_input, "audio:0x%4.4x channels:%d %dHz "
827                                  "%dbits/sample %dkb/s",
828                                  p_stream->p_wf->wFormatTag,
829                                  p_stream->p_wf->nChannels,
830                                  p_stream->p_wf->nSamplesPerSec,
831                                  p_stream->p_wf->wBitsPerSample,
832                                  p_stream->p_wf->nAvgBytesPerSec * 8 / 1024 );
833                         {
834                             char title[sizeof("Stream") + 10];
835                             input_info_category_t *p_cat;
836                             sprintf( title, "Stream %d", p_ogg->i_streams );
837                             p_cat = input_InfoCategory( p_input, title );
838                             input_AddInfo( p_cat, "Type", "Audio" );
839                             input_AddInfo( p_cat, "Codec", "%.4s", 
840                                            (char *)&p_stream->i_fourcc );
841                             input_AddInfo( p_cat, "Sample Rate", "%d",
842                                            p_stream->p_wf->nSamplesPerSec );
843                             input_AddInfo( p_cat, "Bit Rate", "%d",
844                                            p_stream->p_wf->nAvgBytesPerSec * 8
845                                               / 1024 );
846                             input_AddInfo( p_cat, "Channels", "%d",
847                                            p_stream->p_wf->nChannels );
848                             input_AddInfo( p_cat, "Bits per Sample", "%d",
849                                            p_stream->p_wf->wBitsPerSample );
850                         }
851
852                     }
853                     else
854                     {
855                         msg_Dbg( p_input, "stream %d has an old header "
856                             "but is of an unknown type", p_ogg->i_streams-1 );
857                         free( p_stream );
858                         p_ogg->i_streams--;
859                     }
860                 }
861                 else if( (*oggpacket.packet & PACKET_TYPE_BITS )
862                          == PACKET_TYPE_HEADER && 
863                          oggpacket.bytes >= (int)sizeof(stream_header)+1 )
864                 {
865                     stream_header *st = (stream_header *)(oggpacket.packet+1);
866
867                     /* Check for video header (new format) */
868                     if( !strncmp( st->streamtype, "video", 5 ) )
869                     {
870                         p_stream->i_cat = VIDEO_ES;
871
872                         /* We need to get rid of the header packet */
873                         ogg_stream_packetout( &p_stream->os, &oggpacket );
874
875                         p_stream->p_bih = (BITMAPINFOHEADER *)
876                             malloc( sizeof(BITMAPINFOHEADER) );
877                         if( !p_stream->p_bih )
878                         {
879                             /* Mem allocation error, just ignore the stream */
880                             free( p_stream );
881                             p_ogg->i_streams--;
882                             continue;
883                         }
884                         p_stream->p_bih->biSize = sizeof(BITMAPINFOHEADER);
885                         p_stream->p_bih->biCompression=
886                             p_stream->i_fourcc = VLC_FOURCC( st->subtype[0],
887                                                              st->subtype[1],
888                                                              st->subtype[2],
889                                                              st->subtype[3] );
890                         msg_Dbg( p_input, "found video header of type: %.4s",
891                                  (char *)&p_stream->i_fourcc );
892
893                         p_stream->f_rate = 10000000.0 /
894                             GetQWLE((uint8_t *)&st->time_unit);
895                         p_stream->p_bih->biBitCount =
896                             GetWLE((uint8_t *)&st->bits_per_sample);
897                         p_stream->p_bih->biWidth =
898                             GetDWLE((uint8_t *)&st->sh.video.width);
899                         p_stream->p_bih->biHeight =
900                             GetDWLE((uint8_t *)&st->sh.video.height);
901                         p_stream->p_bih->biPlanes= 1 ;
902                         p_stream->p_bih->biSizeImage =
903                             (p_stream->p_bih->biBitCount >> 3) *
904                             p_stream->p_bih->biWidth *
905                             p_stream->p_bih->biHeight;
906
907                         msg_Dbg( p_input,
908                              "fps: %f, width:%i; height:%i, bitcount:%i",
909                             p_stream->f_rate, p_stream->p_bih->biWidth,
910                             p_stream->p_bih->biHeight,
911                             p_stream->p_bih->biBitCount);
912
913                         {
914                             char title[sizeof("Stream") + 10];
915                             input_info_category_t *p_cat;
916                             sprintf( title, "Stream %d", p_ogg->i_streams );
917                             p_cat = input_InfoCategory( p_input, title );
918                             input_AddInfo( p_cat, "Type", "Video" );
919                             input_AddInfo( p_cat, "Codec", "%.4s",
920                                            (char *)&p_stream->i_fourcc );
921                             input_AddInfo( p_cat, "Frame Rate", "%f",
922                                            p_stream->f_rate );
923                             input_AddInfo( p_cat, "Bit Count", "%d",
924                                            p_stream->p_bih->biBitCount );
925                             input_AddInfo( p_cat, "Width", "%d",
926                                            p_stream->p_bih->biWidth );
927                             input_AddInfo( p_cat, "Height", "%d",
928                                            p_stream->p_bih->biHeight );
929                         }
930                         p_stream->i_bitrate = 0;
931                     }
932                     /* Check for audio header (new format) */
933                     else if( !strncmp( st->streamtype, "audio", 5 ) )
934                     {
935                         char p_buffer[5];
936
937                         p_stream->i_cat = AUDIO_ES;
938
939                         /* We need to get rid of the header packet */
940                         ogg_stream_packetout( &p_stream->os, &oggpacket );
941
942                         p_stream->p_wf = (WAVEFORMATEX *)
943                             malloc( sizeof(WAVEFORMATEX) );
944                         if( !p_stream->p_wf )
945                         {
946                             /* Mem allocation error, just ignore the stream */
947                             free( p_stream );
948                             p_ogg->i_streams--;
949                             continue;
950                         }
951
952                         memcpy( p_buffer, st->subtype, 4 );
953                         p_buffer[4] = '\0';
954                         p_stream->p_wf->wFormatTag = strtol(p_buffer,NULL,16);
955                         p_stream->p_wf->nChannels =
956                             GetWLE((uint8_t *)&st->sh.audio.channels);
957                         p_stream->f_rate = p_stream->p_wf->nSamplesPerSec =
958                             GetQWLE((uint8_t *)&st->samples_per_unit);
959                         p_stream->i_bitrate = p_stream->p_wf->nAvgBytesPerSec =
960                             GetDWLE((uint8_t *)&st->sh.audio.avgbytespersec);
961                         p_stream->i_bitrate *= 8;
962                         p_stream->p_wf->nBlockAlign =
963                             GetWLE((uint8_t *)&st->sh.audio.blockalign);
964                         p_stream->p_wf->wBitsPerSample =
965                             GetWLE((uint8_t *)&st->bits_per_sample);
966                         p_stream->p_wf->cbSize = 0;
967
968                         switch( p_stream->p_wf->wFormatTag )
969                         {
970                         case WAVE_FORMAT_PCM:
971                             p_stream->i_fourcc =
972                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
973                             break;
974                         case WAVE_FORMAT_MPEG:
975                         case WAVE_FORMAT_MPEGLAYER3:
976                             p_stream->i_fourcc =
977                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
978                             break;
979                         case WAVE_FORMAT_A52:
980                             p_stream->i_fourcc =
981                                 VLC_FOURCC( 'a', '5', '2', ' ' );
982                             break;
983                         case WAVE_FORMAT_WMA1:
984                             p_stream->i_fourcc =
985                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
986                             break;
987                         case WAVE_FORMAT_WMA2:
988                             p_stream->i_fourcc =
989                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
990                             break;
991                         default:
992                             p_stream->i_fourcc = VLC_FOURCC( 'm', 's',
993                                 ( p_stream->p_wf->wFormatTag >> 8 ) & 0xff,
994                                 p_stream->p_wf->wFormatTag & 0xff );
995                         }
996
997                         msg_Dbg( p_input, "found audio header of type: %.4s",
998                                  (char *)&p_stream->i_fourcc );
999                         msg_Dbg( p_input, "audio:0x%4.4x channels:%d %dHz "
1000                                  "%dbits/sample %dkb/s",
1001                                  p_stream->p_wf->wFormatTag,
1002                                  p_stream->p_wf->nChannels,
1003                                  p_stream->p_wf->nSamplesPerSec,
1004                                  p_stream->p_wf->wBitsPerSample,
1005                                  p_stream->p_wf->nAvgBytesPerSec * 8 / 1024 );
1006                         {
1007                             char title[sizeof("Stream") + 10];
1008                             input_info_category_t *p_cat;
1009                             sprintf( title, "Stream %d", p_ogg->i_streams );
1010                             p_cat = input_InfoCategory( p_input, title );
1011                             input_AddInfo( p_cat, "Type", "Audio" );
1012                             input_AddInfo( p_cat, "Codec", "%.4s", 
1013                                            (char *)&p_stream->i_fourcc );
1014                             input_AddInfo( p_cat, "Sample Rate", "%d",
1015                                            p_stream->p_wf->nSamplesPerSec );
1016                             input_AddInfo( p_cat, "Bit Rate", "%d",
1017                                            p_stream->p_wf->nAvgBytesPerSec * 8
1018                                               / 1024 );
1019                             input_AddInfo( p_cat, "Channels", "%d",
1020                                            p_stream->p_wf->nChannels );
1021                             input_AddInfo( p_cat, "Bits per Sample", "%d",
1022                                            p_stream->p_wf->wBitsPerSample );
1023                         }
1024                     }
1025                     /* Check for text (subtitles) header */
1026                     else if( !strncmp(st->streamtype, "text", 4) )
1027                     {
1028                         /* We need to get rid of the header packet */
1029                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1030
1031                         msg_Dbg( p_input, "found text subtitles header" );
1032                         p_stream->i_cat = SPU_ES;
1033                         p_stream->i_fourcc =
1034                             VLC_FOURCC( 's', 'u', 'b', 't' );
1035                         p_stream->f_rate = 1000; /* granulepos is in milisec */
1036                     }
1037                     else
1038                     {
1039                         msg_Dbg( p_input, "stream %d has a header marker "
1040                             "but is of an unknown type", p_ogg->i_streams-1 );
1041                         free( p_stream );
1042                         p_ogg->i_streams--;
1043                     }
1044                 }
1045                 else
1046                 {
1047                     msg_Dbg( p_input, "stream %d is of unknown type",
1048                              p_ogg->i_streams-1 );
1049                     free( p_stream );
1050                     p_ogg->i_streams--;
1051                 }
1052
1053 #undef p_stream
1054
1055                 if( Ogg_ReadPage( p_input, p_ogg, &oggpage ) != VLC_SUCCESS )
1056                     return VLC_EGENERIC;
1057             }
1058
1059             /* This is the first data page, which means we are now finished
1060              * with the initial pages. We just need to store it in the relevant
1061              * bitstream. */
1062             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1063             {
1064                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
1065                                        &oggpage ) == 0 )
1066                 {
1067                     break;
1068                 }
1069             }
1070             return VLC_SUCCESS;
1071         }
1072     }
1073     return VLC_EGENERIC;
1074 }
1075
1076 /*****************************************************************************
1077  * Activate: initializes ogg demux structures
1078  *****************************************************************************/
1079 static int Activate( vlc_object_t * p_this )
1080 {
1081     int i_stream, b_forced;
1082     demux_sys_t    *p_ogg;
1083     input_thread_t *p_input = (input_thread_t *)p_this;
1084
1085     p_input->p_demux_data = NULL;
1086     b_forced = ( ( *p_input->psz_demux )&&
1087                  ( !strncmp( p_input->psz_demux, "ogg", 10 ) ) ) ? 1 : 0;
1088
1089     /* Check if we are dealing with an ogg stream */
1090     if( !b_forced && ( Ogg_Check( p_input ) != VLC_SUCCESS ) )
1091         return -1;
1092
1093     /* Allocate p_ogg */
1094     if( !( p_ogg = malloc( sizeof( demux_sys_t ) ) ) )
1095     {
1096         msg_Err( p_input, "out of memory" );
1097         goto error;
1098     }
1099     memset( p_ogg, 0, sizeof( demux_sys_t ) );
1100     p_input->p_demux_data = p_ogg;
1101
1102     p_ogg->i_pcr  = 0;
1103     p_ogg->b_seekable = ( ( p_input->stream.b_seekable )
1104                         &&( p_input->stream.i_method == INPUT_METHOD_FILE ) );
1105
1106     /* Initialize the Ogg physical bitstream parser */
1107     ogg_sync_init( &p_ogg->oy );
1108
1109     /* Find the logical streams embedded in the physical stream and
1110      * initialize our p_ogg structure. */
1111     if( Ogg_FindLogicalStreams( p_input, p_ogg ) != VLC_SUCCESS )
1112     {
1113         msg_Err( p_input, "couldn't find an ogg logical stream" );
1114         goto error;
1115     }
1116
1117     /* Set the demux function */
1118     p_input->pf_demux = Demux;
1119
1120     /* Initialize access plug-in structures. */
1121     if( p_input->i_mtu == 0 )
1122     {
1123         /* Improve speed. */
1124         p_input->i_bufsize = INPUT_DEFAULT_BUFSIZE;
1125     }
1126
1127     /* Create one program */
1128     vlc_mutex_lock( &p_input->stream.stream_lock );
1129     if( input_InitStream( p_input, 0 ) == -1)
1130     {
1131         vlc_mutex_unlock( &p_input->stream.stream_lock );
1132         msg_Err( p_input, "cannot init stream" );
1133         goto error;
1134     }
1135     if( input_AddProgram( p_input, 0, 0) == NULL )
1136     {
1137         vlc_mutex_unlock( &p_input->stream.stream_lock );
1138         msg_Err( p_input, "cannot add program" );
1139         goto error;
1140     }
1141     p_input->stream.p_selected_program = p_input->stream.pp_programs[0];
1142     p_input->stream.i_mux_rate = 0;
1143     vlc_mutex_unlock( &p_input->stream.stream_lock );
1144
1145     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1146     {
1147 #define p_stream p_ogg->pp_stream[i_stream]
1148         vlc_mutex_lock( &p_input->stream.stream_lock );
1149         p_stream->p_es = input_AddES( p_input,
1150                                       p_input->stream.p_selected_program,
1151                                       p_ogg->i_streams + 1, 0 );
1152         p_input->stream.i_mux_rate += (p_stream->i_bitrate / ( 8 * 50 ));
1153         vlc_mutex_unlock( &p_input->stream.stream_lock );
1154         p_stream->p_es->i_stream_id = p_stream->p_es->i_id = i_stream;
1155         p_stream->p_es->i_fourcc = p_stream->i_fourcc;
1156         p_stream->p_es->i_cat = p_stream->i_cat;
1157         p_stream->p_es->p_demux_data = p_stream->p_bih ?
1158             (void *)p_stream->p_bih : (void *)p_stream->p_wf;
1159 #undef p_stream
1160     }
1161
1162     for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1163     {
1164 #define p_stream  p_ogg->pp_stream[i_stream]
1165         switch( p_stream->p_es->i_cat )
1166         {
1167             case( VIDEO_ES ):
1168                 if( (p_ogg->p_stream_video == NULL) )
1169                 {
1170                     p_ogg->p_stream_video = p_stream;
1171                     /* TODO add test to see if a decoder has been found */
1172                     Ogg_StreamStart( p_input, p_ogg, i_stream );
1173                 }
1174                 break;
1175
1176             case( AUDIO_ES ):
1177                 if( (p_ogg->p_stream_audio == NULL) )
1178                 {
1179                     int i_audio = config_GetInt( p_input, "audio-channel" );
1180                     if( i_audio == i_stream || i_audio <= 0 ||
1181                         i_audio >= p_ogg->i_streams ||
1182                         p_ogg->pp_stream[i_audio]->p_es->i_cat != AUDIO_ES )
1183                     {
1184                         p_ogg->p_stream_audio = p_stream;
1185                         Ogg_StreamStart( p_input, p_ogg, i_stream );
1186                     }
1187                 }
1188                 break;
1189
1190             case( SPU_ES ):
1191                 if( (p_ogg->p_stream_spu == NULL) )
1192                 {
1193                     /* for spu, default is none */
1194                     int i_spu = config_GetInt( p_input, "spu-channel" );
1195                     if( i_spu < 0 || i_spu >= p_ogg->i_streams ||
1196                         p_ogg->pp_stream[i_spu]->p_es->i_cat != SPU_ES )
1197                     {
1198                         break;
1199                     }
1200                     else if( i_spu == i_stream )
1201                     {
1202                         p_ogg->p_stream_spu = p_stream;
1203                         Ogg_StreamStart( p_input, p_ogg, i_stream );
1204                     }
1205                 }
1206                 break;
1207
1208             default:
1209                 break;
1210         }
1211 #undef p_stream
1212     }
1213
1214     /* we select the first audio and video ES */
1215     vlc_mutex_lock( &p_input->stream.stream_lock );
1216     if( !p_ogg->p_stream_video )
1217     {
1218         msg_Warn( p_input, "no video stream found" );
1219     }
1220     if( !p_ogg->p_stream_audio )
1221     {
1222         msg_Warn( p_input, "no audio stream found!" );
1223     }
1224     p_input->stream.p_selected_program->b_is_ok = 1;
1225     vlc_mutex_unlock( &p_input->stream.stream_lock );
1226
1227     /* Call the pace control */
1228     input_ClockManageRef( p_input,
1229                           p_input->stream.p_selected_program,
1230                           p_ogg->i_pcr );
1231
1232     return 0;
1233
1234  error:
1235     Deactivate( (vlc_object_t *)p_input );
1236     return -1;
1237
1238 }
1239
1240 /*****************************************************************************
1241  * Deactivate: frees unused data
1242  *****************************************************************************/
1243 static void Deactivate( vlc_object_t *p_this )
1244 {
1245     input_thread_t *p_input = (input_thread_t *)p_this;
1246     demux_sys_t *p_ogg = (demux_sys_t *)p_input->p_demux_data  ; 
1247     int i, j;
1248
1249     if( p_ogg )
1250     {
1251         /* Cleanup the bitstream parser */
1252         ogg_sync_clear( &p_ogg->oy );
1253
1254         for( i = 0; i < p_ogg->i_streams; i++ )
1255         {
1256             ogg_stream_clear( &p_ogg->pp_stream[i]->os );
1257             for( j = 0; j < p_ogg->pp_stream[i]->i_packets_backup; j++ )
1258             {
1259                 free( p_ogg->pp_stream[i]->p_packets_backup[j].packet );
1260             }
1261             if( p_ogg->pp_stream[i]->p_packets_backup)
1262                 free( p_ogg->pp_stream[i]->p_packets_backup );
1263 #if 0 /* hmmm, it's already freed in input_DelES() */
1264             if( p_ogg->pp_stream[i]->p_bih )
1265                 free( p_ogg->pp_stream[i]->p_bih );
1266             if( p_ogg->pp_stream[i]->p_wf )
1267                 free( p_ogg->pp_stream[i]->p_wf );
1268 #endif
1269             free( p_ogg->pp_stream[i] );
1270         }
1271         if( p_ogg->pp_stream ) free( p_ogg->pp_stream );
1272
1273         free( p_ogg );
1274     }
1275 }
1276
1277 /*****************************************************************************
1278  * Demux: reads and demuxes data packets
1279  *****************************************************************************
1280  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1281  *****************************************************************************/
1282 static int Demux( input_thread_t * p_input )
1283 {
1284     int i, i_stream, b_eos = 0;
1285     ogg_page    oggpage;
1286     ogg_packet  oggpacket;
1287     demux_sys_t *p_ogg  = (demux_sys_t *)p_input->p_demux_data;
1288
1289 #define p_stream p_ogg->pp_stream[i_stream]
1290     /* detect new selected/unselected streams */
1291     for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1292     {
1293         if( p_stream->p_es )
1294         {
1295             if( p_stream->p_es->p_decoder_fifo &&
1296                 !p_stream->i_activated )
1297             {
1298                 Ogg_StreamStart( p_input, p_ogg, i_stream );
1299             }
1300             else
1301             if( !p_stream->p_es->p_decoder_fifo &&
1302                 p_stream->i_activated )
1303             {
1304                 Ogg_StreamStop( p_input, p_ogg, i_stream );
1305             }
1306         }
1307     }
1308
1309     /* search for new video and audio stream to select
1310      * if current have been unselected */
1311     if( ( !p_ogg->p_stream_video )
1312             || ( !p_ogg->p_stream_video->p_es->p_decoder_fifo ) )
1313     {
1314         p_ogg->p_stream_video = NULL;
1315         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1316         {
1317             if( ( p_stream->i_cat == VIDEO_ES )
1318                   &&( p_stream->p_es->p_decoder_fifo ) )
1319             {
1320                 p_ogg->p_stream_video = p_stream;
1321                 break;
1322             }
1323         }
1324     }
1325     if( ( !p_ogg->p_stream_audio )
1326             ||( !p_ogg->p_stream_audio->p_es->p_decoder_fifo ) )
1327     {
1328         p_ogg->p_stream_audio = NULL;
1329         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1330         {
1331             if( ( p_stream->i_cat == AUDIO_ES )
1332                   &&( p_stream->p_es->p_decoder_fifo ) )
1333             {
1334                 p_ogg->p_stream_audio = p_stream;
1335                 break;
1336             }
1337         }
1338     }
1339
1340     if( p_input->stream.p_selected_program->i_synchro_state == SYNCHRO_REINIT )
1341     {
1342         msg_Warn( p_input, "synchro reinit" );
1343
1344         /* An ogg packet does only contain the starting date of the next
1345          * packet, not its own starting date.
1346          * As a quick work around, we just skip an oggpage */
1347
1348         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1349         {
1350             /* we'll trash all the data until we find the next pcr */
1351             p_stream->b_reinit = 1;
1352             p_stream->i_pcr = -1;
1353             p_stream->i_interpolated_pcr = -1;
1354         }
1355         p_ogg->b_reinit = 1;
1356     }
1357
1358
1359     /*
1360      * Demux ogg pages from the stream
1361      */
1362     for( i = 0; i < PAGES_READ_ONCE || p_ogg->b_reinit;  i++ )
1363     {
1364         if( Ogg_ReadPage( p_input, p_ogg, &oggpage ) != VLC_SUCCESS )
1365         {
1366             b_eos = 1;
1367             break;
1368         }
1369
1370         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1371         {
1372             if( ogg_stream_pagein( &p_stream->os, &oggpage ) != 0 )
1373                 continue;
1374
1375             while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
1376             {
1377                 if( !p_stream->p_es )
1378                 {
1379                     break;
1380                 }
1381
1382                 if( p_stream->b_reinit )
1383                 {
1384                     if( oggpacket.granulepos >= 0 )
1385                     {
1386                         p_stream->b_reinit = 0;
1387
1388                         /* Convert the next granulepos into a pcr */
1389                         Ogg_UpdatePCR( p_stream, &oggpacket );
1390
1391                         /* Call the pace control to reinitialize
1392                          * the system clock */
1393                          input_ClockManageRef( p_input,
1394                              p_input->stream.p_selected_program,
1395                              p_stream->i_pcr );
1396
1397                          if( (!p_ogg->p_stream_video ||
1398                               !p_ogg->p_stream_video->b_reinit) &&
1399                              (!p_ogg->p_stream_audio ||
1400                               !p_ogg->p_stream_audio->b_reinit) )
1401                          {
1402                              p_ogg->b_reinit = 0;
1403                          }
1404                     }
1405                     continue;
1406                 }
1407
1408                 Ogg_DecodePacket( p_input, p_stream, &oggpacket );
1409
1410             }
1411         }
1412     }
1413
1414     i_stream = 0;
1415     p_ogg->i_pcr = p_stream->i_interpolated_pcr;
1416     for( ; i_stream < p_ogg->i_streams; i_stream++ )
1417     {
1418         if( p_stream->i_cat == SPU_ES )
1419             continue;
1420
1421         if( p_stream->i_interpolated_pcr < p_ogg->i_pcr )
1422             p_ogg->i_pcr = p_stream->i_interpolated_pcr;
1423     }
1424 #undef p_stream
1425
1426
1427     /* Call the pace control */
1428     input_ClockManageRef( p_input, p_input->stream.p_selected_program,
1429                           p_ogg->i_pcr );
1430
1431     /* Did we reach the end of stream ? */
1432     return( b_eos ? 0 : 1 );
1433 }