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