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