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