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