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