]> git.sesse.net Git - vlc/blob - modules/demux/ogg.c
* ogg : demux -> demux2. It needs more testings.
[vlc] / modules / demux / ogg.c
1 /*****************************************************************************
2  * ogg.c : ogg stream demux module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <vlc/vlc.h>
29 #include <vlc/input.h>
30
31 #include <ogg/ogg.h>
32
33 #include "codecs.h"
34 #include "vlc_bits.h"
35
36 /*****************************************************************************
37  * Module descriptor
38  *****************************************************************************/
39 static int  Open ( vlc_object_t * );
40 static void Close( vlc_object_t * );
41
42 vlc_module_begin();
43     set_description( _("Ogg stream demuxer" ) );
44     set_capability( "demux2", 50 );
45     set_callbacks( Open, Close );
46     add_shortcut( "ogg" );
47 vlc_module_end();
48
49
50 /*****************************************************************************
51  * Definitions of structures and functions used by this plugins
52  *****************************************************************************/
53 typedef struct logical_stream_s
54 {
55     ogg_stream_state os;                        /* logical stream of packets */
56
57     es_format_t      fmt;
58     es_out_id_t      *p_es;
59     double           f_rate;
60
61     int              i_serial_no;
62     int              b_activated;
63
64     /* the header of some logical streams (eg vorbis) contain essential
65      * data for the decoder. We back them up here in case we need to re-feed
66      * them to the decoder. */
67     int              b_force_backup;
68     int              i_packets_backup;
69     ogg_packet       *p_packets_backup;
70
71     /* program clock reference (in units of 90kHz) derived from the previous
72      * granulepos */
73     mtime_t          i_pcr;
74     mtime_t          i_interpolated_pcr;
75     mtime_t          i_previous_pcr;
76
77     /* Misc */
78     int b_reinit;
79     int i_theora_keyframe_granule_shift;
80
81     /* for Annodex logical bitstreams */
82     int secondary_header_packets;
83
84 } logical_stream_t;
85
86 struct demux_sys_t
87 {
88     ogg_sync_state oy;        /* sync and verify incoming physical bitstream */
89
90     int i_streams;                           /* number of logical bitstreams */
91     logical_stream_t **pp_stream;  /* pointer to an array of logical streams */
92
93     /* program clock reference (in units of 90kHz) derived from the pcr of
94      * the sub-streams */
95     mtime_t i_pcr;
96
97     /* stream state */
98     int     i_eos;
99
100     /* bitrate */
101     int     i_bitrate;
102 };
103
104 /* OggDS headers for the new header format (used in ogm files) */
105 typedef struct stream_header_video
106 {
107     ogg_int32_t width;
108     ogg_int32_t height;
109 } stream_header_video;
110
111 typedef struct stream_header_audio
112 {
113     ogg_int16_t channels;
114     ogg_int16_t blockalign;
115     ogg_int32_t avgbytespersec;
116 } stream_header_audio;
117
118 typedef struct stream_header
119 {
120     char        streamtype[8];
121     char        subtype[4];
122
123     ogg_int32_t size;                               /* size of the structure */
124
125     ogg_int64_t time_unit;                              /* in reference time */
126     ogg_int64_t samples_per_unit;
127     ogg_int32_t default_len;                                /* in media time */
128
129     ogg_int32_t buffersize;
130     ogg_int16_t bits_per_sample;
131
132     union
133     {
134         /* Video specific */
135         stream_header_video video;
136         /* Audio specific */
137         stream_header_audio audio;
138     } sh;
139 } stream_header;
140
141 #define OGG_BLOCK_SIZE 4096
142
143 /* Some defines from OggDS */
144 #define PACKET_TYPE_HEADER   0x01
145 #define PACKET_TYPE_BITS     0x07
146 #define PACKET_LEN_BITS01    0xc0
147 #define PACKET_LEN_BITS2     0x02
148 #define PACKET_IS_SYNCPOINT  0x08
149
150 /*****************************************************************************
151  * Local prototypes
152  *****************************************************************************/
153 static int  Demux  ( demux_t * );
154 static int  Control( demux_t *, int, va_list );
155
156 /* Bitstream manipulation */
157 static int  Ogg_ReadPage     ( demux_t *, ogg_page * );
158 static void Ogg_UpdatePCR    ( logical_stream_t *, ogg_packet * );
159 static void Ogg_DecodePacket ( demux_t *, logical_stream_t *, ogg_packet * );
160
161 static int Ogg_BeginningOfStream( demux_t *p_demux );
162 static int Ogg_FindLogicalStreams( demux_t *p_demux );
163 static void Ogg_EndOfStream( demux_t *p_demux );
164
165 /* Logical bitstream headers */
166 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
167                                   ogg_packet *p_oggpacket );
168 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
169                                   ogg_packet *p_oggpacket );
170 static void Ogg_ReadAnnodexHeader( vlc_object_t *, logical_stream_t *p_stream,
171                                    ogg_packet *p_oggpacket );
172
173 /*****************************************************************************
174  * Open: initializes ogg demux structures
175  *****************************************************************************/
176 static int Open( vlc_object_t * p_this )
177 {
178     demux_t *p_demux = (demux_t *)p_this;
179     demux_sys_t    *p_sys;
180     uint8_t        *p_peek;
181
182
183     /* Check if we are dealing with an ogg stream */
184     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
185     {
186         msg_Err( p_demux, "cannot peek" );
187         return VLC_EGENERIC;
188     }
189     if( strcmp( p_demux->psz_demux, "ogg" ) && strncmp( p_peek, "OggS", 4 ) )
190     {
191         msg_Warn( p_demux, "ogg module discarded (invalid header)" );
192         return VLC_EGENERIC;
193     }
194
195     /* Set exported functions */
196     p_demux->pf_demux = Demux;
197     p_demux->pf_control = Control;
198     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
199
200     memset( p_sys, 0, sizeof( demux_sys_t ) );
201     p_sys->i_bitrate = 0;
202     p_sys->pp_stream = NULL;
203
204     /* Begnning of stream, tell the demux to look for elementary streams. */
205     p_sys->i_eos = 0;
206
207     /* Initialize the Ogg physical bitstream parser */
208     ogg_sync_init( &p_sys->oy );
209
210     return VLC_SUCCESS;
211 }
212
213 /*****************************************************************************
214  * Close: frees unused data
215  *****************************************************************************/
216 static void Close( vlc_object_t *p_this )
217 {
218     demux_t *p_demux = (demux_t *)p_this;
219     demux_sys_t *p_sys = p_demux->p_sys  ;
220
221     /* Cleanup the bitstream parser */
222     ogg_sync_clear( &p_sys->oy );
223
224     Ogg_EndOfStream( p_demux );
225
226     free( p_sys );
227 }
228
229 /*****************************************************************************
230  * Demux: reads and demuxes data packets
231  *****************************************************************************
232  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
233  *****************************************************************************/
234 static int Demux( demux_t * p_demux )
235 {
236     demux_sys_t *p_sys = p_demux->p_sys;
237     ogg_page    oggpage;
238     ogg_packet  oggpacket;
239     int         i_stream;
240
241
242     if( p_sys->i_eos == p_sys->i_streams )
243     {
244         if( p_sys->i_eos )
245         {
246             msg_Dbg( p_demux, "end of a group of logical streams" );
247             Ogg_EndOfStream( p_demux );
248         }
249
250         if( Ogg_BeginningOfStream( p_demux ) != VLC_SUCCESS ) return 0;
251         p_sys->i_eos = 0;
252
253         msg_Dbg( p_demux, "beginning of a group of logical streams" );
254         es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
255     }
256
257     /*
258      * Demux an ogg page from the stream
259      */
260     if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
261     {
262         return 0; /* EOF */
263     }
264
265     /* Test for End of Stream */
266     if( ogg_page_eos( &oggpage ) ) p_sys->i_eos++;
267
268
269     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
270     {
271         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
272
273         if( ogg_stream_pagein( &p_stream->os, &oggpage ) != 0 )
274             continue;
275
276         while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
277         {
278             /* Read info from any secondary header packets, if there are any */
279             if( p_stream->secondary_header_packets > 0 )
280             {
281                 if( p_stream->fmt.i_codec == VLC_FOURCC( 't','h','e','o' ) &&
282                         oggpacket.bytes >= 7 &&
283                         ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
284                 {
285                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
286                     p_stream->secondary_header_packets = 0;
287                 }
288                 else if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) &&
289                         oggpacket.bytes >= 7 &&
290                         ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
291                 {
292                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
293                     p_stream->secondary_header_packets = 0;
294                 }
295                 else if ( p_stream->fmt.i_codec == VLC_FOURCC( 'c','m','m','l' ) )
296                 {
297                     p_stream->secondary_header_packets = 0;
298                 }
299
300                 p_stream->secondary_header_packets--;
301             }
302
303             if( p_stream->b_reinit )
304             {
305                 /* If synchro is re-initialized we need to drop all the packets
306                  * until we find a new dated one. */
307                 Ogg_UpdatePCR( p_stream, &oggpacket );
308
309                 if( p_stream->i_pcr >= 0 )
310                 {
311                     p_stream->b_reinit = 0;
312                 }
313                 else
314                 {
315                     p_stream->i_interpolated_pcr = -1;
316                     continue;
317                 }
318
319                 /* An Ogg/vorbis packet contains an end date granulepos */
320                 if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
321                     p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
322                     p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
323                 {
324                     if( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
325                     {
326                         Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
327                     }
328                     else
329                     {
330                         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_stream->i_pcr );
331                     }
332                     continue;
333                 }
334             }
335
336             Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
337         }
338         break;
339     }
340
341     i_stream = 0; p_sys->i_pcr = -1;
342     for( ; i_stream < p_sys->i_streams; i_stream++ )
343     {
344         logical_stream_t *p_stream = p_sys->pp_stream[i_stream];
345
346         if( p_stream->fmt.i_cat == SPU_ES )
347             continue;
348         if( p_stream->i_interpolated_pcr < 0 )
349             continue;
350
351         if( p_sys->i_pcr < 0 || p_stream->i_interpolated_pcr < p_sys->i_pcr )
352             p_sys->i_pcr = p_stream->i_interpolated_pcr;
353     }
354
355     if( p_sys->i_pcr >= 0 )
356     {
357         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
358     }
359
360
361     return 1;
362 }
363
364 /*****************************************************************************
365  * Control:
366  *****************************************************************************/
367 static int Control( demux_t *p_demux, int i_query, va_list args )
368 {
369     demux_sys_t *p_sys  = p_demux->p_sys;
370     int64_t *pi64;
371     int i;
372
373     switch( i_query )
374     {
375         case DEMUX_GET_TIME:
376             pi64 = (int64_t*)va_arg( args, int64_t * );
377             *pi64 = p_sys->i_pcr;
378             return VLC_SUCCESS;
379
380         case DEMUX_SET_TIME:
381             return VLC_EGENERIC;
382
383         case DEMUX_SET_POSITION:
384             for( i = 0; i < p_sys->i_streams; i++ )
385             {
386                 logical_stream_t *p_stream = p_sys->pp_stream[i];
387
388                 /* we'll trash all the data until we find the next pcr */
389                 p_stream->b_reinit = 1;
390                 p_stream->i_pcr = -1;
391                 p_stream->i_interpolated_pcr = -1;
392                 ogg_stream_reset( &p_stream->os );
393             }
394             ogg_sync_reset( &p_sys->oy );
395
396         default:
397             return demux2_vaControlHelper( p_demux->s,
398                                            0, -1,
399                                            p_sys->i_bitrate, 1, i_query, args );
400     }
401 }
402
403 /****************************************************************************
404  * Ogg_ReadPage: Read a full Ogg page from the physical bitstream.
405  ****************************************************************************
406  * Returns VLC_SUCCESS if a page has been read. An error might happen if we
407  * are at the end of stream.
408  ****************************************************************************/
409 static int Ogg_ReadPage( demux_t *p_demux, ogg_page *p_oggpage )
410 {
411     demux_sys_t *p_ogg = p_demux->p_sys  ;
412     int i_read = 0;
413     byte_t *p_buffer;
414
415     while( ogg_sync_pageout( &p_ogg->oy, p_oggpage ) != 1 )
416     {
417         p_buffer = ogg_sync_buffer( &p_ogg->oy, OGG_BLOCK_SIZE );
418
419         i_read = stream_Read( p_demux->s, p_buffer, OGG_BLOCK_SIZE );
420         if( i_read <= 0 )
421             return VLC_EGENERIC;
422
423         ogg_sync_wrote( &p_ogg->oy, i_read );
424     }
425
426     return VLC_SUCCESS;
427 }
428
429 /****************************************************************************
430  * Ogg_UpdatePCR: update the PCR (90kHz program clock reference) for the
431  *                current stream.
432  ****************************************************************************/
433 static void Ogg_UpdatePCR( logical_stream_t *p_stream,
434                            ogg_packet *p_oggpacket )
435 {
436     /* Convert the granulepos into a pcr */
437     if( p_oggpacket->granulepos >= 0 )
438     {
439         if( p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) )
440         {
441             p_stream->i_pcr = p_oggpacket->granulepos * I64C(1000000)
442                               / p_stream->f_rate;
443         }
444         else
445         {
446             ogg_int64_t iframe = p_oggpacket->granulepos >>
447               p_stream->i_theora_keyframe_granule_shift;
448             ogg_int64_t pframe = p_oggpacket->granulepos -
449               ( iframe << p_stream->i_theora_keyframe_granule_shift );
450
451             p_stream->i_pcr = ( iframe + pframe ) * I64C(1000000)
452                               / p_stream->f_rate;
453         }
454
455         p_stream->i_interpolated_pcr = p_stream->i_pcr;
456     }
457     else
458     {
459         p_stream->i_pcr = -1;
460
461         /* no granulepos available, try to interpolate the pcr.
462          * If we can't then don't touch the old value. */
463         if( p_stream->fmt.i_cat == VIDEO_ES )
464             /* 1 frame per packet */
465             p_stream->i_interpolated_pcr += (I64C(1000000) / p_stream->f_rate);
466         else if( p_stream->fmt.i_bitrate )
467             p_stream->i_interpolated_pcr += ( p_oggpacket->bytes * I64C(1000000)
468                                               / p_stream->fmt.i_bitrate / 8 );
469     }
470 }
471
472 /****************************************************************************
473  * Ogg_DecodePacket: Decode an Ogg packet.
474  ****************************************************************************/
475 static void Ogg_DecodePacket( demux_t *p_demux,
476                               logical_stream_t *p_stream,
477                               ogg_packet *p_oggpacket )
478 {
479     block_t *p_block;
480     vlc_bool_t b_selected;
481     int i_header_len = 0;
482     mtime_t i_pts = 0;
483
484     /* Sanity check */
485     if( !p_oggpacket->bytes )
486     {
487         msg_Dbg( p_demux, "discarding 0 sized packet" );
488         return;
489     }
490
491     if( p_oggpacket->bytes >= 7 &&
492         ! strncmp ( &p_oggpacket->packet[0], "Annodex", 7 ) )
493     {
494         /* it's an Annodex packet -- skip it (do nothing) */
495         return; 
496     }
497     else if( p_oggpacket->bytes >= 7 &&
498         ! strncmp ( &p_oggpacket->packet[0], "AnxData", 7 ) )
499     {
500         /* it's an AnxData packet -- skip it (do nothing) */
501         return; 
502     }
503
504     if( p_stream->b_force_backup )
505     {
506         ogg_packet *p_packet_backup;
507         p_stream->i_packets_backup++;
508         switch( p_stream->fmt.i_codec )
509         {
510         case VLC_FOURCC( 'v','o','r','b' ):
511         case VLC_FOURCC( 's','p','x',' ' ):
512         case VLC_FOURCC( 't','h','e','o' ):
513           if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
514           break;
515
516         case VLC_FOURCC( 'f','l','a','c' ):
517           if( p_stream->i_packets_backup == 1 ) return;
518           else if( p_stream->i_packets_backup == 2 )
519           {
520               /* Parse the STREAMINFO metadata */
521               bs_t s;
522               bs_init( &s, p_oggpacket->packet, p_oggpacket->bytes );
523               bs_read( &s, 1 );
524               if( bs_read( &s, 7 ) == 0 )
525               {
526                   if( bs_read( &s, 24 ) >= 34 /*size STREAMINFO*/ )
527                   {
528                       bs_skip( &s, 80 );
529                       p_stream->f_rate = p_stream->fmt.audio.i_rate =
530                           bs_read( &s, 20 );
531                       p_stream->fmt.audio.i_channels =
532                           bs_read( &s, 3 ) + 1;
533
534                       msg_Dbg( p_demux, "FLAC header, channels: %i, rate: %i",
535                                p_stream->fmt.audio.i_channels,
536                                (int)p_stream->f_rate );
537                   }
538                   else
539                   {
540                       msg_Dbg( p_demux, "FLAC STREAMINFO metadata too short" );
541                   }
542
543                   /* Store STREAMINFO for the decoder and packetizer */
544                   p_stream->fmt.i_extra = p_oggpacket->bytes + 4;
545                   p_stream->fmt.p_extra = malloc( p_stream->fmt.i_extra );
546                   memcpy( p_stream->fmt.p_extra, "fLaC", 4);
547                   memcpy( ((uint8_t *)p_stream->fmt.p_extra) + 4,
548                           p_oggpacket->packet, p_oggpacket->bytes );
549
550                   /* Fake this as the last metadata block */
551                   ((uint8_t*)p_stream->fmt.p_extra)[4] |= 0x80;
552
553                   p_stream->p_es = es_out_Add( p_demux->out,
554                                                &p_stream->fmt );
555               }
556               else
557               {
558                   /* This ain't a STREAMINFO metadata */
559                   msg_Dbg( p_demux, "Invalid FLAC STREAMINFO metadata" );
560               }
561               p_stream->b_force_backup = 0;
562               p_stream->i_packets_backup = 0;
563
564               if( p_oggpacket->granulepos >= 0 )
565                   Ogg_UpdatePCR( p_stream, p_oggpacket );
566
567               p_stream->i_previous_pcr = 0;
568               return;
569           }
570           break;
571
572         default:
573           p_stream->b_force_backup = 0;
574           break;
575         }
576
577         /* Backup the ogg packet (likely an header packet) */
578         p_stream->p_packets_backup =
579             realloc( p_stream->p_packets_backup, p_stream->i_packets_backup *
580                      sizeof(ogg_packet) );
581
582         p_packet_backup =
583             &p_stream->p_packets_backup[p_stream->i_packets_backup - 1];
584
585         p_packet_backup->bytes = p_oggpacket->bytes;
586         p_packet_backup->granulepos = p_oggpacket->granulepos;
587
588         if( p_oggpacket->granulepos >= 0 )
589         {
590             /* Because of vorbis granulepos scheme we must set the pcr for the
591              * 1st header packet so it doesn't get discarded in the
592              * packetizer */
593             Ogg_UpdatePCR( p_stream, p_oggpacket );
594         }
595
596         p_packet_backup->packet = malloc( p_oggpacket->bytes );
597         if( !p_packet_backup->packet ) return;
598         memcpy( p_packet_backup->packet, p_oggpacket->packet,
599                 p_oggpacket->bytes );
600     }
601
602     /* Check the ES is selected */
603     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
604                     p_stream->p_es, &b_selected );
605
606     if( b_selected && !p_stream->b_activated )
607     {
608         p_stream->b_activated = VLC_TRUE;
609
610         /* Newly activated stream, feed the backup headers to the decoder */
611         if( !p_stream->b_force_backup )
612         {
613             int i;
614             for( i = 0; i < p_stream->i_packets_backup; i++ )
615             {
616                 /* Set correct starting date in header packets */
617                 p_stream->p_packets_backup[i].granulepos =
618                     p_stream->i_interpolated_pcr * p_stream->f_rate / I64C(1000000);
619
620                 Ogg_DecodePacket( p_demux, p_stream,
621                                   &p_stream->p_packets_backup[i] );
622             }
623         }
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, p_stream->i_pcr );
642             }
643
644             p_stream->i_previous_pcr = p_stream->i_pcr;
645
646             /* The granulepos is the end date of the sample */
647             i_pts =  p_stream->i_pcr;
648         }
649     }
650
651     /* Convert the granulepos into the next pcr */
652     Ogg_UpdatePCR( p_stream, p_oggpacket );
653
654     if( p_stream->i_pcr >= 0 )
655     {
656         /* This is for streams where the granulepos of the header packets
657          * doesn't match these of the data packets (eg. ogg web radios). */
658         if( p_stream->i_previous_pcr == 0 &&
659             p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
660         {
661             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
662
663             /* Call the pace control */
664             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_stream->i_pcr );
665         }
666     }
667
668     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
669         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
670         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
671         p_stream->i_pcr >= 0 )
672     {
673         p_stream->i_previous_pcr = p_stream->i_pcr;
674
675         /* The granulepos is the start date of the sample */
676         i_pts = p_stream->i_pcr;
677     }
678
679     if( !b_selected )
680     {
681         /* This stream isn't currently selected so we don't need to decode it,
682          * but we did need to store its pcr as it might be selected later on */
683         p_stream->b_activated = VLC_FALSE;
684         return;
685     }
686
687     if( !( p_block = block_New( p_demux, p_oggpacket->bytes ) ) ) return;
688
689     if( p_stream->fmt.i_cat == AUDIO_ES )
690         p_block->i_dts = p_block->i_pts = i_pts;
691     else if( p_stream->fmt.i_cat == SPU_ES )
692     {
693         p_block->i_pts = i_pts;
694         p_block->i_dts = 0;
695     }
696     else if( p_stream->fmt.i_codec == VLC_FOURCC( 't','h','e','o' ) )
697         p_block->i_dts = p_block->i_pts = i_pts;
698     else
699     {
700         p_block->i_dts = i_pts;
701         p_block->i_pts = 0;
702     }
703
704     if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
705         p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
706         p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
707         p_stream->fmt.i_codec != VLC_FOURCC( 't','a','r','k' ) &&
708         p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) &&
709         p_stream->fmt.i_codec != VLC_FOURCC( 'c','m','m','l' ) )
710     {
711         /* We remove the header from the packet */
712         i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
713         i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
714         
715         if( p_stream->fmt.i_codec == VLC_FOURCC( 's','u','b','t' ))
716         {
717             /* But with subtitles we need to retrieve the duration first */
718             int i, lenbytes = 0;
719         
720             if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
721             {
722                 for( i = 0, lenbytes = 0; i < i_header_len; i++ )
723                 {
724                     lenbytes = lenbytes << 8;
725                     lenbytes += *(p_oggpacket->packet + i_header_len - i);
726                 }
727             }
728             if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
729                 ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
730                   p_oggpacket->packet[i_header_len + 1] != 0 && 
731                   p_oggpacket->packet[i_header_len + 1] != '\n' &&
732                   p_oggpacket->packet[i_header_len + 1] != '\r' ) )
733             {
734                 p_block->i_dts = p_block->i_pts + (mtime_t)lenbytes * 1000;
735             }
736         }
737
738         i_header_len++;
739         p_block->i_buffer -= i_header_len;
740     }
741
742     if( p_stream->fmt.i_codec == VLC_FOURCC( 't','a','r','k' ) )
743     {
744         /* FIXME: the biggest hack I've ever done */
745         msg_Warn( p_demux, "tarkin pts: "I64Fd", granule: "I64Fd,
746                   p_block->i_pts, p_block->i_dts );
747         msleep(10000);
748     }
749
750     memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
751             p_oggpacket->bytes - i_header_len );
752
753     es_out_Send( p_demux->out, p_stream->p_es, p_block );
754 }
755
756 /****************************************************************************
757  * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
758  *                         stream and fill p_ogg.
759  *****************************************************************************
760  * The initial page of a logical stream is marked as a 'bos' page.
761  * Furthermore, the Ogg specification mandates that grouped bitstreams begin
762  * together and all of the initial pages must appear before any data pages.
763  *
764  * On success this function returns VLC_SUCCESS.
765  ****************************************************************************/
766 static int Ogg_FindLogicalStreams( demux_t *p_demux )
767 {
768     demux_sys_t *p_ogg = p_demux->p_sys  ;
769     ogg_packet oggpacket;
770     ogg_page oggpage;
771     int i_stream;
772
773 #define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]
774
775     while( Ogg_ReadPage( p_demux, &oggpage ) == VLC_SUCCESS )
776     {
777         if( ogg_page_bos( &oggpage ) )
778         {
779
780             /* All is wonderful in our fine fine little world.
781              * We found the beginning of our first logical stream. */
782             while( ogg_page_bos( &oggpage ) )
783             {
784                 p_ogg->i_streams++;
785                 p_ogg->pp_stream =
786                     realloc( p_ogg->pp_stream, p_ogg->i_streams *
787                              sizeof(logical_stream_t *) );
788
789                 p_stream = malloc( sizeof(logical_stream_t) );
790                 memset( p_stream, 0, sizeof(logical_stream_t) );
791
792                 es_format_Init( &p_stream->fmt, 0, 0 );
793                 p_stream->b_activated = VLC_TRUE;
794
795                 /* Setup the logical stream */
796                 p_stream->i_serial_no = ogg_page_serialno( &oggpage );
797                 ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
798
799                 /* Extract the initial header from the first page and verify
800                  * the codec type of tis Ogg bitstream */
801                 if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
802                 {
803                     /* error. stream version mismatch perhaps */
804                     msg_Err( p_demux, "error reading first page of "
805                              "Ogg bitstream data" );
806                     return VLC_EGENERIC;
807                 }
808
809                 /* FIXME: check return value */
810                 ogg_stream_packetpeek( &p_stream->os, &oggpacket );
811
812                 /* Check for Vorbis header */
813                 if( oggpacket.bytes >= 7 &&
814                     ! strncmp( &oggpacket.packet[1], "vorbis", 6 ) )
815                 {
816                     Ogg_ReadVorbisHeader( p_stream, &oggpacket );
817                     msg_Dbg( p_demux, "found vorbis header" );
818                 }
819                 /* Check for Speex header */
820                 else if( oggpacket.bytes >= 7 &&
821                     ! strncmp( &oggpacket.packet[0], "Speex", 5 ) )
822                 {
823                     oggpack_buffer opb;
824
825                     p_stream->fmt.i_cat = AUDIO_ES;
826                     p_stream->fmt.i_codec = VLC_FOURCC( 's','p','x',' ' );
827
828                     /* Signal that we want to keep a backup of the vorbis
829                      * stream headers. They will be used when switching between
830                      * audio streams. */
831                     p_stream->b_force_backup = 1;
832
833                     /* Cheat and get additionnal info ;) */
834                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
835                     oggpack_adv( &opb, 224 );
836                     oggpack_adv( &opb, 32 ); /* speex_version_id */
837                     oggpack_adv( &opb, 32 ); /* header_size */
838                     p_stream->f_rate = p_stream->fmt.audio.i_rate =
839                         oggpack_read( &opb, 32 );
840                     oggpack_adv( &opb, 32 ); /* mode */
841                     oggpack_adv( &opb, 32 ); /* mode_bitstream_version */
842                     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 32 );
843                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
844
845                     msg_Dbg( p_demux, "found speex header, channels: %i, "
846                              "rate: %i,  bitrate: %i",
847                              p_stream->fmt.audio.i_channels,
848                              (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
849                 }
850                 /* Check for Flac header */
851                 else if( oggpacket.bytes >= 4 &&
852                     ! strncmp( &oggpacket.packet[0], "fLaC", 4 ) )
853                 {
854                     msg_Dbg( p_demux, "found FLAC header" );
855
856                     /* Grrrr!!!! Did they really have to put all the
857                      * important info in the second header packet!!!
858                      * (STREAMINFO metadata is in the following packet) */
859                     p_stream->b_force_backup = 1;
860
861                     p_stream->fmt.i_cat = AUDIO_ES;
862                     p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
863                 }
864                 /* Check for Theora header */
865                 else if( oggpacket.bytes >= 7 &&
866                          ! strncmp( &oggpacket.packet[1], "theora", 6 ) )
867                 {
868                     Ogg_ReadTheoraHeader( p_stream, &oggpacket );
869
870                     msg_Dbg( p_demux,
871                              "found theora header, bitrate: %i, rate: %f",
872                              p_stream->fmt.i_bitrate, p_stream->f_rate );
873                 }
874                 /* Check for Tarkin header */
875                 else if( oggpacket.bytes >= 7 &&
876                          ! strncmp( &oggpacket.packet[1], "tarkin", 6 ) )
877                 {
878                     oggpack_buffer opb;
879
880                     msg_Dbg( p_demux, "found tarkin header" );
881                     p_stream->fmt.i_cat = VIDEO_ES;
882                     p_stream->fmt.i_codec = VLC_FOURCC( 't','a','r','k' );
883
884                     /* Cheat and get additionnal info ;) */
885                     oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
886                     oggpack_adv( &opb, 88 );
887                     oggpack_adv( &opb, 104 );
888                     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
889                     p_stream->f_rate = 2; /* FIXME */
890                     msg_Dbg( p_demux,
891                              "found tarkin header, bitrate: %i, rate: %f",
892                              p_stream->fmt.i_bitrate, p_stream->f_rate );
893                 }
894                 /* Check for Annodex header */
895                 else if( oggpacket.bytes >= 7 &&
896                          ! strncmp( &oggpacket.packet[0], "Annodex", 7 ) )
897                 {
898                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
899                                            &oggpacket );
900                     /* kill annodex track */
901                     free( p_stream );
902                     p_ogg->i_streams--;
903                 }
904                 /* Check for Annodex header */
905                 else if( oggpacket.bytes >= 7 &&
906                          ! strncmp( &oggpacket.packet[0], "AnxData", 7 ) )
907                 {
908                     Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
909                                            &oggpacket );
910                 }
911                 else if( oggpacket.bytes >= 142 &&
912                          !strncmp( &oggpacket.packet[1],
913                                    "Direct Show Samples embedded in Ogg", 35 ))
914                 {
915                     /* Old header type */
916
917                     /* Check for video header (old format) */
918                     if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
919                         oggpacket.bytes >= 184 )
920                     {
921                         p_stream->fmt.i_cat = VIDEO_ES;
922                         p_stream->fmt.i_codec =
923                             VLC_FOURCC( oggpacket.packet[68],
924                                         oggpacket.packet[69],
925                                         oggpacket.packet[70],
926                                         oggpacket.packet[71] );
927                         msg_Dbg( p_demux, "found video header of type: %.4s",
928                                  (char *)&p_stream->fmt.i_codec );
929
930                         p_stream->f_rate = 10000000.0 /
931                             GetQWLE((oggpacket.packet+164));
932                         p_stream->fmt.video.i_bits_per_pixel =
933                             GetWLE((oggpacket.packet+182));
934                         if( !p_stream->fmt.video.i_bits_per_pixel )
935                             /* hack, FIXME */
936                             p_stream->fmt.video.i_bits_per_pixel = 24;
937                         p_stream->fmt.video.i_width =
938                             GetDWLE((oggpacket.packet+176));
939                         p_stream->fmt.video.i_height =
940                             GetDWLE((oggpacket.packet+180));
941
942                         msg_Dbg( p_demux,
943                                  "fps: %f, width:%i; height:%i, bitcount:%i",
944                                  p_stream->f_rate,
945                                  p_stream->fmt.video.i_width,
946                                  p_stream->fmt.video.i_height,
947                                  p_stream->fmt.video.i_bits_per_pixel);
948
949                     }
950                     /* Check for audio header (old format) */
951                     else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
952                     {
953                         unsigned int i_extra_size;
954                         unsigned int i_format_tag;
955
956                         p_stream->fmt.i_cat = AUDIO_ES;
957
958                         i_extra_size = GetWLE((oggpacket.packet+140));
959                         if( i_extra_size )
960                         {
961                             p_stream->fmt.i_extra = i_extra_size;
962                             p_stream->fmt.p_extra = malloc( i_extra_size );
963                             memcpy( p_stream->fmt.p_extra,
964                                     oggpacket.packet + 142, i_extra_size );
965                         }
966
967                         i_format_tag = GetWLE((oggpacket.packet+124));
968                         p_stream->fmt.audio.i_channels =
969                             GetWLE((oggpacket.packet+126));
970                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
971                             GetDWLE((oggpacket.packet+128));
972                         p_stream->fmt.i_bitrate =
973                             GetDWLE((oggpacket.packet+132)) * 8;
974                         p_stream->fmt.audio.i_blockalign =
975                             GetWLE((oggpacket.packet+136));
976                         p_stream->fmt.audio.i_bitspersample =
977                             GetWLE((oggpacket.packet+138));
978
979                         switch( i_format_tag )
980                         {
981                         case WAVE_FORMAT_PCM:
982                             p_stream->fmt.i_codec =
983                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
984                             break;
985                         case WAVE_FORMAT_MPEG:
986                         case WAVE_FORMAT_MPEGLAYER3:
987                             p_stream->fmt.i_codec =
988                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
989                             break;
990                         case WAVE_FORMAT_A52:
991                             p_stream->fmt.i_codec =
992                                 VLC_FOURCC( 'a', '5', '2', ' ' );
993                             break;
994                         case WAVE_FORMAT_WMA1:
995                             p_stream->fmt.i_codec =
996                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
997                             break;
998                         case WAVE_FORMAT_WMA2:
999                             p_stream->fmt.i_codec =
1000                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
1001                             break;
1002                         default:
1003                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1004                                 ( i_format_tag >> 8 ) & 0xff,
1005                                 i_format_tag & 0xff );
1006                         }
1007
1008                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1009                                  (char *)&p_stream->fmt.i_codec );
1010                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1011                                  "%dbits/sample %dkb/s",
1012                                  i_format_tag,
1013                                  p_stream->fmt.audio.i_channels,
1014                                  p_stream->fmt.audio.i_rate,
1015                                  p_stream->fmt.audio.i_bitspersample,
1016                                  p_stream->fmt.i_bitrate / 1024 );
1017
1018                     }
1019                     else
1020                     {
1021                         msg_Dbg( p_demux, "stream %d has an old header "
1022                             "but is of an unknown type", p_ogg->i_streams-1 );
1023                         free( p_stream );
1024                         p_ogg->i_streams--;
1025                     }
1026                 }
1027                 else if( (*oggpacket.packet & PACKET_TYPE_BITS )
1028                          == PACKET_TYPE_HEADER &&
1029                          oggpacket.bytes >= (int)sizeof(stream_header)+1 )
1030                 {
1031                     stream_header *st = (stream_header *)(oggpacket.packet+1);
1032
1033                     /* Check for video header (new format) */
1034                     if( !strncmp( st->streamtype, "video", 5 ) )
1035                     {
1036                         p_stream->fmt.i_cat = VIDEO_ES;
1037
1038                         /* We need to get rid of the header packet */
1039                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1040
1041                         p_stream->fmt.i_codec =
1042                             VLC_FOURCC( st->subtype[0], st->subtype[1],
1043                                         st->subtype[2], st->subtype[3] );
1044                         msg_Dbg( p_demux, "found video header of type: %.4s",
1045                                  (char *)&p_stream->fmt.i_codec );
1046
1047                         p_stream->f_rate = 10000000.0 /
1048                             GetQWLE(&st->time_unit);
1049                         p_stream->fmt.video.i_bits_per_pixel =
1050                             GetWLE(&st->bits_per_sample);
1051                         p_stream->fmt.video.i_width =
1052                             GetDWLE(&st->sh.video.width);
1053                         p_stream->fmt.video.i_height =
1054                             GetDWLE(&st->sh.video.height);
1055
1056                         msg_Dbg( p_demux,
1057                                  "fps: %f, width:%i; height:%i, bitcount:%i",
1058                                  p_stream->f_rate,
1059                                  p_stream->fmt.video.i_width,
1060                                  p_stream->fmt.video.i_height,
1061                                  p_stream->fmt.video.i_bits_per_pixel );
1062                     }
1063                     /* Check for audio header (new format) */
1064                     else if( !strncmp( st->streamtype, "audio", 5 ) )
1065                     {
1066                         char p_buffer[5];
1067                         int i_format_tag;
1068
1069                         p_stream->fmt.i_cat = AUDIO_ES;
1070
1071                         /* We need to get rid of the header packet */
1072                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1073
1074                         memcpy( p_buffer, st->subtype, 4 );
1075                         p_buffer[4] = '\0';
1076                         i_format_tag = strtol(p_buffer,NULL,16);
1077                         p_stream->fmt.audio.i_channels =
1078                             GetWLE(&st->sh.audio.channels);
1079                         p_stream->f_rate = p_stream->fmt.audio.i_rate =
1080                             GetQWLE(&st->samples_per_unit);
1081                         p_stream->fmt.i_bitrate =
1082                             GetDWLE(&st->sh.audio.avgbytespersec) * 8;
1083                         p_stream->fmt.audio.i_blockalign =
1084                             GetWLE(&st->sh.audio.blockalign);
1085                         p_stream->fmt.audio.i_bitspersample =
1086                             GetWLE(&st->bits_per_sample);
1087
1088                         switch( i_format_tag )
1089                         {
1090                         case WAVE_FORMAT_PCM:
1091                             p_stream->fmt.i_codec =
1092                                 VLC_FOURCC( 'a', 'r', 'a', 'w' );
1093                             break;
1094                         case WAVE_FORMAT_MPEG:
1095                         case WAVE_FORMAT_MPEGLAYER3:
1096                             p_stream->fmt.i_codec =
1097                                 VLC_FOURCC( 'm', 'p', 'g', 'a' );
1098                             break;
1099                         case WAVE_FORMAT_A52:
1100                             p_stream->fmt.i_codec =
1101                                 VLC_FOURCC( 'a', '5', '2', ' ' );
1102                             break;
1103                         case WAVE_FORMAT_WMA1:
1104                             p_stream->fmt.i_codec =
1105                                 VLC_FOURCC( 'w', 'm', 'a', '1' );
1106                             break;
1107                         case WAVE_FORMAT_WMA2:
1108                             p_stream->fmt.i_codec =
1109                                 VLC_FOURCC( 'w', 'm', 'a', '2' );
1110                             break;
1111                         default:
1112                             p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
1113                                 ( i_format_tag >> 8 ) & 0xff,
1114                                 i_format_tag & 0xff );
1115                         }
1116
1117                         msg_Dbg( p_demux, "found audio header of type: %.4s",
1118                                  (char *)&p_stream->fmt.i_codec );
1119                         msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
1120                                  "%dbits/sample %dkb/s",
1121                                  i_format_tag,
1122                                  p_stream->fmt.audio.i_channels,
1123                                  p_stream->fmt.audio.i_rate,
1124                                  p_stream->fmt.audio.i_bitspersample,
1125                                  p_stream->fmt.i_bitrate / 1024 );
1126                     }
1127                     /* Check for text (subtitles) header */
1128                     else if( !strncmp(st->streamtype, "text", 4) )
1129                     {
1130                         /* We need to get rid of the header packet */
1131                         ogg_stream_packetout( &p_stream->os, &oggpacket );
1132
1133                         msg_Dbg( p_demux, "found text subtitles header" );
1134                         p_stream->fmt.i_cat = SPU_ES;
1135                         p_stream->fmt.i_codec = VLC_FOURCC('s','u','b','t');
1136                         p_stream->f_rate = 1000; /* granulepos is in milisec */
1137                     }
1138                     else
1139                     {
1140                         msg_Dbg( p_demux, "stream %d has a header marker "
1141                             "but is of an unknown type", p_ogg->i_streams-1 );
1142                         free( p_stream );
1143                         p_ogg->i_streams--;
1144                     }
1145                 }
1146                 else
1147                 {
1148                     msg_Dbg( p_demux, "stream %d is of unknown type",
1149                              p_ogg->i_streams-1 );
1150                     free( p_stream );
1151                     p_ogg->i_streams--;
1152                 }
1153
1154                 if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
1155                     return VLC_EGENERIC;
1156             }
1157
1158             /* This is the first data page, which means we are now finished
1159              * with the initial pages. We just need to store it in the relevant
1160              * bitstream. */
1161             for( i_stream = 0; i_stream < p_ogg->i_streams; i_stream++ )
1162             {
1163                 if( ogg_stream_pagein( &p_ogg->pp_stream[i_stream]->os,
1164                                        &oggpage ) == 0 )
1165                 {
1166                     break;
1167                 }
1168             }
1169
1170             return VLC_SUCCESS;
1171         }
1172     }
1173 #undef p_stream
1174
1175     return VLC_EGENERIC;
1176 }
1177
1178 /****************************************************************************
1179  * Ogg_BeginningOfStream: Look for Beginning of Stream ogg pages and add
1180  *                        Elementary streams.
1181  ****************************************************************************/
1182 static int Ogg_BeginningOfStream( demux_t *p_demux )
1183 {
1184     demux_sys_t *p_ogg = p_demux->p_sys  ;
1185     int i_stream;
1186
1187     /* Find the logical streams embedded in the physical stream and
1188      * initialize our p_ogg structure. */
1189     if( Ogg_FindLogicalStreams( p_demux ) != VLC_SUCCESS )
1190     {
1191         msg_Warn( p_demux, "couldn't find any ogg logical stream" );
1192         return VLC_EGENERIC;
1193     }
1194
1195     p_ogg->i_bitrate = 0;
1196
1197     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1198     {
1199 #define p_stream p_ogg->pp_stream[i_stream]
1200         if( p_stream->fmt.i_codec != VLC_FOURCC('f','l','a','c') )
1201             p_stream->p_es = es_out_Add( p_demux->out, &p_stream->fmt );
1202
1203         if( p_stream->fmt.i_codec == VLC_FOURCC('c','m','m','l') )
1204         {
1205             /* Set the CMML stream active */
1206             es_out_Control( p_demux->out, ES_OUT_SET_ES,
1207                             p_stream->p_es );
1208         }
1209
1210         p_ogg->i_bitrate += p_stream->fmt.i_bitrate;
1211
1212         p_stream->i_pcr = p_stream->i_previous_pcr =
1213             p_stream->i_interpolated_pcr = -1;
1214         p_stream->b_reinit = 0;
1215 #undef p_stream
1216     }
1217
1218     return VLC_SUCCESS;
1219 }
1220
1221 /****************************************************************************
1222  * Ogg_EndOfStream: clean up the ES when an End of Stream is detected.
1223  ****************************************************************************/
1224 static void Ogg_EndOfStream( demux_t *p_demux )
1225 {
1226     demux_sys_t *p_ogg = p_demux->p_sys  ;
1227     int i_stream, j;
1228
1229 #define p_stream p_ogg->pp_stream[i_stream]
1230     for( i_stream = 0 ; i_stream < p_ogg->i_streams; i_stream++ )
1231     {
1232         if( p_stream->p_es )
1233             es_out_Del( p_demux->out, p_stream->p_es );
1234
1235         p_ogg->i_bitrate -= p_stream->fmt.i_bitrate;
1236
1237         ogg_stream_clear( &p_ogg->pp_stream[i_stream]->os );
1238         for( j = 0; j < p_ogg->pp_stream[i_stream]->i_packets_backup; j++ )
1239         {
1240             free( p_ogg->pp_stream[i_stream]->p_packets_backup[j].packet );
1241         }
1242         if( p_ogg->pp_stream[i_stream]->p_packets_backup)
1243             free( p_ogg->pp_stream[i_stream]->p_packets_backup );
1244
1245         es_format_Clean( &p_stream->fmt );
1246
1247         free( p_ogg->pp_stream[i_stream] );
1248     }
1249 #undef p_stream
1250
1251     /* Reinit p_ogg */
1252     if( p_ogg->pp_stream ) free( p_ogg->pp_stream );
1253     p_ogg->pp_stream = NULL;
1254     p_ogg->i_streams = 0;
1255 }
1256
1257 static void Ogg_ReadTheoraHeader( logical_stream_t *p_stream,
1258                                   ogg_packet *p_oggpacket )
1259 {
1260     bs_t bitstream;
1261     int i_fps_numerator;
1262     int i_fps_denominator;
1263     int i_keyframe_frequency_force;
1264
1265     p_stream->fmt.i_cat = VIDEO_ES;
1266     p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1267
1268     /* Signal that we want to keep a backup of the vorbis
1269      * stream headers. They will be used when switching between
1270      * audio streams. */
1271     p_stream->b_force_backup = 1;
1272
1273     /* Cheat and get additionnal info ;) */
1274     bs_init( &bitstream, p_oggpacket->packet, p_oggpacket->bytes );
1275     bs_skip( &bitstream, 56 );
1276     bs_read( &bitstream, 8 ); /* major version num */
1277     bs_read( &bitstream, 8 ); /* minor version num */
1278     bs_read( &bitstream, 8 ); /* subminor version num */
1279     bs_read( &bitstream, 16 ) /*<< 4*/; /* width */
1280     bs_read( &bitstream, 16 ) /*<< 4*/; /* height */
1281     bs_read( &bitstream, 24 ); /* frame width */
1282     bs_read( &bitstream, 24 ); /* frame height */
1283     bs_read( &bitstream, 8 ); /* x offset */
1284     bs_read( &bitstream, 8 ); /* y offset */
1285
1286     i_fps_numerator = bs_read( &bitstream, 32 );
1287     i_fps_denominator = bs_read( &bitstream, 32 );
1288     bs_read( &bitstream, 24 ); /* aspect_numerator */
1289     bs_read( &bitstream, 24 ); /* aspect_denominator */
1290     i_keyframe_frequency_force = 1 << bs_read( &bitstream, 5 );
1291     bs_read( &bitstream, 8 ); /* colorspace */
1292     p_stream->fmt.i_bitrate = bs_read( &bitstream, 24 );
1293     bs_read( &bitstream, 6 ); /* quality */
1294
1295     /* granule_shift = i_log( frequency_force -1 ) */
1296     p_stream->i_theora_keyframe_granule_shift = 0;
1297     i_keyframe_frequency_force--;
1298     while( i_keyframe_frequency_force )
1299     {
1300         p_stream->i_theora_keyframe_granule_shift++;
1301         i_keyframe_frequency_force >>= 1;
1302     }
1303
1304     p_stream->f_rate = ((float)i_fps_numerator) / i_fps_denominator;
1305
1306     /* Save this data in p_extra for ffmpeg */
1307     p_stream->fmt.i_extra = p_oggpacket->bytes;
1308     p_stream->fmt.p_extra = malloc( p_oggpacket->bytes );
1309     memcpy( p_stream->fmt.p_extra, p_oggpacket->packet, p_oggpacket->bytes );
1310
1311 }
1312
1313 static void Ogg_ReadVorbisHeader( logical_stream_t *p_stream,
1314                                   ogg_packet *p_oggpacket )
1315 {
1316     oggpack_buffer opb;
1317
1318     p_stream->fmt.i_cat = AUDIO_ES;
1319     p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1320
1321     /* Signal that we want to keep a backup of the vorbis
1322      * stream headers. They will be used when switching between
1323      * audio streams. */
1324     p_stream->b_force_backup = 1;
1325
1326     /* Cheat and get additionnal info ;) */
1327     oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1328     oggpack_adv( &opb, 88 );
1329     p_stream->fmt.audio.i_channels = oggpack_read( &opb, 8 );
1330     p_stream->f_rate = p_stream->fmt.audio.i_rate =
1331         oggpack_read( &opb, 32 );
1332     oggpack_adv( &opb, 32 );
1333     p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
1334 }
1335
1336 static void Ogg_ReadAnnodexHeader( vlc_object_t *p_this,
1337                                    logical_stream_t *p_stream,
1338                                    ogg_packet *p_oggpacket )
1339 {
1340     if( ! strncmp( &p_oggpacket->packet[0], "Annodex", 7 ) )
1341     {
1342         oggpack_buffer opb;
1343
1344         uint16_t major_version;
1345         uint16_t minor_version;
1346         uint64_t timebase_numerator;
1347         uint64_t timebase_denominator;
1348
1349         Ogg_ReadTheoraHeader( p_stream, p_oggpacket );
1350
1351         oggpack_readinit( &opb, p_oggpacket->packet, p_oggpacket->bytes);
1352         oggpack_adv( &opb, 8*8 ); /* "Annodex\0" header */
1353         major_version = oggpack_read( &opb, 2*8 ); /* major version */
1354         minor_version = oggpack_read( &opb, 2*8 ); /* minor version */
1355         timebase_numerator = GetQWLE( &p_oggpacket->packet[16] );
1356         timebase_denominator = GetQWLE( &p_oggpacket->packet[24] );
1357     }
1358     else if( ! strncmp( &p_oggpacket->packet[0], "AnxData", 7 ) )
1359     {
1360         uint64_t granule_rate_numerator;
1361         uint64_t granule_rate_denominator;
1362         char content_type_string[1024];
1363
1364         /* Read in Annodex header fields */
1365
1366         granule_rate_numerator = GetQWLE( &p_oggpacket->packet[8] );
1367         granule_rate_denominator = GetQWLE( &p_oggpacket->packet[16] );
1368         p_stream->secondary_header_packets =
1369             GetDWLE( &p_oggpacket->packet[24] );
1370
1371         msg_Dbg( p_this, "anxdata packet info: %qd/%qd, %d",
1372                  granule_rate_numerator, granule_rate_denominator,
1373                  p_stream->secondary_header_packets);
1374
1375         /* we are guaranteed that the first header field will be
1376          * the content-type (by the Annodex standard) */
1377         sscanf( &p_oggpacket->packet[28], "Content-Type: %1024s\r\n",
1378                 content_type_string );
1379
1380         p_stream->f_rate = (float) granule_rate_numerator /
1381             (float) granule_rate_denominator;
1382
1383         /* What type of file do we have?
1384          * strcmp is safe to use here because we've extracted
1385          * content_type_string from the stream manually */
1386         if( !strncmp(content_type_string, "audio/x-wav", 11) )
1387         {
1388             /* n.b. WAVs are unsupported right now */
1389             p_stream->fmt.i_cat = UNKNOWN_ES;
1390         }
1391         else if( !strncmp(content_type_string, "audio/x-vorbis", 14) )
1392         {
1393             p_stream->fmt.i_cat = AUDIO_ES;
1394             p_stream->fmt.i_codec = VLC_FOURCC( 'v','o','r','b' );
1395
1396             p_stream->b_force_backup = 1;
1397         }
1398         else if( !strncmp(content_type_string, "video/x-theora", 14) )
1399         {
1400             p_stream->fmt.i_cat = VIDEO_ES;
1401             p_stream->fmt.i_codec = VLC_FOURCC( 't','h','e','o' );
1402
1403             p_stream->b_force_backup = 1;
1404         }
1405         else if( !strncmp(content_type_string, "video/x-xvid", 14) )
1406         {
1407             p_stream->fmt.i_cat = VIDEO_ES;
1408             p_stream->fmt.i_codec = VLC_FOURCC( 'x','v','i','d' );
1409
1410             p_stream->b_force_backup = 1;
1411         }
1412         else if( !strncmp(content_type_string, "video/mpeg", 14) )
1413         {
1414             /* n.b. MPEG streams are unsupported right now */
1415             p_stream->fmt.i_cat = VIDEO_ES;
1416             p_stream->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1417         }
1418         else if( !strncmp(content_type_string, "text/x-cmml", 11) )
1419         {
1420             ogg_stream_packetout( &p_stream->os, p_oggpacket );
1421             p_stream->fmt.i_cat = SPU_ES;
1422             p_stream->fmt.i_codec = VLC_FOURCC( 'c','m','m','l' );
1423         }
1424     }
1425 }