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