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