]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
Use var_Inherit* instead of var_CreateGet*.
[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_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_demux.h>
35 #include <vlc_meta.h>
36 #include <vlc_input.h>
37
38 #include <ogg/ogg.h>
39
40 #include <vlc_codecs.h>
41 #include <vlc_bits.h>
42 #include "xiph.h"
43 #include "vorbis.h"
44 #include "kate_categories.h"
45 #include "ogg.h"
46 #include "oggseek.h"
47
48 /*****************************************************************************
49  * Module descriptor
50  *****************************************************************************/
51 static int  Open ( vlc_object_t * );
52 static void Close( vlc_object_t * );
53
54 vlc_module_begin ()
55     set_shortname ( "OGG" )
56     set_description( N_("OGG demuxer" ) )
57     set_category( CAT_INPUT )
58     set_subcategory( SUBCAT_INPUT_DEMUX )
59     set_capability( "demux", 50 )
60     set_callbacks( Open, Close )
61     add_shortcut( "ogg" )
62 vlc_module_end ()
63
64
65 /*****************************************************************************
66  * Definitions of structures and functions used by this plugins
67  *****************************************************************************/
68
69 /* OggDS headers for the new header format (used in ogm files) */
70 typedef struct
71 {
72     ogg_int32_t width;
73     ogg_int32_t height;
74 } stream_header_video_t;
75
76 typedef struct
77 {
78     ogg_int16_t channels;
79     ogg_int16_t padding;
80     ogg_int16_t blockalign;
81     ogg_int32_t avgbytespersec;
82 } stream_header_audio_t;
83
84 typedef struct
85 {
86     char        streamtype[8];
87     char        subtype[4];
88
89     ogg_int32_t size;                               /* size of the structure */
90
91     ogg_int64_t time_unit;                              /* in reference time */
92     ogg_int64_t samples_per_unit;
93     ogg_int32_t default_len;                                /* in media time */
94
95     ogg_int32_t buffersize;
96     ogg_int16_t bits_per_sample;
97     ogg_int16_t padding;
98
99     union
100     {
101         /* Video specific */
102         stream_header_video_t video;
103         /* Audio specific */
104         stream_header_audio_t audio;
105     } sh;
106 } stream_header_t;
107
108
109 /* Some defines from OggDS */
110 #define PACKET_TYPE_HEADER   0x01
111 #define PACKET_TYPE_BITS     0x07
112 #define PACKET_LEN_BITS01    0xc0
113 #define PACKET_LEN_BITS2     0x02
114 #define PACKET_IS_SYNCPOINT  0x08
115
116 /*****************************************************************************
117  * Local prototypes
118  *****************************************************************************/
119 static int  Demux  ( demux_t * );
120 static int  Control( demux_t *, int, va_list );
121
122 /* Bitstream manipulation */
123 static int  Ogg_ReadPage     ( demux_t *, ogg_page * );
124 static void Ogg_UpdatePCR    ( logical_stream_t *, ogg_packet * );
125 static void Ogg_DecodePacket ( demux_t *, logical_stream_t *, ogg_packet * );
126
127 static int Ogg_BeginningOfStream( demux_t *p_demux );
128 static int Ogg_FindLogicalStreams( demux_t *p_demux );
129 static void Ogg_EndOfStream( demux_t *p_demux );
130
131 /* */
132 static void Ogg_LogicalStreamDelete( demux_t *p_demux, logical_stream_t *p_stream );
133 static bool Ogg_LogicalStreamResetEsFormat( demux_t *p_demux, logical_stream_t *p_stream );
134
135 /* */
136 static void Ogg_ExtractMeta( demux_t *p_demux, vlc_fourcc_t i_codec, const uint8_t *p_headers, int i_headers );
137
138 /* Logical bitstream headers */
139 static void Ogg_ReadTheoraHeader( logical_stream_t *, ogg_packet * );
140 static void Ogg_ReadVorbisHeader( logical_stream_t *, ogg_packet * );
141 static void Ogg_ReadSpeexHeader( logical_stream_t *, ogg_packet * );
142 static void Ogg_ReadKateHeader( logical_stream_t *, ogg_packet * );
143 static void Ogg_ReadFlacHeader( demux_t *, logical_stream_t *, ogg_packet * );
144 static void Ogg_ReadAnnodexHeader( vlc_object_t *, logical_stream_t *, ogg_packet * );
145 static bool Ogg_ReadDiracHeader( logical_stream_t *, ogg_packet * );
146
147 /*****************************************************************************
148  * Open: initializes ogg demux structures
149  *****************************************************************************/
150 static int Open( vlc_object_t * p_this )
151 {
152     demux_t *p_demux = (demux_t *)p_this;
153     demux_sys_t    *p_sys;
154     const uint8_t  *p_peek;
155
156
157     /* Check if we are dealing with an ogg stream */
158     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
159     if( !p_demux->b_force && memcmp( p_peek, "OggS", 4 ) )
160     {
161         return VLC_EGENERIC;
162     }
163
164     /* Set exported functions */
165     p_demux->pf_demux = Demux;
166     p_demux->pf_control = Control;
167     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
168     if( !p_sys )
169         return VLC_ENOMEM;
170
171     memset( p_sys, 0, sizeof( demux_sys_t ) );
172     p_sys->i_bitrate = 0;
173     p_sys->pp_stream = NULL;
174     p_sys->p_old_stream = NULL;
175
176     /* Begnning of stream, tell the demux to look for elementary streams. */
177     p_sys->i_bos = 0;
178     p_sys->i_eos = 0;
179
180     /* Initialize the Ogg physical bitstream parser */
181     ogg_sync_init( &p_sys->oy );
182     p_sys->b_page_waiting = false;
183
184     /* */
185     p_sys->p_meta = NULL;
186
187     return VLC_SUCCESS;
188 }
189
190 /*****************************************************************************
191  * Close: frees unused data
192  *****************************************************************************/
193 static void Close( vlc_object_t *p_this )
194 {
195     demux_t *p_demux = (demux_t *)p_this;
196     demux_sys_t *p_sys = p_demux->p_sys  ;
197
198     /* Cleanup the bitstream parser */
199     ogg_sync_clear( &p_sys->oy );
200
201     Ogg_EndOfStream( p_demux );
202
203     if( p_sys->p_old_stream )
204         Ogg_LogicalStreamDelete( p_demux, p_sys->p_old_stream );
205
206     free( p_sys );
207 }
208
209 /*****************************************************************************
210  * Demux: reads and demuxes data packets
211  *****************************************************************************
212  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
213  *****************************************************************************/
214 static int Demux( demux_t * p_demux )
215 {
216     demux_sys_t *p_sys = p_demux->p_sys;
217     ogg_packet  oggpacket;
218     int         i_stream;
219     bool b_skipping = false;
220
221
222     if( p_sys->i_eos == p_sys->i_streams )
223     {
224         if( p_sys->i_eos )
225         {
226             msg_Dbg( p_demux, "end of a group of logical streams" );
227             /* We keep the ES to try reusing it in Ogg_BeginningOfStream
228              * only 1 ES is supported (common case for ogg web radio) */
229             if( p_sys->i_streams == 1 )
230             {
231                 p_sys->p_old_stream = p_sys->pp_stream[0];
232                 TAB_CLEAN( p_sys->i_streams, p_sys->pp_stream );
233             }
234             Ogg_EndOfStream( p_demux );
235         }
236
237         p_sys->i_eos = 0;
238         if( Ogg_BeginningOfStream( p_demux ) != VLC_SUCCESS )
239             return 0;
240
241         msg_Dbg( p_demux, "beginning of a group of logical streams" );
242         es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
243     }
244
245     /*
246      * The first data page of a physical stream is stored in the relevant logical stream
247      * in Ogg_FindLogicalStreams. Therefore, we must not read a page and only update the
248      * stream it belongs to if we haven't processed this first page yet. If we do, we
249      * will only process that first page whenever we find the second page for this stream.
250      * While this is fine for Vorbis and Theora, which are continuous codecs, which means
251      * the second page will arrive real quick, this is not fine for Kate, whose second
252      * data page will typically arrive much later.
253      * This means it is now possible to seek right at the start of a stream where the last
254      * logical stream is Kate, without having to wait for the second data page to unblock
255      * the first one, which is the one that triggers the 'no more headers to backup' code.
256      * And, as we all know, seeking without having backed up all headers is bad, since the
257      * codec will fail to initialize if it's missing its headers.
258      */
259     if( !p_sys->b_page_waiting)
260     {
261         /*
262          * Demux an ogg page from the stream
263          */
264         if( Ogg_ReadPage( p_demux, &p_sys->current_page ) != VLC_SUCCESS )
265             return 0; /* EOF */
266
267         /* Test for End of Stream */
268         if( ogg_page_eos( &p_sys->current_page ) )
269             p_sys->i_eos++;
270     }
271
272
273     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
274     {
275         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
276
277         /* if we've just pulled page, look for the right logical stream */
278         if( !p_sys->b_page_waiting )
279         {
280             if( p_sys->i_streams == 1 &&
281                 ogg_page_serialno( &p_sys->current_page ) != p_stream->os.serialno )
282             {
283                 msg_Err( p_demux, "Broken Ogg stream (serialno) mismatch" );
284                 ogg_stream_reset_serialno( &p_stream->os, ogg_page_serialno( &p_sys->current_page ) );
285
286                 p_stream->b_reinit = true;
287                 p_stream->i_pcr = -1;
288                 p_stream->i_interpolated_pcr = -1;
289                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
290             }
291
292             if( ogg_stream_pagein( &p_stream->os, &p_sys->current_page ) != 0 )
293             {
294                 continue;
295             }
296
297         }
298
299         while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
300         {
301             /* Read info from any secondary header packets, if there are any */
302             if( p_stream->i_secondary_header_packets > 0 )
303             {
304                 if( p_stream->fmt.i_codec == VLC_CODEC_THEORA &&
305                         oggpacket.bytes >= 7 &&
306                         ! memcmp( oggpacket.packet, "\x80theora", 7 ) )
307                 {
308                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
309                     p_stream->i_secondary_header_packets = 0;
310                 }
311                 else if( p_stream->fmt.i_codec == VLC_CODEC_VORBIS &&
312                         oggpacket.bytes >= 7 &&
313                         ! memcmp( oggpacket.packet, "\x01vorbis", 7 ) )
314                 {
315                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
316                     p_stream->i_secondary_header_packets = 0;
317                 }
318                 else if( p_stream->fmt.i_codec == VLC_CODEC_CMML )
319                 {
320                     p_stream->i_secondary_header_packets = 0;
321                 }
322
323                 /* update start of data pointer */
324                 p_stream->i_data_start = stream_Tell( p_demux->s );
325
326             }
327
328             /* If any streams have i_skip_frames, only decode (pre-roll)
329              *  for those streams */
330             if ( b_skipping && p_stream->i_skip_frames == 0 ) continue;
331
332
333             if( p_stream->b_reinit )
334             {
335                 /* If synchro is re-initialized we need to drop all the packets
336                  * until we find a new dated one. */
337                 Ogg_UpdatePCR( p_stream, &oggpacket );
338
339                 if( p_stream->i_pcr >= 0 )
340                 {
341                     p_stream->b_reinit = false;
342                 }
343                 else
344                 {
345                     p_stream->i_interpolated_pcr = -1;
346                     continue;
347                 }
348
349                 /* An Ogg/vorbis packet contains an end date granulepos */
350                 if( p_stream->fmt.i_codec == VLC_CODEC_VORBIS ||
351                     p_stream->fmt.i_codec == VLC_CODEC_SPEEX ||
352                     p_stream->fmt.i_codec == VLC_CODEC_FLAC )
353                 {
354                     if( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
355                     {
356                         Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
357                     }
358                     else
359                     {
360                         es_out_Control( p_demux->out, ES_OUT_SET_PCR,
361                                         VLC_TS_0 + p_stream->i_pcr );
362                     }
363                     continue;
364                 }
365             }
366
367             Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
368         }
369
370         if( !p_sys->b_page_waiting )
371             break;
372     }
373
374     /* if a page was waiting, it's now processed */
375     p_sys->b_page_waiting = false;
376
377     p_sys->i_pcr = -1;
378     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
379     {
380         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
381
382         if( p_stream->fmt.i_cat == SPU_ES )
383             continue;
384         if( p_stream->i_interpolated_pcr < 0 )
385             continue;
386
387         if( p_sys->i_pcr < 0 || p_stream->i_interpolated_pcr < p_sys->i_pcr )
388             p_sys->i_pcr = p_stream->i_interpolated_pcr;
389     }
390
391     if( p_sys->i_pcr >= 0 && ! b_skipping )
392         es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
393
394     return 1;
395 }
396
397 /*****************************************************************************
398  * Control:
399  *****************************************************************************/
400 static int Control( demux_t *p_demux, int i_query, va_list args )
401 {
402     demux_sys_t *p_sys  = p_demux->p_sys;
403     vlc_meta_t *p_meta;
404     int64_t *pi64;
405     bool *pb_bool;
406     int i;
407
408     switch( i_query )
409     {
410         case DEMUX_GET_META:
411             p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t* );
412             if( p_sys->p_meta )
413                 vlc_meta_Merge( p_meta, p_sys->p_meta );
414             return VLC_SUCCESS;
415
416         case DEMUX_HAS_UNSUPPORTED_META:
417             pb_bool = (bool*)va_arg( args, bool* );
418             *pb_bool = true;
419             return VLC_SUCCESS;
420
421         case DEMUX_GET_TIME:
422             pi64 = (int64_t*)va_arg( args, int64_t * );
423             *pi64 = p_sys->i_pcr;
424             return VLC_SUCCESS;
425
426         case DEMUX_SET_TIME:
427             return VLC_EGENERIC;
428
429         case DEMUX_SET_POSITION:
430             /* forbid seeking if we haven't initialized all logical bitstreams yet;
431                if we allowed, some headers would not get backed up and decoder init
432                would fail, making that logical stream unusable */
433             if( p_sys->i_bos > 0 )
434             {
435                 return VLC_EGENERIC;
436             }
437
438             for( i = 0; i < p_sys->i_streams; i++ )
439             {
440                 logical_stream_t *p_stream = p_sys->pp_stream[i];
441
442                 /* we'll trash all the data until we find the next pcr */
443                 p_stream->b_reinit = true;
444                 p_stream->i_pcr = -1;
445                 p_stream->i_interpolated_pcr = -1;
446                 ogg_stream_reset( &p_stream->os );
447             }
448             ogg_sync_reset( &p_sys->oy );
449             /* XXX The break/return is missing on purpose as
450              * demux_vaControlHelper will do the last part of the job */
451
452         default:
453             return demux_vaControlHelper( p_demux->s, 0, -1, p_sys->i_bitrate,
454                                            1, i_query, args );
455     }
456 }
457
458 /****************************************************************************
459  * Ogg_ReadPage: Read a full Ogg page from the physical bitstream.
460  ****************************************************************************
461  * Returns VLC_SUCCESS if a page has been read. An error might happen if we
462  * are at the end of stream.
463  ****************************************************************************/
464 static int Ogg_ReadPage( demux_t *p_demux, ogg_page *p_oggpage )
465 {
466     demux_sys_t *p_ogg = p_demux->p_sys  ;
467     int i_read = 0;
468     char *p_buffer;
469
470     while( ogg_sync_pageout( &p_ogg->oy, p_oggpage ) != 1 )
471     {
472         p_buffer = ogg_sync_buffer( &p_ogg->oy, OGGSEEK_BYTES_TO_READ );
473
474         i_read = stream_Read( p_demux->s, p_buffer, OGGSEEK_BYTES_TO_READ );
475         if( i_read <= 0 )
476             return VLC_EGENERIC;
477
478         ogg_sync_wrote( &p_ogg->oy, i_read );
479     }
480
481     return VLC_SUCCESS;
482 }
483
484 /****************************************************************************
485  * Ogg_UpdatePCR: update the PCR (90kHz program clock reference) for the
486  *                current stream.
487  ****************************************************************************/
488 static void Ogg_UpdatePCR( logical_stream_t *p_stream,
489                            ogg_packet *p_oggpacket )
490 {
491     /* Convert the granulepos into a pcr */
492     if( p_oggpacket->granulepos >= 0 )
493     {
494         if( p_stream->fmt.i_codec == VLC_CODEC_THEORA ||
495             p_stream->fmt.i_codec == VLC_CODEC_KATE )
496         {
497             ogg_int64_t iframe = p_oggpacket->granulepos >>
498               p_stream->i_granule_shift;
499             ogg_int64_t pframe = p_oggpacket->granulepos -
500               ( iframe << p_stream->i_granule_shift );
501
502             p_stream->i_pcr = ( iframe + pframe - p_stream->i_keyframe_offset )
503               * INT64_C(1000000) / p_stream->f_rate;
504         }
505         else if( p_stream->fmt.i_codec == VLC_CODEC_DIRAC )
506         {
507             ogg_int64_t i_dts = p_oggpacket->granulepos >> 31;
508             /* NB, OggDirac granulepos values are in units of 2*picturerate */
509             p_stream->i_pcr = (i_dts/2) * INT64_C(1000000) / p_stream->f_rate;
510         }
511         else
512         {
513             p_stream->i_pcr = p_oggpacket->granulepos * INT64_C(1000000)
514                               / p_stream->f_rate;
515         }
516
517         p_stream->i_pcr += 1;
518         p_stream->i_interpolated_pcr = p_stream->i_pcr;
519     }
520     else
521     {
522         p_stream->i_pcr = -1;
523
524         /* no granulepos available, try to interpolate the pcr.
525          * If we can't then don't touch the old value. */
526         if( p_stream->fmt.i_cat == VIDEO_ES )
527             /* 1 frame per packet */
528             p_stream->i_interpolated_pcr += (INT64_C(1000000) / p_stream->f_rate);
529         else if( p_stream->fmt.i_bitrate )
530             p_stream->i_interpolated_pcr +=
531                 ( p_oggpacket->bytes * INT64_C(1000000) /
532                   p_stream->fmt.i_bitrate / 8 );
533     }
534 }
535
536 /****************************************************************************
537  * Ogg_DecodePacket: Decode an Ogg packet.
538  ****************************************************************************/
539 static void Ogg_DecodePacket( demux_t *p_demux,
540                               logical_stream_t *p_stream,
541                               ogg_packet *p_oggpacket )
542 {
543     block_t *p_block;
544     bool b_selected;
545     int i_header_len = 0;
546     mtime_t i_pts = -1, i_interpolated_pts;
547     demux_sys_t *p_ogg = p_demux->p_sys;
548
549     /* Sanity check */
550     if( !p_oggpacket->bytes )
551     {
552         msg_Dbg( p_demux, "discarding 0 sized packet" );
553         return;
554     }
555
556     if( p_oggpacket->bytes >= 7 &&
557         ! memcmp ( p_oggpacket->packet, "Annodex", 7 ) )
558     {
559         /* it's an Annodex packet -- skip it (do nothing) */
560         return;
561     }
562     else if( p_oggpacket->bytes >= 7 &&
563         ! memcmp ( p_oggpacket->packet, "AnxData", 7 ) )
564     {
565         /* it's an AnxData packet -- skip it (do nothing) */
566         return;
567     }
568
569     if( p_stream->fmt.i_codec == VLC_CODEC_SUBT &&
570         p_oggpacket->packet[0] & PACKET_TYPE_BITS ) return;
571
572     /* Check the ES is selected */
573     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
574                     p_stream->p_es, &b_selected );
575
576     if( p_stream->b_force_backup )
577     {
578         bool b_xiph;
579         p_stream->i_packets_backup++;
580         switch( p_stream->fmt.i_codec )
581         {
582         case VLC_CODEC_VORBIS:
583         case VLC_CODEC_SPEEX:
584         case VLC_CODEC_THEORA:
585             if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
586             b_xiph = true;
587             break;
588
589         case VLC_CODEC_FLAC:
590             if( !p_stream->fmt.audio.i_rate && p_stream->i_packets_backup == 2 )
591             {
592                 Ogg_ReadFlacHeader( p_demux, p_stream, p_oggpacket );
593                 p_stream->b_force_backup = 0;
594             }
595             else if( p_stream->fmt.audio.i_rate )
596             {
597                 p_stream->b_force_backup = 0;
598                 if( p_oggpacket->bytes >= 9 )
599                 {
600                     p_oggpacket->packet += 9;
601                     p_oggpacket->bytes -= 9;
602                 }
603             }
604             b_xiph = false;
605             break;
606
607         case VLC_CODEC_KATE:
608             if( p_stream->i_packets_backup == p_stream->i_kate_num_headers ) p_stream->b_force_backup = 0;
609             b_xiph = true;
610             break;
611
612         default:
613             p_stream->b_force_backup = 0;
614             b_xiph = false;
615             break;
616         }
617
618         /* Backup the ogg packet (likely an header packet) */
619         if( !b_xiph )
620         {
621             void *p_org = p_stream->p_headers;
622             p_stream->i_headers += p_oggpacket->bytes;
623             p_stream->p_headers = realloc( p_stream->p_headers, p_stream->i_headers );
624             if( p_stream->p_headers )
625             {
626                 memcpy( (unsigned char *)p_stream->p_headers + p_stream->i_headers - p_oggpacket->bytes,
627                         p_oggpacket->packet, p_stream->i_headers );
628             }
629             else
630             {
631                 p_stream->i_headers = 0;
632                 p_stream->p_headers = NULL;
633                 free( p_org );
634             }
635         }
636         else if( xiph_AppendHeaders( &p_stream->i_headers, &p_stream->p_headers,
637                                      p_oggpacket->bytes, p_oggpacket->packet ) )
638         {
639             p_stream->i_headers = 0;
640             p_stream->p_headers = NULL;
641         }
642         if( p_stream->i_headers > 0 )
643         {
644             if( !p_stream->b_force_backup )
645             {
646                 /* Last header received, commit changes */
647                 free( p_stream->fmt.p_extra );
648
649                 p_stream->fmt.i_extra = p_stream->i_headers;
650                 p_stream->fmt.p_extra = malloc( p_stream->i_headers );
651                 if( p_stream->fmt.p_extra )
652                     memcpy( p_stream->fmt.p_extra, p_stream->p_headers,
653                             p_stream->i_headers );
654                 else
655                     p_stream->fmt.i_extra = 0;
656
657                 if( Ogg_LogicalStreamResetEsFormat( p_demux, p_stream ) )
658                     es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
659                                     p_stream->p_es, &p_stream->fmt );
660
661                 if( p_stream->i_headers > 0 )
662                     Ogg_ExtractMeta( p_demux, p_stream->fmt.i_codec,
663                                      p_stream->p_headers, p_stream->i_headers );
664
665                 /* we're not at BOS anymore for this logical stream */
666                 p_ogg->i_bos--;
667             }
668         }
669
670         b_selected = false; /* Discard the header packet */
671     }
672
673     /* Convert the pcr into a pts */
674     if( p_stream->fmt.i_codec == VLC_CODEC_VORBIS ||
675         p_stream->fmt.i_codec == VLC_CODEC_SPEEX ||
676         p_stream->fmt.i_codec == VLC_CODEC_FLAC )
677     {
678         if( p_stream->i_pcr >= 0 )
679         {
680             /* This is for streams where the granulepos of the header packets
681              * doesn't match these of the data packets (eg. ogg web radios). */
682             if( p_stream->i_previous_pcr == 0 &&
683                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
684             {
685                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
686
687                 /* Call the pace control */
688                 es_out_Control( p_demux->out, ES_OUT_SET_PCR,
689                                 VLC_TS_0 + p_stream->i_pcr );
690             }
691
692             p_stream->i_previous_pcr = p_stream->i_pcr;
693
694             /* The granulepos is the end date of the sample */
695             i_pts =  p_stream->i_pcr;
696         }
697     }
698
699     /* Convert the granulepos into the next pcr */
700     i_interpolated_pts = p_stream->i_interpolated_pcr;
701     Ogg_UpdatePCR( p_stream, p_oggpacket );
702
703     /* SPU streams are typically discontinuous, do not mind large gaps */
704     if( p_stream->fmt.i_cat != SPU_ES )
705     {
706         if( p_stream->i_pcr >= 0 )
707         {
708             /* This is for streams where the granulepos of the header packets
709              * doesn't match these of the data packets (eg. ogg web radios). */
710             if( p_stream->i_previous_pcr == 0 &&
711                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
712             {
713                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
714
715                 /* Call the pace control */
716                 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_stream->i_pcr );
717             }
718         }
719     }
720
721     if( p_stream->fmt.i_codec != VLC_CODEC_VORBIS &&
722         p_stream->fmt.i_codec != VLC_CODEC_SPEEX &&
723         p_stream->fmt.i_codec != VLC_CODEC_FLAC &&
724         p_stream->i_pcr >= 0 )
725     {
726         p_stream->i_previous_pcr = p_stream->i_pcr;
727
728         /* The granulepos is the start date of the sample */
729         i_pts = p_stream->i_pcr;
730     }
731
732     if( !b_selected )
733     {
734         /* This stream isn't currently selected so we don't need to decode it,
735          * but we did need to store its pcr as it might be selected later on */
736         return;
737     }
738
739     if( p_oggpacket->bytes <= 0 )
740         return;
741
742     if( !( p_block = block_New( p_demux, p_oggpacket->bytes ) ) ) return;
743
744
745     /* may need to preroll video frames after a seek */
746     if ( p_stream->i_skip_frames > 0 )
747     {
748         p_block->i_flags |= BLOCK_FLAG_PREROLL;
749         p_stream->i_skip_frames--;
750     }
751
752
753     /* Normalize PTS */
754     if( i_pts == 0 ) i_pts = VLC_TS_0;
755     else if( i_pts == -1 && i_interpolated_pts == 0 ) i_pts = VLC_TS_0;
756     else if( i_pts == -1 ) i_pts = VLC_TS_INVALID;
757
758     if( p_stream->fmt.i_cat == AUDIO_ES )
759         p_block->i_dts = p_block->i_pts = i_pts;
760     else if( p_stream->fmt.i_cat == SPU_ES )
761     {
762         p_block->i_dts = p_block->i_pts = i_pts;
763         p_block->i_length = 0;
764     }
765     else if( p_stream->fmt.i_codec == VLC_CODEC_THEORA )
766     {
767         p_block->i_dts = p_block->i_pts = i_pts;
768         if( (p_oggpacket->granulepos & ((1<<p_stream->i_granule_shift)-1)) == 0 )
769         {
770             p_block->i_flags |= BLOCK_FLAG_TYPE_I;
771         }
772     }
773     else if( p_stream->fmt.i_codec == VLC_CODEC_DIRAC )
774     {
775         ogg_int64_t dts = p_oggpacket->granulepos >> 31;
776         ogg_int64_t delay = (p_oggpacket->granulepos >> 9) & 0x1fff;
777
778         uint64_t u_pnum = dts + delay;
779
780         p_block->i_dts = p_stream->i_pcr;
781         p_block->i_pts = VLC_TS_INVALID;
782         /* NB, OggDirac granulepos values are in units of 2*picturerate */
783
784         /* granulepos for dirac is possibly broken, this value should be ignored */
785         if( -1 != p_oggpacket->granulepos )
786             p_block->i_pts = u_pnum * INT64_C(1000000) / p_stream->f_rate / 2;
787     }
788     else
789     {
790         p_block->i_dts = i_pts;
791         p_block->i_pts = VLC_TS_INVALID;
792     }
793
794     if( p_stream->fmt.i_codec != VLC_CODEC_VORBIS &&
795         p_stream->fmt.i_codec != VLC_CODEC_SPEEX &&
796         p_stream->fmt.i_codec != VLC_CODEC_FLAC &&
797         p_stream->fmt.i_codec != VLC_CODEC_TARKIN &&
798         p_stream->fmt.i_codec != VLC_CODEC_THEORA &&
799         p_stream->fmt.i_codec != VLC_CODEC_CMML &&
800         p_stream->fmt.i_codec != VLC_CODEC_DIRAC &&
801         p_stream->fmt.i_codec != VLC_CODEC_KATE )
802     {
803         /* We remove the header from the packet */
804         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
805         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
806
807         if( p_stream->fmt.i_codec == VLC_CODEC_SUBT)
808         {
809             /* But with subtitles we need to retrieve the duration first */
810             int i, lenbytes = 0;
811
812             if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
813             {
814                 for( i = 0, lenbytes = 0; i < i_header_len; i++ )
815                 {
816                     lenbytes = lenbytes << 8;
817                     lenbytes += *(p_oggpacket->packet + i_header_len - i);
818                 }
819             }
820             if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
821                 ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
822                   p_oggpacket->packet[i_header_len + 1] != 0 &&
823                   p_oggpacket->packet[i_header_len + 1] != '\n' &&
824                   p_oggpacket->packet[i_header_len + 1] != '\r' ) )
825             {
826                 p_block->i_length = (mtime_t)lenbytes * 1000;
827             }
828         }
829
830         i_header_len++;
831         if( p_block->i_buffer >= (unsigned int)i_header_len )
832             p_block->i_buffer -= i_header_len;
833         else
834             p_block->i_buffer = 0;
835     }
836
837     if( p_stream->fmt.i_codec == VLC_CODEC_TARKIN )
838     {
839         /* FIXME: the biggest hack I've ever done */
840         msg_Warn( p_demux, "tarkin pts: %"PRId64", granule: %"PRId64,
841                   p_block->i_pts, p_block->i_dts );
842         msleep(10000);
843     }
844
845     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
846             p_oggpacket->bytes - i_header_len );
847
848     es_out_Send( p_demux->out, p_stream->p_es, p_block );
849 }
850
851 /****************************************************************************
852  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
853  *                         stream and fill p_ogg.
854  *****************************************************************************
855  * The initial page of a logical stream is marked as a 'bos' page.
856  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
857  * together and all of the initial pages must appear before any data pages.
858  *
859  * On success this function returns VLC_SUCCESS.
860  ****************************************************************************/
861 static int Ogg_FindLogicalStreams( demux_t *p_demux )
862 {
863     demux_sys_t *p_ogg = p_demux->p_sys  ;
864     ogg_packet oggpacket;
865     int i_stream;
866
867     p_ogg->i_total_length = stream_Size ( p_demux->s );
868     msg_Dbg( p_demux, "File length is %"PRId64" bytes", p_ogg->i_total_length );
869
870
871     while( Ogg_ReadPage( p_demux, &p_ogg->current_page ) == VLC_SUCCESS )
872     {
873
874         if( ogg_page_bos( &p_ogg->current_page ) )
875         {
876
877             /* All is wonderful in our fine fine little world.
878              * We found the beginning of our first logical stream. */
879             while( ogg_page_bos( &p_ogg->current_page ) )
880             {
881                 logical_stream_t *p_stream;
882
883                 p_stream = malloc( sizeof(logical_stream_t) );
884                 if( !p_stream )
885                     return VLC_ENOMEM;
886
887                 TAB_APPEND( p_ogg->i_streams, p_ogg->pp_stream, p_stream );
888
889                 memset( p_stream, 0, sizeof(logical_stream_t) );
890                 p_stream->p_headers = 0;
891                 p_stream->i_secondary_header_packets = 0;
892
893                 p_stream->i_keyframe_offset = 0;
894                 p_stream->i_skip_frames = 0;
895
896                 p_stream->i_data_start = 0;
897
898                 es_format_Init( &p_stream->fmt, 0, 0 );
899                 es_format_Init( &p_stream->fmt_old, 0, 0 );
900
901                 /* Setup the logical stream */
902                 p_stream->i_serial_no = ogg_page_serialno( &p_ogg->current_page );
903                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
904
905                 /* Extract the initial header from the first page and verify
906                  * the codec type of this Ogg bitstream */
907                 if( ogg_stream_pagein( &p_stream->os, &p_ogg->current_page ) < 0 )
908                 {
909                     /* error. stream version mismatch perhaps */
910                     msg_Err( p_demux, "error reading first page of "
911                              "Ogg bitstream data" );
912                     return VLC_EGENERIC;
913                 }
914
915                 /* FIXME: check return value */
916                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
917
918                 /* Check for Vorbis header */
919                 if( oggpacket.bytes >= 7 &&
920                     ! memcmp( oggpacket.packet, "\x01vorbis", 7 ) )
921                 {
922                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
923                     msg_Dbg( p_demux, "found vorbis header" );
924                 }
925                 /* Check for Speex header */
926                 else if( oggpacket.bytes >= 5 &&
927                     ! memcmp( oggpacket.packet, "Speex", 5 ) )
928                 {
929                     Ogg_ReadSpeexHeader( p_stream, &oggpacket );
930                     msg_Dbg( p_demux, "found speex header, channels: %i, "
931                              "rate: %i,  bitrate: %i",
932                              p_stream->fmt.audio.i_channels,
933                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
934                 }
935                 /* Check for Flac header (< version 1.1.1) */
936                 else if( oggpacket.bytes >= 4 &&
937                     ! memcmp( oggpacket.packet, "fLaC", 4 ) )
938                 {
939                     msg_Dbg( p_demux, "found FLAC header" );
940
941                     /* Grrrr!!!! Did they really have to put all the
942                      * important info in the second header packet!!!
943                      * (STREAMINFO metadata is in the following packet) */
944                     p_stream->b_force_backup = 1;
945
946                     p_stream->fmt.i_cat = AUDIO_ES;
947                     p_stream->fmt.i_codec = VLC_CODEC_FLAC;
948                 }
949                 /* Check for Flac header (>= version 1.1.1) */
950                 else if( oggpacket.bytes >= 13 && oggpacket.packet[0] ==0x7F &&
951                     ! memcmp( &oggpacket.packet[1], "FLAC", 4 ) &&
952                     ! memcmp( &oggpacket.packet[9], "fLaC", 4 ) )
953                 {
954                     int i_packets = ((int)oggpacket.packet[7]) << 8 |
955                         oggpacket.packet[8];
956                     msg_Dbg( p_demux, "found FLAC header version %i.%i "
957                              "(%i header packets)",
958                              oggpacket.packet[5], oggpacket.packet[6],
959                              i_packets );
960
961                     p_stream->b_force_backup = 1;
962
963                     p_stream->fmt.i_cat = AUDIO_ES;
964                     p_stream->fmt.i_codec = VLC_CODEC_FLAC;
965                     oggpacket.packet += 13; oggpacket.bytes -= 13;
966                     Ogg_ReadFlacHeader( p_demux, p_stream, &oggpacket );
967                 }
968                 /* Check for Theora header */
969                 else if( oggpacket.bytes >= 7 &&
970                          ! memcmp( oggpacket.packet, "\x80theora", 7 ) )
971                 {
972                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
973
974                     msg_Dbg( p_demux,
975                              "found theora header, bitrate: %i, rate: %f",
976                              p_stream->fmt.i_bitrate, p_stream->f_rate );
977                 }
978                 /* Check for Dirac header */
979                 else if( ( oggpacket.bytes >= 5 &&
980                            ! memcmp( oggpacket.packet, "BBCD\x00", 5 ) ) ||
981                          ( oggpacket.bytes >= 9 &&
982                            ! memcmp( oggpacket.packet, "KW-DIRAC\x00", 9 ) ) )
983                 {
984                     if( Ogg_ReadDiracHeader( p_stream, &oggpacket ) )
985                         msg_Dbg( p_demux, "found dirac header" );
986                     else
987                     {
988                         msg_Warn( p_demux, "found dirac header isn't decodable" );
989                         free( p_stream );
990                         p_ogg->i_streams--;
991                     }
992                 }
993                 /* Check for Tarkin header */
994                 else if( oggpacket.bytes >= 7 &&
995                          ! memcmp( &oggpacket.packet[1], "tarkin", 6 ) )
996                 {
997                     oggpack_buffer opb;
998
999                     msg_Dbg( p_demux, "found tarkin header" );
1000                     p_stream->fmt.i_cat = VIDEO_ES;
1001                     p_stream->fmt.i_codec = VLC_CODEC_TARKIN;
1002
1003                     /* Cheat and get additionnal info ;) */
1004                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
1005                     oggpack_adv( &opb, 88 );
1006                     oggpack_adv( &opb, 104 );
1007                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1008                     p_stream->f_rate = 2; /* FIXME */
1009                     msg_Dbg( p_demux,
1010                              "found tarkin header, bitrate: %i, rate: %f",
1011                              p_stream->fmt.i_bitrate, p_stream->f_rate );
1012                 }
1013                 /* Check for Annodex header */
1014                 else if( oggpacket.bytes >= 7 &&
1015                          ! memcmp( oggpacket.packet, "Annodex", 7 ) )
1016                 {
1017                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
1018                                            &oggpacket );
1019                     /* kill annodex track */
1020                     free( p_stream );
1021                     p_ogg->i_streams--;
1022                 }
1023                 /* Check for Annodex header */
1024                 else if( oggpacket.bytes >= 7 &&
1025                          ! memcmp( oggpacket.packet, "AnxData", 7 ) )
1026                 {
1027                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
1028                                            &oggpacket );
1029                 }
1030                 /* Check for Kate header */
1031                 else if( oggpacket.bytes >= 8 &&
1032                     ! memcmp( &oggpacket.packet[1], "kate\0\0\0", 7 ) )
1033                 {
1034                     Ogg_ReadKateHeader( p_stream, &oggpacket );
1035                     msg_Dbg( p_demux, "found kate header" );
1036                 }
1037                 else if( oggpacket.bytes >= 142 &&
1038                          !memcmp( &oggpacket.packet[1],
1039                                    "Direct Show Samples embedded in Ogg", 35 ))
1040                 {
1041                     /* Old header type */
1042
1043                     /* Check for video header (old format) */
1044                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
1045                         oggpacket.bytes >= 184 )
1046                     {
1047                         p_stream->fmt.i_cat = VIDEO_ES;
1048                         p_stream->fmt.i_codec =
1049                             VLC_FOURCC( oggpacket.packet[68],
1050                                         oggpacket.packet[69],
1051                                         oggpacket.packet[70],
1052                                         oggpacket.packet[71] );
1053                         msg_Dbg( p_demux, "found video header of type: %.4s",
1054                                  (char *)&p_stream->fmt.i_codec );
1055
1056                         p_stream->fmt.video.i_frame_rate = 10000000;
1057                         p_stream->fmt.video.i_frame_rate_base =
1058                             GetQWLE((oggpacket.packet+164));
1059                         p_stream->f_rate = 10000000.0 /
1060                             GetQWLE((oggpacket.packet+164));
1061                         p_stream->fmt.video.i_bits_per_pixel =
1062                             GetWLE((oggpacket.packet+182));
1063                         if( !p_stream->fmt.video.i_bits_per_pixel )
1064                             /* hack, FIXME */
1065                             p_stream->fmt.video.i_bits_per_pixel = 24;
1066                         p_stream->fmt.video.i_width =
1067                             GetDWLE((oggpacket.packet+176));
1068                         p_stream->fmt.video.i_height =
1069                             GetDWLE((oggpacket.packet+180));
1070
1071                         msg_Dbg( p_demux,
1072                                  "fps: %f, width:%i; height:%i, bitcount:%i",
1073                                  p_stream->f_rate,
1074                                  p_stream->fmt.video.i_width,
1075                                  p_stream->fmt.video.i_height,
1076                                  p_stream->fmt.video.i_bits_per_pixel);
1077
1078                     }
1079                     /* Check for audio header (old format) */
1080                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
1081                     {
1082                         int i_extra_size;
1083                         unsigned int i_format_tag;
1084
1085                         p_stream->fmt.i_cat = AUDIO_ES;
1086
1087                         i_extra_size = GetWLE((oggpacket.packet+140));
1088                         if( i_extra_size > 0 && i_extra_size < oggpacket.bytes - 142 )
1089                         {
1090                             p_stream->fmt.i_extra = i_extra_size;
1091                             p_stream->fmt.p_extra = malloc( i_extra_size );
1092                             if( p_stream->fmt.p_extra )
1093                                 memcpy( p_stream->fmt.p_extra,
1094                                         oggpacket.packet + 142, i_extra_size );
1095                             else
1096                                 p_stream->fmt.i_extra = 0;
1097                         }
1098
1099                         i_format_tag = GetWLE((oggpacket.packet+124));
1100                         p_stream->fmt.audio.i_channels =
1101                             GetWLE((oggpacket.packet+126));
1102                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
1103                             GetDWLE((oggpacket.packet+128));
1104                         p_stream->fmt.i_bitrate =
1105                             GetDWLE((oggpacket.packet+132)) * 8;
1106                         p_stream->fmt.audio.i_blockalign =
1107                             GetWLE((oggpacket.packet+136));
1108                         p_stream->fmt.audio.i_bitspersample =
1109                             GetWLE((oggpacket.packet+138));
1110
1111                         wf_tag_to_fourcc( i_format_tag,
1112                                           &p_stream->fmt.i_codec, 0 );
1113
1114                         if( p_stream->fmt.i_codec ==
1115                             VLC_FOURCC('u','n','d','f') )
1116                         {
1117                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1118                                 ( i_format_tag >> 8 ) & 0xff,
1119                                 i_format_tag & 0xff );
1120                         }
1121
1122                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1123                                  (char *)&p_stream->fmt.i_codec );
1124                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1125                                  "%dbits/sample %dkb/s",
1126                                  i_format_tag,
1127                                  p_stream->fmt.audio.i_channels,
1128                                  p_stream->fmt.audio.i_rate,
1129                                  p_stream->fmt.audio.i_bitspersample,
1130                                  p_stream->fmt.i_bitrate / 1024 );
1131
1132                     }
1133                     else
1134                     {
1135                         msg_Dbg( p_demux, "stream %d has an old header "
1136                             "but is of an unknown type", p_ogg->i_streams-1 );
1137                         free( p_stream );
1138                         p_ogg->i_streams--;
1139                     }
1140                 }
1141                 else if( (*oggpacket.packet & PACKET_TYPE_BITS ) == PACKET_TYPE_HEADER &&
1142                          oggpacket.bytes >= 56+1 )
1143                 {
1144                     stream_header_t tmp;
1145                     stream_header_t *st = &tmp;
1146
1147                     memcpy( st->streamtype, &oggpacket.packet[1+0], 8 );
1148                     memcpy( st->subtype, &oggpacket.packet[1+8], 4 );
1149                     st->size = GetDWLE( &oggpacket.packet[1+12] );
1150                     st->time_unit = GetQWLE( &oggpacket.packet[1+16] );
1151                     st->samples_per_unit = GetQWLE( &oggpacket.packet[1+24] );
1152                     st->default_len = GetDWLE( &oggpacket.packet[1+32] );
1153                     st->buffersize = GetDWLE( &oggpacket.packet[1+36] );
1154                     st->bits_per_sample = GetWLE( &oggpacket.packet[1+40] ); // (padding 2)
1155
1156                     /* Check for video header (new format) */
1157                     if( !strncmp( st->streamtype, "video", 5 ) )
1158                     {
1159                         st->sh.video.width = GetDWLE( &oggpacket.packet[1+44] );
1160                         st->sh.video.height = GetDWLE( &oggpacket.packet[1+48] );
1161
1162                         p_stream->fmt.i_cat = VIDEO_ES;
1163
1164                         /* We need to get rid of the header packet */
1165                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1166
1167                         p_stream->fmt.i_codec =
1168                             VLC_FOURCC( st->subtype[0], st->subtype[1],
1169                                         st->subtype[2], st->subtype[3] );
1170                         msg_Dbg( p_demux, "found video header of type: %.4s",
1171                                  (char *)&p_stream->fmt.i_codec );
1172
1173                         p_stream->fmt.video.i_frame_rate = 10000000;
1174                         p_stream->fmt.video.i_frame_rate_base = st->time_unit;
1175                         if( st->time_unit <= 0 )
1176                             st->time_unit = 400000;
1177                         p_stream->f_rate = 10000000.0 / st->time_unit;
1178                         p_stream->fmt.video.i_bits_per_pixel = st->bits_per_sample;
1179                         p_stream->fmt.video.i_width = st->sh.video.width;
1180                         p_stream->fmt.video.i_height = st->sh.video.height;
1181
1182                         msg_Dbg( p_demux,
1183                                  "fps: %f, width:%i; height:%i, bitcount:%i",
1184                                  p_stream->f_rate,
1185                                  p_stream->fmt.video.i_width,
1186                                  p_stream->fmt.video.i_height,
1187                                  p_stream->fmt.video.i_bits_per_pixel );
1188                     }
1189                     /* Check for audio header (new format) */
1190                     else if( !strncmp( st->streamtype, "audio", 5 ) )
1191                     {
1192                         char p_buffer[5];
1193                         int i_extra_size;
1194                         int i_format_tag;
1195
1196                         st->sh.audio.channels = GetWLE( &oggpacket.packet[1+44] );
1197                         st->sh.audio.blockalign = GetWLE( &oggpacket.packet[1+48] );
1198                         st->sh.audio.avgbytespersec = GetDWLE( &oggpacket.packet[1+52] );
1199
1200                         p_stream->fmt.i_cat = AUDIO_ES;
1201
1202                         /* We need to get rid of the header packet */
1203                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1204
1205                         i_extra_size = st->size - 56;
1206
1207                         if( i_extra_size > 0 &&
1208                             i_extra_size < oggpacket.bytes - 1 - 56 )
1209                         {
1210                             p_stream->fmt.i_extra = i_extra_size;
1211                             p_stream->fmt.p_extra = malloc( p_stream->fmt.i_extra );
1212                             if( p_stream->fmt.p_extra )
1213                                 memcpy( p_stream->fmt.p_extra, st + 1,
1214                                         p_stream->fmt.i_extra );
1215                             else
1216                                 p_stream->fmt.i_extra = 0;
1217                         }
1218
1219                         memcpy( p_buffer, st->subtype, 4 );
1220                         p_buffer[4] = '\0';
1221                         i_format_tag = strtol(p_buffer,NULL,16);
1222                         p_stream->fmt.audio.i_channels = st->sh.audio.channels;
1223                         if( st->time_unit <= 0 )
1224                             st->time_unit = 10000000;
1225                         p_stream->f_rate = p_stream->fmt.audio.i_rate = st->samples_per_unit * 10000000 / st->time_unit;
1226                         p_stream->fmt.i_bitrate = st->sh.audio.avgbytespersec * 8;
1227                         p_stream->fmt.audio.i_blockalign = st->sh.audio.blockalign;
1228                         p_stream->fmt.audio.i_bitspersample = st->bits_per_sample;
1229
1230                         wf_tag_to_fourcc( i_format_tag,
1231                                           &p_stream->fmt.i_codec, 0 );
1232
1233                         if( p_stream->fmt.i_codec ==
1234                             VLC_FOURCC('u','n','d','f') )
1235                         {
1236                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1237                                 ( i_format_tag >> 8 ) & 0xff,
1238                                 i_format_tag & 0xff );
1239                         }
1240
1241                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1242                                  (char *)&p_stream->fmt.i_codec );
1243                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1244                                  "%dbits/sample %dkb/s",
1245                                  i_format_tag,
1246                                  p_stream->fmt.audio.i_channels,
1247                                  p_stream->fmt.audio.i_rate,
1248                                  p_stream->fmt.audio.i_bitspersample,
1249                                  p_stream->fmt.i_bitrate / 1024 );
1250                     }
1251                     /* Check for text (subtitles) header */
1252                     else if( !strncmp(st->streamtype, "text", 4) )
1253                     {
1254                         /* We need to get rid of the header packet */
1255                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1256
1257                         msg_Dbg( p_demux, "found text subtitles header" );
1258                         p_stream->fmt.i_cat = SPU_ES;
1259                         p_stream->fmt.i_codec = VLC_CODEC_SUBT;
1260                         p_stream->f_rate = 1000; /* granulepos is in millisec */
1261                     }
1262                     else
1263                     {
1264                         msg_Dbg( p_demux, "stream %d has a header marker "
1265                             "but is of an unknown type", p_ogg->i_streams-1 );
1266                         free( p_stream );
1267                         p_ogg->i_streams--;
1268                     }
1269                 }
1270                 else if( oggpacket.bytes >= 7 &&
1271                              ! memcmp( oggpacket.packet, "fishead", 7 ) )
1272
1273                 {
1274                     /* Skeleton */
1275                     msg_Dbg( p_demux, "stream %d is a skeleton",
1276                                 p_ogg->i_streams-1 );
1277                     /* FIXME: https://trac.videolan.org/vlc/ticket/1412 */
1278                 }
1279                 else
1280                 {
1281                     msg_Dbg( p_demux, "stream %d is of unknown type",
1282                              p_ogg->i_streams-1 );
1283                     free( p_stream );
1284                     p_ogg->i_streams--;
1285                 }
1286
1287                 if( Ogg_ReadPage( p_demux, &p_ogg->current_page ) != VLC_SUCCESS )
1288                     return VLC_EGENERIC;
1289             }
1290
1291             /* we'll need to get all headers for all of those streams
1292                that we have to backup headers for */
1293             p_ogg->i_bos = 0;
1294             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1295             {
1296                 if( p_ogg->pp_stream[i_stream]->b_force_backup )
1297                     p_ogg->i_bos++;
1298             }
1299
1300
1301             /* This is the first data page, which means we are now finished
1302              * with the initial pages. We just need to store it in the relevant
1303              * bitstream. */
1304             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1305             {
1306                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
1307                                        &p_ogg->current_page ) == 0 )
1308                 {
1309                     p_ogg->b_page_waiting = true;
1310                     break;
1311                 }
1312             }
1313
1314             return VLC_SUCCESS;
1315         }
1316     }
1317
1318     return VLC_EGENERIC;
1319 }
1320
1321 /****************************************************************************
1322  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1323  *                        Elementary streams.
1324  ****************************************************************************/
1325 static int Ogg_BeginningOfStream( demux_t *p_demux )
1326 {
1327     demux_sys_t *p_ogg = p_demux->p_sys  ;
1328     logical_stream_t *p_old_stream = p_ogg->p_old_stream;
1329     int i_stream;
1330
1331     /* Find the logical streams embedded in the physical stream and
1332      * initialize our p_ogg structure. */
1333     if( Ogg_FindLogicalStreams( p_demux ) != VLC_SUCCESS )
1334     {
1335         msg_Warn( p_demux, "couldn't find any ogg logical stream" );
1336         return VLC_EGENERIC;
1337     }
1338
1339     p_ogg->i_bitrate = 0;
1340
1341     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1342     {
1343         logical_stream_t *p_stream = p_ogg->pp_stream[i_stream];
1344
1345         p_stream->p_es = NULL;
1346
1347         /* initialise kframe index */
1348         p_stream->idx=NULL;
1349
1350         /* Try first to reuse an old ES */
1351         if( p_old_stream &&
1352             p_old_stream->fmt.i_cat == p_stream->fmt.i_cat &&
1353             p_old_stream->fmt.i_codec == p_stream->fmt.i_codec )
1354         {
1355             msg_Dbg( p_demux, "will reuse old stream to avoid glitch" );
1356
1357             p_stream->p_es = p_old_stream->p_es;
1358             es_format_Copy( &p_stream->fmt_old, &p_old_stream->fmt );
1359
1360             p_old_stream->p_es = NULL;
1361             p_old_stream = NULL;
1362         }
1363
1364         if( !p_stream->p_es )
1365         {
1366             /* Better be safe than sorry when possible with ogm */
1367             if( p_stream->fmt.i_codec == VLC_CODEC_MPGA ||
1368                 p_stream->fmt.i_codec == VLC_CODEC_A52 )
1369                 p_stream->fmt.b_packetized = false;
1370
1371             p_stream->p_es = es_out_Add( p_demux->out, &p_stream->fmt );
1372         }
1373
1374         // TODO: something to do here ?
1375         if( p_stream->fmt.i_codec == VLC_CODEC_CMML )
1376         {
1377             /* Set the CMML stream active */
1378             es_out_Control( p_demux->out, ES_OUT_SET_ES, p_stream->p_es );
1379         }
1380
1381         p_ogg->i_bitrate += p_stream->fmt.i_bitrate;
1382
1383         p_stream->i_pcr = p_stream->i_previous_pcr =
1384             p_stream->i_interpolated_pcr = -1;
1385         p_stream->b_reinit = false;
1386     }
1387
1388     if( p_ogg->p_old_stream )
1389     {
1390         if( p_ogg->p_old_stream->p_es )
1391             msg_Dbg( p_demux, "old stream not reused" );
1392         Ogg_LogicalStreamDelete( p_demux, p_ogg->p_old_stream );
1393         p_ogg->p_old_stream = NULL;
1394     }
1395
1396
1397     /* get total frame count for video stream; we will need this for seeking */
1398     p_ogg->i_total_frames = 0;
1399
1400     return VLC_SUCCESS;
1401 }
1402
1403 /****************************************************************************
1404  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1405  ****************************************************************************/
1406 static void Ogg_EndOfStream( demux_t *p_demux )
1407 {
1408     demux_sys_t *p_ogg = p_demux->p_sys  ;
1409     int i_stream;
1410
1411     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1412         Ogg_LogicalStreamDelete( p_demux, p_ogg->pp_stream[i_stream] );
1413     free( p_ogg->pp_stream );
1414
1415     /* Reinit p_ogg */
1416     p_ogg->i_bitrate = 0;
1417     p_ogg->i_streams = 0;
1418     p_ogg->pp_stream = NULL;
1419
1420     /* */
1421     if( p_ogg->p_meta )
1422         vlc_meta_Delete( p_ogg->p_meta );
1423     p_ogg->p_meta = NULL;
1424 }
1425
1426 /**
1427  * This function delete and release all data associated to a logical_stream_t
1428  */
1429 static void Ogg_LogicalStreamDelete( demux_t *p_demux, logical_stream_t *p_stream )
1430 {
1431     if( p_stream->p_es )
1432         es_out_Del( p_demux->out, p_stream->p_es );
1433
1434     ogg_stream_clear( &p_stream->os );
1435     free( p_stream->p_headers );
1436
1437     es_format_Clean( &p_stream->fmt_old );
1438     es_format_Clean( &p_stream->fmt );
1439
1440     if ( p_stream->idx != NULL)
1441     {
1442         oggseek_index_entries_free( p_stream->idx );
1443     }
1444
1445     free( p_stream );
1446 }
1447 /**
1448  * This function check if a we need to reset a decoder in case we are
1449  * reusing an old ES
1450  */
1451 static bool Ogg_IsVorbisFormatCompatible( const es_format_t *p_new, const es_format_t *p_old )
1452 {
1453     unsigned pi_new_size[XIPH_MAX_HEADER_COUNT];
1454     void     *pp_new_data[XIPH_MAX_HEADER_COUNT];
1455     unsigned i_new_count;
1456     if( xiph_SplitHeaders(pi_new_size, pp_new_data, &i_new_count, p_new->i_extra, p_new->p_extra ) )
1457         i_new_count = 0;
1458
1459     unsigned pi_old_size[XIPH_MAX_HEADER_COUNT];
1460     void     *pp_old_data[XIPH_MAX_HEADER_COUNT];
1461     unsigned i_old_count;
1462     if( xiph_SplitHeaders(pi_old_size, pp_old_data, &i_old_count, p_old->i_extra, p_old->p_extra ) )
1463         i_old_count = 0;
1464
1465     bool b_match = i_new_count == i_old_count;
1466     for( unsigned i = 0; i < i_new_count && b_match; i++ )
1467     {
1468         /* Ignore vorbis comment */
1469         if( i == 1 )
1470             continue;
1471         if( pi_new_size[i] != pi_old_size[i] ||
1472             memcmp( pp_new_data[i], pp_old_data[i], pi_new_size[i] ) )
1473             b_match = false;
1474     }
1475
1476     for( unsigned i = 0; i < i_new_count; i++ )
1477         free( pp_new_data[i] );
1478     for( unsigned i = 0; i < i_old_count; i++ )
1479         free( pp_old_data[i] );
1480     return b_match;
1481 }
1482 static bool Ogg_LogicalStreamResetEsFormat( demux_t *p_demux, logical_stream_t *p_stream )
1483 {
1484     bool b_compatible = false;
1485     if( !p_stream->fmt_old.i_cat || !p_stream->fmt_old.i_codec )
1486         return true;
1487
1488     /* Only vorbis is supported */
1489     if( p_stream->fmt.i_codec == VLC_CODEC_VORBIS )
1490         b_compatible = Ogg_IsVorbisFormatCompatible( &p_stream->fmt, &p_stream->fmt_old );
1491
1492     if( !b_compatible )
1493         msg_Warn( p_demux, "cannot reuse old stream, resetting the decoder" );
1494
1495     return !b_compatible;
1496 }
1497 static void Ogg_ExtractXiphMeta( demux_t *p_demux, const void *p_headers, unsigned i_headers, unsigned i_skip )
1498 {
1499     demux_sys_t *p_ogg = p_demux->p_sys;
1500
1501     unsigned pi_size[XIPH_MAX_HEADER_COUNT];
1502     void     *pp_data[XIPH_MAX_HEADER_COUNT];
1503     unsigned i_count;
1504     if( xiph_SplitHeaders( pi_size, pp_data, &i_count, i_headers, p_headers ) )
1505         return;
1506
1507     /* TODO how to handle multiple comments properly ? */
1508     if( i_count >= 2 && pi_size[1] > i_skip )
1509         vorbis_ParseComment( &p_ogg->p_meta, (uint8_t*)pp_data[1] + i_skip, pi_size[1] - i_skip );
1510
1511     for( unsigned i = 0; i < i_count; i++ )
1512         free( pp_data[i] );
1513 }
1514 static void Ogg_ExtractMeta( demux_t *p_demux, vlc_fourcc_t i_codec, const uint8_t *p_headers, int i_headers )
1515 {
1516     demux_sys_t *p_ogg = p_demux->p_sys;
1517
1518     switch( i_codec )
1519     {
1520     /* 3 headers with the 2° one being the comments */
1521     case VLC_CODEC_VORBIS:
1522         Ogg_ExtractXiphMeta( p_demux, p_headers, i_headers, 1+6 );
1523         break;
1524     case VLC_CODEC_THEORA:
1525         Ogg_ExtractXiphMeta( p_demux, p_headers, i_headers, 1+6 );
1526         break;
1527     case VLC_CODEC_SPEEX:
1528         Ogg_ExtractXiphMeta( p_demux, p_headers, i_headers, 0 );
1529         break;
1530
1531     /* N headers with the 2° one being the comments */
1532     case VLC_CODEC_KATE:
1533         /* 1 byte for header type, 7 bytes for magic, 1 reserved zero byte */
1534         Ogg_ExtractXiphMeta( p_demux, p_headers, i_headers, 1+7+1 );
1535         break;
1536
1537     /* TODO */
1538     case VLC_CODEC_FLAC:
1539         msg_Warn( p_demux, "Ogg_ExtractMeta does not support %4.4s", (const char*)&i_codec );
1540         break;
1541
1542     /* No meta data */
1543     case VLC_CODEC_CMML: /* CMML is XML text, doesn't have Vorbis comments */
1544     case VLC_CODEC_DIRAC:
1545     default:
1546         break;
1547     }
1548     if( p_ogg->p_meta )
1549         p_demux->info.i_update |= INPUT_UPDATE_META;
1550 }
1551
1552 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
1553                                   ogg_packet *p_oggpacket )
1554 {
1555     bs_t bitstream;
1556     int i_fps_numerator;
1557     int i_fps_denominator;
1558     int i_keyframe_frequency_force;
1559     int i_major;
1560     int i_minor;
1561     int i_subminor;
1562     int i_version;
1563
1564     p_stream->fmt.i_cat = VIDEO_ES;
1565     p_stream->fmt.i_codec = VLC_CODEC_THEORA;
1566
1567     /* Signal that we want to keep a backup of the theora
1568      * stream headers. They will be used when switching between
1569      * audio streams. */
1570     p_stream->b_force_backup = 1;
1571
1572     /* Cheat and get additionnal info ;) */
1573     bs_init( &bitstream, p_oggpacket->packet, p_oggpacket->bytes );
1574     bs_skip( &bitstream, 56 );
1575
1576     i_major = bs_read( &bitstream, 8 ); /* major version num */
1577     i_minor = bs_read( &bitstream, 8 ); /* minor version num */
1578     i_subminor = bs_read( &bitstream, 8 ); /* subminor version num */
1579
1580     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
1581     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
1582     bs_read( &bitstream, 24 ); /* frame width */
1583     bs_read( &bitstream, 24 ); /* frame height */
1584     bs_read( &bitstream, 8 ); /* x offset */
1585     bs_read( &bitstream, 8 ); /* y offset */
1586
1587     i_fps_numerator = bs_read( &bitstream, 32 );
1588     i_fps_denominator = bs_read( &bitstream, 32 );
1589     bs_read( &bitstream, 24 ); /* aspect_numerator */
1590     bs_read( &bitstream, 24 ); /* aspect_denominator */
1591
1592     p_stream->fmt.video.i_frame_rate = i_fps_numerator;
1593     p_stream->fmt.video.i_frame_rate_base = i_fps_denominator;
1594
1595     bs_read( &bitstream, 8 ); /* colorspace */
1596     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
1597     bs_read( &bitstream, 6 ); /* quality */
1598
1599     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
1600
1601     /* granule_shift = i_log( frequency_force -1 ) */
1602     p_stream->i_granule_shift = 0;
1603     i_keyframe_frequency_force--;
1604     while( i_keyframe_frequency_force )
1605     {
1606         p_stream->i_granule_shift++;
1607         i_keyframe_frequency_force >>= 1;
1608     }
1609
1610     i_version = i_major * 1000000 + i_minor * 1000 + i_subminor;
1611     p_stream->i_keyframe_offset = 0;
1612
1613     if ( i_version >= 3002001 )
1614     {
1615         p_stream->i_keyframe_offset = 1;
1616     }
1617
1618     p_stream->f_rate = ((float)i_fps_numerator) / i_fps_denominator;
1619 }
1620
1621 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
1622                                   ogg_packet *p_oggpacket )
1623 {
1624     oggpack_buffer opb;
1625
1626     p_stream->fmt.i_cat = AUDIO_ES;
1627     p_stream->fmt.i_codec = VLC_CODEC_VORBIS;
1628
1629     /* Signal that we want to keep a backup of the vorbis
1630      * stream headers. They will be used when switching between
1631      * audio streams. */
1632     p_stream->b_force_backup = 1;
1633
1634     /* Cheat and get additionnal info ;) */
1635     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1636     oggpack_adv( &opb, 88 );
1637     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
1638     p_stream->f_rate = p_stream->fmt.audio.i_rate =
1639         oggpack_read( &opb, 32 );
1640     oggpack_adv( &opb, 32 );
1641     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1642 }
1643
1644 static void Ogg_ReadSpeexHeader( logical_stream_t *p_stream,
1645                                  ogg_packet *p_oggpacket )
1646 {
1647     oggpack_buffer opb;
1648
1649     p_stream->fmt.i_cat = AUDIO_ES;
1650     p_stream->fmt.i_codec = VLC_CODEC_SPEEX;
1651
1652     /* Signal that we want to keep a backup of the speex
1653      * stream headers. They will be used when switching between
1654      * audio streams. */
1655     p_stream->b_force_backup = 1;
1656
1657     /* Cheat and get additionnal info ;) */
1658     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1659     oggpack_adv( &opb, 224 );
1660     oggpack_adv( &opb, 32 ); /* speex_version_id */
1661     oggpack_adv( &opb, 32 ); /* header_size */
1662     p_stream->f_rate = p_stream->fmt.audio.i_rate = oggpack_read( &opb, 32 );
1663     oggpack_adv( &opb, 32 ); /* mode */
1664     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
1665     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
1666     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1667 }
1668
1669 static void Ogg_ReadFlacHeader( demux_t *p_demux, logical_stream_t *p_stream,
1670                                 ogg_packet *p_oggpacket )
1671 {
1672     /* Parse the STREAMINFO metadata */
1673     bs_t s;
1674
1675     bs_init( &s, p_oggpacket->packet, p_oggpacket->bytes );
1676
1677     bs_read( &s, 1 );
1678     if( bs_read( &s, 7 ) == 0 )
1679     {
1680         if( bs_read( &s, 24 ) >= 34 /*size STREAMINFO*/ )
1681         {
1682             bs_skip( &s, 80 );
1683             p_stream->f_rate = p_stream->fmt.audio.i_rate = bs_read( &s, 20 );
1684             p_stream->fmt.audio.i_channels = bs_read( &s, 3 ) + 1;
1685
1686             msg_Dbg( p_demux, "FLAC header, channels: %i, rate: %i",
1687                      p_stream->fmt.audio.i_channels, (int)p_stream->f_rate );
1688         }
1689         else
1690         {
1691             msg_Dbg( p_demux, "FLAC STREAMINFO metadata too short" );
1692         }
1693
1694         /* Fake this as the last metadata block */
1695         *((uint8_t*)p_oggpacket->packet) |= 0x80;
1696     }
1697     else
1698     {
1699         /* This ain't a STREAMINFO metadata */
1700         msg_Dbg( p_demux, "Invalid FLAC STREAMINFO metadata" );
1701     }
1702 }
1703
1704 static void Ogg_ReadKateHeader( logical_stream_t *p_stream,
1705                                 ogg_packet *p_oggpacket )
1706 {
1707     oggpack_buffer opb;
1708     int32_t gnum;
1709     int32_t gden;
1710     int n;
1711     char *psz_desc;
1712
1713     p_stream->fmt.i_cat = SPU_ES;
1714     p_stream->fmt.i_codec = VLC_CODEC_KATE;
1715
1716     /* Signal that we want to keep a backup of the kate
1717      * stream headers. They will be used when switching between
1718      * kate streams. */
1719     p_stream->b_force_backup = 1;
1720
1721     /* Cheat and get additionnal info ;) */
1722     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1723     oggpack_adv( &opb, 11*8 ); /* packet type, kate magic, version */
1724     p_stream->i_kate_num_headers = oggpack_read( &opb, 8 );
1725     oggpack_adv( &opb, 3*8 );
1726     p_stream->i_granule_shift = oggpack_read( &opb, 8 );
1727     oggpack_adv( &opb, 8*8 ); /* reserved */
1728     gnum = oggpack_read( &opb, 32 );
1729     gden = oggpack_read( &opb, 32 );
1730     p_stream->f_rate = (double)gnum/gden;
1731
1732     p_stream->fmt.psz_language = malloc(16);
1733     if( p_stream->fmt.psz_language )
1734     {
1735         for( n = 0; n < 16; n++ )
1736             p_stream->fmt.psz_language[n] = oggpack_read(&opb,8);
1737         p_stream->fmt.psz_language[15] = 0; /* just in case */
1738     }
1739     else
1740     {
1741         for( n = 0; n < 16; n++ )
1742             oggpack_read(&opb,8);
1743     }
1744     p_stream->fmt.psz_description = malloc(16);
1745     if( p_stream->fmt.psz_description )
1746     {
1747         for( n = 0; n < 16; n++ )
1748             p_stream->fmt.psz_description[n] = oggpack_read(&opb,8);
1749         p_stream->fmt.psz_description[15] = 0; /* just in case */
1750
1751         /* Now find a localized user readable description for this category */
1752         psz_desc = strdup(FindKateCategoryName(p_stream->fmt.psz_description));
1753         if( psz_desc )
1754         {
1755             free( p_stream->fmt.psz_description );
1756             p_stream->fmt.psz_description = psz_desc;
1757         }
1758     }
1759     else
1760     {
1761         for( n = 0; n < 16; n++ )
1762             oggpack_read(&opb,8);
1763     }
1764 }
1765
1766 static void Ogg_ReadAnnodexHeader( vlc_object_t *p_this,
1767                                    logical_stream_t *p_stream,
1768                                    ogg_packet *p_oggpacket )
1769 {
1770     if( p_oggpacket->bytes >= 28 &&
1771         !memcmp( p_oggpacket->packet, "Annodex", 7 ) )
1772     {
1773         oggpack_buffer opb;
1774
1775         uint16_t major_version;
1776         uint16_t minor_version;
1777         uint64_t timebase_numerator;
1778         uint64_t timebase_denominator;
1779
1780         Ogg_ReadTheoraHeader( p_stream, p_oggpacket );
1781
1782         oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1783         oggpack_adv( &opb, 8*8 ); /* "Annodex\0" header */
1784         major_version = oggpack_read( &opb, 2*8 ); /* major version */
1785         minor_version = oggpack_read( &opb, 2*8 ); /* minor version */
1786         timebase_numerator = GetQWLE( &p_oggpacket->packet[16] );
1787         timebase_denominator = GetQWLE( &p_oggpacket->packet[24] );
1788     }
1789     else if( p_oggpacket->bytes >= 42 &&
1790              !memcmp( p_oggpacket->packet, "AnxData", 7 ) )
1791     {
1792         uint64_t granule_rate_numerator;
1793         uint64_t granule_rate_denominator;
1794         char content_type_string[1024];
1795
1796         /* Read in Annodex header fields */
1797
1798         granule_rate_numerator = GetQWLE( &p_oggpacket->packet[8] );
1799         granule_rate_denominator = GetQWLE( &p_oggpacket->packet[16] );
1800         p_stream->i_secondary_header_packets =
1801             GetDWLE( &p_oggpacket->packet[24] );
1802
1803         /* we are guaranteed that the first header field will be
1804          * the content-type (by the Annodex standard) */
1805         content_type_string[0] = '\0';
1806         if( !strncasecmp( (char*)(&p_oggpacket->packet[28]), "Content-Type: ", 14 ) )
1807         {
1808             uint8_t *p = memchr( &p_oggpacket->packet[42], '\r',
1809                                  p_oggpacket->bytes - 1 );
1810             if( p && p[0] == '\r' && p[1] == '\n' )
1811                 sscanf( (char*)(&p_oggpacket->packet[42]), "%1023s\r\n",
1812                         content_type_string );
1813         }
1814
1815         msg_Dbg( p_this, "AnxData packet info: %"PRId64" / %"PRId64", %d, ``%s''",
1816                  granule_rate_numerator, granule_rate_denominator,
1817                  p_stream->i_secondary_header_packets, content_type_string );
1818
1819         p_stream->f_rate = (float) granule_rate_numerator /
1820             (float) granule_rate_denominator;
1821
1822         /* What type of file do we have?
1823          * strcmp is safe to use here because we've extracted
1824          * content_type_string from the stream manually */
1825         if( !strncmp(content_type_string, "audio/x-wav", 11) )
1826         {
1827             /* n.b. WAVs are unsupported right now */
1828             p_stream->fmt.i_cat = UNKNOWN_ES;
1829         }
1830         else if( !strncmp(content_type_string, "audio/x-vorbis", 14) )
1831         {
1832             p_stream->fmt.i_cat = AUDIO_ES;
1833             p_stream->fmt.i_codec = VLC_CODEC_VORBIS;
1834
1835             p_stream->b_force_backup = 1;
1836         }
1837         else if( !strncmp(content_type_string, "audio/x-speex", 14) )
1838         {
1839             p_stream->fmt.i_cat = AUDIO_ES;
1840             p_stream->fmt.i_codec = VLC_CODEC_SPEEX;
1841
1842             p_stream->b_force_backup = 1;
1843         }
1844         else if( !strncmp(content_type_string, "video/x-theora", 14) )
1845         {
1846             p_stream->fmt.i_cat = VIDEO_ES;
1847             p_stream->fmt.i_codec = VLC_CODEC_THEORA;
1848
1849             p_stream->b_force_backup = 1;
1850         }
1851         else if( !strncmp(content_type_string, "video/x-xvid", 14) )
1852         {
1853             p_stream->fmt.i_cat = VIDEO_ES;
1854             p_stream->fmt.i_codec = VLC_FOURCC( 'x','v','i','d' );
1855
1856             p_stream->b_force_backup = 1;
1857         }
1858         else if( !strncmp(content_type_string, "video/mpeg", 14) )
1859         {
1860             /* n.b. MPEG streams are unsupported right now */
1861             p_stream->fmt.i_cat = VIDEO_ES;
1862             p_stream->fmt.i_codec = VLC_CODEC_MPGV;
1863         }
1864         else if( !strncmp(content_type_string, "text/x-cmml", 11) )
1865         {
1866             ogg_stream_packetout( &p_stream->os, p_oggpacket );
1867             p_stream->fmt.i_cat = SPU_ES;
1868             p_stream->fmt.i_codec = VLC_CODEC_CMML;
1869         }
1870     }
1871 }
1872
1873 static uint32_t dirac_uint( bs_t *p_bs )
1874 {
1875     uint32_t u_count = 0, u_value = 0;
1876
1877     while( !bs_eof( p_bs ) && !bs_read( p_bs, 1 ) )
1878     {
1879         u_count++;
1880         u_value <<= 1;
1881         u_value |= bs_read( p_bs, 1 );
1882     }
1883
1884     return (1<<u_count) - 1 + u_value;
1885 }
1886
1887 static int dirac_bool( bs_t *p_bs )
1888 {
1889     return bs_read( p_bs, 1 );
1890 }
1891
1892 static bool Ogg_ReadDiracHeader( logical_stream_t *p_stream,
1893                                  ogg_packet *p_oggpacket )
1894 {
1895     static const struct {
1896         uint32_t u_n /* numerator */, u_d /* denominator */;
1897     } p_dirac_frate_tbl[] = { /* table 10.3 */
1898         {1,1}, /* this first value is never used */
1899         {24000,1001}, {24,1}, {25,1}, {30000,1001}, {30,1},
1900         {50,1}, {60000,1001}, {60,1}, {15000,1001}, {25,2},
1901     };
1902     static const size_t u_dirac_frate_tbl = sizeof(p_dirac_frate_tbl)/sizeof(*p_dirac_frate_tbl);
1903
1904     static const uint32_t pu_dirac_vidfmt_frate[] = { /* table C.1 */
1905         1, 9, 10, 9, 10, 9, 10, 4, 3, 7, 6, 4, 3, 7, 6, 2, 2, 7, 6, 7, 6,
1906     };
1907     static const size_t u_dirac_vidfmt_frate = sizeof(pu_dirac_vidfmt_frate)/sizeof(*pu_dirac_vidfmt_frate);
1908
1909     bs_t bs;
1910
1911     p_stream->i_granule_shift = 22; /* not 32 */
1912
1913     /* Backing up stream headers is not required -- seqhdrs are repeated
1914      * thoughout the stream at suitable decoding start points */
1915     p_stream->b_force_backup = 0;
1916
1917     /* read in useful bits from sequence header */
1918     bs_init( &bs, p_oggpacket->packet, p_oggpacket->bytes );
1919     bs_skip( &bs, 13*8); /* parse_info_header */
1920     dirac_uint( &bs ); /* major_version */
1921     dirac_uint( &bs ); /* minor_version */
1922     dirac_uint( &bs ); /* profile */
1923     dirac_uint( &bs ); /* level */
1924
1925     uint32_t u_video_format = dirac_uint( &bs ); /* index */
1926     if( u_video_format >= u_dirac_vidfmt_frate )
1927     {
1928         /* don't know how to parse this ogg dirac stream */
1929         return false;
1930     }
1931
1932     if( dirac_bool( &bs ) )
1933     {
1934         dirac_uint( &bs ); /* frame_width */
1935         dirac_uint( &bs ); /* frame_height */
1936     }
1937
1938     if( dirac_bool( &bs ) )
1939     {
1940         dirac_uint( &bs ); /* chroma_format */
1941     }
1942
1943     if( dirac_bool( &bs ) )
1944     {
1945         dirac_uint( &bs ); /* scan_format */
1946     }
1947
1948     uint32_t u_n = p_dirac_frate_tbl[pu_dirac_vidfmt_frate[u_video_format]].u_n;
1949     uint32_t u_d = p_dirac_frate_tbl[pu_dirac_vidfmt_frate[u_video_format]].u_d;
1950     if( dirac_bool( &bs ) )
1951     {
1952         uint32_t u_frame_rate_index = dirac_uint( &bs );
1953         if( u_frame_rate_index >= u_dirac_frate_tbl )
1954         {
1955             /* something is wrong with this stream */
1956             return false;
1957         }
1958         u_n = p_dirac_frate_tbl[u_frame_rate_index].u_n;
1959         u_d = p_dirac_frate_tbl[u_frame_rate_index].u_d;
1960         if( u_frame_rate_index == 0 )
1961         {
1962             u_n = dirac_uint( &bs ); /* frame_rate_numerator */
1963             u_d = dirac_uint( &bs ); /* frame_rate_denominator */
1964         }
1965     }
1966     p_stream->f_rate = (float) u_n / u_d;
1967
1968     /* probably is an ogg dirac es */
1969     p_stream->fmt.i_cat = VIDEO_ES;
1970     p_stream->fmt.i_codec = VLC_CODEC_DIRAC;
1971
1972     return true;
1973 }