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