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