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