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