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