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