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