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