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