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