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