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