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