]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
* modules/demux/ogg.c: fixed reading extra data for oggds audio header (needed for...
[vlc] / modules / demux / ogg.c
1 /*****************************************************************************
2  * ogg.c : ogg stream demux module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
8  *          Andre Pang <Andre.Pang@csiro.au> (Annodex support)
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <vlc/vlc.h>
29 #include <vlc/input.h>
30
31 #include <ogg/ogg.h>
32
33 #include "codecs.h"
34 #include "vlc_bits.h"
35
36 /*****************************************************************************
37  * Module descriptor
38  *****************************************************************************/
39 static int  Open ( vlc_object_t * );
40 static void Close( vlc_object_t * );
41
42 vlc_module_begin();
43     set_description( _("Ogg stream demuxer" ) );
44     set_capability( "demux2", 50 );
45     set_callbacks( Open, Close );
46     add_shortcut( "ogg" );
47 vlc_module_end();
48
49
50 /*****************************************************************************
51  * Definitions of structures and functions used by this plugins
52  *****************************************************************************/
53 typedef struct logical_stream_s
54 {
55     ogg_stream_state os;                        /* logical stream of packets */
56
57     es_format_t      fmt;
58     es_out_id_t      *p_es;
59     double           f_rate;
60
61     int              i_serial_no;
62     int              b_activated;
63
64     /* the header of some logical streams (eg vorbis) contain essential
65      * data for the decoder. We back them up here in case we need to re-feed
66      * them to the decoder. */
67     int              b_force_backup;
68     int              i_packets_backup;
69     ogg_packet       *p_packets_backup;
70
71     /* program clock reference (in units of 90kHz) derived from the previous
72      * granulepos */
73     mtime_t          i_pcr;
74     mtime_t          i_interpolated_pcr;
75     mtime_t          i_previous_pcr;
76
77     /* Misc */
78     int b_reinit;
79     int i_theora_keyframe_granule_shift;
80
81     /* for Annodex logical bitstreams */
82     int secondary_header_packets;
83
84 } logical_stream_t;
85
86 struct demux_sys_t
87 {
88     ogg_sync_state oy;        /* sync and verify incoming physical bitstream */
89
90     int i_streams;                           /* number of logical bitstreams */
91     logical_stream_t **pp_stream;  /* pointer to an array of logical streams */
92
93     /* program clock reference (in units of 90kHz) derived from the pcr of
94      * the sub-streams */
95     mtime_t i_pcr;
96
97     /* stream state */
98     int     i_eos;
99
100     /* bitrate */
101     int     i_bitrate;
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 #define OGG_BLOCK_SIZE 4096
142
143 /* Some defines from OggDS */
144 #define PACKET_TYPE_HEADER   0x01
145 #define PACKET_TYPE_BITS     0x07
146 #define PACKET_LEN_BITS01    0xc0
147 #define PACKET_LEN_BITS2     0x02
148 #define PACKET_IS_SYNCPOINT  0x08
149
150 /*****************************************************************************
151  * Local prototypes
152  *****************************************************************************/
153 static int  Demux  ( demux_t * );
154 static int  Control( demux_t *, int, va_list );
155
156 /* Bitstream manipulation */
157 static int  Ogg_ReadPage     ( demux_t *, ogg_page * );
158 static void Ogg_UpdatePCR    ( logical_stream_t *, ogg_packet * );
159 static void Ogg_DecodePacket ( demux_t *, logical_stream_t *, ogg_packet * );
160
161 static int Ogg_BeginningOfStream( demux_t *p_demux );
162 static int Ogg_FindLogicalStreams( demux_t *p_demux );
163 static void Ogg_EndOfStream( demux_t *p_demux );
164
165 /* Logical bitstream headers */
166 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
167                                   ogg_packet *p_oggpacket );
168 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
169                                   ogg_packet *p_oggpacket );
170 static void Ogg_ReadAnnodexHeader( vlc_object_t *, logical_stream_t *p_stream,
171                                    ogg_packet *p_oggpacket );
172
173 /*****************************************************************************
174  * Open: initializes ogg demux structures
175  *****************************************************************************/
176 static int Open( vlc_object_t * p_this )
177 {
178     demux_t *p_demux = (demux_t *)p_this;
179     demux_sys_t    *p_sys;
180     uint8_t        *p_peek;
181
182
183     /* Check if we are dealing with an ogg stream */
184     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
185     {
186         msg_Err( p_demux, "cannot peek" );
187         return VLC_EGENERIC;
188     }
189     if( strcmp( p_demux->psz_demux, "ogg" ) && strncmp( p_peek, "OggS", 4 ) )
190     {
191         msg_Warn( p_demux, "ogg module discarded (invalid header)" );
192         return VLC_EGENERIC;
193     }
194
195     /* Set exported functions */
196     p_demux->pf_demux = Demux;
197     p_demux->pf_control = Control;
198     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
199
200     memset( p_sys, 0, sizeof( demux_sys_t ) );
201     p_sys->i_bitrate = 0;
202     p_sys->pp_stream = NULL;
203
204     /* Begnning of stream, tell the demux to look for elementary streams. */
205     p_sys->i_eos = 0;
206
207     /* Initialize the Ogg physical bitstream parser */
208     ogg_sync_init( &p_sys->oy );
209
210     return VLC_SUCCESS;
211 }
212
213 /*****************************************************************************
214  * Close: frees unused data
215  *****************************************************************************/
216 static void Close( vlc_object_t *p_this )
217 {
218     demux_t *p_demux = (demux_t *)p_this;
219     demux_sys_t *p_sys = p_demux->p_sys  ;
220
221     /* Cleanup the bitstream parser */
222     ogg_sync_clear( &p_sys->oy );
223
224     Ogg_EndOfStream( p_demux );
225
226     free( p_sys );
227 }
228
229 /*****************************************************************************
230  * Demux: reads and demuxes data packets
231  *****************************************************************************
232  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
233  *****************************************************************************/
234 static int Demux( demux_t * p_demux )
235 {
236     demux_sys_t *p_sys = p_demux->p_sys;
237     ogg_page    oggpage;
238     ogg_packet  oggpacket;
239     int         i_stream;
240
241
242     if( p_sys->i_eos == p_sys->i_streams )
243     {
244         if( p_sys->i_eos )
245         {
246             msg_Dbg( p_demux, "end of a group of logical streams" );
247             Ogg_EndOfStream( p_demux );
248         }
249
250         p_sys->i_eos = 0;
251         if( Ogg_BeginningOfStream( p_demux ) != VLC_SUCCESS ) return 0;
252
253         msg_Dbg( p_demux, "beginning of a group of logical streams" );
254         es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
255     }
256
257     /*
258      * Demux an ogg page from the stream
259      */
260     if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
261     {
262         return 0; /* EOF */
263     }
264
265     /* Test for End of Stream */
266     if( ogg_page_eos( &oggpage ) ) p_sys->i_eos++;
267
268
269     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
270     {
271         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
272
273         if( ogg_stream_pagein( &p_stream->os, &oggpage ) != 0 )
274             continue;
275
276         while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
277         {
278             /* Read info from any secondary header packets, if there are any */
279             if( p_stream->secondary_header_packets > 0 )
280             {
281                 if( p_stream->fmt.i_codec == VLC_FOURCC('t','h','e','o') &&
282                         oggpacket.bytes >= 7 &&
283                         ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
284                 {
285                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
286                     p_stream->secondary_header_packets = 0;
287                 }
288                 else if( p_stream->fmt.i_codec == VLC_FOURCC('v','o','r','b') &&
289                         oggpacket.bytes >= 7 &&
290                         ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
291                 {
292                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
293                     p_stream->secondary_header_packets = 0;
294                 }
295                 else if ( p_stream->fmt.i_codec == VLC_FOURCC('c','m','m','l') )
296                 {
297                     p_stream->secondary_header_packets = 0;
298                 }
299
300                 p_stream->secondary_header_packets--;
301             }
302
303             if( p_stream->b_reinit )
304             {
305                 /* If synchro is re-initialized we need to drop all the packets
306                  * until we find a new dated one. */
307                 Ogg_UpdatePCR( p_stream, &oggpacket );
308
309                 if( p_stream->i_pcr >= 0 )
310                 {
311                     p_stream->b_reinit = 0;
312                 }
313                 else
314                 {
315                     p_stream->i_interpolated_pcr = -1;
316                     continue;
317                 }
318
319                 /* An Ogg/vorbis packet contains an end date granulepos */
320                 if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
321                     p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
322                     p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
323                 {
324                     if( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
325                     {
326                         Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
327                     }
328                     else
329                     {
330                         es_out_Control( p_demux->out, ES_OUT_SET_PCR,
331                                         p_stream->i_pcr );
332                     }
333                     continue;
334                 }
335             }
336
337             Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
338         }
339         break;
340     }
341
342     i_stream = 0; p_sys->i_pcr = -1;
343     for( ; i_stream < p_sys->i_streams; i_stream++ )
344     {
345         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
346
347         if( p_stream->fmt.i_cat == SPU_ES )
348             continue;
349         if( p_stream->i_interpolated_pcr < 0 )
350             continue;
351
352         if( p_sys->i_pcr < 0 || p_stream->i_interpolated_pcr < p_sys->i_pcr )
353             p_sys->i_pcr = p_stream->i_interpolated_pcr;
354     }
355
356     if( p_sys->i_pcr >= 0 )
357     {
358         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
359     }
360
361
362     return 1;
363 }
364
365 /*****************************************************************************
366  * Control:
367  *****************************************************************************/
368 static int Control( demux_t *p_demux, int i_query, va_list args )
369 {
370     demux_sys_t *p_sys  = p_demux->p_sys;
371     int64_t *pi64;
372     int i;
373
374     switch( i_query )
375     {
376         case DEMUX_GET_TIME:
377             pi64 = (int64_t*)va_arg( args, int64_t * );
378             *pi64 = p_sys->i_pcr;
379             return VLC_SUCCESS;
380
381         case DEMUX_SET_TIME:
382             return VLC_EGENERIC;
383
384         case DEMUX_SET_POSITION:
385             for( i = 0; i < p_sys->i_streams; i++ )
386             {
387                 logical_stream_t *p_stream = p_sys->pp_stream[i];
388
389                 /* we'll trash all the data until we find the next pcr */
390                 p_stream->b_reinit = 1;
391                 p_stream->i_pcr = -1;
392                 p_stream->i_interpolated_pcr = -1;
393                 ogg_stream_reset( &p_stream->os );
394             }
395             ogg_sync_reset( &p_sys->oy );
396
397         default:
398             return demux2_vaControlHelper( p_demux->s, 0, -1, p_sys->i_bitrate,
399                                            1, i_query, args );
400     }
401 }
402
403 /****************************************************************************
404  * Ogg_ReadPage: Read a full Ogg page from the physical bitstream.
405  ****************************************************************************
406  * Returns VLC_SUCCESS if a page has been read. An error might happen if we
407  * are at the end of stream.
408  ****************************************************************************/
409 static int Ogg_ReadPage( demux_t *p_demux, ogg_page *p_oggpage )
410 {
411     demux_sys_t *p_ogg = p_demux->p_sys  ;
412     int i_read = 0;
413     byte_t *p_buffer;
414
415     while( ogg_sync_pageout( &p_ogg->oy, p_oggpage ) != 1 )
416     {
417         p_buffer = ogg_sync_buffer( &p_ogg->oy, OGG_BLOCK_SIZE );
418
419         i_read = stream_Read( p_demux->s, p_buffer, OGG_BLOCK_SIZE );
420         if( i_read <= 0 )
421             return VLC_EGENERIC;
422
423         ogg_sync_wrote( &p_ogg->oy, i_read );
424     }
425
426     return VLC_SUCCESS;
427 }
428
429 /****************************************************************************
430  * Ogg_UpdatePCR: update the PCR (90kHz program clock reference) for the
431  *                current stream.
432  ****************************************************************************/
433 static void Ogg_UpdatePCR( logical_stream_t *p_stream,
434                            ogg_packet *p_oggpacket )
435 {
436     /* Convert the granulepos into a pcr */
437     if( p_oggpacket->granulepos >= 0 )
438     {
439         if( p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) )
440         {
441             p_stream->i_pcr = p_oggpacket->granulepos * I64C(1000000)
442                               / p_stream->f_rate;
443         }
444         else
445         {
446             ogg_int64_t iframe = p_oggpacket->granulepos >>
447               p_stream->i_theora_keyframe_granule_shift;
448             ogg_int64_t pframe = p_oggpacket->granulepos -
449               ( iframe << p_stream->i_theora_keyframe_granule_shift );
450
451             p_stream->i_pcr = ( iframe + pframe ) * I64C(1000000)
452                               / p_stream->f_rate;
453         }
454
455         p_stream->i_interpolated_pcr = p_stream->i_pcr;
456     }
457     else
458     {
459         p_stream->i_pcr = -1;
460
461         /* no granulepos available, try to interpolate the pcr.
462          * If we can't then don't touch the old value. */
463         if( p_stream->fmt.i_cat == VIDEO_ES )
464             /* 1 frame per packet */
465             p_stream->i_interpolated_pcr += (I64C(1000000) / p_stream->f_rate);
466         else if( p_stream->fmt.i_bitrate )
467             p_stream->i_interpolated_pcr +=
468                 ( p_oggpacket->bytes * I64C(1000000) /
469                   p_stream->fmt.i_bitrate / 8 );
470     }
471 }
472
473 /****************************************************************************
474  * Ogg_DecodePacket: Decode an Ogg packet.
475  ****************************************************************************/
476 static void Ogg_DecodePacket( demux_t *p_demux,
477                               logical_stream_t *p_stream,
478                               ogg_packet *p_oggpacket )
479 {
480     block_t *p_block;
481     vlc_bool_t b_selected;
482     int i_header_len = 0;
483     mtime_t i_pts = 0;
484
485     /* Sanity check */
486     if( !p_oggpacket->bytes )
487     {
488         msg_Dbg( p_demux, "discarding 0 sized packet" );
489         return;
490     }
491
492     if( p_oggpacket->bytes >= 7 &&
493         ! strncmp ( &p_oggpacket->packet[0], "Annodex", 7 ) )
494     {
495         /* it's an Annodex packet -- skip it (do nothing) */
496         return; 
497     }
498     else if( p_oggpacket->bytes >= 7 &&
499         ! strncmp ( &p_oggpacket->packet[0], "AnxData", 7 ) )
500     {
501         /* it's an AnxData packet -- skip it (do nothing) */
502         return; 
503     }
504
505     if( p_stream->b_force_backup )
506     {
507         ogg_packet *p_packet_backup;
508         p_stream->i_packets_backup++;
509         switch( p_stream->fmt.i_codec )
510         {
511         case VLC_FOURCC( 'v','o','r','b' ):
512         case VLC_FOURCC( 's','p','x',' ' ):
513         case VLC_FOURCC( 't','h','e','o' ):
514           if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
515           break;
516
517         case VLC_FOURCC( 'f','l','a','c' ):
518           if( p_stream->i_packets_backup == 1 ) return;
519           else if( p_stream->i_packets_backup == 2 )
520           {
521               /* Parse the STREAMINFO metadata */
522               bs_t s;
523               bs_init( &s, p_oggpacket->packet, p_oggpacket->bytes );
524               bs_read( &s, 1 );
525               if( bs_read( &s, 7 ) == 0 )
526               {
527                   if( bs_read( &s, 24 ) >= 34 /*size STREAMINFO*/ )
528                   {
529                       bs_skip( &s, 80 );
530                       p_stream->f_rate = p_stream->fmt.audio.i_rate =
531                           bs_read( &s, 20 );
532                       p_stream->fmt.audio.i_channels =
533                           bs_read( &s, 3 ) + 1;
534
535                       msg_Dbg( p_demux, "FLAC header, channels: %i, rate: %i",
536                                p_stream->fmt.audio.i_channels,
537                                (int)p_stream->f_rate );
538                   }
539                   else
540                   {
541                       msg_Dbg( p_demux, "FLAC STREAMINFO metadata too short" );
542                   }
543
544                   /* Store STREAMINFO for the decoder and packetizer */
545                   p_stream->fmt.i_extra = p_oggpacket->bytes + 4;
546                   p_stream->fmt.p_extra = malloc( p_stream->fmt.i_extra );
547                   memcpy( p_stream->fmt.p_extra, "fLaC", 4);
548                   memcpy( ((uint8_t *)p_stream->fmt.p_extra) + 4,
549                           p_oggpacket->packet, p_oggpacket->bytes );
550
551                   /* Fake this as the last metadata block */
552                   ((uint8_t*)p_stream->fmt.p_extra)[4] |= 0x80;
553
554                   p_stream->p_es = es_out_Add( p_demux->out,
555                                                &p_stream->fmt );
556               }
557               else
558               {
559                   /* This ain't a STREAMINFO metadata */
560                   msg_Dbg( p_demux, "Invalid FLAC STREAMINFO metadata" );
561               }
562               p_stream->b_force_backup = 0;
563               p_stream->i_packets_backup = 0;
564
565               if( p_oggpacket->granulepos >= 0 )
566                   Ogg_UpdatePCR( p_stream, p_oggpacket );
567
568               p_stream->i_previous_pcr = 0;
569               return;
570           }
571           break;
572
573         default:
574           p_stream->b_force_backup = 0;
575           break;
576         }
577
578         /* Backup the ogg packet (likely an header packet) */
579         p_stream->p_packets_backup =
580             realloc( p_stream->p_packets_backup, p_stream->i_packets_backup *
581                      sizeof(ogg_packet) );
582
583         p_packet_backup =
584             &p_stream->p_packets_backup[p_stream->i_packets_backup - 1];
585
586         p_packet_backup->bytes = p_oggpacket->bytes;
587         p_packet_backup->granulepos = p_oggpacket->granulepos;
588
589         if( p_oggpacket->granulepos >= 0 )
590         {
591             /* Because of vorbis granulepos scheme we must set the pcr for the
592              * 1st header packet so it doesn't get discarded in the
593              * packetizer */
594             Ogg_UpdatePCR( p_stream, p_oggpacket );
595         }
596
597         p_packet_backup->packet = malloc( p_oggpacket->bytes );
598         if( !p_packet_backup->packet ) return;
599         memcpy( p_packet_backup->packet, p_oggpacket->packet,
600                 p_oggpacket->bytes );
601     }
602
603     /* Check the ES is selected */
604     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
605                     p_stream->p_es, &b_selected );
606
607     if( b_selected && !p_stream->b_activated )
608     {
609         p_stream->b_activated = VLC_TRUE;
610
611         /* Newly activated stream, feed the backup headers to the decoder */
612         if( !p_stream->b_force_backup )
613         {
614             int i;
615             for( i = 0; i < p_stream->i_packets_backup; i++ )
616             {
617                 /* Set correct starting date in header packets */
618                 p_stream->p_packets_backup[i].granulepos =
619                     p_stream->i_interpolated_pcr * p_stream->f_rate /
620                     I64C(1000000);
621
622                 Ogg_DecodePacket( p_demux, p_stream,
623                                   &p_stream->p_packets_backup[i] );
624             }
625         }
626     }
627
628     /* Convert the pcr into a pts */
629     if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
630         p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
631         p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
632     {
633         if( p_stream->i_pcr >= 0 )
634         {
635             /* This is for streams where the granulepos of the header packets
636              * doesn't match these of the data packets (eg. ogg web radios). */
637             if( p_stream->i_previous_pcr == 0 &&
638                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
639             {
640                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
641
642                 /* Call the pace control */
643                 es_out_Control( p_demux->out, ES_OUT_SET_PCR,
644                                 p_stream->i_pcr );
645             }
646
647             p_stream->i_previous_pcr = p_stream->i_pcr;
648
649             /* The granulepos is the end date of the sample */
650             i_pts =  p_stream->i_pcr;
651         }
652     }
653
654     /* Convert the granulepos into the next pcr */
655     Ogg_UpdatePCR( p_stream, p_oggpacket );
656
657     if( p_stream->i_pcr >= 0 )
658     {
659         /* This is for streams where the granulepos of the header packets
660          * doesn't match these of the data packets (eg. ogg web radios). */
661         if( p_stream->i_previous_pcr == 0 &&
662             p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
663         {
664             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
665
666             /* Call the pace control */
667             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_stream->i_pcr );
668         }
669     }
670
671     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
672         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
673         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
674         p_stream->i_pcr >= 0 )
675     {
676         p_stream->i_previous_pcr = p_stream->i_pcr;
677
678         /* The granulepos is the start date of the sample */
679         i_pts = p_stream->i_pcr;
680     }
681
682     if( !b_selected )
683     {
684         /* This stream isn't currently selected so we don't need to decode it,
685          * but we did need to store its pcr as it might be selected later on */
686         p_stream->b_activated = VLC_FALSE;
687         return;
688     }
689
690     if( !( p_block = block_New( p_demux, p_oggpacket->bytes ) ) ) return;
691
692     if( p_stream->fmt.i_cat == AUDIO_ES )
693         p_block->i_dts = p_block->i_pts = i_pts;
694     else if( p_stream->fmt.i_cat == SPU_ES )
695     {
696         p_block->i_dts = p_block->i_pts = i_pts;
697         p_block->i_length = 0;
698     }
699     else if( p_stream->fmt.i_codec == VLC_FOURCC( 't','h','e','o' ) )
700         p_block->i_dts = p_block->i_pts = i_pts;
701     else
702     {
703         p_block->i_dts = i_pts;
704         p_block->i_pts = 0;
705     }
706
707     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
708         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
709         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
710         p_stream->fmt.i_codec != VLC_FOURCC( 't','a','r','k' ) &&
711         p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) &&
712         p_stream->fmt.i_codec != VLC_FOURCC( 'c','m','m','l' ) )
713     {
714         /* We remove the header from the packet */
715         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
716         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
717         
718         if( p_stream->fmt.i_codec == VLC_FOURCC( 's','u','b','t' ))
719         {
720             /* But with subtitles we need to retrieve the duration first */
721             int i, lenbytes = 0;
722         
723             if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
724             {
725                 for( i = 0, lenbytes = 0; i < i_header_len; i++ )
726                 {
727                     lenbytes = lenbytes << 8;
728                     lenbytes += *(p_oggpacket->packet + i_header_len - i);
729                 }
730             }
731             if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
732                 ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
733                   p_oggpacket->packet[i_header_len + 1] != 0 && 
734                   p_oggpacket->packet[i_header_len + 1] != '\n' &&
735                   p_oggpacket->packet[i_header_len + 1] != '\r' ) )
736             {
737                 p_block->i_length = (mtime_t)lenbytes * 1000;
738             }
739         }
740
741         i_header_len++;
742         p_block->i_buffer -= i_header_len;
743     }
744
745     if( p_stream->fmt.i_codec == VLC_FOURCC( 't','a','r','k' ) )
746     {
747         /* FIXME: the biggest hack I've ever done */
748         msg_Warn( p_demux, "tarkin pts: "I64Fd", granule: "I64Fd,
749                   p_block->i_pts, p_block->i_dts );
750         msleep(10000);
751     }
752
753     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
754             p_oggpacket->bytes - i_header_len );
755
756     es_out_Send( p_demux->out, p_stream->p_es, p_block );
757 }
758
759 /****************************************************************************
760  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
761  *                         stream and fill p_ogg.
762  *****************************************************************************
763  * The initial page of a logical stream is marked as a 'bos' page.
764  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
765  * together and all of the initial pages must appear before any data pages.
766  *
767  * On success this function returns VLC_SUCCESS.
768  ****************************************************************************/
769 static int Ogg_FindLogicalStreams( demux_t *p_demux )
770 {
771     demux_sys_t *p_ogg = p_demux->p_sys  ;
772     ogg_packet oggpacket;
773     ogg_page oggpage;
774     int i_stream;
775
776 #define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]
777
778     while( Ogg_ReadPage( p_demux, &oggpage ) == VLC_SUCCESS )
779     {
780         if( ogg_page_bos( &oggpage ) )
781         {
782
783             /* All is wonderful in our fine fine little world.
784              * We found the beginning of our first logical stream. */
785             while( ogg_page_bos( &oggpage ) )
786             {
787                 p_ogg->i_streams++;
788                 p_ogg->pp_stream =
789                     realloc( p_ogg->pp_stream, p_ogg->i_streams *
790                              sizeof(logical_stream_t *) );
791
792                 p_stream = malloc( sizeof(logical_stream_t) );
793                 memset( p_stream, 0, sizeof(logical_stream_t) );
794
795                 es_format_Init( &p_stream->fmt, 0, 0 );
796                 p_stream->b_activated = VLC_TRUE;
797
798                 /* Setup the logical stream */
799                 p_stream->i_serial_no = ogg_page_serialno( &oggpage );
800                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
801
802                 /* Extract the initial header from the first page and verify
803                  * the codec type of tis Ogg bitstream */
804                 if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
805                 {
806                     /* error. stream version mismatch perhaps */
807                     msg_Err( p_demux, "error reading first page of "
808                              "Ogg bitstream data" );
809                     return VLC_EGENERIC;
810                 }
811
812                 /* FIXME: check return value */
813                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
814
815                 /* Check for Vorbis header */
816                 if( oggpacket.bytes >= 7 &&
817                     ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
818                 {
819                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
820                     msg_Dbg( p_demux, "found vorbis header" );
821                 }
822                 /* Check for Speex header */
823                 else if( oggpacket.bytes >= 7 &&
824                     ! strncmp( &oggpacket.packet[0], "Speex", 5 ) )
825                 {
826                     oggpack_buffer opb;
827
828                     p_stream->fmt.i_cat = AUDIO_ES;
829                     p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
830
831                     /* Signal that we want to keep a backup of the vorbis
832                      * stream headers. They will be used when switching between
833                      * audio streams. */
834                     p_stream->b_force_backup = 1;
835
836                     /* Cheat and get additionnal info ;) */
837                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
838                     oggpack_adv( &opb, 224 );
839                     oggpack_adv( &opb, 32 ); /* speex_version_id */
840                     oggpack_adv( &opb, 32 ); /* header_size */
841                     p_stream->f_rate = p_stream->fmt.audio.i_rate =
842                         oggpack_read( &opb, 32 );
843                     oggpack_adv( &opb, 32 ); /* mode */
844                     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
845                     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
846                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
847
848                     msg_Dbg( p_demux, "found speex header, channels: %i, "
849                              "rate: %i,  bitrate: %i",
850                              p_stream->fmt.audio.i_channels,
851                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
852                 }
853                 /* Check for Flac header */
854                 else if( oggpacket.bytes >= 4 &&
855                     ! strncmp( &oggpacket.packet[0], "fLaC", 4 ) )
856                 {
857                     msg_Dbg( p_demux, "found FLAC header" );
858
859                     /* Grrrr!!!! Did they really have to put all the
860                      * important info in the second header packet!!!
861                      * (STREAMINFO metadata is in the following packet) */
862                     p_stream->b_force_backup = 1;
863
864                     p_stream->fmt.i_cat = AUDIO_ES;
865                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
866                 }
867                 /* Check for Theora header */
868                 else if( oggpacket.bytes >= 7 &&
869                          ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
870                 {
871                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
872
873                     msg_Dbg( p_demux,
874                              "found theora header, bitrate: %i, rate: %f",
875                              p_stream->fmt.i_bitrate, p_stream->f_rate );
876                 }
877                 /* Check for Tarkin header */
878                 else if( oggpacket.bytes >= 7 &&
879                          ! strncmp( &oggpacket.packet[1], "tarkin", 6 ) )
880                 {
881                     oggpack_buffer opb;
882
883                     msg_Dbg( p_demux, "found tarkin header" );
884                     p_stream->fmt.i_cat = VIDEO_ES;
885                     p_stream->fmt.i_codec = VLC_FOURCC( 't','a','r','k' );
886
887                     /* Cheat and get additionnal info ;) */
888                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
889                     oggpack_adv( &opb, 88 );
890                     oggpack_adv( &opb, 104 );
891                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
892                     p_stream->f_rate = 2; /* FIXME */
893                     msg_Dbg( p_demux,
894                              "found tarkin header, bitrate: %i, rate: %f",
895                              p_stream->fmt.i_bitrate, p_stream->f_rate );
896                 }
897                 /* Check for Annodex header */
898                 else if( oggpacket.bytes >= 7 &&
899                          ! strncmp( &oggpacket.packet[0], "Annodex", 7 ) )
900                 {
901                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
902                                            &oggpacket );
903                     /* kill annodex track */
904                     free( p_stream );
905                     p_ogg->i_streams--;
906                 }
907                 /* Check for Annodex header */
908                 else if( oggpacket.bytes >= 7 &&
909                          ! strncmp( &oggpacket.packet[0], "AnxData", 7 ) )
910                 {
911                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
912                                            &oggpacket );
913                 }
914                 else if( oggpacket.bytes >= 142 &&
915                          !strncmp( &oggpacket.packet[1],
916                                    "Direct Show Samples embedded in Ogg", 35 ))
917                 {
918                     /* Old header type */
919
920                     /* Check for video header (old format) */
921                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
922                         oggpacket.bytes >= 184 )
923                     {
924                         p_stream->fmt.i_cat = VIDEO_ES;
925                         p_stream->fmt.i_codec =
926                             VLC_FOURCC( oggpacket.packet[68],
927                                         oggpacket.packet[69],
928                                         oggpacket.packet[70],
929                                         oggpacket.packet[71] );
930                         msg_Dbg( p_demux, "found video header of type: %.4s",
931                                  (char *)&p_stream->fmt.i_codec );
932
933                         p_stream->f_rate = 10000000.0 /
934                             GetQWLE((oggpacket.packet+164));
935                         p_stream->fmt.video.i_bits_per_pixel =
936                             GetWLE((oggpacket.packet+182));
937                         if( !p_stream->fmt.video.i_bits_per_pixel )
938                             /* hack, FIXME */
939                             p_stream->fmt.video.i_bits_per_pixel = 24;
940                         p_stream->fmt.video.i_width =
941                             GetDWLE((oggpacket.packet+176));
942                         p_stream->fmt.video.i_height =
943                             GetDWLE((oggpacket.packet+180));
944
945                         msg_Dbg( p_demux,
946                                  "fps: %f, width:%i; height:%i, bitcount:%i",
947                                  p_stream->f_rate,
948                                  p_stream->fmt.video.i_width,
949                                  p_stream->fmt.video.i_height,
950                                  p_stream->fmt.video.i_bits_per_pixel);
951
952                     }
953                     /* Check for audio header (old format) */
954                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
955                     {
956                         unsigned int i_extra_size;
957                         unsigned int i_format_tag;
958
959                         p_stream->fmt.i_cat = AUDIO_ES;
960
961                         i_extra_size = GetWLE((oggpacket.packet+140));
962                         if( i_extra_size )
963                         {
964                             p_stream->fmt.i_extra = i_extra_size;
965                             p_stream->fmt.p_extra = malloc( i_extra_size );
966                             memcpy( p_stream->fmt.p_extra,
967                                     oggpacket.packet + 142, i_extra_size );
968                         }
969
970                         i_format_tag = GetWLE((oggpacket.packet+124));
971                         p_stream->fmt.audio.i_channels =
972                             GetWLE((oggpacket.packet+126));
973                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
974                             GetDWLE((oggpacket.packet+128));
975                         p_stream->fmt.i_bitrate =
976                             GetDWLE((oggpacket.packet+132)) * 8;
977                         p_stream->fmt.audio.i_blockalign =
978                             GetWLE((oggpacket.packet+136));
979                         p_stream->fmt.audio.i_bitspersample =
980                             GetWLE((oggpacket.packet+138));
981
982                         wf_tag_to_fourcc( i_format_tag,
983                                           &p_stream->fmt.i_codec, 0 );
984
985                         if( p_stream->fmt.i_codec ==
986                             VLC_FOURCC('u','n','d','f') )
987                         {
988                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
989                                 ( i_format_tag >> 8 ) & 0xff,
990                                 i_format_tag & 0xff );
991                         }
992
993                         msg_Dbg( p_demux, "found audio header of type: %.4s",
994                                  (char *)&p_stream->fmt.i_codec );
995                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
996                                  "%dbits/sample %dkb/s",
997                                  i_format_tag,
998                                  p_stream->fmt.audio.i_channels,
999                                  p_stream->fmt.audio.i_rate,
1000                                  p_stream->fmt.audio.i_bitspersample,
1001                                  p_stream->fmt.i_bitrate / 1024 );
1002
1003                     }
1004                     else
1005                     {
1006                         msg_Dbg( p_demux, "stream %d has an old header "
1007                             "but is of an unknown type", p_ogg->i_streams-1 );
1008                         free( p_stream );
1009                         p_ogg->i_streams--;
1010                     }
1011                 }
1012                 else if( (*oggpacket.packet & PACKET_TYPE_BITS )
1013                          == PACKET_TYPE_HEADER &&
1014                          oggpacket.bytes >= (int)sizeof(stream_header)+1 )
1015                 {
1016                     stream_header *st = (stream_header *)(oggpacket.packet+1);
1017
1018                     /* Check for video header (new format) */
1019                     if( !strncmp( st->streamtype, "video", 5 ) )
1020                     {
1021                         p_stream->fmt.i_cat = VIDEO_ES;
1022
1023                         /* We need to get rid of the header packet */
1024                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1025
1026                         p_stream->fmt.i_codec =
1027                             VLC_FOURCC( st->subtype[0], st->subtype[1],
1028                                         st->subtype[2], st->subtype[3] );
1029                         msg_Dbg( p_demux, "found video header of type: %.4s",
1030                                  (char *)&p_stream->fmt.i_codec );
1031
1032                         p_stream->f_rate = 10000000.0 /
1033                             GetQWLE(&st->time_unit);
1034                         p_stream->fmt.video.i_bits_per_pixel =
1035                             GetWLE(&st->bits_per_sample);
1036                         p_stream->fmt.video.i_width =
1037                             GetDWLE(&st->sh.video.width);
1038                         p_stream->fmt.video.i_height =
1039                             GetDWLE(&st->sh.video.height);
1040
1041                         msg_Dbg( p_demux,
1042                                  "fps: %f, width:%i; height:%i, bitcount:%i",
1043                                  p_stream->f_rate,
1044                                  p_stream->fmt.video.i_width,
1045                                  p_stream->fmt.video.i_height,
1046                                  p_stream->fmt.video.i_bits_per_pixel );
1047                     }
1048                     /* Check for audio header (new format) */
1049                     else if( !strncmp( st->streamtype, "audio", 5 ) )
1050                     {
1051                         char p_buffer[5];
1052                         int i_format_tag;
1053
1054                         p_stream->fmt.i_cat = AUDIO_ES;
1055
1056                         /* We need to get rid of the header packet */
1057                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1058
1059                         p_stream->fmt.i_extra = GetQWLE(&st->size) -
1060                             sizeof(stream_header);
1061                         if( p_stream->fmt.i_extra )
1062                         {
1063                             p_stream->fmt.p_extra =
1064                                 malloc( p_stream->fmt.i_extra );
1065                             memcpy( p_stream->fmt.p_extra, st + 1,
1066                                     p_stream->fmt.i_extra );
1067                         }
1068
1069                         memcpy( p_buffer, st->subtype, 4 );
1070                         p_buffer[4] = '\0';
1071                         i_format_tag = strtol(p_buffer,NULL,16);
1072                         p_stream->fmt.audio.i_channels =
1073                             GetWLE(&st->sh.audio.channels);
1074                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
1075                             GetQWLE(&st->samples_per_unit);
1076                         p_stream->fmt.i_bitrate =
1077                             GetDWLE(&st->sh.audio.avgbytespersec) * 8;
1078                         p_stream->fmt.audio.i_blockalign =
1079                             GetWLE(&st->sh.audio.blockalign);
1080                         p_stream->fmt.audio.i_bitspersample =
1081                             GetWLE(&st->bits_per_sample);
1082
1083                         wf_tag_to_fourcc( i_format_tag,
1084                                           &p_stream->fmt.i_codec, 0 );
1085
1086                         if( p_stream->fmt.i_codec ==
1087                             VLC_FOURCC('u','n','d','f') )
1088                         {
1089                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1090                                 ( i_format_tag >> 8 ) & 0xff,
1091                                 i_format_tag & 0xff );
1092                         }
1093
1094                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1095                                  (char *)&p_stream->fmt.i_codec );
1096                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1097                                  "%dbits/sample %dkb/s",
1098                                  i_format_tag,
1099                                  p_stream->fmt.audio.i_channels,
1100                                  p_stream->fmt.audio.i_rate,
1101                                  p_stream->fmt.audio.i_bitspersample,
1102                                  p_stream->fmt.i_bitrate / 1024 );
1103                     }
1104                     /* Check for text (subtitles) header */
1105                     else if( !strncmp(st->streamtype, "text", 4) )
1106                     {
1107                         /* We need to get rid of the header packet */
1108                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1109
1110                         msg_Dbg( p_demux, "found text subtitles header" );
1111                         p_stream->fmt.i_cat = SPU_ES;
1112                         p_stream->fmt.i_codec = VLC_FOURCC('s','u','b','t');
1113                         p_stream->f_rate = 1000; /* granulepos is in milisec */
1114                     }
1115                     else
1116                     {
1117                         msg_Dbg( p_demux, "stream %d has a header marker "
1118                             "but is of an unknown type", p_ogg->i_streams-1 );
1119                         free( p_stream );
1120                         p_ogg->i_streams--;
1121                     }
1122                 }
1123                 else
1124                 {
1125                     msg_Dbg( p_demux, "stream %d is of unknown type",
1126                              p_ogg->i_streams-1 );
1127                     free( p_stream );
1128                     p_ogg->i_streams--;
1129                 }
1130
1131                 if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
1132                     return VLC_EGENERIC;
1133             }
1134
1135             /* This is the first data page, which means we are now finished
1136              * with the initial pages. We just need to store it in the relevant
1137              * bitstream. */
1138             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1139             {
1140                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
1141                                        &oggpage ) == 0 )
1142                 {
1143                     break;
1144                 }
1145             }
1146
1147             return VLC_SUCCESS;
1148         }
1149     }
1150 #undef p_stream
1151
1152     return VLC_EGENERIC;
1153 }
1154
1155 /****************************************************************************
1156  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1157  *                        Elementary streams.
1158  ****************************************************************************/
1159 static int Ogg_BeginningOfStream( demux_t *p_demux )
1160 {
1161     demux_sys_t *p_ogg = p_demux->p_sys  ;
1162     int i_stream;
1163
1164     /* Find the logical streams embedded in the physical stream and
1165      * initialize our p_ogg structure. */
1166     if( Ogg_FindLogicalStreams( p_demux ) != VLC_SUCCESS )
1167     {
1168         msg_Warn( p_demux, "couldn't find any ogg logical stream" );
1169         return VLC_EGENERIC;
1170     }
1171
1172     p_ogg->i_bitrate = 0;
1173
1174     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1175     {
1176 #define p_stream p_ogg->pp_stream[i_stream]
1177         if( p_stream->fmt.i_codec != VLC_FOURCC('f','l','a','c') )
1178             p_stream->p_es = es_out_Add( p_demux->out, &p_stream->fmt );
1179
1180         if( p_stream->fmt.i_codec == VLC_FOURCC('c','m','m','l') )
1181         {
1182             /* Set the CMML stream active */
1183             es_out_Control( p_demux->out, ES_OUT_SET_ES,
1184                             p_stream->p_es );
1185         }
1186
1187         p_ogg->i_bitrate += p_stream->fmt.i_bitrate;
1188
1189         p_stream->i_pcr = p_stream->i_previous_pcr =
1190             p_stream->i_interpolated_pcr = -1;
1191         p_stream->b_reinit = 0;
1192 #undef p_stream
1193     }
1194
1195     return VLC_SUCCESS;
1196 }
1197
1198 /****************************************************************************
1199  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1200  ****************************************************************************/
1201 static void Ogg_EndOfStream( demux_t *p_demux )
1202 {
1203     demux_sys_t *p_ogg = p_demux->p_sys  ;
1204     int i_stream, j;
1205
1206 #define p_stream p_ogg->pp_stream[i_stream]
1207     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1208     {
1209         if( p_stream->p_es )
1210             es_out_Del( p_demux->out, p_stream->p_es );
1211
1212         p_ogg->i_bitrate -= p_stream->fmt.i_bitrate;
1213
1214         ogg_stream_clear( &p_ogg->pp_stream[i_stream]->os );
1215         for( j = 0; j < p_ogg->pp_stream[i_stream]->i_packets_backup; j++ )
1216         {
1217             free( p_ogg->pp_stream[i_stream]->p_packets_backup[j].packet );
1218         }
1219         if( p_ogg->pp_stream[i_stream]->p_packets_backup)
1220             free( p_ogg->pp_stream[i_stream]->p_packets_backup );
1221
1222         es_format_Clean( &p_stream->fmt );
1223
1224         free( p_ogg->pp_stream[i_stream] );
1225     }
1226 #undef p_stream
1227
1228     /* Reinit p_ogg */
1229     if( p_ogg->pp_stream ) free( p_ogg->pp_stream );
1230     p_ogg->pp_stream = NULL;
1231     p_ogg->i_streams = 0;
1232 }
1233
1234 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
1235                                   ogg_packet *p_oggpacket )
1236 {
1237     bs_t bitstream;
1238     int i_fps_numerator;
1239     int i_fps_denominator;
1240     int i_keyframe_frequency_force;
1241
1242     p_stream->fmt.i_cat = VIDEO_ES;
1243     p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1244
1245     /* Signal that we want to keep a backup of the vorbis
1246      * stream headers. They will be used when switching between
1247      * audio streams. */
1248     p_stream->b_force_backup = 1;
1249
1250     /* Cheat and get additionnal info ;) */
1251     bs_init( &bitstream, p_oggpacket->packet, p_oggpacket->bytes );
1252     bs_skip( &bitstream, 56 );
1253     bs_read( &bitstream, 8 ); /* major version num */
1254     bs_read( &bitstream, 8 ); /* minor version num */
1255     bs_read( &bitstream, 8 ); /* subminor version num */
1256     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
1257     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
1258     bs_read( &bitstream, 24 ); /* frame width */
1259     bs_read( &bitstream, 24 ); /* frame height */
1260     bs_read( &bitstream, 8 ); /* x offset */
1261     bs_read( &bitstream, 8 ); /* y offset */
1262
1263     i_fps_numerator = bs_read( &bitstream, 32 );
1264     i_fps_denominator = bs_read( &bitstream, 32 );
1265     bs_read( &bitstream, 24 ); /* aspect_numerator */
1266     bs_read( &bitstream, 24 ); /* aspect_denominator */
1267
1268     bs_read( &bitstream, 8 ); /* colorspace */
1269     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
1270     bs_read( &bitstream, 6 ); /* quality */
1271
1272     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
1273
1274     /* granule_shift = i_log( frequency_force -1 ) */
1275     p_stream->i_theora_keyframe_granule_shift = 0;
1276     i_keyframe_frequency_force--;
1277     while( i_keyframe_frequency_force )
1278     {
1279         p_stream->i_theora_keyframe_granule_shift++;
1280         i_keyframe_frequency_force >>= 1;
1281     }
1282
1283     p_stream->f_rate = ((float)i_fps_numerator) / i_fps_denominator;
1284
1285     /* Save this data in p_extra for ffmpeg */
1286     p_stream->fmt.i_extra = p_oggpacket->bytes;
1287     p_stream->fmt.p_extra = malloc( p_oggpacket->bytes );
1288     memcpy( p_stream->fmt.p_extra, p_oggpacket->packet, p_oggpacket->bytes );
1289
1290 }
1291
1292 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
1293                                   ogg_packet *p_oggpacket )
1294 {
1295     oggpack_buffer opb;
1296
1297     p_stream->fmt.i_cat = AUDIO_ES;
1298     p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1299
1300     /* Signal that we want to keep a backup of the vorbis
1301      * stream headers. They will be used when switching between
1302      * audio streams. */
1303     p_stream->b_force_backup = 1;
1304
1305     /* Cheat and get additionnal info ;) */
1306     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1307     oggpack_adv( &opb, 88 );
1308     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
1309     p_stream->f_rate = p_stream->fmt.audio.i_rate =
1310         oggpack_read( &opb, 32 );
1311     oggpack_adv( &opb, 32 );
1312     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1313 }
1314
1315 static void Ogg_ReadAnnodexHeader( vlc_object_t *p_this,
1316                                    logical_stream_t *p_stream,
1317                                    ogg_packet *p_oggpacket )
1318 {
1319     if( ! strncmp( &p_oggpacket->packet[0], "Annodex", 7 ) )
1320     {
1321         oggpack_buffer opb;
1322
1323         uint16_t major_version;
1324         uint16_t minor_version;
1325         uint64_t timebase_numerator;
1326         uint64_t timebase_denominator;
1327
1328         Ogg_ReadTheoraHeader( p_stream, p_oggpacket );
1329
1330         oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1331         oggpack_adv( &opb, 8*8 ); /* "Annodex\0" header */
1332         major_version = oggpack_read( &opb, 2*8 ); /* major version */
1333         minor_version = oggpack_read( &opb, 2*8 ); /* minor version */
1334         timebase_numerator = GetQWLE( &p_oggpacket->packet[16] );
1335         timebase_denominator = GetQWLE( &p_oggpacket->packet[24] );
1336     }
1337     else if( ! strncmp( &p_oggpacket->packet[0], "AnxData", 7 ) )
1338     {
1339         uint64_t granule_rate_numerator;
1340         uint64_t granule_rate_denominator;
1341         char content_type_string[1024];
1342
1343         /* Read in Annodex header fields */
1344
1345         granule_rate_numerator = GetQWLE( &p_oggpacket->packet[8] );
1346         granule_rate_denominator = GetQWLE( &p_oggpacket->packet[16] );
1347         p_stream->secondary_header_packets =
1348             GetDWLE( &p_oggpacket->packet[24] );
1349
1350         msg_Dbg( p_this, "anxdata packet info: %qd/%qd, %d",
1351                  granule_rate_numerator, granule_rate_denominator,
1352                  p_stream->secondary_header_packets);
1353
1354         /* we are guaranteed that the first header field will be
1355          * the content-type (by the Annodex standard) */
1356         sscanf( &p_oggpacket->packet[28], "Content-Type: %1024s\r\n",
1357                 content_type_string );
1358
1359         p_stream->f_rate = (float) granule_rate_numerator /
1360             (float) granule_rate_denominator;
1361
1362         /* What type of file do we have?
1363          * strcmp is safe to use here because we've extracted
1364          * content_type_string from the stream manually */
1365         if( !strncmp(content_type_string, "audio/x-wav", 11) )
1366         {
1367             /* n.b. WAVs are unsupported right now */
1368             p_stream->fmt.i_cat = UNKNOWN_ES;
1369         }
1370         else if( !strncmp(content_type_string, "audio/x-vorbis", 14) )
1371         {
1372             p_stream->fmt.i_cat = AUDIO_ES;
1373             p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1374
1375             p_stream->b_force_backup = 1;
1376         }
1377         else if( !strncmp(content_type_string, "video/x-theora", 14) )
1378         {
1379             p_stream->fmt.i_cat = VIDEO_ES;
1380             p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1381
1382             p_stream->b_force_backup = 1;
1383         }
1384         else if( !strncmp(content_type_string, "video/x-xvid", 14) )
1385         {
1386             p_stream->fmt.i_cat = VIDEO_ES;
1387             p_stream->fmt.i_codec = VLC_FOURCC( 'x','v','i','d' );
1388
1389             p_stream->b_force_backup = 1;
1390         }
1391         else if( !strncmp(content_type_string, "video/mpeg", 14) )
1392         {
1393             /* n.b. MPEG streams are unsupported right now */
1394             p_stream->fmt.i_cat = VIDEO_ES;
1395             p_stream->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1396         }
1397         else if( !strncmp(content_type_string, "text/x-cmml", 11) )
1398         {
1399             ogg_stream_packetout( &p_stream->os, p_oggpacket );
1400             p_stream->fmt.i_cat = SPU_ES;
1401             p_stream->fmt.i_codec = VLC_FOURCC( 'c','m','m','l' );
1402         }
1403     }
1404 }