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