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