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