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