]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
do not mind large time discontinuities in SPU streams these are to be expected, so...
[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_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     /* SPU streams are typically discontinuous, do not mind large gaps */
678     if( p_stream->fmt.i_cat != SPU_ES )
679     {
680         if( p_stream->i_pcr >= 0 )
681         {
682             /* This is for streams where the granulepos of the header packets
683              * doesn't match these of the data packets (eg. ogg web radios). */
684             if( p_stream->i_previous_pcr == 0 &&
685                 p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
686             {
687                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
688
689                 /* Call the pace control */
690                 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_stream->i_pcr );
691             }
692         }
693     }
694
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         p_stream->i_pcr >= 0 )
699     {
700         p_stream->i_previous_pcr = p_stream->i_pcr;
701
702         /* The granulepos is the start date of the sample */
703         i_pts = p_stream->i_pcr;
704     }
705
706     if( !b_selected )
707     {
708         /* This stream isn't currently selected so we don't need to decode it,
709          * but we did need to store its pcr as it might be selected later on */
710         return;
711     }
712
713     if( p_oggpacket->bytes <= 0 )
714         return;
715
716     if( !( p_block = block_New( p_demux, p_oggpacket->bytes ) ) ) return;
717
718     /* Normalize PTS */
719     if( i_pts == 0 ) i_pts = 1;
720     else if( i_pts == -1 && i_interpolated_pts == 0 ) i_pts = 1;
721     else if( i_pts == -1 ) i_pts = 0;
722
723     if( p_stream->fmt.i_cat == AUDIO_ES )
724         p_block->i_dts = p_block->i_pts = i_pts;
725     else if( p_stream->fmt.i_cat == SPU_ES )
726     {
727         p_block->i_dts = p_block->i_pts = i_pts;
728         p_block->i_length = 0;
729     }
730     else if( p_stream->fmt.i_codec == VLC_FOURCC( 't','h','e','o' ) )
731         p_block->i_dts = p_block->i_pts = i_pts;
732     else if( p_stream->fmt.i_codec == VLC_FOURCC( 'd','r','a','c' ) )
733     {
734         ogg_int64_t dts = p_oggpacket->granulepos >> 31;
735         ogg_int64_t delay = (p_oggpacket->granulepos >> 9) & 0x1fff;
736
737         uint64_t u_pnum = dts + delay;
738
739         p_block->i_dts = p_stream->i_pcr;
740         p_block->i_pts = 0;
741         /* NB, OggDirac granulepos values are in units of 2*picturerate */
742         if( -1 != p_oggpacket->granulepos )
743             p_block->i_pts = u_pnum * INT64_C(1000000) / p_stream->f_rate / 2;
744     }
745     else
746     {
747         p_block->i_dts = i_pts;
748         p_block->i_pts = 0;
749     }
750
751     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
752         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
753         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
754         p_stream->fmt.i_codec != VLC_FOURCC( 't','a','r','k' ) &&
755         p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) &&
756         p_stream->fmt.i_codec != VLC_FOURCC( 'c','m','m','l' ) &&
757         p_stream->fmt.i_codec != VLC_FOURCC( 'd','r','a','c' ) &&
758         p_stream->fmt.i_codec != VLC_FOURCC( 'k','a','t','e' ) )
759     {
760         /* We remove the header from the packet */
761         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
762         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
763
764         if( p_stream->fmt.i_codec == VLC_FOURCC( 's','u','b','t' ))
765         {
766             /* But with subtitles we need to retrieve the duration first */
767             int i, lenbytes = 0;
768
769             if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
770             {
771                 for( i = 0, lenbytes = 0; i < i_header_len; i++ )
772                 {
773                     lenbytes = lenbytes << 8;
774                     lenbytes += *(p_oggpacket->packet + i_header_len - i);
775                 }
776             }
777             if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
778                 ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
779                   p_oggpacket->packet[i_header_len + 1] != 0 &&
780                   p_oggpacket->packet[i_header_len + 1] != '\n' &&
781                   p_oggpacket->packet[i_header_len + 1] != '\r' ) )
782             {
783                 p_block->i_length = (mtime_t)lenbytes * 1000;
784             }
785         }
786
787         i_header_len++;
788         if( p_block->i_buffer >= (unsigned int)i_header_len )
789             p_block->i_buffer -= i_header_len;
790         else
791             p_block->i_buffer = 0;
792     }
793
794     if( p_stream->fmt.i_codec == VLC_FOURCC( 't','a','r','k' ) )
795     {
796         /* FIXME: the biggest hack I've ever done */
797         msg_Warn( p_demux, "tarkin pts: %"PRId64", granule: %"PRId64,
798                   p_block->i_pts, p_block->i_dts );
799         msleep(10000);
800     }
801
802     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
803             p_oggpacket->bytes - i_header_len );
804
805     es_out_Send( p_demux->out, p_stream->p_es, p_block );
806 }
807
808 /****************************************************************************
809  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
810  *                         stream and fill p_ogg.
811  *****************************************************************************
812  * The initial page of a logical stream is marked as a 'bos' page.
813  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
814  * together and all of the initial pages must appear before any data pages.
815  *
816  * On success this function returns VLC_SUCCESS.
817  ****************************************************************************/
818 static int Ogg_FindLogicalStreams( demux_t *p_demux )
819 {
820     demux_sys_t *p_ogg = p_demux->p_sys  ;
821     ogg_packet oggpacket;
822     ogg_page oggpage;
823     int i_stream;
824
825     while( Ogg_ReadPage( p_demux, &oggpage ) == VLC_SUCCESS )
826     {
827         if( ogg_page_bos( &oggpage ) )
828         {
829
830             /* All is wonderful in our fine fine little world.
831              * We found the beginning of our first logical stream. */
832             while( ogg_page_bos( &oggpage ) )
833             {
834                 logical_stream_t **pp_sav = p_ogg->pp_stream;
835                 logical_stream_t *p_stream;
836
837                 p_stream = malloc( sizeof(logical_stream_t) );
838                 if( !p_stream )
839                     return VLC_ENOMEM;
840
841                 TAB_APPEND( p_ogg->i_streams, p_ogg->pp_stream, p_stream );
842
843                 memset( p_stream, 0, sizeof(logical_stream_t) );
844                 p_stream->p_headers = 0;
845                 p_stream->secondary_header_packets = 0;
846
847                 es_format_Init( &p_stream->fmt, 0, 0 );
848                 es_format_Init( &p_stream->fmt_old, 0, 0 );
849
850                 /* Setup the logical stream */
851                 p_stream->i_serial_no = ogg_page_serialno( &oggpage );
852                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
853
854                 /* Extract the initial header from the first page and verify
855                  * the codec type of tis Ogg bitstream */
856                 if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
857                 {
858                     /* error. stream version mismatch perhaps */
859                     msg_Err( p_demux, "error reading first page of "
860                              "Ogg bitstream data" );
861                     return VLC_EGENERIC;
862                 }
863
864                 /* FIXME: check return value */
865                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
866
867                 /* Check for Vorbis header */
868                 if( oggpacket.bytes >= 7 &&
869                     ! memcmp( oggpacket.packet, "\x01vorbis", 7 ) )
870                 {
871                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
872                     msg_Dbg( p_demux, "found vorbis header" );
873                 }
874                 /* Check for Speex header */
875                 else if( oggpacket.bytes >= 5 &&
876                     ! memcmp( oggpacket.packet, "Speex", 5 ) )
877                 {
878                     Ogg_ReadSpeexHeader( p_stream, &oggpacket );
879                     msg_Dbg( p_demux, "found speex header, channels: %i, "
880                              "rate: %i,  bitrate: %i",
881                              p_stream->fmt.audio.i_channels,
882                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
883                 }
884                 /* Check for Flac header (< version 1.1.1) */
885                 else if( oggpacket.bytes >= 4 &&
886                     ! memcmp( oggpacket.packet, "fLaC", 4 ) )
887                 {
888                     msg_Dbg( p_demux, "found FLAC header" );
889
890                     /* Grrrr!!!! Did they really have to put all the
891                      * important info in the second header packet!!!
892                      * (STREAMINFO metadata is in the following packet) */
893                     p_stream->b_force_backup = 1;
894
895                     p_stream->fmt.i_cat = AUDIO_ES;
896                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
897                 }
898                 /* Check for Flac header (>= version 1.1.1) */
899                 else if( oggpacket.bytes >= 13 && oggpacket.packet[0] ==0x7F &&
900                     ! memcmp( &oggpacket.packet[1], "FLAC", 4 ) &&
901                     ! memcmp( &oggpacket.packet[9], "fLaC", 4 ) )
902                 {
903                     int i_packets = ((int)oggpacket.packet[7]) << 8 |
904                         oggpacket.packet[8];
905                     msg_Dbg( p_demux, "found FLAC header version %i.%i "
906                              "(%i header packets)",
907                              oggpacket.packet[5], oggpacket.packet[6],
908                              i_packets );
909
910                     p_stream->b_force_backup = 1;
911
912                     p_stream->fmt.i_cat = AUDIO_ES;
913                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
914                     oggpacket.packet += 13; oggpacket.bytes -= 13;
915                     Ogg_ReadFlacHeader( p_demux, p_stream, &oggpacket );
916                 }
917                 /* Check for Theora header */
918                 else if( oggpacket.bytes >= 7 &&
919                          ! memcmp( oggpacket.packet, "\x80theora", 7 ) )
920                 {
921                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
922
923                     msg_Dbg( p_demux,
924                              "found theora header, bitrate: %i, rate: %f",
925                              p_stream->fmt.i_bitrate, p_stream->f_rate );
926                 }
927                 /* Check for Dirac header */
928                 else if( oggpacket.bytes >= 5 &&
929                          ! memcmp( oggpacket.packet, "BBCD\x00", 5 ) )
930                 {
931                     Ogg_ReadDiracHeader( p_stream, &oggpacket );
932                     msg_Dbg( p_demux, "found dirac header" );
933                 }
934                 /* Check for Tarkin header */
935                 else if( oggpacket.bytes >= 7 &&
936                          ! memcmp( &oggpacket.packet[1], "tarkin", 6 ) )
937                 {
938                     oggpack_buffer opb;
939
940                     msg_Dbg( p_demux, "found tarkin header" );
941                     p_stream->fmt.i_cat = VIDEO_ES;
942                     p_stream->fmt.i_codec = VLC_FOURCC( 't','a','r','k' );
943
944                     /* Cheat and get additionnal info ;) */
945                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
946                     oggpack_adv( &opb, 88 );
947                     oggpack_adv( &opb, 104 );
948                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
949                     p_stream->f_rate = 2; /* FIXME */
950                     msg_Dbg( p_demux,
951                              "found tarkin header, bitrate: %i, rate: %f",
952                              p_stream->fmt.i_bitrate, p_stream->f_rate );
953                 }
954                 /* Check for Annodex header */
955                 else if( oggpacket.bytes >= 7 &&
956                          ! memcmp( oggpacket.packet, "Annodex", 7 ) )
957                 {
958                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
959                                            &oggpacket );
960                     /* kill annodex track */
961                     free( p_stream );
962                     p_ogg->i_streams--;
963                 }
964                 /* Check for Annodex header */
965                 else if( oggpacket.bytes >= 7 &&
966                          ! memcmp( oggpacket.packet, "AnxData", 7 ) )
967                 {
968                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
969                                            &oggpacket );
970                 }
971                 /* Check for Kate header */
972                 else if( oggpacket.bytes >= 8 &&
973                     ! memcmp( &oggpacket.packet[1], "kate\0\0\0", 7 ) )
974                 {
975                     Ogg_ReadKateHeader( p_stream, &oggpacket );
976                     msg_Dbg( p_demux, "found kate header" );
977                 }
978                 else if( oggpacket.bytes >= 142 &&
979                          !memcmp( &oggpacket.packet[1],
980                                    "Direct Show Samples embedded in Ogg", 35 ))
981                 {
982                     /* Old header type */
983
984                     /* Check for video header (old format) */
985                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
986                         oggpacket.bytes >= 184 )
987                     {
988                         p_stream->fmt.i_cat = VIDEO_ES;
989                         p_stream->fmt.i_codec =
990                             VLC_FOURCC( oggpacket.packet[68],
991                                         oggpacket.packet[69],
992                                         oggpacket.packet[70],
993                                         oggpacket.packet[71] );
994                         msg_Dbg( p_demux, "found video header of type: %.4s",
995                                  (char *)&p_stream->fmt.i_codec );
996
997                         p_stream->fmt.video.i_frame_rate = 10000000;
998                         p_stream->fmt.video.i_frame_rate_base =
999                             GetQWLE((oggpacket.packet+164));
1000                         p_stream->f_rate = 10000000.0 /
1001                             GetQWLE((oggpacket.packet+164));
1002                         p_stream->fmt.video.i_bits_per_pixel =
1003                             GetWLE((oggpacket.packet+182));
1004                         if( !p_stream->fmt.video.i_bits_per_pixel )
1005                             /* hack, FIXME */
1006                             p_stream->fmt.video.i_bits_per_pixel = 24;
1007                         p_stream->fmt.video.i_width =
1008                             GetDWLE((oggpacket.packet+176));
1009                         p_stream->fmt.video.i_height =
1010                             GetDWLE((oggpacket.packet+180));
1011
1012                         msg_Dbg( p_demux,
1013                                  "fps: %f, width:%i; height:%i, bitcount:%i",
1014                                  p_stream->f_rate,
1015                                  p_stream->fmt.video.i_width,
1016                                  p_stream->fmt.video.i_height,
1017                                  p_stream->fmt.video.i_bits_per_pixel);
1018
1019                     }
1020                     /* Check for audio header (old format) */
1021                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
1022                     {
1023                         unsigned int i_extra_size;
1024                         unsigned int i_format_tag;
1025
1026                         p_stream->fmt.i_cat = AUDIO_ES;
1027
1028                         i_extra_size = GetWLE((oggpacket.packet+140));
1029                         if( i_extra_size > 0 && i_extra_size < oggpacket.bytes - 142 )
1030                         {
1031                             p_stream->fmt.i_extra = i_extra_size;
1032                             p_stream->fmt.p_extra = malloc( i_extra_size );
1033                             if( p_stream->fmt.p_extra )
1034                                 memcpy( p_stream->fmt.p_extra,
1035                                         oggpacket.packet + 142, i_extra_size );
1036                             else
1037                                 p_stream->fmt.i_extra = 0;
1038                         }
1039
1040                         i_format_tag = GetWLE((oggpacket.packet+124));
1041                         p_stream->fmt.audio.i_channels =
1042                             GetWLE((oggpacket.packet+126));
1043                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
1044                             GetDWLE((oggpacket.packet+128));
1045                         p_stream->fmt.i_bitrate =
1046                             GetDWLE((oggpacket.packet+132)) * 8;
1047                         p_stream->fmt.audio.i_blockalign =
1048                             GetWLE((oggpacket.packet+136));
1049                         p_stream->fmt.audio.i_bitspersample =
1050                             GetWLE((oggpacket.packet+138));
1051
1052                         wf_tag_to_fourcc( i_format_tag,
1053                                           &p_stream->fmt.i_codec, 0 );
1054
1055                         if( p_stream->fmt.i_codec ==
1056                             VLC_FOURCC('u','n','d','f') )
1057                         {
1058                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1059                                 ( i_format_tag >> 8 ) & 0xff,
1060                                 i_format_tag & 0xff );
1061                         }
1062
1063                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1064                                  (char *)&p_stream->fmt.i_codec );
1065                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1066                                  "%dbits/sample %dkb/s",
1067                                  i_format_tag,
1068                                  p_stream->fmt.audio.i_channels,
1069                                  p_stream->fmt.audio.i_rate,
1070                                  p_stream->fmt.audio.i_bitspersample,
1071                                  p_stream->fmt.i_bitrate / 1024 );
1072
1073                     }
1074                     else
1075                     {
1076                         msg_Dbg( p_demux, "stream %d has an old header "
1077                             "but is of an unknown type", p_ogg->i_streams-1 );
1078                         free( p_stream );
1079                         p_ogg->i_streams--;
1080                     }
1081                 }
1082                 else if( (*oggpacket.packet & PACKET_TYPE_BITS ) == PACKET_TYPE_HEADER &&
1083                          oggpacket.bytes >= 56+1 )
1084                 {
1085                     stream_header_t tmp;
1086                     stream_header_t *st = &tmp;
1087
1088                     memcpy( st->streamtype, &oggpacket.packet[1+0], 8 );
1089                     memcpy( st->subtype, &oggpacket.packet[1+8], 4 );
1090                     st->size = GetDWLE( &oggpacket.packet[1+12] );
1091                     st->time_unit = GetQWLE( &oggpacket.packet[1+16] );
1092                     st->samples_per_unit = GetQWLE( &oggpacket.packet[1+24] );
1093                     st->default_len = GetDWLE( &oggpacket.packet[1+32] );
1094                     st->buffersize = GetDWLE( &oggpacket.packet[1+36] );
1095                     st->bits_per_sample = GetWLE( &oggpacket.packet[1+40] ); // (padding 2)
1096
1097                     /* Check for video header (new format) */
1098                     if( !strncmp( st->streamtype, "video", 5 ) )
1099                     {
1100                         st->sh.video.width = GetDWLE( &oggpacket.packet[1+44] );
1101                         st->sh.video.height = GetDWLE( &oggpacket.packet[1+48] );
1102
1103                         p_stream->fmt.i_cat = VIDEO_ES;
1104
1105                         /* We need to get rid of the header packet */
1106                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1107
1108                         p_stream->fmt.i_codec =
1109                             VLC_FOURCC( st->subtype[0], st->subtype[1],
1110                                         st->subtype[2], st->subtype[3] );
1111                         msg_Dbg( p_demux, "found video header of type: %.4s",
1112                                  (char *)&p_stream->fmt.i_codec );
1113
1114                         p_stream->fmt.video.i_frame_rate = 10000000;
1115                         p_stream->fmt.video.i_frame_rate_base = st->time_unit;
1116                         if( st->time_unit <= 0 )
1117                             st->time_unit = 400000;
1118                         p_stream->f_rate = 10000000.0 / st->time_unit;
1119                         p_stream->fmt.video.i_bits_per_pixel = st->bits_per_sample;
1120                         p_stream->fmt.video.i_width = st->sh.video.width;
1121                         p_stream->fmt.video.i_height = st->sh.video.height;
1122
1123                         msg_Dbg( p_demux,
1124                                  "fps: %f, width:%i; height:%i, bitcount:%i",
1125                                  p_stream->f_rate,
1126                                  p_stream->fmt.video.i_width,
1127                                  p_stream->fmt.video.i_height,
1128                                  p_stream->fmt.video.i_bits_per_pixel );
1129                     }
1130                     /* Check for audio header (new format) */
1131                     else if( !strncmp( st->streamtype, "audio", 5 ) )
1132                     {
1133                         char p_buffer[5];
1134                         unsigned int i_extra_size;
1135                         int i_format_tag;
1136
1137                         st->sh.audio.channels = GetWLE( &oggpacket.packet[1+44] );
1138                         st->sh.audio.blockalign = GetWLE( &oggpacket.packet[1+48] );
1139                         st->sh.audio.avgbytespersec = GetDWLE( &oggpacket.packet[1+52] );
1140
1141                         p_stream->fmt.i_cat = AUDIO_ES;
1142
1143                         /* We need to get rid of the header packet */
1144                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1145
1146                         i_extra_size = st->size - 56;
1147
1148                         if( i_extra_size > 0 &&
1149                             i_extra_size < oggpacket.bytes - 1 - 56 )
1150                         {
1151                             p_stream->fmt.i_extra = i_extra_size;
1152                             p_stream->fmt.p_extra = malloc( p_stream->fmt.i_extra );
1153                             if( p_stream->fmt.p_extra )
1154                                 memcpy( p_stream->fmt.p_extra, st + 1,
1155                                         p_stream->fmt.i_extra );
1156                             else
1157                                 p_stream->fmt.i_extra = 0;
1158                         }
1159
1160                         memcpy( p_buffer, st->subtype, 4 );
1161                         p_buffer[4] = '\0';
1162                         i_format_tag = strtol(p_buffer,NULL,16);
1163                         p_stream->fmt.audio.i_channels = st->sh.audio.channels;
1164                         if( st->time_unit <= 0 )
1165                             st->time_unit = 10000000;
1166                         p_stream->f_rate = p_stream->fmt.audio.i_rate = st->samples_per_unit * 10000000 / st->time_unit;
1167                         p_stream->fmt.i_bitrate = st->sh.audio.avgbytespersec * 8;
1168                         p_stream->fmt.audio.i_blockalign = st->sh.audio.blockalign;
1169                         p_stream->fmt.audio.i_bitspersample = st->bits_per_sample;
1170
1171                         wf_tag_to_fourcc( i_format_tag,
1172                                           &p_stream->fmt.i_codec, 0 );
1173
1174                         if( p_stream->fmt.i_codec ==
1175                             VLC_FOURCC('u','n','d','f') )
1176                         {
1177                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1178                                 ( i_format_tag >> 8 ) & 0xff,
1179                                 i_format_tag & 0xff );
1180                         }
1181
1182                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1183                                  (char *)&p_stream->fmt.i_codec );
1184                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1185                                  "%dbits/sample %dkb/s",
1186                                  i_format_tag,
1187                                  p_stream->fmt.audio.i_channels,
1188                                  p_stream->fmt.audio.i_rate,
1189                                  p_stream->fmt.audio.i_bitspersample,
1190                                  p_stream->fmt.i_bitrate / 1024 );
1191                     }
1192                     /* Check for text (subtitles) header */
1193                     else if( !strncmp(st->streamtype, "text", 4) )
1194                     {
1195                         /* We need to get rid of the header packet */
1196                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1197
1198                         msg_Dbg( p_demux, "found text subtitles header" );
1199                         p_stream->fmt.i_cat = SPU_ES;
1200                         p_stream->fmt.i_codec = VLC_FOURCC('s','u','b','t');
1201                         p_stream->f_rate = 1000; /* granulepos is in millisec */
1202                     }
1203                     else
1204                     {
1205                         msg_Dbg( p_demux, "stream %d has a header marker "
1206                             "but is of an unknown type", p_ogg->i_streams-1 );
1207                         free( p_stream );
1208                         p_ogg->i_streams--;
1209                     }
1210                 }
1211                 else if( oggpacket.bytes >= 7 &&
1212                              ! memcmp( oggpacket.packet, "fishead", 7 ) )
1213
1214                 {
1215                     /* Skeleton */
1216                     msg_Dbg( p_demux, "stream %d is a skeleton",
1217                                 p_ogg->i_streams-1 );
1218                     /* FIXME: https://trac.videolan.org/vlc/ticket/1412 */
1219                 }
1220                 else
1221                 {
1222                     msg_Dbg( p_demux, "stream %d is of unknown type",
1223                              p_ogg->i_streams-1 );
1224                     free( p_stream );
1225                     p_ogg->i_streams--;
1226                 }
1227
1228                 if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
1229                     return VLC_EGENERIC;
1230             }
1231
1232             /* This is the first data page, which means we are now finished
1233              * with the initial pages. We just need to store it in the relevant
1234              * bitstream. */
1235             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1236             {
1237                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
1238                                        &oggpage ) == 0 )
1239                 {
1240                     break;
1241                 }
1242             }
1243
1244             return VLC_SUCCESS;
1245         }
1246     }
1247
1248     return VLC_EGENERIC;
1249 }
1250
1251 /****************************************************************************
1252  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1253  *                        Elementary streams.
1254  ****************************************************************************/
1255 static int Ogg_BeginningOfStream( demux_t *p_demux )
1256 {
1257     demux_sys_t *p_ogg = p_demux->p_sys  ;
1258     logical_stream_t *p_old_stream = p_ogg->p_old_stream;
1259     int i_stream;
1260
1261     /* Find the logical streams embedded in the physical stream and
1262      * initialize our p_ogg structure. */
1263     if( Ogg_FindLogicalStreams( p_demux ) != VLC_SUCCESS )
1264     {
1265         msg_Warn( p_demux, "couldn't find any ogg logical stream" );
1266         return VLC_EGENERIC;
1267     }
1268
1269     p_ogg->i_bitrate = 0;
1270
1271     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1272     {
1273         logical_stream_t *p_stream = p_ogg->pp_stream[i_stream];
1274
1275         p_stream->p_es = NULL;
1276
1277         /* Try first to reuse an old ES */
1278         if( p_old_stream &&
1279             p_old_stream->fmt.i_cat == p_stream->fmt.i_cat &&
1280             p_old_stream->fmt.i_codec == p_stream->fmt.i_codec )
1281         {
1282             msg_Dbg( p_demux, "will reuse old stream to avoid glitch" );
1283
1284             p_stream->p_es = p_old_stream->p_es;
1285             es_format_Copy( &p_stream->fmt_old, &p_old_stream->fmt );
1286
1287             p_old_stream->p_es = NULL;
1288             p_old_stream = NULL;
1289         }
1290
1291         if( !p_stream->p_es )
1292             p_stream->p_es = es_out_Add( p_demux->out, &p_stream->fmt );
1293
1294         // TODO: something to do here ?
1295         if( p_stream->fmt.i_codec == VLC_FOURCC('c','m','m','l') )
1296         {
1297             /* Set the CMML stream active */
1298             es_out_Control( p_demux->out, ES_OUT_SET_ES, p_stream->p_es );
1299         }
1300
1301         p_ogg->i_bitrate += p_stream->fmt.i_bitrate;
1302
1303         p_stream->i_pcr = p_stream->i_previous_pcr =
1304             p_stream->i_interpolated_pcr = -1;
1305         p_stream->b_reinit = 0;
1306     }
1307
1308     if( p_ogg->p_old_stream )
1309     {
1310         if( p_ogg->p_old_stream->p_es )
1311             msg_Dbg( p_demux, "old stream not reused" );
1312         Ogg_LogicalStreamDelete( p_demux, p_ogg->p_old_stream );
1313         p_ogg->p_old_stream = NULL;
1314     }
1315     return VLC_SUCCESS;
1316 }
1317
1318 /****************************************************************************
1319  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1320  ****************************************************************************/
1321 static void Ogg_EndOfStream( demux_t *p_demux )
1322 {
1323     demux_sys_t *p_ogg = p_demux->p_sys  ;
1324     int i_stream;
1325
1326     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1327         Ogg_LogicalStreamDelete( p_demux, p_ogg->pp_stream[i_stream] );
1328     free( p_ogg->pp_stream );
1329
1330     /* Reinit p_ogg */
1331     p_ogg->i_bitrate = 0;
1332     p_ogg->i_streams = 0;
1333     p_ogg->pp_stream = NULL;
1334 }
1335
1336 /**
1337  * This function delete and release all data associated to a logical_stream_t
1338  */
1339 static void Ogg_LogicalStreamDelete( demux_t *p_demux, logical_stream_t *p_stream )
1340 {
1341     if( p_stream->p_es )
1342         es_out_Del( p_demux->out, p_stream->p_es );
1343
1344     ogg_stream_clear( &p_stream->os );
1345     free( p_stream->p_headers );
1346
1347     es_format_Clean( &p_stream->fmt_old );
1348     es_format_Clean( &p_stream->fmt );
1349
1350     free( p_stream );
1351 }
1352 /**
1353  * This function check if a we need to reset a decoder in case we are
1354  * reusing an old ES
1355  */
1356 static bool Ogg_IsVorbisFormatCompatible( const es_format_t *p_new, const es_format_t *p_old )
1357 {
1358     int i_new = 0;
1359     int i_old = 0;
1360     int i;
1361
1362     for( i = 0; i < 3; i++ )
1363     {
1364         const uint8_t *p_new_extra = ( const uint8_t*)p_new->p_extra + i_new;
1365         const uint8_t *p_old_extra = ( const uint8_t*)p_old->p_extra + i_old;
1366
1367         if( p_new->i_extra < i_new+2 || p_old->i_extra < i_old+2 )
1368             return false;
1369
1370         const int i_new_size = GetWBE( &p_new_extra[0] );
1371         const int i_old_size = GetWBE( &p_old_extra[0] );
1372
1373         if( i != 1 ) /* Ignore vorbis comment */
1374         {
1375             if( i_new_size != i_old_size )
1376                 return false;
1377             if( memcmp( &p_new_extra[2], &p_old_extra[2], i_new_size ) )
1378                 return false;
1379         }
1380
1381         i_new += 2 + i_new_size;
1382         i_old += 2 + i_old_size;
1383     }
1384     return true;
1385 }
1386 static bool Ogg_LogicalStreamResetEsFormat( demux_t *p_demux, logical_stream_t *p_stream )
1387 {
1388     bool b_compatible = false;
1389     if( !p_stream->fmt_old.i_cat || !p_stream->fmt_old.i_codec )
1390         return true;
1391
1392     /* Only vorbis is supported */
1393     if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) )
1394         b_compatible = Ogg_IsVorbisFormatCompatible( &p_stream->fmt, &p_stream->fmt_old );
1395
1396     if( !b_compatible )
1397         msg_Warn( p_demux, "cannot reuse old stream, resetting the decoder" );
1398
1399     return !b_compatible;
1400 }
1401
1402 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
1403                                   ogg_packet *p_oggpacket )
1404 {
1405     bs_t bitstream;
1406     int i_fps_numerator;
1407     int i_fps_denominator;
1408     int i_keyframe_frequency_force;
1409
1410     p_stream->fmt.i_cat = VIDEO_ES;
1411     p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1412
1413     /* Signal that we want to keep a backup of the theora
1414      * stream headers. They will be used when switching between
1415      * audio streams. */
1416     p_stream->b_force_backup = 1;
1417
1418     /* Cheat and get additionnal info ;) */
1419     bs_init( &bitstream, p_oggpacket->packet, p_oggpacket->bytes );
1420     bs_skip( &bitstream, 56 );
1421     bs_read( &bitstream, 8 ); /* major version num */
1422     bs_read( &bitstream, 8 ); /* minor version num */
1423     bs_read( &bitstream, 8 ); /* subminor version num */
1424     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
1425     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
1426     bs_read( &bitstream, 24 ); /* frame width */
1427     bs_read( &bitstream, 24 ); /* frame height */
1428     bs_read( &bitstream, 8 ); /* x offset */
1429     bs_read( &bitstream, 8 ); /* y offset */
1430
1431     i_fps_numerator = bs_read( &bitstream, 32 );
1432     i_fps_denominator = bs_read( &bitstream, 32 );
1433     bs_read( &bitstream, 24 ); /* aspect_numerator */
1434     bs_read( &bitstream, 24 ); /* aspect_denominator */
1435
1436     p_stream->fmt.video.i_frame_rate = i_fps_numerator;
1437     p_stream->fmt.video.i_frame_rate_base = i_fps_denominator;
1438
1439     bs_read( &bitstream, 8 ); /* colorspace */
1440     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
1441     bs_read( &bitstream, 6 ); /* quality */
1442
1443     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
1444
1445     /* granule_shift = i_log( frequency_force -1 ) */
1446     p_stream->i_granule_shift = 0;
1447     i_keyframe_frequency_force--;
1448     while( i_keyframe_frequency_force )
1449     {
1450         p_stream->i_granule_shift++;
1451         i_keyframe_frequency_force >>= 1;
1452     }
1453
1454     p_stream->f_rate = ((float)i_fps_numerator) / i_fps_denominator;
1455 }
1456
1457 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
1458                                   ogg_packet *p_oggpacket )
1459 {
1460     oggpack_buffer opb;
1461
1462     p_stream->fmt.i_cat = AUDIO_ES;
1463     p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1464
1465     /* Signal that we want to keep a backup of the vorbis
1466      * stream headers. They will be used when switching between
1467      * audio streams. */
1468     p_stream->b_force_backup = 1;
1469
1470     /* Cheat and get additionnal info ;) */
1471     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1472     oggpack_adv( &opb, 88 );
1473     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
1474     p_stream->f_rate = p_stream->fmt.audio.i_rate =
1475         oggpack_read( &opb, 32 );
1476     oggpack_adv( &opb, 32 );
1477     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1478 }
1479
1480 static void Ogg_ReadSpeexHeader( logical_stream_t *p_stream,
1481                                  ogg_packet *p_oggpacket )
1482 {
1483     oggpack_buffer opb;
1484
1485     p_stream->fmt.i_cat = AUDIO_ES;
1486     p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
1487
1488     /* Signal that we want to keep a backup of the speex
1489      * stream headers. They will be used when switching between
1490      * audio streams. */
1491     p_stream->b_force_backup = 1;
1492
1493     /* Cheat and get additionnal info ;) */
1494     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1495     oggpack_adv( &opb, 224 );
1496     oggpack_adv( &opb, 32 ); /* speex_version_id */
1497     oggpack_adv( &opb, 32 ); /* header_size */
1498     p_stream->f_rate = p_stream->fmt.audio.i_rate = oggpack_read( &opb, 32 );
1499     oggpack_adv( &opb, 32 ); /* mode */
1500     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
1501     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
1502     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1503 }
1504
1505 static void Ogg_ReadFlacHeader( demux_t *p_demux, logical_stream_t *p_stream,
1506                                 ogg_packet *p_oggpacket )
1507 {
1508     /* Parse the STREAMINFO metadata */
1509     bs_t s;
1510
1511     bs_init( &s, p_oggpacket->packet, p_oggpacket->bytes );
1512
1513     bs_read( &s, 1 );
1514     if( bs_read( &s, 7 ) == 0 )
1515     {
1516         if( bs_read( &s, 24 ) >= 34 /*size STREAMINFO*/ )
1517         {
1518             bs_skip( &s, 80 );
1519             p_stream->f_rate = p_stream->fmt.audio.i_rate = bs_read( &s, 20 );
1520             p_stream->fmt.audio.i_channels = bs_read( &s, 3 ) + 1;
1521
1522             msg_Dbg( p_demux, "FLAC header, channels: %i, rate: %i",
1523                      p_stream->fmt.audio.i_channels, (int)p_stream->f_rate );
1524         }
1525         else msg_Dbg( p_demux, "FLAC STREAMINFO metadata too short" );
1526
1527         /* Fake this as the last metadata block */
1528         *((uint8_t*)p_oggpacket->packet) |= 0x80;
1529     }
1530     else
1531     {
1532         /* This ain't a STREAMINFO metadata */
1533         msg_Dbg( p_demux, "Invalid FLAC STREAMINFO metadata" );
1534     }
1535 }
1536
1537 static void Ogg_ReadKateHeader( logical_stream_t *p_stream,
1538                                 ogg_packet *p_oggpacket )
1539 {
1540     oggpack_buffer opb;
1541     int32_t gnum;
1542     int32_t gden;
1543     int n;
1544
1545     p_stream->fmt.i_cat = SPU_ES;
1546     p_stream->fmt.i_codec = VLC_FOURCC( 'k','a','t','e' );
1547
1548     /* Signal that we want to keep a backup of the kate
1549      * stream headers. They will be used when switching between
1550      * kate streams. */
1551     p_stream->b_force_backup = 1;
1552
1553     /* Cheat and get additionnal info ;) */
1554     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1555     oggpack_adv( &opb, 11*8 ); /* packet type, kate magic, version */
1556     p_stream->i_kate_num_headers = oggpack_read( &opb, 8 );
1557     oggpack_adv( &opb, 3*8 );
1558     p_stream->i_granule_shift = oggpack_read( &opb, 8 );
1559     oggpack_adv( &opb, 8*8 ); /* reserved */
1560     gnum = oggpack_read( &opb, 32 );
1561     gden = oggpack_read( &opb, 32 );
1562     p_stream->f_rate = (double)gnum/gden;
1563
1564     p_stream->fmt.psz_language = malloc(16);
1565     if (p_stream->fmt.psz_language)
1566     {
1567         for (n=0;n<16;++n)
1568             p_stream->fmt.psz_language[n] = oggpack_read(&opb,8);
1569         p_stream->fmt.psz_language[15] = 0; /* just in case */
1570     }
1571     else
1572     {
1573         for (n=0;n<16;++n)
1574             oggpack_read(&opb,8);
1575     }
1576     p_stream->fmt.psz_description = malloc(16);
1577     if (p_stream->fmt.psz_description)
1578     {
1579         for (n=0;n<16;++n)
1580             p_stream->fmt.psz_description[n] = oggpack_read(&opb,8);
1581         p_stream->fmt.psz_description[15] = 0; /* just in case */
1582     }
1583     else
1584     {
1585         for (n=0;n<16;++n)
1586             oggpack_read(&opb,8);
1587     }
1588 }
1589
1590 static void Ogg_ReadAnnodexHeader( vlc_object_t *p_this,
1591                                    logical_stream_t *p_stream,
1592                                    ogg_packet *p_oggpacket )
1593 {
1594     if( p_oggpacket->bytes >= 28 &&
1595         !memcmp( p_oggpacket->packet, "Annodex", 7 ) )
1596     {
1597         oggpack_buffer opb;
1598
1599         uint16_t major_version;
1600         uint16_t minor_version;
1601         uint64_t timebase_numerator;
1602         uint64_t timebase_denominator;
1603
1604         Ogg_ReadTheoraHeader( p_stream, p_oggpacket );
1605
1606         oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1607         oggpack_adv( &opb, 8*8 ); /* "Annodex\0" header */
1608         major_version = oggpack_read( &opb, 2*8 ); /* major version */
1609         minor_version = oggpack_read( &opb, 2*8 ); /* minor version */
1610         timebase_numerator = GetQWLE( &p_oggpacket->packet[16] );
1611         timebase_denominator = GetQWLE( &p_oggpacket->packet[24] );
1612     }
1613     else if( p_oggpacket->bytes >= 42 &&
1614              !memcmp( p_oggpacket->packet, "AnxData", 7 ) )
1615     {
1616         uint64_t granule_rate_numerator;
1617         uint64_t granule_rate_denominator;
1618         char content_type_string[1024];
1619
1620         /* Read in Annodex header fields */
1621
1622         granule_rate_numerator = GetQWLE( &p_oggpacket->packet[8] );
1623         granule_rate_denominator = GetQWLE( &p_oggpacket->packet[16] );
1624         p_stream->secondary_header_packets =
1625             GetDWLE( &p_oggpacket->packet[24] );
1626
1627         /* we are guaranteed that the first header field will be
1628          * the content-type (by the Annodex standard) */
1629         content_type_string[0] = '\0';
1630         if( !strncasecmp( (char*)(&p_oggpacket->packet[28]), "Content-Type: ", 14 ) )
1631         {
1632             uint8_t *p = memchr( &p_oggpacket->packet[42], '\r',
1633                                  p_oggpacket->bytes - 1 );
1634             if( p && p[0] == '\r' && p[1] == '\n' )
1635                 sscanf( (char*)(&p_oggpacket->packet[42]), "%1024s\r\n",
1636                         content_type_string );
1637         }
1638
1639         msg_Dbg( p_this, "AnxData packet info: %"PRId64" / %"PRId64", %d, ``%s''",
1640                  granule_rate_numerator, granule_rate_denominator,
1641                  p_stream->secondary_header_packets, content_type_string );
1642
1643         p_stream->f_rate = (float) granule_rate_numerator /
1644             (float) granule_rate_denominator;
1645
1646         /* What type of file do we have?
1647          * strcmp is safe to use here because we've extracted
1648          * content_type_string from the stream manually */
1649         if( !strncmp(content_type_string, "audio/x-wav", 11) )
1650         {
1651             /* n.b. WAVs are unsupported right now */
1652             p_stream->fmt.i_cat = UNKNOWN_ES;
1653         }
1654         else if( !strncmp(content_type_string, "audio/x-vorbis", 14) )
1655         {
1656             p_stream->fmt.i_cat = AUDIO_ES;
1657             p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1658
1659             p_stream->b_force_backup = 1;
1660         }
1661         else if( !strncmp(content_type_string, "audio/x-speex", 14) )
1662         {
1663             p_stream->fmt.i_cat = AUDIO_ES;
1664             p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
1665
1666             p_stream->b_force_backup = 1;
1667         }
1668         else if( !strncmp(content_type_string, "video/x-theora", 14) )
1669         {
1670             p_stream->fmt.i_cat = VIDEO_ES;
1671             p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1672
1673             p_stream->b_force_backup = 1;
1674         }
1675         else if( !strncmp(content_type_string, "video/x-xvid", 14) )
1676         {
1677             p_stream->fmt.i_cat = VIDEO_ES;
1678             p_stream->fmt.i_codec = VLC_FOURCC( 'x','v','i','d' );
1679
1680             p_stream->b_force_backup = 1;
1681         }
1682         else if( !strncmp(content_type_string, "video/mpeg", 14) )
1683         {
1684             /* n.b. MPEG streams are unsupported right now */
1685             p_stream->fmt.i_cat = VIDEO_ES;
1686             p_stream->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1687         }
1688         else if( !strncmp(content_type_string, "text/x-cmml", 11) )
1689         {
1690             ogg_stream_packetout( &p_stream->os, p_oggpacket );
1691             p_stream->fmt.i_cat = SPU_ES;
1692             p_stream->fmt.i_codec = VLC_FOURCC( 'c','m','m','l' );
1693         }
1694     }
1695 }
1696
1697 static uint32_t dirac_uint( bs_t *p_bs )
1698 {
1699   uint32_t count = 0, value = 0;
1700   while( !bs_read ( p_bs, 1 ) ) {
1701     count++;
1702     value <<= 1;
1703     value |= bs_read ( p_bs, 1 );
1704   }
1705
1706   return (1<<count) - 1 + value;
1707 }
1708
1709 static int dirac_bool( bs_t *p_bs )
1710 {
1711     return bs_read ( p_bs, 1 );
1712 }
1713
1714 static void Ogg_ReadDiracHeader( logical_stream_t *p_stream,
1715                                  ogg_packet *p_oggpacket )
1716 {
1717     bs_t bs;
1718
1719     p_stream->fmt.i_cat = VIDEO_ES;
1720     p_stream->fmt.i_codec = VLC_FOURCC( 'd','r','a','c' );
1721     p_stream->i_granule_shift = 32;
1722
1723     /* Backing up stream headers is not required -- seqhdrs are repeated
1724      * thoughout the stream at suitable decoding start points */
1725     p_stream->b_force_backup = 0;
1726
1727     /* read in useful bits from sequence header */
1728     bs_init( &bs, p_oggpacket->packet, p_oggpacket->bytes );
1729     bs_skip( &bs, 13*8); /* parse_info_header */
1730     dirac_uint( &bs ); /* major_version */
1731     dirac_uint( &bs ); /* minor_version */
1732     dirac_uint( &bs ); /* profile */
1733     dirac_uint( &bs ); /* level */
1734
1735     uint32_t u_video_format = dirac_uint( &bs ); /* index */
1736
1737     if (dirac_bool( &bs )) {
1738         dirac_uint( &bs ); /* frame_width */
1739         dirac_uint( &bs ); /* frame_height */
1740     }
1741
1742     if (dirac_bool( &bs )) {
1743         dirac_uint( &bs ); /* chroma_format */
1744     }
1745
1746     if (dirac_bool( &bs )) {
1747         dirac_uint( &bs ); /* scan_format */
1748     }
1749
1750     static const struct {
1751         uint32_t u_n /* numerator */, u_d /* denominator */;
1752     } dirac_frate_tbl[] = { /* table 10.3 */
1753         {1,1}, /* this first value is never used */
1754         {24000,1001}, {24,1}, {25,1}, {30000,1001}, {30,1},
1755         {50,1}, {60000,1001}, {60,1}, {15000,1001}, {25,2},
1756     };
1757
1758     static const uint32_t dirac_vidfmt_frate[] = { /* table C.1 */
1759         1, 9, 10, 9, 10, 9, 10, 4, 3, 7, 6, 4, 3, 7, 6, 2, 2, 7, 6, 7, 6,
1760     };
1761
1762     uint32_t u_n = dirac_frate_tbl[dirac_vidfmt_frate[u_video_format]].u_n;
1763     uint32_t u_d = dirac_frate_tbl[dirac_vidfmt_frate[u_video_format]].u_d;
1764     if (dirac_bool( &bs )) {
1765         uint32_t frame_rate_index = dirac_uint( &bs );
1766         u_n = dirac_frate_tbl[frame_rate_index].u_n;
1767         u_d = dirac_frate_tbl[frame_rate_index].u_d;
1768         if (frame_rate_index == 0) {
1769             u_n = dirac_uint( &bs ); /* frame_rate_numerator */
1770             u_d = dirac_uint( &bs ); /* frame_rate_denominator */
1771         }
1772     }
1773     p_stream->f_rate = (float) u_n / u_d;
1774 }