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