]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
* modules/demux/ogg.c: fixed recent breakage (what a shameful bug).
[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.58 2004/02/15 13:16:43 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 ) ) ) return;
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         /* We 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         
486         if( p_stream->fmt.i_codec == VLC_FOURCC( 's','u','b','t' ))
487         {
488             /* But with subtitles we need to retrieve the duration first */
489             int i, lenbytes = 0;
490         
491             if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
492             {
493                 for( i = 0, lenbytes = 0; i < i_header_len; i++ )
494                 {
495                     lenbytes = lenbytes << 8;
496                     lenbytes += *(p_oggpacket->packet + i_header_len - i);
497                 }
498             }
499             if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
500                 ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
501                   p_oggpacket->packet[i_header_len + 1] != 0 && 
502                   p_oggpacket->packet[i_header_len + 1] != '\n' &&
503                   p_oggpacket->packet[i_header_len + 1] != '\r' ) )
504             {
505                 p_block->i_dts = p_block->i_pts + (mtime_t)lenbytes * 1000;
506             }
507         }
508
509         i_header_len++;
510         p_block->i_buffer -= i_header_len;
511     }
512
513     if( p_stream->fmt.i_codec == VLC_FOURCC( 't','a','r','k' ) )
514     {
515         /* FIXME: the biggest hack I've ever done */
516         msg_Warn( p_input, "tarkin pts: "I64Fd", granule: "I64Fd,
517                   p_block->i_pts, p_block->i_dts );
518         msleep(10000);
519     }
520
521     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
522             p_oggpacket->bytes - i_header_len );
523
524     es_out_Send( p_input->p_es_out, p_stream->p_es, p_block );
525 }
526
527 /****************************************************************************
528  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
529  *                         stream and fill p_ogg.
530  *****************************************************************************
531  * The initial page of a logical stream is marked as a 'bos' page.
532  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
533  * together and all of the initial pages must appear before any data pages.
534  *
535  * On success this function returns VLC_SUCCESS.
536  ****************************************************************************/
537 static int Ogg_FindLogicalStreams( input_thread_t *p_input, demux_sys_t *p_ogg)
538 {
539     ogg_packet oggpacket;
540     ogg_page oggpage;
541     int i_stream;
542
543 #define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]
544
545     while( Ogg_ReadPage( p_input, p_ogg, &oggpage ) == VLC_SUCCESS )
546     {
547         if( ogg_page_bos( &oggpage ) )
548         {
549
550             /* All is wonderful in our fine fine little world.
551              * We found the beginning of our first logical stream. */
552             while( ogg_page_bos( &oggpage ) )
553             {
554                 p_ogg->i_streams++;
555                 p_ogg->pp_stream =
556                     realloc( p_ogg->pp_stream, p_ogg->i_streams *
557                              sizeof(logical_stream_t *) );
558
559                 p_stream = malloc( sizeof(logical_stream_t) );
560                 memset( p_stream, 0, sizeof(logical_stream_t) );
561
562                 es_format_Init( &p_stream->fmt, 0, 0 );
563                 p_stream->b_activated = VLC_TRUE;
564
565                 /* Setup the logical stream */
566                 p_stream->i_serial_no = ogg_page_serialno( &oggpage );
567                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
568
569                 /* Extract the initial header from the first page and verify
570                  * the codec type of tis Ogg bitstream */
571                 if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
572                 {
573                     /* error. stream version mismatch perhaps */
574                     msg_Err( p_input, "error reading first page of "
575                              "Ogg bitstream data" );
576                     return VLC_EGENERIC;
577                 }
578
579                 /* FIXME: check return value */
580                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
581
582                 /* Check for Vorbis header */
583                 if( oggpacket.bytes >= 7 &&
584                     ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
585                 {
586                     oggpack_buffer opb;
587
588                     msg_Dbg( p_input, "found vorbis header" );
589                     p_stream->fmt.i_cat = AUDIO_ES;
590                     p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
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, 88 );
600                     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
601                     p_stream->f_rate = p_stream->fmt.audio.i_rate =
602                         oggpack_read( &opb, 32 );
603                     oggpack_adv( &opb, 32 );
604                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
605                 }
606                 /* Check for Speex header */
607                 else if( oggpacket.bytes >= 7 &&
608                     ! strncmp( &oggpacket.packet[0], "Speex", 5 ) )
609                 {
610                     oggpack_buffer opb;
611
612                     p_stream->fmt.i_cat = AUDIO_ES;
613                     p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
614
615                     /* Signal that we want to keep a backup of the vorbis
616                      * stream headers. They will be used when switching between
617                      * audio streams. */
618                     p_stream->b_force_backup = 1;
619
620                     /* Cheat and get additionnal info ;) */
621                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
622                     oggpack_adv( &opb, 224 );
623                     oggpack_adv( &opb, 32 ); /* speex_version_id */
624                     oggpack_adv( &opb, 32 ); /* header_size */
625                     p_stream->f_rate = p_stream->fmt.audio.i_rate =
626                         oggpack_read( &opb, 32 );
627                     oggpack_adv( &opb, 32 ); /* mode */
628                     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
629                     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
630                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
631
632                     msg_Dbg( p_input, "found speex header, channels: %i, "
633                              "rate: %i,  bitrate: %i",
634                              p_stream->fmt.audio.i_channels,
635                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
636                 }
637                 /* Check for Flac header */
638                 else if( oggpacket.bytes >= 4 &&
639                     ! strncmp( &oggpacket.packet[0], "fLaC", 4 ) )
640                 {
641                     msg_Dbg( p_input, "found FLAC header" );
642
643                     /* Grrrr!!!! Did they really have to put all the
644                      * important info in the second header packet!!!
645                      * (STREAMINFO metadata is in the following packet) */
646                     p_stream->b_force_backup = 1;
647
648                     p_stream->fmt.i_cat = AUDIO_ES;
649                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
650                 }
651                 /* Check for Theora header */
652                 else if( oggpacket.bytes >= 7 &&
653                          ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
654                 {
655                     bs_t bitstream;
656                     int i_fps_numerator;
657                     int i_fps_denominator;
658                     int i_keyframe_frequency_force;
659
660                     msg_Dbg( p_input, "found theora header" );
661                     p_stream->fmt.i_cat = VIDEO_ES;
662                     p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
663
664                     /* Signal that we want to keep a backup of the vorbis
665                      * stream headers. They will be used when switching between
666                      * audio streams. */
667                     p_stream->b_force_backup = 1;
668
669                     /* Cheat and get additionnal info ;) */
670                     bs_init( &bitstream, oggpacket.packet, oggpacket.bytes );
671                     bs_skip( &bitstream, 56 );
672                     bs_read( &bitstream, 8 ); /* major version num */
673                     bs_read( &bitstream, 8 ); /* minor version num */
674                     bs_read( &bitstream, 8 ); /* subminor version num */
675                     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
676                     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
677                     bs_read( &bitstream, 24 ); /* frame width */
678                     bs_read( &bitstream, 24 ); /* frame height */
679                     bs_read( &bitstream, 8 ); /* x offset */
680                     bs_read( &bitstream, 8 ); /* y offset */
681
682                     i_fps_numerator = bs_read( &bitstream, 32 );
683                     i_fps_denominator = bs_read( &bitstream, 32 );
684                     bs_read( &bitstream, 24 ); /* aspect_numerator */
685                     bs_read( &bitstream, 24 ); /* aspect_denominator */
686                     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
687                     bs_read( &bitstream, 8 ); /* colorspace */
688                     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
689                     bs_read( &bitstream, 6 ); /* quality */
690
691                     /* granule_shift = i_log( frequency_force -1 ) */
692                     p_stream->i_theora_keyframe_granule_shift = 0;
693                     i_keyframe_frequency_force--;
694                     while( i_keyframe_frequency_force )
695                     {
696                         p_stream->i_theora_keyframe_granule_shift++;
697                         i_keyframe_frequency_force >>= 1;
698                     }
699
700                     p_stream->f_rate = ((float)i_fps_numerator) /
701                                                 i_fps_denominator;
702                     msg_Dbg( p_input,
703                              "found theora header, bitrate: %i, rate: %f",
704                              p_stream->fmt.i_bitrate, p_stream->f_rate );
705
706                     /* Save this data in p_extra for ffmpeg */
707                     p_stream->fmt.i_extra = oggpacket.bytes;
708                     p_stream->fmt.p_extra = malloc( oggpacket.bytes );
709                     memcpy( p_stream->fmt.p_extra,
710                             oggpacket.packet, oggpacket.bytes );
711                 }
712                 /* Check for Tarkin header */
713                 else if( oggpacket.bytes >= 7 &&
714                          ! strncmp( &oggpacket.packet[1], "tarkin", 6 ) )
715                 {
716                     oggpack_buffer opb;
717
718                     msg_Dbg( p_input, "found tarkin header" );
719                     p_stream->fmt.i_cat = VIDEO_ES;
720                     p_stream->fmt.i_codec = VLC_FOURCC( 't','a','r','k' );
721
722                     /* Cheat and get additionnal info ;) */
723                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
724                     oggpack_adv( &opb, 88 );
725                     oggpack_adv( &opb, 104 );
726                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
727                     p_stream->f_rate = 2; /* FIXME */
728                     msg_Dbg( p_input,
729                              "found tarkin header, bitrate: %i, rate: %f",
730                              p_stream->fmt.i_bitrate, p_stream->f_rate );
731                 }
732                 else if( oggpacket.bytes >= 142 &&
733                          !strncmp( &oggpacket.packet[1],
734                                    "Direct Show Samples embedded in Ogg", 35 ))
735                 {
736                     /* Old header type */
737
738                     /* Check for video header (old format) */
739                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
740                         oggpacket.bytes >= 184 )
741                     {
742                         p_stream->fmt.i_cat = VIDEO_ES;
743                         p_stream->fmt.i_codec =
744                             VLC_FOURCC( oggpacket.packet[68],
745                                         oggpacket.packet[69],
746                                         oggpacket.packet[70],
747                                         oggpacket.packet[71] );
748                         msg_Dbg( p_input, "found video header of type: %.4s",
749                                  (char *)&p_stream->fmt.i_codec );
750
751                         p_stream->f_rate = 10000000.0 /
752                             GetQWLE((oggpacket.packet+164));
753                         p_stream->fmt.video.i_bits_per_pixel =
754                             GetWLE((oggpacket.packet+182));
755                         if( !p_stream->fmt.video.i_bits_per_pixel )
756                             /* hack, FIXME */
757                             p_stream->fmt.video.i_bits_per_pixel = 24;
758                         p_stream->fmt.video.i_width =
759                             GetDWLE((oggpacket.packet+176));
760                         p_stream->fmt.video.i_height =
761                             GetDWLE((oggpacket.packet+180));
762
763                         msg_Dbg( p_input,
764                                  "fps: %f, width:%i; height:%i, bitcount:%i",
765                                  p_stream->f_rate,
766                                  p_stream->fmt.video.i_width,
767                                  p_stream->fmt.video.i_height,
768                                  p_stream->fmt.video.i_bits_per_pixel);
769
770                     }
771                     /* Check for audio header (old format) */
772                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
773                     {
774                         unsigned int i_extra_size;
775                         unsigned int i_format_tag;
776
777                         p_stream->fmt.i_cat = AUDIO_ES;
778
779                         i_extra_size = GetWLE((oggpacket.packet+140));
780                         if( i_extra_size )
781                         {
782                             p_stream->fmt.i_extra = i_extra_size;
783                             p_stream->fmt.p_extra = malloc( i_extra_size );
784                             memcpy( p_stream->fmt.p_extra,
785                                     oggpacket.packet + 142, i_extra_size );
786                         }
787
788                         i_format_tag = GetWLE((oggpacket.packet+124));
789                         p_stream->fmt.audio.i_channels =
790                             GetWLE((oggpacket.packet+126));
791                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
792                             GetDWLE((oggpacket.packet+128));
793                         p_stream->fmt.i_bitrate =
794                             GetDWLE((oggpacket.packet+132)) * 8;
795                         p_stream->fmt.audio.i_blockalign =
796                             GetWLE((oggpacket.packet+136));
797                         p_stream->fmt.audio.i_bitspersample =
798                             GetWLE((oggpacket.packet+138));
799
800                         switch( i_format_tag )
801                         {
802                         case WAVE_FORMAT_PCM:
803                             p_stream->fmt.i_codec =
804                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
805                             break;
806                         case WAVE_FORMAT_MPEG:
807                         case WAVE_FORMAT_MPEGLAYER3:
808                             p_stream->fmt.i_codec =
809                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
810                             break;
811                         case WAVE_FORMAT_A52:
812                             p_stream->fmt.i_codec =
813                                 VLC_FOURCC( 'a', '5', '2', ' ' );
814                             break;
815                         case WAVE_FORMAT_WMA1:
816                             p_stream->fmt.i_codec =
817                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
818                             break;
819                         case WAVE_FORMAT_WMA2:
820                             p_stream->fmt.i_codec =
821                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
822                             break;
823                         default:
824                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
825                                 ( i_format_tag >> 8 ) & 0xff,
826                                 i_format_tag & 0xff );
827                         }
828
829                         msg_Dbg( p_input, "found audio header of type: %.4s",
830                                  (char *)&p_stream->fmt.i_codec );
831                         msg_Dbg( p_input, "audio:0x%4.4x channels:%d %dHz "
832                                  "%dbits/sample %dkb/s",
833                                  i_format_tag,
834                                  p_stream->fmt.audio.i_channels,
835                                  p_stream->fmt.audio.i_rate,
836                                  p_stream->fmt.audio.i_bitspersample,
837                                  p_stream->fmt.i_bitrate / 1024 );
838
839                     }
840                     else
841                     {
842                         msg_Dbg( p_input, "stream %d has an old header "
843                             "but is of an unknown type", p_ogg->i_streams-1 );
844                         free( p_stream );
845                         p_ogg->i_streams--;
846                     }
847                 }
848                 else if( (*oggpacket.packet & PACKET_TYPE_BITS )
849                          == PACKET_TYPE_HEADER &&
850                          oggpacket.bytes >= (int)sizeof(stream_header)+1 )
851                 {
852                     stream_header *st = (stream_header *)(oggpacket.packet+1);
853
854                     /* Check for video header (new format) */
855                     if( !strncmp( st->streamtype, "video", 5 ) )
856                     {
857                         p_stream->fmt.i_cat = VIDEO_ES;
858
859                         /* We need to get rid of the header packet */
860                         ogg_stream_packetout( &p_stream->os, &oggpacket );
861
862                         p_stream->fmt.i_codec =
863                             VLC_FOURCC( st->subtype[0], st->subtype[1],
864                                         st->subtype[2], st->subtype[3] );
865                         msg_Dbg( p_input, "found video header of type: %.4s",
866                                  (char *)&p_stream->fmt.i_codec );
867
868                         p_stream->f_rate = 10000000.0 /
869                             GetQWLE(&st->time_unit);
870                         p_stream->fmt.video.i_bits_per_pixel =
871                             GetWLE(&st->bits_per_sample);
872                         p_stream->fmt.video.i_width =
873                             GetDWLE(&st->sh.video.width);
874                         p_stream->fmt.video.i_height =
875                             GetDWLE(&st->sh.video.height);
876
877                         msg_Dbg( p_input,
878                                  "fps: %f, width:%i; height:%i, bitcount:%i",
879                                  p_stream->f_rate,
880                                  p_stream->fmt.video.i_width,
881                                  p_stream->fmt.video.i_height,
882                                  p_stream->fmt.video.i_bits_per_pixel );
883                     }
884                     /* Check for audio header (new format) */
885                     else if( !strncmp( st->streamtype, "audio", 5 ) )
886                     {
887                         char p_buffer[5];
888                         int i_format_tag;
889
890                         p_stream->fmt.i_cat = AUDIO_ES;
891
892                         /* We need to get rid of the header packet */
893                         ogg_stream_packetout( &p_stream->os, &oggpacket );
894
895                         memcpy( p_buffer, st->subtype, 4 );
896                         p_buffer[4] = '\0';
897                         i_format_tag = strtol(p_buffer,NULL,16);
898                         p_stream->fmt.audio.i_channels =
899                             GetWLE(&st->sh.audio.channels);
900                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
901                             GetQWLE(&st->samples_per_unit);
902                         p_stream->fmt.i_bitrate =
903                             GetDWLE(&st->sh.audio.avgbytespersec) * 8;
904                         p_stream->fmt.audio.i_blockalign =
905                             GetWLE(&st->sh.audio.blockalign);
906                         p_stream->fmt.audio.i_bitspersample =
907                             GetWLE(&st->bits_per_sample);
908
909                         switch( i_format_tag )
910                         {
911                         case WAVE_FORMAT_PCM:
912                             p_stream->fmt.i_codec =
913                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
914                             break;
915                         case WAVE_FORMAT_MPEG:
916                         case WAVE_FORMAT_MPEGLAYER3:
917                             p_stream->fmt.i_codec =
918                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
919                             break;
920                         case WAVE_FORMAT_A52:
921                             p_stream->fmt.i_codec =
922                                 VLC_FOURCC( 'a', '5', '2', ' ' );
923                             break;
924                         case WAVE_FORMAT_WMA1:
925                             p_stream->fmt.i_codec =
926                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
927                             break;
928                         case WAVE_FORMAT_WMA2:
929                             p_stream->fmt.i_codec =
930                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
931                             break;
932                         default:
933                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
934                                 ( i_format_tag >> 8 ) & 0xff,
935                                 i_format_tag & 0xff );
936                         }
937
938                         msg_Dbg( p_input, "found audio header of type: %.4s",
939                                  (char *)&p_stream->fmt.i_codec );
940                         msg_Dbg( p_input, "audio:0x%4.4x channels:%d %dHz "
941                                  "%dbits/sample %dkb/s",
942                                  i_format_tag,
943                                  p_stream->fmt.audio.i_channels,
944                                  p_stream->fmt.audio.i_rate,
945                                  p_stream->fmt.audio.i_bitspersample,
946                                  p_stream->fmt.i_bitrate / 1024 );
947                     }
948                     /* Check for text (subtitles) header */
949                     else if( !strncmp(st->streamtype, "text", 4) )
950                     {
951                         /* We need to get rid of the header packet */
952                         ogg_stream_packetout( &p_stream->os, &oggpacket );
953
954                         msg_Dbg( p_input, "found text subtitles header" );
955                         p_stream->fmt.i_cat = SPU_ES;
956                         p_stream->fmt.i_codec = VLC_FOURCC('s','u','b','t');
957                         p_stream->f_rate = 1000; /* granulepos is in milisec */
958                     }
959                     else
960                     {
961                         msg_Dbg( p_input, "stream %d has a header marker "
962                             "but is of an unknown type", p_ogg->i_streams-1 );
963                         free( p_stream );
964                         p_ogg->i_streams--;
965                     }
966                 }
967                 else
968                 {
969                     msg_Dbg( p_input, "stream %d is of unknown type",
970                              p_ogg->i_streams-1 );
971                     free( p_stream );
972                     p_ogg->i_streams--;
973                 }
974
975                 if( Ogg_ReadPage( p_input, p_ogg, &oggpage ) != VLC_SUCCESS )
976                     return VLC_EGENERIC;
977             }
978
979             /* This is the first data page, which means we are now finished
980              * with the initial pages. We just need to store it in the relevant
981              * bitstream. */
982             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
983             {
984                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
985                                        &oggpage ) == 0 )
986                 {
987                     break;
988                 }
989             }
990
991             return VLC_SUCCESS;
992         }
993     }
994 #undef p_stream
995
996     return VLC_EGENERIC;
997 }
998
999 /*****************************************************************************
1000  * Activate: initializes ogg demux structures
1001  *****************************************************************************/
1002 static int Activate( vlc_object_t * p_this )
1003 {
1004     input_thread_t *p_input = (input_thread_t *)p_this;
1005     demux_sys_t    *p_ogg;
1006     int            b_forced;
1007
1008     p_input->p_demux_data = NULL;
1009     b_forced = ( ( *p_input->psz_demux )&&
1010                  ( !strncmp( p_input->psz_demux, "ogg", 10 ) ) ) ? 1 : 0;
1011
1012     /* Check if we are dealing with an ogg stream */
1013     if( !b_forced && ( Ogg_Check( p_input ) != VLC_SUCCESS ) )
1014         return -1;
1015
1016     /* Allocate p_ogg */
1017     if( !( p_ogg = malloc( sizeof( demux_sys_t ) ) ) )
1018     {
1019         msg_Err( p_input, "out of memory" );
1020         goto error;
1021     }
1022     memset( p_ogg, 0, sizeof( demux_sys_t ) );
1023     p_input->p_demux_data = p_ogg;
1024     p_ogg->pp_stream = NULL;
1025
1026     /* Initialize the Ogg physical bitstream parser */
1027     ogg_sync_init( &p_ogg->oy );
1028
1029     /* Set exported functions */
1030     p_input->pf_demux = Demux;
1031     p_input->pf_demux_control = Control;
1032
1033     /* Initialize access plug-in structures. */
1034     if( p_input->i_mtu == 0 )
1035     {
1036         /* Improve speed. */
1037         p_input->i_bufsize = INPUT_DEFAULT_BUFSIZE;
1038     }
1039
1040     /* Create one program */
1041     vlc_mutex_lock( &p_input->stream.stream_lock );
1042     if( input_InitStream( p_input, 0 ) == -1)
1043     {
1044         vlc_mutex_unlock( &p_input->stream.stream_lock );
1045         msg_Err( p_input, "cannot init stream" );
1046         goto error;
1047     }
1048     if( input_AddProgram( p_input, 0, 0) == NULL )
1049     {
1050         vlc_mutex_unlock( &p_input->stream.stream_lock );
1051         msg_Err( p_input, "cannot add program" );
1052         goto error;
1053     }
1054     p_input->stream.p_selected_program = p_input->stream.pp_programs[0];
1055     vlc_mutex_unlock( &p_input->stream.stream_lock );
1056
1057     /* Begnning of stream, tell the demux to look for elementary streams. */
1058     p_ogg->i_eos = 0;
1059
1060     p_ogg->i_old_synchro_state = !SYNCHRO_REINIT;
1061
1062     return 0;
1063
1064  error:
1065     Deactivate( (vlc_object_t *)p_input );
1066     return -1;
1067
1068 }
1069
1070 /****************************************************************************
1071  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1072  *                        Elementary streams.
1073  ****************************************************************************/
1074 static int Ogg_BeginningOfStream( input_thread_t *p_input, demux_sys_t *p_ogg)
1075 {
1076     int i_stream;
1077
1078     /* Find the logical streams embedded in the physical stream and
1079      * initialize our p_ogg structure. */
1080     if( Ogg_FindLogicalStreams( p_input, p_ogg ) != VLC_SUCCESS )
1081     {
1082         msg_Warn( p_input, "couldn't find any ogg logical stream" );
1083         return VLC_EGENERIC;
1084     }
1085
1086     vlc_mutex_lock( &p_input->stream.stream_lock );
1087     p_input->stream.i_mux_rate = 0;
1088     vlc_mutex_unlock( &p_input->stream.stream_lock );
1089
1090     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1091     {
1092 #define p_stream p_ogg->pp_stream[i_stream]
1093         if( p_stream->fmt.i_codec != VLC_FOURCC('f','l','a','c') )
1094             p_stream->p_es = es_out_Add( p_input->p_es_out, &p_stream->fmt );
1095
1096         vlc_mutex_lock( &p_input->stream.stream_lock );
1097         p_input->stream.i_mux_rate += (p_stream->fmt.i_bitrate / ( 8 * 50 ));
1098         vlc_mutex_unlock( &p_input->stream.stream_lock );
1099
1100         p_stream->i_pcr = p_stream->i_previous_pcr =
1101             p_stream->i_interpolated_pcr = -1;
1102         p_stream->b_reinit = 0;
1103 #undef p_stream
1104     }
1105
1106     return VLC_SUCCESS;
1107 }
1108
1109 /****************************************************************************
1110  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1111  ****************************************************************************/
1112 static void Ogg_EndOfStream( input_thread_t *p_input, demux_sys_t *p_ogg )
1113 {
1114     int i_stream, j;
1115
1116 #define p_stream p_ogg->pp_stream[i_stream]
1117     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1118     {
1119         if( p_stream->p_es )
1120             es_out_Del( p_input->p_es_out, p_stream->p_es );
1121
1122         vlc_mutex_lock( &p_input->stream.stream_lock );
1123         p_input->stream.i_mux_rate -= (p_stream->fmt.i_bitrate / ( 8 * 50 ));
1124         vlc_mutex_unlock( &p_input->stream.stream_lock );
1125
1126         ogg_stream_clear( &p_ogg->pp_stream[i_stream]->os );
1127         for( j = 0; j < p_ogg->pp_stream[i_stream]->i_packets_backup; j++ )
1128         {
1129             free( p_ogg->pp_stream[i_stream]->p_packets_backup[j].packet );
1130         }
1131         if( p_ogg->pp_stream[i_stream]->p_packets_backup)
1132             free( p_ogg->pp_stream[i_stream]->p_packets_backup );
1133
1134         es_format_Clean( &p_stream->fmt );
1135
1136         free( p_ogg->pp_stream[i_stream] );
1137     }
1138 #undef p_stream
1139
1140     /* Reinit p_ogg */
1141     if( p_ogg->pp_stream ) free( p_ogg->pp_stream );
1142     p_ogg->pp_stream = NULL;
1143     p_ogg->i_streams = 0;
1144 }
1145
1146 /*****************************************************************************
1147  * Deactivate: frees unused data
1148  *****************************************************************************/
1149 static void Deactivate( vlc_object_t *p_this )
1150 {
1151     input_thread_t *p_input = (input_thread_t *)p_this;
1152     demux_sys_t *p_ogg = (demux_sys_t *)p_input->p_demux_data  ;
1153
1154     if( p_ogg )
1155     {
1156         /* Cleanup the bitstream parser */
1157         ogg_sync_clear( &p_ogg->oy );
1158
1159         Ogg_EndOfStream( p_input, p_ogg );
1160
1161         free( p_ogg );
1162     }
1163 }
1164
1165 /*****************************************************************************
1166  * Demux: reads and demuxes data packets
1167  *****************************************************************************
1168  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1169  *****************************************************************************/
1170 static int Demux( input_thread_t * p_input )
1171 {
1172     demux_sys_t *p_ogg = (demux_sys_t *)p_input->p_demux_data;
1173     ogg_page    oggpage;
1174     ogg_packet  oggpacket;
1175     int         i_stream;
1176
1177 #define p_stream p_ogg->pp_stream[i_stream]
1178
1179     if( p_ogg->i_eos == p_ogg->i_streams )
1180     {
1181         if( p_ogg->i_eos )
1182         {
1183             msg_Dbg( p_input, "end of a group of logical streams" );
1184             Ogg_EndOfStream( p_input, p_ogg );
1185         }
1186
1187         if( Ogg_BeginningOfStream( p_input, p_ogg ) != VLC_SUCCESS ) return 0;
1188         p_ogg->i_eos = 0;
1189
1190         msg_Dbg( p_input, "beginning of a group of logical streams" );
1191
1192         p_input->stream.p_selected_program->i_synchro_state = SYNCHRO_REINIT;
1193         input_ClockManageRef( p_input, p_input->stream.p_selected_program, 0 );
1194     }
1195
1196     if( p_input->stream.p_selected_program->i_synchro_state == SYNCHRO_REINIT )
1197     {
1198         msg_Warn( p_input, "synchro reinit" );
1199
1200         if( p_ogg->i_old_synchro_state != SYNCHRO_REINIT )
1201         for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1202         {
1203             /* we'll trash all the data until we find the next pcr */
1204             p_stream->b_reinit = 1;
1205             p_stream->i_pcr = -1;
1206             p_stream->i_interpolated_pcr = -1;
1207             ogg_stream_reset( &p_stream->os );
1208         }
1209         if( p_ogg->i_old_synchro_state != SYNCHRO_REINIT )
1210         ogg_sync_reset( &p_ogg->oy );
1211     }
1212
1213     /*
1214      * Demux an ogg page from the stream
1215      */
1216     if( Ogg_ReadPage( p_input, p_ogg, &oggpage ) != VLC_SUCCESS )
1217     {
1218         return 0; /* EOF */
1219     }
1220
1221     /* Test for End of Stream */
1222     if( ogg_page_eos( &oggpage ) ) p_ogg->i_eos++;
1223
1224
1225     for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1226     {
1227         if( ogg_stream_pagein( &p_stream->os, &oggpage ) != 0 )
1228             continue;
1229
1230         while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
1231         {
1232             if( p_stream->b_reinit )
1233             {
1234                 /* If synchro is re-initialized we need to drop all the packets
1235                  * until we find a new dated one. */
1236                 Ogg_UpdatePCR( p_stream, &oggpacket );
1237
1238                 if( p_stream->i_pcr >= 0 )
1239                 {
1240                     p_stream->b_reinit = 0;
1241                 }
1242                 else
1243                 {
1244                     p_stream->i_interpolated_pcr = -1;
1245                     continue;
1246                 }
1247
1248                 /* An Ogg/vorbis packet contains an end date granulepos */
1249                 if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
1250                     p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
1251                     p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
1252                 {
1253                     if( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
1254                     {
1255                         Ogg_DecodePacket( p_input, p_stream, &oggpacket );
1256                     }
1257                     else
1258                     {
1259                         input_ClockManageRef( p_input,
1260                                       p_input->stream.p_selected_program,
1261                                       p_stream->i_pcr );
1262                     }
1263                     continue;
1264                 }
1265             }
1266
1267             Ogg_DecodePacket( p_input, p_stream, &oggpacket );
1268         }
1269         break;
1270     }
1271
1272     i_stream = 0; p_ogg->i_pcr = -1;
1273     for( ; i_stream < p_ogg->i_streams; i_stream++ )
1274     {
1275         if( p_stream->fmt.i_cat == SPU_ES )
1276             continue;
1277         if( p_stream->i_interpolated_pcr < 0 )
1278             continue;
1279
1280         if( p_ogg->i_pcr < 0 || p_stream->i_interpolated_pcr < p_ogg->i_pcr )
1281             p_ogg->i_pcr = p_stream->i_interpolated_pcr;
1282     }
1283
1284     if( p_ogg->i_pcr >= 0 )
1285     {
1286         input_ClockManageRef( p_input, p_input->stream.p_selected_program,
1287                               p_ogg->i_pcr );
1288     }
1289
1290 #undef p_stream
1291
1292     p_ogg->i_old_synchro_state =
1293         p_input->stream.p_selected_program->i_synchro_state;
1294
1295     return 1;
1296 }
1297
1298 /*****************************************************************************
1299  * Control:
1300  *****************************************************************************/
1301 static int Control( input_thread_t *p_input, int i_query, va_list args )
1302 {
1303     demux_sys_t *p_ogg  = (demux_sys_t *)p_input->p_demux_data;
1304     int64_t *pi64;
1305
1306     switch( i_query )
1307     {
1308         case DEMUX_GET_TIME:
1309             pi64 = (int64_t*)va_arg( args, int64_t * );
1310             *pi64 = p_ogg->i_pcr * 100 / 9;
1311             return VLC_SUCCESS;
1312
1313         default:
1314             return demux_vaControlDefault( p_input, i_query, args );
1315     }
1316 }