]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
e9b8a342bb59761e89d1a6c09b20a07e2bba911c
[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.7 2002/11/05 21:57: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     long    l_previous_granulepos;
69
70     /* info from logical streams */
71     double i_rate;
72     int i_bitrate;
73     int b_reinit;
74
75     BITMAPINFOHEADER *p_bih;
76     WAVEFORMATEX *p_wf;
77
78 } logical_stream_t;
79
80 struct demux_sys_t
81 {
82     ogg_sync_state oy;        /* sync and verify incoming physical bitstream */
83
84     int i_streams;                           /* number of logical bitstreams */
85     logical_stream_t **pp_stream;  /* pointer to an array of logical streams */
86
87     /* current audio and video es */
88     logical_stream_t *p_stream_video;
89     logical_stream_t *p_stream_audio;
90
91     /* stream we use as a time reference for demux reading speed */
92     logical_stream_t *p_stream_timeref;
93
94     /* program clock reference (in units of 90kHz) derived from the pcr of
95      * one of the sub-streams (p_stream_timeref) */
96     mtime_t i_pcr;
97
98     mtime_t i_length;
99     int     b_seekable;
100 };
101
102 /* OggDS headers for the new header format (used in ogm files) */
103 typedef struct stream_header_video
104 {
105     ogg_int32_t width;
106     ogg_int32_t height;
107 } stream_header_video;
108         
109 typedef struct stream_header_audio
110 {
111     ogg_int16_t channels;
112     ogg_int16_t blockalign;
113     ogg_int32_t avgbytespersec;
114 } stream_header_audio;
115
116 typedef struct stream_header
117 {
118     char        streamtype[8];
119     char        subtype[4];
120
121     ogg_int32_t size;                               /* size of the structure */
122
123     ogg_int64_t time_unit;                              /* in reference time */
124     ogg_int64_t samples_per_unit;
125     ogg_int32_t default_len;                                /* in media time */
126
127     ogg_int32_t buffersize;
128     ogg_int16_t bits_per_sample;
129
130     union
131     {
132         /* Video specific */
133         stream_header_video video;
134         /* Audio specific */
135         stream_header_audio audio;
136     } sh;
137 } stream_header;
138
139 /* Some defines from OggDS */
140 #define PACKET_TYPE_HEADER   0x01
141 #define PACKET_TYPE_BITS     0x07
142 #define PACKET_LEN_BITS01    0xc0
143 #define PACKET_LEN_BITS2     0x02
144 #define PACKET_IS_SYNCPOINT  0x08
145
146 /* Some functions to manipulate memory */
147 static uint16_t GetWLE( uint8_t *p_buff )
148 {
149     return( (p_buff[0]) + ( p_buff[1] <<8 ) );
150 }
151
152 static uint32_t GetDWLE( uint8_t *p_buff )
153 {
154     return( p_buff[0] + ( p_buff[1] <<8 ) +
155             ( p_buff[2] <<16 ) + ( p_buff[3] <<24 ) );
156 }
157
158 static uint64_t GetQWLE( uint8_t *p_buff )
159 {
160     return( GetDWLE( p_buff ) + ( ((uint64_t)GetDWLE( p_buff + 4 )) << 32 ) );
161 }
162 /*****************************************************************************
163  * Local prototypes
164  *****************************************************************************/
165 static int  Activate  ( vlc_object_t * );
166 static void Deactivate( vlc_object_t * );
167 static int  Demux     ( input_thread_t * );
168
169 /* Stream managment */
170 static int  Ogg_StreamStart  ( input_thread_t *, demux_sys_t *, int );
171 static int  Ogg_StreamSeek   ( input_thread_t *, demux_sys_t *, int, mtime_t );
172 static void Ogg_StreamStop   ( input_thread_t *, demux_sys_t *, int );
173
174 /* Bitstream manipulation */
175 static int  Ogg_Check        ( input_thread_t *p_input );
176 static int  Ogg_ReadPage     ( input_thread_t *, demux_sys_t *, ogg_page * );
177 static void Ogg_DecodePacket ( input_thread_t *p_input,
178                                logical_stream_t *p_stream,
179                                ogg_packet *p_oggpacket );
180 static int  Ogg_FindLogicalStreams( input_thread_t *p_input,
181                                     demux_sys_t *p_ogg );
182
183 /*****************************************************************************
184  * Module descriptor
185  *****************************************************************************/
186 vlc_module_begin();
187     set_description( _("ogg stream demux" ) );
188     set_capability( "demux", 50 );
189     set_callbacks( Activate, Deactivate );
190     add_shortcut( "ogg" );
191 vlc_module_end();
192
193 /*****************************************************************************
194  * Stream managment
195  *****************************************************************************/
196 static int Ogg_StreamStart( input_thread_t *p_input,
197                             demux_sys_t *p_ogg, int i_stream )
198 {
199 #define p_stream p_ogg->pp_stream[i_stream]
200     if( !p_stream->p_es )
201     {
202         msg_Warn( p_input, "stream[%d] unselectable", i_stream );
203         return( 0 );
204     }
205     if( p_stream->i_activated )
206     {
207         msg_Warn( p_input, "stream[%d] already selected", i_stream );
208         return( 1 );
209     }
210
211     if( !p_stream->p_es->p_decoder_fifo )
212     {
213         vlc_mutex_lock( &p_input->stream.stream_lock );
214         input_SelectES( p_input, p_stream->p_es );
215         vlc_mutex_unlock( &p_input->stream.stream_lock );
216     }
217     p_stream->i_activated = p_stream->p_es->p_decoder_fifo ? 1 : 0;
218
219     /* Feed the backup header to the decoder */
220     if( !p_stream->b_force_backup )
221     {
222         int i;
223         for( i = 0; i < p_stream->i_packets_backup; i++ )
224         {
225             Ogg_DecodePacket( p_input, p_stream,
226                               &p_stream->p_packets_backup[i] );
227         }
228     }
229
230     //Ogg_StreamSeek( p_input, p_ogg, i_stream, p_ogg->i_time );
231
232     return( p_stream->i_activated );
233 #undef  p_stream
234 }
235
236 static void Ogg_StreamStop( input_thread_t *p_input,
237                             demux_sys_t *p_ogg, int i_stream )
238 {
239 #define p_stream    p_ogg->pp_stream[i_stream]
240
241     if( !p_stream->i_activated )
242     {
243         msg_Warn( p_input, "stream[%d] already unselected", i_stream );
244         return;
245     }
246
247     if( p_stream->p_es->p_decoder_fifo )
248     {
249         vlc_mutex_lock( &p_input->stream.stream_lock );
250         input_UnselectES( p_input, p_stream->p_es );
251         vlc_mutex_unlock( &p_input->stream.stream_lock );
252     }
253
254     p_stream->i_activated = 0;
255
256 #undef  p_stream
257 }
258
259 static int Ogg_StreamSeek( input_thread_t *p_input, demux_sys_t  *p_ogg,
260                            int i_stream, mtime_t i_date )
261 {
262 #define p_stream    p_ogg->pp_stream[i_stream]
263
264     /* FIXME: todo */
265
266     return 1;
267 #undef p_stream
268 }
269
270 /****************************************************************************
271  * Ogg_Check: Check we are dealing with an ogg stream.
272  ****************************************************************************/
273 static int Ogg_Check( input_thread_t *p_input )
274 {
275     u8 *p_peek;
276     int i_size = input_Peek( p_input, &p_peek, 4 );
277
278     /* Check for the Ogg capture pattern */
279     if( !(i_size>3) || !(p_peek[0] == 'O') || !(p_peek[1] == 'g') ||
280         !(p_peek[2] == 'g') || !(p_peek[3] == 'S') )
281         return VLC_EGENERIC;
282
283     /* FIXME: Capture pattern might not be enough so we can also check for the
284      * the first complete page */
285
286     return VLC_SUCCESS;
287 }
288
289 /****************************************************************************
290  * Ogg_ReadPage: Read a full Ogg page from the physical bitstream.
291  ****************************************************************************
292  * Returns VLC_SUCCESS if a page has been read. An error might happen if we
293  * are at the end of stream.
294  ****************************************************************************/
295 static int Ogg_ReadPage( input_thread_t *p_input, demux_sys_t *p_ogg,
296                          ogg_page *p_oggpage )
297 {
298     int i_read = 0;
299     data_packet_t *p_data;
300     byte_t *p_buffer;
301
302     while( ogg_sync_pageout( &p_ogg->oy, p_oggpage ) != 1 )
303     {
304         i_read = input_SplitBuffer( p_input, &p_data, OGG_BLOCK_SIZE );
305         if( i_read <= 0 )
306             return VLC_EGENERIC;
307
308         p_buffer = ogg_sync_buffer( &p_ogg->oy, i_read );
309         p_input->p_vlc->pf_memcpy( p_buffer, p_data->p_payload_start, i_read );
310         ogg_sync_wrote( &p_ogg->oy, i_read );
311         input_DeletePacket( p_input->p_method_data, p_data );
312     }
313
314     return VLC_SUCCESS;
315 }
316
317 /****************************************************************************
318  * Ogg_DecodePacket: Decode an Ogg packet.
319  ****************************************************************************/
320 static void Ogg_DecodePacket( input_thread_t *p_input,
321                               logical_stream_t *p_stream,
322                               ogg_packet *p_oggpacket )
323 {
324     pes_packet_t  *p_pes;
325     data_packet_t *p_data;
326     demux_sys_t *p_ogg = p_input->p_demux_data;
327     int i_header_len = 0;
328
329     if( p_stream->b_force_backup )
330     {
331         /* Backup the ogg packet (likely an header) */
332         ogg_packet *p_packet_backup;
333         p_stream->i_packets_backup++;
334         p_stream->p_packets_backup =
335             realloc( p_stream->p_packets_backup, p_stream->i_packets_backup *
336                      sizeof(ogg_packet) );
337
338         p_packet_backup =
339             &p_stream->p_packets_backup[p_stream->i_packets_backup - 1];
340
341         p_packet_backup->bytes = p_oggpacket->bytes;
342         p_packet_backup->granulepos = p_oggpacket->granulepos;
343         p_packet_backup->packet = malloc( p_oggpacket->bytes );
344         if( !p_packet_backup->packet ) return;
345         memcpy( p_packet_backup->packet, p_oggpacket->packet,
346                 p_oggpacket->bytes );
347
348         switch( p_stream->i_fourcc )
349         {
350         case VLC_FOURCC( 'v','o','r','b' ):
351           if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
352           break;
353
354         default:
355           p_stream->b_force_backup = 0;
356           break;
357         }
358     }
359
360     if( !p_stream->p_es->p_decoder_fifo )
361     {
362         /* This stream isn't currently selected so we don't need to decode it,
363          * but we do need to store its pcr as it might be selected later on. */
364
365         /* Convert the next granule into a pcr */
366         p_stream->i_pcr = ( p_oggpacket->granulepos < 0 ) ?
367             p_stream->i_pcr + ( p_oggpacket->bytes * 90000
368                 / p_stream->i_bitrate / 8 ):
369             p_oggpacket->granulepos * 90000 / p_stream->i_rate;
370
371         return;
372     }
373
374     if( !( p_pes = input_NewPES( p_input->p_method_data ) ) )
375     {
376         return;
377     }
378     if( !( p_data = input_NewPacket( p_input->p_method_data,
379                                      p_oggpacket->bytes ) ) )
380     {
381         input_DeletePES( p_input->p_method_data, p_pes );
382         return;
383     }
384
385     /* Convert the pcr into a pts */
386     p_pes->i_pts = ( p_stream->i_pcr < 0 ) ? 0 :
387         input_ClockGetTS( p_input, p_input->stream.p_selected_program,
388                           p_stream->i_pcr );
389
390     /* Convert the next granule into a pcr */
391     if( p_oggpacket->granulepos < 0 )
392     {
393         /* FIXME: ffmpeg doesn't like null pts */
394         if( p_stream->i_cat == VIDEO_ES )
395             p_stream->i_pcr += (90000 / p_stream->i_rate);
396         else
397             p_stream->i_pcr = -1;
398     }
399     else
400     {
401         p_stream->i_pcr = p_oggpacket->granulepos * 90000 / p_stream->i_rate;
402     }
403
404     /* Update the main pcr */
405     if( p_stream == p_ogg->p_stream_timeref )
406     {
407         if( p_ogg->p_stream_timeref->i_pcr >= 0 )
408         {
409             p_ogg->i_pcr = p_ogg->p_stream_timeref->i_pcr;
410         }
411         else
412         {
413             p_ogg->i_pcr += ( p_oggpacket->bytes * 90000
414                               / p_stream->i_bitrate / 8 );
415         }
416     }
417
418     p_pes->i_nb_data = 1;
419     p_pes->i_dts = p_oggpacket->granulepos;
420     p_pes->p_first = p_pes->p_last = p_data;
421     p_pes->i_pes_size = p_oggpacket->bytes;
422
423     if( p_stream->i_fourcc != VLC_FOURCC( 'v','o','r','b' ) )
424     {
425         /* Remove the header from the packet */
426         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
427         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
428         i_header_len++;
429
430         p_pes->i_pes_size -= i_header_len;
431     }
432
433     memcpy( p_data->p_payload_start,
434             p_oggpacket->packet + i_header_len,
435             p_oggpacket->bytes - i_header_len );
436
437     p_data->p_payload_end = p_data->p_payload_start + p_pes->i_pes_size;
438
439     input_DecodePES( p_stream->p_es->p_decoder_fifo, p_pes );
440 }
441
442 /****************************************************************************
443  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
444  *                         stream and fill p_ogg.
445  *****************************************************************************
446  * The initial page of a logical stream is marked as a 'bos' page.
447  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
448  * together and all of the initial pages must appear before any data pages.
449  *
450  * On success this function returns VLC_SUCCESS.
451  ****************************************************************************/
452 static int Ogg_FindLogicalStreams( input_thread_t *p_input, demux_sys_t *p_ogg)
453 {
454     ogg_packet oggpacket;
455     ogg_page oggpage;
456     int i_stream;
457
458     while( Ogg_ReadPage( p_input, p_ogg, &oggpage ) == VLC_SUCCESS )
459     {
460         if( ogg_page_bos( &oggpage ) )
461         {
462
463             /* All is wonderful in our fine fine little world.
464              * We found the beginning of our first logical stream. */
465             while( ogg_page_bos( &oggpage ) )
466             {
467                 p_ogg->i_streams++;
468                 p_ogg->pp_stream =
469                     realloc( p_ogg->pp_stream, p_ogg->i_streams *
470                              sizeof(logical_stream_t *) );
471
472 #define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]
473
474                 p_stream = malloc( sizeof(logical_stream_t) );
475                 memset( p_stream, 0, sizeof(logical_stream_t) );
476
477                 /* Setup the logical stream */
478                 p_stream->i_serial_no = ogg_page_serialno( &oggpage );
479                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
480
481                 /* The first stream we find is our timeref (might be changed
482                  * later on) */
483                 p_ogg->p_stream_timeref = p_stream;
484
485                 /* Extract the initial header from the first page and verify
486                  * the codec type of tis Ogg bitstream */
487                 if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
488                 {
489                     /* error. stream version mismatch perhaps */
490                     msg_Err( p_input, "Error reading first page of "
491                              "Ogg bitstream data" );
492                     return VLC_EGENERIC;
493                 }
494
495                 /* FIXME: check return value */
496                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
497
498                 /* Check for Vorbis header */
499                 if( oggpacket.bytes >= 7 &&
500                     ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
501                 {
502                     oggpack_buffer opb;
503
504                     msg_Dbg( p_input, "found vorbis header" );
505                     p_stream->i_cat = AUDIO_ES;
506                     p_stream->i_fourcc = VLC_FOURCC( 'v','o','r','b' );
507
508                     /* Signal that we want to keep a backup of the vorbis
509                      * stream headers. They will be used when switching between
510                      * audio streams. */
511                     p_stream->b_force_backup = 1;
512
513                     /* Cheat and get additionnal info ;) */
514                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
515                     oggpack_adv( &opb, 96 );
516                     p_stream->i_rate = oggpack_read( &opb, 32 );
517                     oggpack_adv( &opb, 32 );
518                     p_stream->i_bitrate = oggpack_read( &opb, 32 );
519                 }
520                 else if( (*oggpacket.packet & PACKET_TYPE_BITS )
521                          == PACKET_TYPE_HEADER && 
522                          oggpacket.bytes >= (int)sizeof(stream_header)+1 )
523                 {
524                     stream_header *st = (stream_header *)(oggpacket.packet+1);
525
526                     /* Check for video header (new format) */
527                     if( !strncmp( st->streamtype, "video", 5 ) )
528                     {
529                         p_stream->i_cat = VIDEO_ES;
530
531                         /* We need to get rid of the header packet */
532                         ogg_stream_packetout( &p_stream->os, &oggpacket );
533
534                         p_stream->p_bih = (BITMAPINFOHEADER *)
535                             malloc( sizeof(BITMAPINFOHEADER) );
536                         if( !p_stream->p_bih )
537                         {
538                             /* Mem allocation error, just ignore the stream */
539                             free( p_stream );
540                             p_ogg->i_streams--;
541                             continue;
542                         }
543                         p_stream->p_bih->biSize = sizeof(BITMAPINFOHEADER);
544                         p_stream->p_bih->biCompression=
545                             p_stream->i_fourcc = VLC_FOURCC( st->subtype[0],
546                                                              st->subtype[1],
547                                                              st->subtype[2],
548                                                              st->subtype[3] );
549                         msg_Dbg( p_input, "found video header of type: %.4s",
550                                  (char *)&p_stream->i_fourcc );
551
552                         p_stream->i_rate = 10000000.0 /
553                             GetQWLE((uint8_t *)&st->time_unit);
554                         p_stream->p_bih->biBitCount =
555                             GetWLE((uint8_t *)&st->bits_per_sample);
556                         p_stream->p_bih->biWidth =
557                             GetDWLE((uint8_t *)&st->sh.video.width);
558                         p_stream->p_bih->biHeight =
559                             GetDWLE((uint8_t *)&st->sh.video.height);
560                         p_stream->p_bih->biPlanes= 1 ;
561                         p_stream->p_bih->biSizeImage =
562                             (p_stream->p_bih->biBitCount >> 3) *
563                             p_stream->p_bih->biWidth *
564                             p_stream->p_bih->biHeight;
565
566                         msg_Dbg( p_input,
567                              "fps: %f, width:%i; height:%i, bitcount:%i",
568                             p_stream->i_rate, p_stream->p_bih->biWidth,
569                             p_stream->p_bih->biHeight,
570                             p_stream->p_bih->biBitCount);
571
572                         p_stream->i_bitrate = 1; /* FIXME */
573                     }
574                     /* Check for audio header (new format) */
575                     else if( !strncmp( st->streamtype, "audio", 5 ) )
576                     {
577                         char p_buffer[5];
578
579                         p_stream->i_cat = AUDIO_ES;
580
581                         /* We need to get rid of the header packet */
582                         ogg_stream_packetout( &p_stream->os, &oggpacket );
583
584                         p_stream->p_wf = (WAVEFORMATEX *)
585                             malloc( sizeof(WAVEFORMATEX) );
586                         if( !p_stream->p_wf )
587                         {
588                             /* Mem allocation error, just ignore the stream */
589                             free( p_stream );
590                             p_ogg->i_streams--;
591                             continue;
592                         }
593
594                         memcpy( p_buffer, st->subtype, 4 );
595                         p_buffer[4] = '\0';
596                         p_stream->p_wf->wFormatTag = strtol(p_buffer,NULL,16);
597                         p_stream->p_wf->nChannels =
598                             GetWLE((uint8_t *)&st->sh.audio.channels);
599                         p_stream->i_rate = p_stream->p_wf->nSamplesPerSec =
600                             GetQWLE((uint8_t *)&st->samples_per_unit);
601                         p_stream->i_bitrate = p_stream->p_wf->nAvgBytesPerSec =
602                             GetDWLE((uint8_t *)&st->sh.audio.avgbytespersec);
603                         p_stream->i_bitrate *= 8;
604                         p_stream->p_wf->nBlockAlign =
605                             GetWLE((uint8_t *)&st->sh.audio.blockalign);
606                         p_stream->p_wf->wBitsPerSample =
607                             GetWLE((uint8_t *)&st->bits_per_sample);
608                         p_stream->p_wf->cbSize = 0;
609
610                         switch( p_stream->p_wf->wFormatTag )
611                         {
612                         case WAVE_FORMAT_PCM:
613                             p_stream->i_fourcc =
614                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
615                             break;
616                         case WAVE_FORMAT_MPEG:
617                         case WAVE_FORMAT_MPEGLAYER3:
618                             p_stream->i_fourcc =
619                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
620                             break;
621                         case WAVE_FORMAT_A52:
622                             p_stream->i_fourcc =
623                                 VLC_FOURCC( 'a', '5', '2', ' ' );
624                             break;
625                         case WAVE_FORMAT_WMA1:
626                             p_stream->i_fourcc =
627                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
628                             break;
629                         case WAVE_FORMAT_WMA2:
630                             p_stream->i_fourcc =
631                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
632                             break;
633                         default:
634                             p_stream->i_fourcc = VLC_FOURCC( 'm', 's',
635                                 ( p_stream->p_wf->wFormatTag >> 8 ) & 0xff,
636                                 p_stream->p_wf->wFormatTag & 0xff );
637                         }
638
639                         msg_Dbg( p_input, "found audio header of type: %.4s",
640                                  (char *)&p_stream->i_fourcc );
641                         msg_Dbg( p_input, "audio:0x%4.4x channels:%d %dHz "
642                                  "%dbits/sample %dkb/s",
643                                  p_stream->p_wf->wFormatTag,
644                                  p_stream->p_wf->nChannels,
645                                  p_stream->p_wf->nSamplesPerSec,
646                                  p_stream->p_wf->wBitsPerSample,
647                                  p_stream->p_wf->nAvgBytesPerSec * 8 / 1024 );
648                     }
649                     /* Check for text (subtitles) header */
650                     else if( !strncmp(st->streamtype, "text", 4) )
651                     {
652                         msg_Dbg( p_input, "found text subtitles header" );
653                         p_stream->i_cat = SPU_ES;
654                         p_stream->i_fourcc =
655                             VLC_FOURCC( 's', 'u', 'b', 't' );
656                     }
657                     else
658                     {
659                         msg_Dbg( p_input, "stream %d has a header marker "
660                             "but is of an unknown type", p_ogg->i_streams-1 );
661                         free( p_stream );
662                         p_ogg->i_streams--;
663                     }
664                 }
665                 else
666                 {
667                     msg_Dbg( p_input, "stream %d is of unknown type",
668                              p_ogg->i_streams-1 );
669                     free( p_stream );
670                     p_ogg->i_streams--;
671                 }
672
673 #undef p_stream
674
675                 if( Ogg_ReadPage( p_input, p_ogg, &oggpage ) != VLC_SUCCESS )
676                     return VLC_EGENERIC;
677             }
678
679             /* This is the first data page, which means we are now finished
680              * with the initial pages. We just need to store it in the relevant
681              * bitstream. */
682             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
683             {
684                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
685                                        &oggpage ) == 0 )
686                 {
687                     break;
688                 }
689             }
690             return VLC_SUCCESS;
691         }
692     }
693     return VLC_EGENERIC;
694 }
695
696 /*****************************************************************************
697  * Activate: initializes ogg demux structures
698  *****************************************************************************/
699 static int Activate( vlc_object_t * p_this )
700 {
701     int i_stream, b_forced;
702     demux_sys_t    *p_ogg;
703     input_thread_t *p_input = (input_thread_t *)p_this;
704
705     p_input->p_demux_data = NULL;
706     b_forced = ( ( *p_input->psz_demux )&&
707                  ( !strncmp( p_input->psz_demux, "ogg", 10 ) ) ) ? 1 : 0;
708
709     /* Check if we are dealing with an ogg stream */
710     if( !b_forced && ( Ogg_Check( p_input ) != VLC_SUCCESS ) )
711         return -1;
712
713     /* Allocate p_ogg */
714     if( !( p_ogg = malloc( sizeof( demux_sys_t ) ) ) )
715     {
716         msg_Err( p_input, "out of memory" );
717         goto error;
718     }
719     memset( p_ogg, 0, sizeof( demux_sys_t ) );
720     p_input->p_demux_data = p_ogg;
721
722     p_ogg->i_pcr  = 0;
723     p_ogg->p_stream_timeref = NULL;
724     p_ogg->b_seekable = ( ( p_input->stream.b_seekable )
725                         &&( p_input->stream.i_method == INPUT_METHOD_FILE ) );
726
727     /* Initialize the Ogg physical bitstream parser */
728     ogg_sync_init( &p_ogg->oy );
729
730     /* Find the logical streams embedded in the physical stream and
731      * initialize our p_ogg structure. */
732     if( Ogg_FindLogicalStreams( p_input, p_ogg ) != VLC_SUCCESS )
733     {
734         msg_Err( p_input, "couldn't find an ogg logical stream" );
735         goto error;
736     }
737
738     /* Set the demux function */
739     p_input->pf_demux = Demux;
740
741     /* Initialize access plug-in structures. */
742     if( p_input->i_mtu == 0 )
743     {
744         /* Improve speed. */
745         p_input->i_bufsize = INPUT_DEFAULT_BUFSIZE;
746     }
747
748     /* Create one program */
749     vlc_mutex_lock( &p_input->stream.stream_lock );
750     if( input_InitStream( p_input, 0 ) == -1)
751     {
752         vlc_mutex_unlock( &p_input->stream.stream_lock );
753         msg_Err( p_input, "cannot init stream" );
754         goto error;
755     }
756     if( input_AddProgram( p_input, 0, 0) == NULL )
757     {
758         vlc_mutex_unlock( &p_input->stream.stream_lock );
759         msg_Err( p_input, "cannot add program" );
760         goto error;
761     }
762     p_input->stream.p_selected_program = p_input->stream.pp_programs[0];
763     p_input->stream.i_mux_rate = 0;
764     vlc_mutex_unlock( &p_input->stream.stream_lock );
765
766     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
767     {
768 #define p_stream p_ogg->pp_stream[i_stream]
769         vlc_mutex_lock( &p_input->stream.stream_lock );
770         p_stream->p_es = input_AddES( p_input,
771                                       p_input->stream.p_selected_program,
772                                       p_ogg->i_streams + 1, 0 );
773         p_input->stream.i_mux_rate += (p_stream->i_bitrate / ( 8 * 50 ));
774         vlc_mutex_unlock( &p_input->stream.stream_lock );
775         p_stream->p_es->i_stream_id = i_stream;
776         p_stream->p_es->i_fourcc = p_stream->i_fourcc;
777         p_stream->p_es->i_cat = p_stream->i_cat;
778         p_stream->p_es->p_demux_data = p_stream->p_bih ?
779             (void *)p_stream->p_bih : (void *)p_stream->p_wf;
780 #undef p_stream
781     }
782
783     for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
784     {
785 #define p_stream  p_ogg->pp_stream[i_stream]
786         switch( p_stream->p_es->i_cat )
787         {
788             case( VIDEO_ES ):
789
790                 if( (p_ogg->p_stream_video == NULL) )
791                 {
792                     p_ogg->p_stream_video = p_stream;
793                     /* TODO add test to see if a decoder has been found */
794                     Ogg_StreamStart( p_input, p_ogg, i_stream );
795                 }
796                 break;
797
798             case( AUDIO_ES ):
799                 if( (p_ogg->p_stream_audio == NULL) )
800                 {
801                     p_ogg->p_stream_audio = p_stream;
802                     p_ogg->p_stream_timeref = p_stream;
803                     Ogg_StreamStart( p_input, p_ogg, i_stream );
804                 }
805                 break;
806
807             default:
808                 break;
809         }
810 #undef p_stream
811     }
812
813     /* we select the first audio and video ES */
814     vlc_mutex_lock( &p_input->stream.stream_lock );
815     if( !p_ogg->p_stream_video )
816     {
817         msg_Warn( p_input, "no video stream found" );
818     }
819     if( !p_ogg->p_stream_audio )
820     {
821         msg_Warn( p_input, "no audio stream found!" );
822     }
823     p_input->stream.p_selected_program->b_is_ok = 1;
824     vlc_mutex_unlock( &p_input->stream.stream_lock );
825
826     /* Call the pace control */
827     input_ClockManageRef( p_input,
828                           p_input->stream.p_selected_program,
829                           p_ogg->i_pcr );
830
831     return 0;
832
833  error:
834     Deactivate( (vlc_object_t *)p_input );
835     return -1;
836
837 }
838
839 /*****************************************************************************
840  * Deactivate: frees unused data
841  *****************************************************************************/
842 static void Deactivate( vlc_object_t *p_this )
843 {
844     input_thread_t *p_input = (input_thread_t *)p_this;
845     demux_sys_t *p_ogg = (demux_sys_t *)p_input->p_demux_data  ; 
846     int i, j;
847
848     if( p_ogg )
849     {
850         /* Cleanup the bitstream parser */
851         ogg_sync_clear( &p_ogg->oy );
852
853         for( i = 0; i < p_ogg->i_streams; i++ )
854         {
855             ogg_stream_clear( &p_ogg->pp_stream[i]->os );
856             for( j = 0; j < p_ogg->pp_stream[i]->i_packets_backup; j++ )
857             {
858                 free( p_ogg->pp_stream[i]->p_packets_backup[j].packet );
859             }
860             if( p_ogg->pp_stream[i]->p_packets_backup)
861                 free( p_ogg->pp_stream[i]->p_packets_backup );
862 #if 0 /* hmmm, it's already freed in input_DelES() */
863             if( p_ogg->pp_stream[i]->p_bih )
864                 free( p_ogg->pp_stream[i]->p_bih );
865             if( p_ogg->pp_stream[i]->p_wf )
866                 free( p_ogg->pp_stream[i]->p_wf );
867 #endif
868             free( p_ogg->pp_stream[i] );
869         }
870         if( p_ogg->pp_stream ) free( p_ogg->pp_stream );
871
872         free( p_ogg );
873     }
874 }
875
876 /*****************************************************************************
877  * Demux: reads and demuxes data packets
878  *****************************************************************************
879  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
880  *****************************************************************************/
881 static int Demux( input_thread_t * p_input )
882 {
883     int i, i_stream, b_eos = 0;
884     ogg_page    oggpage;
885     ogg_packet  oggpacket;
886     demux_sys_t *p_ogg  = (demux_sys_t *)p_input->p_demux_data;
887
888 #define p_stream p_ogg->pp_stream[i_stream]
889     /* detect new selected/unselected streams */
890     for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
891     {
892         if( p_stream->p_es )
893         {
894             if( p_stream->p_es->p_decoder_fifo &&
895                 !p_stream->i_activated )
896             {
897                 Ogg_StreamStart( p_input, p_ogg, i_stream );
898             }
899             else
900             if( !p_stream->p_es->p_decoder_fifo &&
901                 p_stream->i_activated )
902             {
903                 Ogg_StreamStop( p_input, p_ogg, i_stream );
904             }
905         }
906     }
907
908     /* search for new video and audio stream to select
909      * if current have been unselected */
910     if( ( !p_ogg->p_stream_video )
911             || ( !p_ogg->p_stream_video->p_es->p_decoder_fifo ) )
912     {
913         p_ogg->p_stream_video = NULL;
914         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
915         {
916             if( ( p_stream->i_cat == VIDEO_ES )
917                   &&( p_stream->p_es->p_decoder_fifo ) )
918             {
919                 p_ogg->p_stream_video = p_stream;
920                 break;
921             }
922         }
923     }
924     if( ( !p_ogg->p_stream_audio )
925             ||( !p_ogg->p_stream_audio->p_es->p_decoder_fifo ) )
926     {
927         p_ogg->p_stream_audio = NULL;
928         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
929         {
930             if( ( p_stream->i_cat == AUDIO_ES )
931                   &&( p_stream->p_es->p_decoder_fifo ) )
932             {
933                 p_ogg->p_stream_audio = p_stream;
934                 p_ogg->p_stream_timeref = p_stream;
935                 break;
936             }
937         }
938     }
939
940     if( p_input->stream.p_selected_program->i_synchro_state == SYNCHRO_REINIT )
941     {
942         msg_Warn( p_input, "synchro reinit" );
943
944         /* An ogg packet does only contain the starting date of the next
945          * packet, not its own starting date.
946          * As a quick work around, we just skip an oggpage */
947
948         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
949         {
950             /* we'll trash all the data until we find the next pcr */
951             p_stream->b_reinit = 1;
952             p_ogg->i_pcr = 0;
953         }
954     }
955
956
957     /* Demux ogg pages from the stream */
958     for( i = 0; (i < PAGES_READ_ONCE) || p_ogg->p_stream_timeref->b_reinit;
959          i++ )
960     {
961         if( Ogg_ReadPage( p_input, p_ogg, &oggpage ) != VLC_SUCCESS )
962         {
963             b_eos = 1;
964             break;
965         }
966
967         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
968         {
969             if( ogg_stream_pagein( &p_stream->os, &oggpage ) != 0 )
970                 continue;
971
972             while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
973             {
974                 if( !p_stream->p_es )
975                 {
976                     break;
977                 }
978
979                 if( p_stream->b_reinit )
980                 {
981                     if( oggpacket.granulepos >= 0 )
982                     {
983                         p_stream->b_reinit = 0;
984                         p_stream->i_pcr = oggpacket.granulepos
985                             * 90000 / p_stream->i_rate;
986
987                         if( !p_ogg->i_pcr ||
988                             (p_stream == p_ogg->p_stream_timeref) )
989                         {
990                             /* Call the pace control to reinitialize
991                              * the system clock */
992                             p_ogg->i_pcr = p_stream->i_pcr;
993                             input_ClockManageRef( p_input,
994                                p_input->stream.p_selected_program,
995                                p_ogg->i_pcr );
996                         }
997                     }
998                     continue;
999                 }
1000
1001                 Ogg_DecodePacket( p_input, p_stream, &oggpacket );
1002
1003             }
1004         }
1005 #undef p_stream
1006     }
1007
1008     /* Call the pace control */
1009     if( !b_eos ) input_ClockManageRef( p_input,
1010                                        p_input->stream.p_selected_program,
1011                                        p_ogg->i_pcr );
1012
1013     /* Did we reach the end of stream ? */
1014     return( b_eos ? 0 : 1 );
1015 }