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