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