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