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