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