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