0e9e30f03694382acfbdfd832f2357f45eb7b570
[vlc.git] / modules / demux / ogg.c
1 /*****************************************************************************
2  * ogg.c : ogg stream input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
5  * $Id: ogg.c,v 1.46 2003/11/23 13:15:27 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 <vlc/vlc.h>
28 #include <vlc/input.h>
29
30 #include <ogg/ogg.h>
31
32 #include "codecs.h"
33 #include "vlc_bits.h"
34
35 #define OGG_BLOCK_SIZE 4096
36
37 /*****************************************************************************
38  * Definitions of structures and functions used by this plugins
39  *****************************************************************************/
40 typedef struct logical_stream_s
41 {
42     ogg_stream_state os;                        /* logical stream of packets */
43
44     es_format_t      fmt;
45     es_out_id_t      *p_es;
46     double           f_rate;
47
48     int              i_serial_no;
49     int              b_activated;
50
51     /* the header of some logical streams (eg vorbis) contain essential
52      * data for the decoder. We back them up here in case we need to re-feed
53      * them to the decoder. */
54     int              b_force_backup;
55     int              i_packets_backup;
56     ogg_packet       *p_packets_backup;
57
58     /* program clock reference (in units of 90kHz) derived from the previous
59      * granulepos */
60     mtime_t          i_pcr;
61     mtime_t          i_interpolated_pcr;
62     mtime_t          i_previous_pcr;
63
64     /* Misc */
65     int b_reinit;
66     int i_theora_keyframe_granule_shift;
67
68 } logical_stream_t;
69
70 struct demux_sys_t
71 {
72     ogg_sync_state oy;        /* sync and verify incoming physical bitstream */
73
74     int i_streams;                           /* number of logical bitstreams */
75     logical_stream_t **pp_stream;  /* pointer to an array of logical streams */
76
77     /* program clock reference (in units of 90kHz) derived from the pcr of
78      * the sub-streams */
79     mtime_t i_pcr;
80     int     b_reinit;
81     int     i_prev_sync_state;
82
83     /* stream state */
84     int     i_eos;
85 };
86
87 /* OggDS headers for the new header format (used in ogm files) */
88 typedef struct stream_header_video
89 {
90     ogg_int32_t width;
91     ogg_int32_t height;
92 } stream_header_video;
93
94 typedef struct stream_header_audio
95 {
96     ogg_int16_t channels;
97     ogg_int16_t blockalign;
98     ogg_int32_t avgbytespersec;
99 } stream_header_audio;
100
101 typedef struct stream_header
102 {
103     char        streamtype[8];
104     char        subtype[4];
105
106     ogg_int32_t size;                               /* size of the structure */
107
108     ogg_int64_t time_unit;                              /* in reference time */
109     ogg_int64_t samples_per_unit;
110     ogg_int32_t default_len;                                /* in media time */
111
112     ogg_int32_t buffersize;
113     ogg_int16_t bits_per_sample;
114
115     union
116     {
117         /* Video specific */
118         stream_header_video video;
119         /* Audio specific */
120         stream_header_audio audio;
121     } sh;
122 } stream_header;
123
124 /* Some defines from OggDS */
125 #define PACKET_TYPE_HEADER   0x01
126 #define PACKET_TYPE_BITS     0x07
127 #define PACKET_LEN_BITS01    0xc0
128 #define PACKET_LEN_BITS2     0x02
129 #define PACKET_IS_SYNCPOINT  0x08
130
131 /*****************************************************************************
132  * Local prototypes
133  *****************************************************************************/
134 static int  Activate  ( vlc_object_t * );
135 static void Deactivate( vlc_object_t * );
136 static int  Demux     ( input_thread_t * );
137 static int  Control   ( input_thread_t *, int, va_list );
138
139 /* Bitstream manipulation */
140 static int  Ogg_Check        ( input_thread_t *p_input );
141 static int  Ogg_ReadPage     ( input_thread_t *, demux_sys_t *, ogg_page * );
142 static void Ogg_UpdatePCR    ( logical_stream_t *, ogg_packet * );
143 static void Ogg_DecodePacket ( input_thread_t *p_input,
144                                logical_stream_t *p_stream, ogg_packet * );
145
146 static int Ogg_BeginningOfStream( input_thread_t *p_input, demux_sys_t *p_ogg);
147 static int Ogg_FindLogicalStreams( input_thread_t *p_input,demux_sys_t *p_ogg);
148 static void Ogg_EndOfStream( input_thread_t *p_input, demux_sys_t *p_ogg );
149
150 /*****************************************************************************
151  * Module descriptor
152  *****************************************************************************/
153 vlc_module_begin();
154     set_description( _("ogg stream demuxer" ) );
155     set_capability( "demux", 50 );
156     set_callbacks( Activate, Deactivate );
157     add_shortcut( "ogg" );
158 vlc_module_end();
159
160 /****************************************************************************
161  * Ogg_Check: Check we are dealing with an ogg stream.
162  ****************************************************************************/
163 static int Ogg_Check( input_thread_t *p_input )
164 {
165     uint8_t *p_peek;
166     int i_size = input_Peek( p_input, &p_peek, 4 );
167
168     /* Check for the Ogg capture pattern */
169     if( !(i_size>3) || !(p_peek[0] == 'O') || !(p_peek[1] == 'g') ||
170         !(p_peek[2] == 'g') || !(p_peek[3] == 'S') )
171         return VLC_EGENERIC;
172
173     /* FIXME: Capture pattern might not be enough so we can also check for the
174      * the first complete page */
175
176     return VLC_SUCCESS;
177 }
178
179 /****************************************************************************
180  * Ogg_ReadPage: Read a full Ogg page from the physical bitstream.
181  ****************************************************************************
182  * Returns VLC_SUCCESS if a page has been read. An error might happen if we
183  * are at the end of stream.
184  ****************************************************************************/
185 static int Ogg_ReadPage( input_thread_t *p_input, demux_sys_t *p_ogg,
186                          ogg_page *p_oggpage )
187 {
188     int i_read = 0;
189     data_packet_t *p_data;
190     byte_t *p_buffer;
191
192     while( ogg_sync_pageout( &p_ogg->oy, p_oggpage ) != 1 )
193     {
194         i_read = input_SplitBuffer( p_input, &p_data, OGG_BLOCK_SIZE );
195         if( i_read <= 0 )
196             return VLC_EGENERIC;
197
198         p_buffer = ogg_sync_buffer( &p_ogg->oy, i_read );
199         p_input->p_vlc->pf_memcpy( p_buffer, p_data->p_payload_start, i_read );
200         ogg_sync_wrote( &p_ogg->oy, i_read );
201         input_DeletePacket( p_input->p_method_data, p_data );
202     }
203
204     return VLC_SUCCESS;
205 }
206
207 /****************************************************************************
208  * Ogg_UpdatePCR: update the PCR (90kHz program clock reference) for the
209  *                current stream.
210  ****************************************************************************/
211 static void Ogg_UpdatePCR( logical_stream_t *p_stream,
212                            ogg_packet *p_oggpacket )
213 {
214     /* Convert the granulepos into a pcr */
215     if( p_oggpacket->granulepos >= 0 )
216     {
217         if( p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) )
218         {
219             p_stream->i_pcr = p_oggpacket->granulepos * 90000
220                               / p_stream->f_rate;
221         }
222         else
223         {
224             ogg_int64_t iframe = p_oggpacket->granulepos >>
225               p_stream->i_theora_keyframe_granule_shift;
226             ogg_int64_t pframe = p_oggpacket->granulepos -
227               ( iframe << p_stream->i_theora_keyframe_granule_shift );
228
229             p_stream->i_pcr = ( iframe + pframe ) * 90000
230                               / p_stream->f_rate;
231         }
232
233         p_stream->i_interpolated_pcr = p_stream->i_pcr;
234     }
235     else
236     {
237         p_stream->i_pcr = -1;
238
239         /* no granulepos available, try to interpolate the pcr.
240          * If we can't then don't touch the old value. */
241         if( p_stream->fmt.i_cat == VIDEO_ES )
242             /* 1 frame per packet */
243             p_stream->i_interpolated_pcr += (90000 / p_stream->f_rate);
244         else if( p_stream->fmt.i_bitrate )
245             p_stream->i_interpolated_pcr += ( p_oggpacket->bytes * 90000
246                                               / p_stream->fmt.i_bitrate / 8 );
247     }
248 }
249
250 /****************************************************************************
251  * Ogg_DecodePacket: Decode an Ogg packet.
252  ****************************************************************************/
253 static void Ogg_DecodePacket( input_thread_t *p_input,
254                               logical_stream_t *p_stream,
255                               ogg_packet *p_oggpacket )
256 {
257     block_t *p_block;
258     vlc_bool_t b_selected;
259     int i_header_len = 0;
260     mtime_t i_pts;
261
262     /* Sanity check */
263     if( !p_oggpacket->bytes )
264     {
265         msg_Dbg( p_input, "discarding 0 sized packet" );
266         return;
267     }
268
269     if( p_stream->b_force_backup )
270     {
271         ogg_packet *p_packet_backup;
272         p_stream->i_packets_backup++;
273         switch( p_stream->fmt.i_codec )
274         {
275         case VLC_FOURCC( 'v','o','r','b' ):
276         case VLC_FOURCC( 's','p','x',' ' ):
277         case VLC_FOURCC( 't','h','e','o' ):
278           if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
279           break;
280
281         case VLC_FOURCC( 'f','l','a','c' ):
282           if( p_stream->i_packets_backup == 1 ) return;
283           else if( p_stream->i_packets_backup == 2 )
284           {
285               /* Parse the STREAMINFO metadata */
286               bs_t s;
287               bs_init( &s, p_oggpacket->packet, p_oggpacket->bytes );
288               bs_read( &s, 1 );
289               if( bs_read( &s, 7 ) == 0 )
290               {
291                   if( bs_read( &s, 24 ) >= 34 /*size STREAMINFO*/ )
292                   {
293                       bs_skip( &s, 80 );
294                       p_stream->f_rate = p_stream->fmt.audio.i_rate =
295                           bs_read( &s, 20 );
296                       p_stream->fmt.audio.i_channels =
297                           bs_read( &s, 3 ) + 1;
298
299                       msg_Dbg( p_input, "Flac header, channels: %i, rate: %i",
300                                p_stream->fmt.audio.i_channels,
301                                (int)p_stream->f_rate );
302                   }
303                   else
304                   {
305                       msg_Dbg( p_input, "FLAC STREAMINFO metadata too short" );
306                   }
307
308                   /* Store STREAMINFO for the decoder and packetizer */
309                   p_stream->fmt.i_extra = p_oggpacket->bytes + 4;
310                   p_stream->fmt.p_extra = malloc( p_stream->fmt.i_extra );
311                   memcpy( p_stream->fmt.p_extra, "fLaC", 4);
312                   memcpy( ((uint8_t *)p_stream->fmt.p_extra) + 4,
313                           p_oggpacket->packet, p_oggpacket->bytes );
314
315                   /* Fake this as the last metadata block */
316                   ((uint8_t*)p_stream->fmt.p_extra)[4] |= 0x80;
317
318                   p_stream->p_es = es_out_Add( p_input->p_es_out,
319                                                &p_stream->fmt );
320               }
321               else
322               {
323                   /* This ain't a STREAMINFO metadata */
324                   msg_Dbg( p_input, "Invalid FLAC STREAMINFO metadata" );
325               }
326               p_stream->b_force_backup = 0;
327               p_stream->i_packets_backup = 0;
328               return;
329           }
330           break;
331
332         default:
333           p_stream->b_force_backup = 0;
334           break;
335         }
336
337         /* Backup the ogg packet (likely an header packet) */
338         p_stream->p_packets_backup =
339             realloc( p_stream->p_packets_backup, p_stream->i_packets_backup *
340                      sizeof(ogg_packet) );
341
342         p_packet_backup =
343             &p_stream->p_packets_backup[p_stream->i_packets_backup - 1];
344
345         p_packet_backup->bytes = p_oggpacket->bytes;
346         p_packet_backup->granulepos = p_oggpacket->granulepos;
347
348         if( p_oggpacket->granulepos >= 0 )
349         {
350             /* Because of vorbis granulepos scheme we must set the pcr for the
351              * 1st header packet so it doesn't get discarded in the
352              * packetizer */
353             Ogg_UpdatePCR( p_stream, p_oggpacket );
354         }
355
356         p_packet_backup->packet = malloc( p_oggpacket->bytes );
357         if( !p_packet_backup->packet ) return;
358         memcpy( p_packet_backup->packet, p_oggpacket->packet,
359                 p_oggpacket->bytes );
360     }
361
362     /* Check the ES is selected */
363     es_out_Control( p_input->p_es_out, ES_OUT_GET_SELECT,
364                     p_stream->p_es, &b_selected );
365
366     if( b_selected && !p_stream->b_activated )
367     {
368         p_stream->b_activated = VLC_TRUE;
369
370         /* Newly activated stream, feed the backup headers to the decoder */
371         if( !p_stream->b_force_backup )
372         {
373             int i;
374             for( i = 0; i < p_stream->i_packets_backup; i++ )
375             {
376                 /* Set correct starting date in header packets */
377                 p_stream->p_packets_backup[i].granulepos =
378                     p_stream->i_interpolated_pcr * p_stream->f_rate / 90000;
379
380                 Ogg_DecodePacket( p_input, p_stream,
381                                   &p_stream->p_packets_backup[i] );
382             }
383         }
384     }
385
386     /* Convert the pcr into a pts */
387     if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
388         p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
389         p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
390     {
391         if( p_stream->i_pcr >= 0 )
392         {
393             /* This is for streams where the granulepos of the header packets
394              * doesn't match these of the data packets (eg. ogg web radios). */
395             if( p_stream->i_previous_pcr == 0 &&
396                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY * 9/100 )
397                 p_input->stream.p_selected_program->i_synchro_state =
398                     SYNCHRO_REINIT;
399
400             p_stream->i_previous_pcr = p_stream->i_pcr;
401
402             /* Call the pace control */
403             if( p_input->stream.p_selected_program->i_synchro_state ==
404                 SYNCHRO_REINIT )
405             input_ClockManageRef( p_input,
406                                   p_input->stream.p_selected_program,
407                                   p_stream->i_pcr );
408         }
409
410         /* The granulepos is the end date of the sample */
411         i_pts = ( p_stream->i_pcr < 0 ) ? 0 :
412             input_ClockGetTS( p_input, p_input->stream.p_selected_program,
413                               p_stream->i_pcr );
414
415         /* Convert the granulepos into the next pcr */
416         Ogg_UpdatePCR( p_stream, p_oggpacket );
417     }
418     else
419     {
420         /* Convert the granulepos into the current pcr */
421         Ogg_UpdatePCR( p_stream, p_oggpacket );
422
423         if( p_stream->i_pcr >= 0 )
424         {
425             /* This is for streams where the granulepos of the header packets
426              * doesn't match these of the data packets (eg. ogg web radios). */
427             if( p_stream->i_previous_pcr == 0 &&
428                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY * 9/100 )
429                 p_input->stream.p_selected_program->i_synchro_state =
430                     SYNCHRO_REINIT;
431
432             p_stream->i_previous_pcr = p_stream->i_pcr;
433
434             /* Call the pace control */
435             if( p_input->stream.p_selected_program->i_synchro_state ==
436                 SYNCHRO_REINIT )
437             input_ClockManageRef( p_input,
438                                   p_input->stream.p_selected_program,
439                                   p_stream->i_pcr );
440         }
441
442         /* The granulepos is the start date of the sample */
443         i_pts = ( p_stream->i_pcr < 0 ) ? 0 :
444             input_ClockGetTS( p_input, p_input->stream.p_selected_program,
445                               p_stream->i_pcr );
446     }
447
448     if( !b_selected )
449     {
450         /* This stream isn't currently selected so we don't need to decode it,
451          * but we did need to store its pcr as it might be selected later on */
452         p_stream->b_activated = VLC_FALSE;
453         return;
454     }
455
456     if( !( p_block = block_New( p_input, p_oggpacket->bytes ) ) )
457     {
458         return;
459     }
460
461     if( p_stream->fmt.i_cat == AUDIO_ES )
462         p_block->i_dts = p_block->i_pts = i_pts;
463     else if( p_stream->fmt.i_cat == SPU_ES )
464     {
465         p_block->i_pts = i_pts;
466         p_block->i_dts = 0;
467     }
468     else if( p_stream->fmt.i_codec == VLC_FOURCC( 't','h','e','o' ) )
469         p_block->i_dts = p_block->i_pts = i_pts;
470     else
471     {
472         p_block->i_dts = i_pts;
473         p_block->i_pts = 0;
474     }
475
476     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
477         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
478         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
479         p_stream->fmt.i_codec != VLC_FOURCC( 't','a','r','k' ) &&
480         p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) )
481     {
482         /* Remove the header from the packet */
483         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
484         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
485         i_header_len++;
486
487         p_block->i_buffer -= i_header_len;
488     }
489
490     if( p_stream->fmt.i_codec == VLC_FOURCC( 't','a','r','k' ) )
491     {
492         /* FIXME: the biggest hack I've ever done */
493         msg_Warn( p_input, "tark pts: "I64Fd", granule: "I64Fd,
494                   p_block->i_pts, p_block->i_dts );
495         msleep(10000);
496     }
497
498     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
499             p_oggpacket->bytes - i_header_len );
500
501     es_out_Send( p_input->p_es_out, p_stream->p_es, p_block );
502 }
503
504 /****************************************************************************
505  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
506  *                         stream and fill p_ogg.
507  *****************************************************************************
508  * The initial page of a logical stream is marked as a 'bos' page.
509  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
510  * together and all of the initial pages must appear before any data pages.
511  *
512  * On success this function returns VLC_SUCCESS.
513  ****************************************************************************/
514 static int Ogg_FindLogicalStreams( input_thread_t *p_input, demux_sys_t *p_ogg)
515 {
516     ogg_packet oggpacket;
517     ogg_page oggpage;
518     int i_stream;
519
520 #define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]
521
522     while( Ogg_ReadPage( p_input, p_ogg, &oggpage ) == VLC_SUCCESS )
523     {
524         if( ogg_page_bos( &oggpage ) )
525         {
526
527             /* All is wonderful in our fine fine little world.
528              * We found the beginning of our first logical stream. */
529             while( ogg_page_bos( &oggpage ) )
530             {
531                 p_ogg->i_streams++;
532                 p_ogg->pp_stream =
533                     realloc( p_ogg->pp_stream, p_ogg->i_streams *
534                              sizeof(logical_stream_t *) );
535
536                 p_stream = malloc( sizeof(logical_stream_t) );
537                 memset( p_stream, 0, sizeof(logical_stream_t) );
538
539                 es_format_Init( &p_stream->fmt, 0, 0 );
540                 p_stream->b_activated = VLC_TRUE;
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->fmt.i_cat = AUDIO_ES;
567                     p_stream->fmt.i_codec = 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->fmt.audio.i_channels = oggpack_read( &opb, 8 );
578                     p_stream->f_rate = p_stream->fmt.audio.i_rate =
579                         oggpack_read( &opb, 32 );
580                     oggpack_adv( &opb, 32 );
581                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
582                 }
583                 /* Check for Speex header */
584                 else if( oggpacket.bytes >= 7 &&
585                     ! strncmp( &oggpacket.packet[0], "Speex", 5 ) )
586                 {
587                     oggpack_buffer opb;
588
589                     p_stream->fmt.i_cat = AUDIO_ES;
590                     p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
591
592                     /* Signal that we want to keep a backup of the vorbis
593                      * stream headers. They will be used when switching between
594                      * audio streams. */
595                     p_stream->b_force_backup = 1;
596
597                     /* Cheat and get additionnal info ;) */
598                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
599                     oggpack_adv( &opb, 224 );
600                     oggpack_adv( &opb, 32 ); /* speex_version_id */
601                     oggpack_adv( &opb, 32 ); /* header_size */
602                     p_stream->f_rate = p_stream->fmt.audio.i_rate =
603                         oggpack_read( &opb, 32 );
604                     oggpack_adv( &opb, 32 ); /* mode */
605                     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
606                     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
607                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
608
609                     msg_Dbg( p_input, "found speex header, channels: %i, "
610                              "rate: %i,  bitrate: %i",
611                              p_stream->fmt.audio.i_channels,
612                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
613                 }
614                 /* Check for Flac header */
615                 else if( oggpacket.bytes >= 4 &&
616                     ! strncmp( &oggpacket.packet[0], "fLaC", 4 ) )
617                 {
618                     msg_Dbg( p_input, "found Flac header" );
619
620                     /* Grrrr!!!! Did they really have to put all the
621                      * important info in the second header packet!!!
622                      * (STREAMINFO metadata is in the following packet) */
623                     p_stream->b_force_backup = 1;
624
625                     p_stream->fmt.i_cat = AUDIO_ES;
626                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
627                 }
628                 /* Check for Theora header */
629                 else if( oggpacket.bytes >= 7 &&
630                          ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
631                 {
632                     bs_t bitstream;
633                     int i_fps_numerator;
634                     int i_fps_denominator;
635                     int i_keyframe_frequency_force;
636
637                     msg_Dbg( p_input, "found theora header" );
638                     p_stream->fmt.i_cat = VIDEO_ES;
639                     p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
640
641                     /* Signal that we want to keep a backup of the vorbis
642                      * stream headers. They will be used when switching between
643                      * audio streams. */
644                     p_stream->b_force_backup = 1;
645
646                     /* Cheat and get additionnal info ;) */
647                     bs_init( &bitstream, oggpacket.packet, oggpacket.bytes );
648                     bs_skip( &bitstream, 56 );
649                     bs_read( &bitstream, 8 ); /* major version num */
650                     bs_read( &bitstream, 8 ); /* minor version num */
651                     bs_read( &bitstream, 8 ); /* subminor version num */
652                     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
653                     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
654                     bs_read( &bitstream, 24 ); /* frame width */
655                     bs_read( &bitstream, 24 ); /* frame height */
656                     bs_read( &bitstream, 8 ); /* x offset */
657                     bs_read( &bitstream, 8 ); /* y offset */
658
659                     i_fps_numerator = bs_read( &bitstream, 32 );
660                     i_fps_denominator = bs_read( &bitstream, 32 );
661                     bs_read( &bitstream, 24 ); /* aspect_numerator */
662                     bs_read( &bitstream, 24 ); /* aspect_denominator */
663                     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
664                     bs_read( &bitstream, 8 ); /* colorspace */
665                     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
666                     bs_read( &bitstream, 6 ); /* quality */
667
668                     /* granule_shift = i_log( frequency_force -1 ) */
669                     p_stream->i_theora_keyframe_granule_shift = 0;
670                     i_keyframe_frequency_force--;
671                     while( i_keyframe_frequency_force )
672                     {
673                         p_stream->i_theora_keyframe_granule_shift++;
674                         i_keyframe_frequency_force >>= 1;
675                     }
676
677                     p_stream->f_rate = ((float)i_fps_numerator) /
678                                                 i_fps_denominator;
679                     msg_Dbg( p_input,
680                              "found theora header, bitrate: %i, rate: %f",
681                              p_stream->fmt.i_bitrate, p_stream->f_rate );
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->fmt.i_cat = VIDEO_ES;
691                     p_stream->fmt.i_codec = 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->fmt.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->fmt.i_bitrate, p_stream->f_rate );
702                 }
703                 else if( oggpacket.bytes >= 142 &&
704                          !strncmp( &oggpacket.packet[1],
705                                    "Direct Show Samples embedded in Ogg", 35 ))
706                 {
707                     /* Old header type */
708
709                     /* Check for video header (old format) */
710                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
711                         oggpacket.bytes >= 184 )
712                     {
713                         p_stream->fmt.i_cat = VIDEO_ES;
714                         p_stream->fmt.i_codec =
715                             VLC_FOURCC( oggpacket.packet[68],
716                                         oggpacket.packet[69],
717                                         oggpacket.packet[70],
718                                         oggpacket.packet[71] );
719                         msg_Dbg( p_input, "found video header of type: %.4s",
720                                  (char *)&p_stream->fmt.i_codec );
721
722                         p_stream->f_rate = 10000000.0 /
723                             GetQWLE((oggpacket.packet+164));
724                         p_stream->fmt.video.i_bits_per_pixel =
725                             GetWLE((oggpacket.packet+182));
726                         if( !p_stream->fmt.video.i_bits_per_pixel )
727                             /* hack, FIXME */
728                             p_stream->fmt.video.i_bits_per_pixel = 24;
729                         p_stream->fmt.video.i_width =
730                             GetDWLE((oggpacket.packet+176));
731                         p_stream->fmt.video.i_height =
732                             GetDWLE((oggpacket.packet+180));
733
734                         msg_Dbg( p_input,
735                                  "fps: %f, width:%i; height:%i, bitcount:%i",
736                                  p_stream->f_rate,
737                                  p_stream->fmt.video.i_width,
738                                  p_stream->fmt.video.i_height,
739                                  p_stream->fmt.video.i_bits_per_pixel);
740
741                     }
742                     /* Check for audio header (old format) */
743                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
744                     {
745                         unsigned int i_extra_size;
746                         unsigned int i_format_tag;
747
748                         p_stream->fmt.i_cat = AUDIO_ES;
749
750                         i_extra_size = GetWLE((oggpacket.packet+140));
751                         if( i_extra_size )
752                         {
753                             p_stream->fmt.i_extra = i_extra_size;
754                             p_stream->fmt.p_extra = malloc( i_extra_size );
755                             memcpy( p_stream->fmt.p_extra,
756                                     oggpacket.packet + 142, i_extra_size );
757                         }
758
759                         i_format_tag = GetWLE((oggpacket.packet+124));
760                         p_stream->fmt.audio.i_channels =
761                             GetWLE((oggpacket.packet+126));
762                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
763                             GetDWLE((oggpacket.packet+128));
764                         p_stream->fmt.i_bitrate =
765                             GetDWLE((oggpacket.packet+132)) * 8;
766                         p_stream->fmt.audio.i_blockalign =
767                             GetWLE((oggpacket.packet+136));
768                         p_stream->fmt.audio.i_bitspersample =
769                             GetWLE((oggpacket.packet+138));
770
771                         switch( i_format_tag )
772                         {
773                         case WAVE_FORMAT_PCM:
774                             p_stream->fmt.i_codec =
775                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
776                             break;
777                         case WAVE_FORMAT_MPEG:
778                         case WAVE_FORMAT_MPEGLAYER3:
779                             p_stream->fmt.i_codec =
780                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
781                             break;
782                         case WAVE_FORMAT_A52:
783                             p_stream->fmt.i_codec =
784                                 VLC_FOURCC( 'a', '5', '2', ' ' );
785                             break;
786                         case WAVE_FORMAT_WMA1:
787                             p_stream->fmt.i_codec =
788                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
789                             break;
790                         case WAVE_FORMAT_WMA2:
791                             p_stream->fmt.i_codec =
792                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
793                             break;
794                         default:
795                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
796                                 ( i_format_tag >> 8 ) & 0xff,
797                                 i_format_tag & 0xff );
798                         }
799
800                         msg_Dbg( p_input, "found audio header of type: %.4s",
801                                  (char *)&p_stream->fmt.i_codec );
802                         msg_Dbg( p_input, "audio:0x%4.4x channels:%d %dHz "
803                                  "%dbits/sample %dkb/s",
804                                  i_format_tag,
805                                  p_stream->fmt.audio.i_channels,
806                                  p_stream->fmt.audio.i_rate,
807                                  p_stream->fmt.audio.i_bitspersample,
808                                  p_stream->fmt.i_bitrate / 1024 );
809
810                     }
811                     else
812                     {
813                         msg_Dbg( p_input, "stream %d has an old header "
814                             "but is of an unknown type", p_ogg->i_streams-1 );
815                         free( p_stream );
816                         p_ogg->i_streams--;
817                     }
818                 }
819                 else if( (*oggpacket.packet & PACKET_TYPE_BITS )
820                          == PACKET_TYPE_HEADER &&
821                          oggpacket.bytes >= (int)sizeof(stream_header)+1 )
822                 {
823                     stream_header *st = (stream_header *)(oggpacket.packet+1);
824
825                     /* Check for video header (new format) */
826                     if( !strncmp( st->streamtype, "video", 5 ) )
827                     {
828                         p_stream->fmt.i_cat = VIDEO_ES;
829
830                         /* We need to get rid of the header packet */
831                         ogg_stream_packetout( &p_stream->os, &oggpacket );
832
833                         p_stream->fmt.i_codec =
834                             VLC_FOURCC( st->subtype[0], st->subtype[1],
835                                         st->subtype[2], st->subtype[3] );
836                         msg_Dbg( p_input, "found video header of type: %.4s",
837                                  (char *)&p_stream->fmt.i_codec );
838
839                         p_stream->f_rate = 10000000.0 /
840                             GetQWLE(&st->time_unit);
841                         p_stream->fmt.video.i_bits_per_pixel =
842                             GetWLE(&st->bits_per_sample);
843                         p_stream->fmt.video.i_width =
844                             GetDWLE(&st->sh.video.width);
845                         p_stream->fmt.video.i_height =
846                             GetDWLE(&st->sh.video.height);
847
848                         msg_Dbg( p_input,
849                                  "fps: %f, width:%i; height:%i, bitcount:%i",
850                                  p_stream->f_rate,
851                                  p_stream->fmt.video.i_width,
852                                  p_stream->fmt.video.i_height,
853                                  p_stream->fmt.video.i_bits_per_pixel );
854                     }
855                     /* Check for audio header (new format) */
856                     else if( !strncmp( st->streamtype, "audio", 5 ) )
857                     {
858                         char p_buffer[5];
859                         int i_format_tag;
860
861                         p_stream->fmt.i_cat = AUDIO_ES;
862
863                         /* We need to get rid of the header packet */
864                         ogg_stream_packetout( &p_stream->os, &oggpacket );
865
866                         memcpy( p_buffer, st->subtype, 4 );
867                         p_buffer[4] = '\0';
868                         i_format_tag = strtol(p_buffer,NULL,16);
869                         p_stream->fmt.audio.i_channels =
870                             GetWLE(&st->sh.audio.channels);
871                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
872                             GetQWLE(&st->samples_per_unit);
873                         p_stream->fmt.i_bitrate =
874                             GetDWLE(&st->sh.audio.avgbytespersec) * 8;
875                         p_stream->fmt.audio.i_blockalign =
876                             GetWLE(&st->sh.audio.blockalign);
877                         p_stream->fmt.audio.i_bitspersample =
878                             GetWLE(&st->bits_per_sample);
879
880                         switch( i_format_tag )
881                         {
882                         case WAVE_FORMAT_PCM:
883                             p_stream->fmt.i_codec =
884                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
885                             break;
886                         case WAVE_FORMAT_MPEG:
887                         case WAVE_FORMAT_MPEGLAYER3:
888                             p_stream->fmt.i_codec =
889                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
890                             break;
891                         case WAVE_FORMAT_A52:
892                             p_stream->fmt.i_codec =
893                                 VLC_FOURCC( 'a', '5', '2', ' ' );
894                             break;
895                         case WAVE_FORMAT_WMA1:
896                             p_stream->fmt.i_codec =
897                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
898                             break;
899                         case WAVE_FORMAT_WMA2:
900                             p_stream->fmt.i_codec =
901                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
902                             break;
903                         default:
904                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
905                                 ( i_format_tag >> 8 ) & 0xff,
906                                 i_format_tag & 0xff );
907                         }
908
909                         msg_Dbg( p_input, "found audio header of type: %.4s",
910                                  (char *)&p_stream->fmt.i_codec );
911                         msg_Dbg( p_input, "audio:0x%4.4x channels:%d %dHz "
912                                  "%dbits/sample %dkb/s",
913                                  i_format_tag,
914                                  p_stream->fmt.audio.i_channels,
915                                  p_stream->fmt.audio.i_rate,
916                                  p_stream->fmt.audio.i_bitspersample,
917                                  p_stream->fmt.i_bitrate / 1024 );
918                     }
919                     /* Check for text (subtitles) header */
920                     else if( !strncmp(st->streamtype, "text", 4) )
921                     {
922                         /* We need to get rid of the header packet */
923                         ogg_stream_packetout( &p_stream->os, &oggpacket );
924
925                         msg_Dbg( p_input, "found text subtitles header" );
926                         p_stream->fmt.i_cat = SPU_ES;
927                         p_stream->fmt.i_codec = VLC_FOURCC('s','u','b','t');
928                         p_stream->f_rate = 1000; /* granulepos is in milisec */
929                     }
930                     else
931                     {
932                         msg_Dbg( p_input, "stream %d has a header marker "
933                             "but is of an unknown type", p_ogg->i_streams-1 );
934                         free( p_stream );
935                         p_ogg->i_streams--;
936                     }
937                 }
938                 else
939                 {
940                     msg_Dbg( p_input, "stream %d is of unknown type",
941                              p_ogg->i_streams-1 );
942                     free( p_stream );
943                     p_ogg->i_streams--;
944                 }
945
946                 if( Ogg_ReadPage( p_input, p_ogg, &oggpage ) != VLC_SUCCESS )
947                     return VLC_EGENERIC;
948             }
949
950             /* This is the first data page, which means we are now finished
951              * with the initial pages. We just need to store it in the relevant
952              * bitstream. */
953             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
954             {
955                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
956                                        &oggpage ) == 0 )
957                 {
958                     break;
959                 }
960             }
961
962             return VLC_SUCCESS;
963         }
964     }
965 #undef p_stream
966
967     return VLC_EGENERIC;
968 }
969
970 /*****************************************************************************
971  * Activate: initializes ogg demux structures
972  *****************************************************************************/
973 static int Activate( vlc_object_t * p_this )
974 {
975     input_thread_t *p_input = (input_thread_t *)p_this;
976     demux_sys_t    *p_ogg;
977     int            b_forced;
978
979     p_input->p_demux_data = NULL;
980     b_forced = ( ( *p_input->psz_demux )&&
981                  ( !strncmp( p_input->psz_demux, "ogg", 10 ) ) ) ? 1 : 0;
982
983     /* Check if we are dealing with an ogg stream */
984     if( !b_forced && ( Ogg_Check( p_input ) != VLC_SUCCESS ) )
985         return -1;
986
987     /* Allocate p_ogg */
988     if( !( p_ogg = malloc( sizeof( demux_sys_t ) ) ) )
989     {
990         msg_Err( p_input, "out of memory" );
991         goto error;
992     }
993     memset( p_ogg, 0, sizeof( demux_sys_t ) );
994     p_input->p_demux_data = p_ogg;
995     p_ogg->pp_stream = NULL;
996
997     /* Initialize the Ogg physical bitstream parser */
998     ogg_sync_init( &p_ogg->oy );
999
1000     /* Set exported functions */
1001     p_input->pf_demux = Demux;
1002     p_input->pf_demux_control = Control;
1003
1004     /* Initialize access plug-in structures. */
1005     if( p_input->i_mtu == 0 )
1006     {
1007         /* Improve speed. */
1008         p_input->i_bufsize = INPUT_DEFAULT_BUFSIZE;
1009     }
1010
1011     /* Create one program */
1012     vlc_mutex_lock( &p_input->stream.stream_lock );
1013     if( input_InitStream( p_input, 0 ) == -1)
1014     {
1015         vlc_mutex_unlock( &p_input->stream.stream_lock );
1016         msg_Err( p_input, "cannot init stream" );
1017         goto error;
1018     }
1019     if( input_AddProgram( p_input, 0, 0) == NULL )
1020     {
1021         vlc_mutex_unlock( &p_input->stream.stream_lock );
1022         msg_Err( p_input, "cannot add program" );
1023         goto error;
1024     }
1025     p_input->stream.p_selected_program = p_input->stream.pp_programs[0];
1026     vlc_mutex_unlock( &p_input->stream.stream_lock );
1027
1028     /* Begnning of stream, tell the demux to look for elementary streams. */
1029     p_ogg->i_eos = 0;
1030
1031     p_ogg->i_prev_sync_state = SYNCHRO_REINIT;
1032
1033     return 0;
1034
1035  error:
1036     Deactivate( (vlc_object_t *)p_input );
1037     return -1;
1038
1039 }
1040
1041 /****************************************************************************
1042  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1043  *                        Elementary streams.
1044  ****************************************************************************/
1045 static int Ogg_BeginningOfStream( input_thread_t *p_input, demux_sys_t *p_ogg)
1046 {
1047     int i_stream;
1048
1049     /* Find the logical streams embedded in the physical stream and
1050      * initialize our p_ogg structure. */
1051     if( Ogg_FindLogicalStreams( p_input, p_ogg ) != VLC_SUCCESS )
1052     {
1053         msg_Warn( p_input, "couldn't find any ogg logical stream" );
1054         return VLC_EGENERIC;
1055     }
1056
1057     vlc_mutex_lock( &p_input->stream.stream_lock );
1058     p_input->stream.i_mux_rate = 0;
1059     vlc_mutex_unlock( &p_input->stream.stream_lock );
1060
1061     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1062     {
1063 #define p_stream p_ogg->pp_stream[i_stream]
1064         if( p_stream->fmt.i_codec != VLC_FOURCC('f','l','a','c') )
1065             p_stream->p_es = es_out_Add( p_input->p_es_out, &p_stream->fmt );
1066
1067         vlc_mutex_lock( &p_input->stream.stream_lock );
1068         p_input->stream.i_mux_rate += (p_stream->fmt.i_bitrate / ( 8 * 50 ));
1069         vlc_mutex_unlock( &p_input->stream.stream_lock );
1070
1071         p_stream->i_pcr  = p_stream->i_previous_pcr = -1;
1072         p_stream->b_reinit = 0;
1073 #undef p_stream
1074     }
1075
1076     return VLC_SUCCESS;
1077 }
1078
1079 /****************************************************************************
1080  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1081  ****************************************************************************/
1082 static void Ogg_EndOfStream( input_thread_t *p_input, demux_sys_t *p_ogg )
1083 {
1084     int i_stream, j;
1085
1086 #define p_stream p_ogg->pp_stream[i_stream]
1087     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1088     {
1089         es_out_Del( p_input->p_es_out, p_stream->p_es );
1090
1091         vlc_mutex_lock( &p_input->stream.stream_lock );
1092         p_input->stream.i_mux_rate -= (p_stream->fmt.i_bitrate / ( 8 * 50 ));
1093         vlc_mutex_unlock( &p_input->stream.stream_lock );
1094
1095         ogg_stream_clear( &p_ogg->pp_stream[i_stream]->os );
1096         for( j = 0; j < p_ogg->pp_stream[i_stream]->i_packets_backup; j++ )
1097         {
1098             free( p_ogg->pp_stream[i_stream]->p_packets_backup[j].packet );
1099         }
1100         if( p_ogg->pp_stream[i_stream]->p_packets_backup)
1101             free( p_ogg->pp_stream[i_stream]->p_packets_backup );
1102
1103         free( p_ogg->pp_stream[i_stream] );
1104     }
1105 #undef p_stream
1106
1107     /* Reinit p_ogg */
1108     if( p_ogg->pp_stream ) free( p_ogg->pp_stream );
1109     p_ogg->pp_stream = NULL;
1110     p_ogg->i_streams = 0;
1111 }
1112
1113 /*****************************************************************************
1114  * Deactivate: frees unused data
1115  *****************************************************************************/
1116 static void Deactivate( vlc_object_t *p_this )
1117 {
1118     input_thread_t *p_input = (input_thread_t *)p_this;
1119     demux_sys_t *p_ogg = (demux_sys_t *)p_input->p_demux_data  ;
1120
1121     if( p_ogg )
1122     {
1123         /* Cleanup the bitstream parser */
1124         ogg_sync_clear( &p_ogg->oy );
1125
1126         Ogg_EndOfStream( p_input, p_ogg );
1127
1128         free( p_ogg );
1129     }
1130 }
1131
1132 /*****************************************************************************
1133  * Demux: reads and demuxes data packets
1134  *****************************************************************************
1135  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1136  *****************************************************************************/
1137 static int Demux( input_thread_t * p_input )
1138 {
1139     demux_sys_t *p_ogg = (demux_sys_t *)p_input->p_demux_data;
1140     ogg_page    oggpage;
1141     ogg_packet  oggpacket;
1142     int         i_stream;
1143
1144 #define p_stream p_ogg->pp_stream[i_stream]
1145
1146     if( p_ogg->i_eos == p_ogg->i_streams )
1147     {
1148         if( p_ogg->i_eos )
1149         {
1150             msg_Dbg( p_input, "end of a group of logical streams" );
1151             Ogg_EndOfStream( p_input, p_ogg );
1152         }
1153
1154         if( Ogg_BeginningOfStream( p_input, p_ogg ) != VLC_SUCCESS ) return 0;
1155         p_ogg->i_eos = 0;
1156
1157         msg_Dbg( p_input, "beginning of a group of logical streams" );
1158
1159         p_input->stream.p_selected_program->i_synchro_state = SYNCHRO_REINIT;
1160         input_ClockManageRef( p_input, p_input->stream.p_selected_program, 0 );
1161     }
1162
1163     if( p_input->stream.p_selected_program->i_synchro_state == SYNCHRO_REINIT )
1164     {
1165         msg_Warn( p_input, "synchro reinit" );
1166
1167         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1168         {
1169             /* we'll trash all the data until we find the next pcr */
1170             p_stream->b_reinit = 1;
1171             p_stream->i_pcr = -1;
1172             p_stream->i_interpolated_pcr = -1;
1173         }
1174         if( p_ogg->i_prev_sync_state != SYNCHRO_REINIT )
1175             ogg_sync_reset( &p_ogg->oy );
1176     }
1177
1178     p_ogg->i_prev_sync_state =
1179         p_input->stream.p_selected_program->i_synchro_state;
1180
1181     /*
1182      * Demux an ogg page from the stream
1183      */
1184     if( Ogg_ReadPage( p_input, p_ogg, &oggpage ) != VLC_SUCCESS )
1185     {
1186         return 0; /* EOF */
1187     }
1188
1189     /* Test for End of Stream */
1190     if( ogg_page_eos( &oggpage ) ) p_ogg->i_eos++;
1191
1192
1193     for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1194     {
1195         if( ogg_stream_pagein( &p_stream->os, &oggpage ) != 0 )
1196             continue;
1197
1198         while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
1199         {
1200             if( p_stream->b_reinit )
1201             {
1202                 /* If synchro is re-initialized we need to drop all the packets
1203                  * until we find a new dated one. */
1204                 Ogg_UpdatePCR( p_stream, &oggpacket );
1205
1206                 if( p_stream->i_pcr >= 0 )
1207                 {
1208                     p_stream->b_reinit = 0;
1209                 }
1210                 else
1211                 {
1212                     p_stream->i_interpolated_pcr = -1;
1213                     continue;
1214                 }
1215
1216                 /* An Ogg/vorbis packet contains an end date granulepos */
1217                 if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
1218                     p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
1219                     p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
1220                 {
1221                     if( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
1222                     {
1223                         Ogg_DecodePacket( p_input, p_stream, &oggpacket );
1224                     }
1225                     else
1226                     {
1227                         input_ClockManageRef( p_input,
1228                             p_input->stream.p_selected_program, p_ogg->i_pcr );
1229                     }
1230                     continue;
1231                 }
1232             }
1233
1234             Ogg_DecodePacket( p_input, p_stream, &oggpacket );
1235         }
1236         break;
1237     }
1238
1239     i_stream = 0; p_ogg->i_pcr = -1;
1240     for( ; i_stream < p_ogg->i_streams; i_stream++ )
1241     {
1242         if( p_stream->fmt.i_cat == SPU_ES )
1243             continue;
1244         if( p_stream->i_interpolated_pcr < 0 )
1245             continue;
1246
1247         if( p_ogg->i_pcr < 0 || p_stream->i_interpolated_pcr < p_ogg->i_pcr )
1248             p_ogg->i_pcr = p_stream->i_interpolated_pcr;
1249     }
1250
1251     if( p_input->stream.p_selected_program->i_synchro_state != SYNCHRO_REINIT )
1252     {
1253         input_ClockManageRef( p_input, p_input->stream.p_selected_program,
1254                               p_ogg->i_pcr );
1255     }
1256
1257 #undef p_stream
1258
1259     return 1;
1260 }
1261
1262 /*****************************************************************************
1263  * Control:
1264  *****************************************************************************/
1265 static int Control( input_thread_t *p_input, int i_query, va_list args )
1266 {
1267     demux_sys_t *p_ogg  = (demux_sys_t *)p_input->p_demux_data;
1268     int64_t *pi64;
1269
1270     switch( i_query )
1271     {
1272         case DEMUX_GET_TIME:
1273             pi64 = (int64_t*)va_arg( args, int64_t * );
1274             *pi64 = p_ogg->i_pcr * 100 / 9;
1275             return VLC_SUCCESS;
1276
1277         default:
1278             return demux_vaControlDefault( p_input, i_query, args );
1279     }
1280 }