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