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