ogg.c 53.8 KB
Newer Older
1
/*****************************************************************************
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
2
 * ogg.c : ogg stream demux module for vlc
3
 *****************************************************************************
4
 * Copyright (C) 2001-2007 the VideoLAN team
5
 * $Id$
6
 *
7 8
 * Authors: Gildas Bazin <gbazin@netcourrier.com>
 *          Andre Pang <Andre.Pang@csiro.au> (Annodex support)
Sam Hocevar's avatar
Sam Hocevar committed
9
 *
10 11 12 13
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
Sam Hocevar's avatar
Sam Hocevar committed
14
 *
15 16 17 18 19 20 21
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
Antoine Cellerier's avatar
Antoine Cellerier committed
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 24 25 26 27 28
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include <vlc/vlc.h>
Clément Stenac's avatar
Clément Stenac committed
29 30
#include <vlc_input.h>
#include <vlc_demux.h>
31 32 33

#include <ogg/ogg.h>

Clément Stenac's avatar
Clément Stenac committed
34 35
#include <vlc_codecs.h>
#include <vlc_bits.h>
36

37 38 39 40 41 42 43
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
static int  Open ( vlc_object_t * );
static void Close( vlc_object_t * );

vlc_module_begin();
Clément Stenac's avatar
Clément Stenac committed
44 45
    set_shortname ( "OGG" );
    set_description( _("OGG demuxer" ) );
46 47
    set_category( CAT_INPUT );
    set_subcategory( SUBCAT_INPUT_DEMUX );
48
    set_capability( "demux2", 50 );
49 50 51 52
    set_callbacks( Open, Close );
    add_shortcut( "ogg" );
vlc_module_end();

53 54

/*****************************************************************************
Sam Hocevar's avatar
Sam Hocevar committed
55
 * Definitions of structures and functions used by this plugins
56 57 58 59 60
 *****************************************************************************/
typedef struct logical_stream_s
{
    ogg_stream_state os;                        /* logical stream of packets */

61 62 63
    es_format_t      fmt;
    es_out_id_t      *p_es;
    double           f_rate;
64

65
    int              i_serial_no;
66

67 68 69 70 71
    /* the header of some logical streams (eg vorbis) contain essential
     * data for the decoder. We back them up here in case we need to re-feed
     * them to the decoder. */
    int              b_force_backup;
    int              i_packets_backup;
72 73
    uint8_t          *p_headers;
    int              i_headers;
74

75 76
    /* program clock reference (in units of 90kHz) derived from the previous
     * granulepos */
77
    mtime_t          i_pcr;
78
    mtime_t          i_interpolated_pcr;
79
    mtime_t          i_previous_pcr;
80

81
    /* Misc */
82
    int b_reinit;
83
    int i_theora_keyframe_granule_shift;
84

85 86 87
    /* for Annodex logical bitstreams */
    int secondary_header_packets;

88 89 90 91 92 93 94 95 96
} logical_stream_t;

struct demux_sys_t
{
    ogg_sync_state oy;        /* sync and verify incoming physical bitstream */

    int i_streams;                           /* number of logical bitstreams */
    logical_stream_t **pp_stream;  /* pointer to an array of logical streams */

97
    /* program clock reference (in units of 90kHz) derived from the pcr of
98
     * the sub-streams */
99
    mtime_t i_pcr;
100 101

    /* stream state */
102
    int     i_eos;
103 104 105

    /* bitrate */
    int     i_bitrate;
106 107
};

108 109 110 111 112 113
/* OggDS headers for the new header format (used in ogm files) */
typedef struct stream_header_video
{
    ogg_int32_t width;
    ogg_int32_t height;
} stream_header_video;
Sam Hocevar's avatar
Sam Hocevar committed
114

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
typedef struct stream_header_audio
{
    ogg_int16_t channels;
    ogg_int16_t blockalign;
    ogg_int32_t avgbytespersec;
} stream_header_audio;

typedef struct stream_header
{
    char        streamtype[8];
    char        subtype[4];

    ogg_int32_t size;                               /* size of the structure */

    ogg_int64_t time_unit;                              /* in reference time */
    ogg_int64_t samples_per_unit;
    ogg_int32_t default_len;                                /* in media time */

    ogg_int32_t buffersize;
    ogg_int16_t bits_per_sample;

    union
    {
        /* Video specific */
        stream_header_video video;
        /* Audio specific */
        stream_header_audio audio;
    } sh;
} stream_header;

145 146
#define OGG_BLOCK_SIZE 4096

147 148 149 150 151 152 153
/* Some defines from OggDS */
#define PACKET_TYPE_HEADER   0x01
#define PACKET_TYPE_BITS     0x07
#define PACKET_LEN_BITS01    0xc0
#define PACKET_LEN_BITS2     0x02
#define PACKET_IS_SYNCPOINT  0x08

154 155 156
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
157 158
static int  Demux  ( demux_t * );
static int  Control( demux_t *, int, va_list );
159 160

/* Bitstream manipulation */
161
static int  Ogg_ReadPage     ( demux_t *, ogg_page * );
162
static void Ogg_UpdatePCR    ( logical_stream_t *, ogg_packet * );
163
static void Ogg_DecodePacket ( demux_t *, logical_stream_t *, ogg_packet * );
164

165 166 167
static int Ogg_BeginningOfStream( demux_t *p_demux );
static int Ogg_FindLogicalStreams( demux_t *p_demux );
static void Ogg_EndOfStream( demux_t *p_demux );
168

169
/* Logical bitstream headers */
170 171 172 173 174
static void Ogg_ReadTheoraHeader( logical_stream_t *, ogg_packet * );
static void Ogg_ReadVorbisHeader( logical_stream_t *, ogg_packet * );
static void Ogg_ReadSpeexHeader( logical_stream_t *, ogg_packet * );
static void Ogg_ReadFlacHeader( demux_t *, logical_stream_t *, ogg_packet * );
static void Ogg_ReadAnnodexHeader( vlc_object_t *, logical_stream_t *, ogg_packet * );
175

176
/*****************************************************************************
177
 * Open: initializes ogg demux structures
178
 *****************************************************************************/
179
static int Open( vlc_object_t * p_this )
180
{
181
    demux_t *p_demux = (demux_t *)p_this;
182
    input_thread_t *p_input;
183
    demux_sys_t    *p_sys;
184
    const uint8_t  *p_peek;
185

186 187

    /* Check if we are dealing with an ogg stream */
188
    if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
189
    if( !p_demux->b_force && memcmp( p_peek, "OggS", 4 ) )
190 191 192
    {
        return VLC_EGENERIC;
    }
193

194
    /* Set exported functions */
195 196 197
    p_demux->pf_demux = Demux;
    p_demux->pf_control = Control;
    p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
198 199

    memset( p_sys, 0, sizeof( demux_sys_t ) );
200
    p_sys->i_bitrate = 0;
201 202 203 204 205
    p_sys->pp_stream = NULL;

    /* Begnning of stream, tell the demux to look for elementary streams. */
    p_sys->i_eos = 0;

206

207
    p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT );
208
    if( p_input )
209 210 211 212
    {
        module_t *p_meta = module_Need( p_demux, "meta reader", NULL, 0 );
        if( p_meta )
        {
213
            vlc_meta_Merge( input_GetItem(p_input)->p_meta, (vlc_meta_t*)(p_demux->p_private ) );
214 215
            module_Unneed( p_demux, p_meta );
        }
216
        vlc_object_release( p_input );
217 218
        return VLC_SUCCESS;
    }
219 220
    if( p_input )
        vlc_object_release( p_input );
221

222 223
    /* Initialize the Ogg physical bitstream parser */
    ogg_sync_init( &p_sys->oy );
224 225 226 227

    return VLC_SUCCESS;
}

228 229 230 231 232
/*****************************************************************************
 * Close: frees unused data
 *****************************************************************************/
static void Close( vlc_object_t *p_this )
{
233 234
    demux_t *p_demux = (demux_t *)p_this;
    demux_sys_t *p_sys = p_demux->p_sys  ;
235 236 237 238

    /* Cleanup the bitstream parser */
    ogg_sync_clear( &p_sys->oy );

239
    Ogg_EndOfStream( p_demux );
240 241 242 243 244 245 246 247 248

    free( p_sys );
}

/*****************************************************************************
 * Demux: reads and demuxes data packets
 *****************************************************************************
 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
 *****************************************************************************/
249
static int Demux( demux_t * p_demux )
250
{
251
    demux_sys_t *p_sys = p_demux->p_sys;
252 253 254 255 256 257 258 259 260
    ogg_page    oggpage;
    ogg_packet  oggpacket;
    int         i_stream;


    if( p_sys->i_eos == p_sys->i_streams )
    {
        if( p_sys->i_eos )
        {
261 262
            msg_Dbg( p_demux, "end of a group of logical streams" );
            Ogg_EndOfStream( p_demux );
263 264 265
        }

        p_sys->i_eos = 0;
266
        if( Ogg_BeginningOfStream( p_demux ) != VLC_SUCCESS ) return 0;
267

268 269
        msg_Dbg( p_demux, "beginning of a group of logical streams" );
        es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
270 271 272 273 274
    }

    /*
     * Demux an ogg page from the stream
     */
275
    if( Ogg_ReadPage( p_demux, &oggpage ) != VLC_SUCCESS )
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    {
        return 0; /* EOF */
    }

    /* Test for End of Stream */
    if( ogg_page_eos( &oggpage ) ) p_sys->i_eos++;


    for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
    {
        logical_stream_t *p_stream = p_sys->pp_stream[i_stream];

        if( ogg_stream_pagein( &p_stream->os, &oggpage ) != 0 )
            continue;

        while( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
        {
            /* Read info from any secondary header packets, if there are any */
            if( p_stream->secondary_header_packets > 0 )
            {
296
                if( p_stream->fmt.i_codec == VLC_FOURCC('t','h','e','o') &&
297
                        oggpacket.bytes >= 7 &&
298
                        ! memcmp( &oggpacket.packet[1], "theora", 6 ) )
299 300 301 302
                {
                    Ogg_ReadTheoraHeader( p_stream, &oggpacket );
                    p_stream->secondary_header_packets = 0;
                }
303
                else if( p_stream->fmt.i_codec == VLC_FOURCC('v','o','r','b') &&
304
                        oggpacket.bytes >= 7 &&
305
                        ! memcmp( &oggpacket.packet[1], "vorbis", 6 ) )
306 307 308 309
                {
                    Ogg_ReadVorbisHeader( p_stream, &oggpacket );
                    p_stream->secondary_header_packets = 0;
                }
310
                else if ( p_stream->fmt.i_codec == VLC_FOURCC('c','m','m','l') )
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
                {
                    p_stream->secondary_header_packets = 0;
                }
            }

            if( p_stream->b_reinit )
            {
                /* If synchro is re-initialized we need to drop all the packets
                 * until we find a new dated one. */
                Ogg_UpdatePCR( p_stream, &oggpacket );

                if( p_stream->i_pcr >= 0 )
                {
                    p_stream->b_reinit = 0;
                }
                else
                {
                    p_stream->i_interpolated_pcr = -1;
                    continue;
                }

                /* An Ogg/vorbis packet contains an end date granulepos */
                if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
                    p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
                    p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
                {
                    if( ogg_stream_packetout( &p_stream->os, &oggpacket ) > 0 )
                    {
339
                        Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
340 341 342
                    }
                    else
                    {
343 344
                        es_out_Control( p_demux->out, ES_OUT_SET_PCR,
                                        p_stream->i_pcr );
345 346 347 348 349
                    }
                    continue;
                }
            }

350
            Ogg_DecodePacket( p_demux, p_stream, &oggpacket );
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
        }
        break;
    }

    i_stream = 0; p_sys->i_pcr = -1;
    for( ; i_stream < p_sys->i_streams; i_stream++ )
    {
        logical_stream_t *p_stream = p_sys->pp_stream[i_stream];

        if( p_stream->fmt.i_cat == SPU_ES )
            continue;
        if( p_stream->i_interpolated_pcr < 0 )
            continue;

        if( p_sys->i_pcr < 0 || p_stream->i_interpolated_pcr < p_sys->i_pcr )
            p_sys->i_pcr = p_stream->i_interpolated_pcr;
    }

    if( p_sys->i_pcr >= 0 )
    {
371
        es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
372 373 374 375 376 377 378 379 380
    }


    return 1;
}

/*****************************************************************************
 * Control:
 *****************************************************************************/
381
static int Control( demux_t *p_demux, int i_query, va_list args )
382
{
383
    demux_sys_t *p_sys  = p_demux->p_sys;
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    int64_t *pi64;
    int i;

    switch( i_query )
    {
        case DEMUX_GET_TIME:
            pi64 = (int64_t*)va_arg( args, int64_t * );
            *pi64 = p_sys->i_pcr;
            return VLC_SUCCESS;

        case DEMUX_SET_TIME:
            return VLC_EGENERIC;

        case DEMUX_SET_POSITION:
            for( i = 0; i < p_sys->i_streams; i++ )
            {
                logical_stream_t *p_stream = p_sys->pp_stream[i];

                /* we'll trash all the data until we find the next pcr */
                p_stream->b_reinit = 1;
                p_stream->i_pcr = -1;
                p_stream->i_interpolated_pcr = -1;
                ogg_stream_reset( &p_stream->os );
            }
            ogg_sync_reset( &p_sys->oy );

        default:
411 412
            return demux2_vaControlHelper( p_demux->s, 0, -1, p_sys->i_bitrate,
                                           1, i_query, args );
413 414 415
    }
}

416 417 418 419 420 421
/****************************************************************************
 * Ogg_ReadPage: Read a full Ogg page from the physical bitstream.
 ****************************************************************************
 * Returns VLC_SUCCESS if a page has been read. An error might happen if we
 * are at the end of stream.
 ****************************************************************************/
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 429

    while( ogg_sync_pageout( &p_ogg->oy, p_oggpage ) != 1 )
    {
430 431 432
        p_buffer = ogg_sync_buffer( &p_ogg->oy, OGG_BLOCK_SIZE );

        i_read = stream_Read( p_demux->s, p_buffer, OGG_BLOCK_SIZE );
433 434 435 436 437 438 439 440 441
        if( i_read <= 0 )
            return VLC_EGENERIC;

        ogg_sync_wrote( &p_ogg->oy, i_read );
    }

    return VLC_SUCCESS;
}

442 443 444 445 446 447 448
/****************************************************************************
 * Ogg_UpdatePCR: update the PCR (90kHz program clock reference) for the
 *                current stream.
 ****************************************************************************/
static void Ogg_UpdatePCR( logical_stream_t *p_stream,
                           ogg_packet *p_oggpacket )
{
449
    /* Convert the granulepos into a pcr */
450 451
    if( p_oggpacket->granulepos >= 0 )
    {
452
        if( p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) )
453
        {
454
            p_stream->i_pcr = p_oggpacket->granulepos * I64C(1000000)
455 456 457 458 459 460 461 462 463
                              / p_stream->f_rate;
        }
        else
        {
            ogg_int64_t iframe = p_oggpacket->granulepos >>
              p_stream->i_theora_keyframe_granule_shift;
            ogg_int64_t pframe = p_oggpacket->granulepos -
              ( iframe << p_stream->i_theora_keyframe_granule_shift );

464
            p_stream->i_pcr = ( iframe + pframe ) * I64C(1000000)
465 466 467 468 469 470 471
                              / p_stream->f_rate;
        }

        p_stream->i_interpolated_pcr = p_stream->i_pcr;
    }
    else
    {
472
        p_stream->i_pcr = -1;
473

474 475
        /* no granulepos available, try to interpolate the pcr.
         * If we can't then don't touch the old value. */
476
        if( p_stream->fmt.i_cat == VIDEO_ES )
477
            /* 1 frame per packet */
478
            p_stream->i_interpolated_pcr += (I64C(1000000) / p_stream->f_rate);
479
        else if( p_stream->fmt.i_bitrate )
480 481 482
            p_stream->i_interpolated_pcr +=
                ( p_oggpacket->bytes * I64C(1000000) /
                  p_stream->fmt.i_bitrate / 8 );
483 484 485
    }
}

486 487 488
/****************************************************************************
 * Ogg_DecodePacket: Decode an Ogg packet.
 ****************************************************************************/
489
static void Ogg_DecodePacket( demux_t *p_demux,
490 491 492
                              logical_stream_t *p_stream,
                              ogg_packet *p_oggpacket )
{
493 494
    block_t *p_block;
    vlc_bool_t b_selected;
495
    int i_header_len = 0;
496
    mtime_t i_pts = -1, i_interpolated_pts;
497

498 499 500
    /* Sanity check */
    if( !p_oggpacket->bytes )
    {
501
        msg_Dbg( p_demux, "discarding 0 sized packet" );
502 503 504
        return;
    }

505
    if( p_oggpacket->bytes >= 7 &&
506
        ! memcmp ( &p_oggpacket->packet[0], "Annodex", 7 ) )
507 508
    {
        /* it's an Annodex packet -- skip it (do nothing) */
509
        return;
510 511
    }
    else if( p_oggpacket->bytes >= 7 &&
512
        ! memcmp ( &p_oggpacket->packet[0], "AnxData", 7 ) )
513 514
    {
        /* it's an AnxData packet -- skip it (do nothing) */
515
        return;
516 517
    }

518 519 520
    if( p_stream->fmt.i_codec == VLC_FOURCC( 's','u','b','t' ) &&
        p_oggpacket->packet[0] & PACKET_TYPE_BITS ) return;

521 522 523 524
    /* Check the ES is selected */
    es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
                    p_stream->p_es, &b_selected );

525 526
    if( p_stream->b_force_backup )
    {
527
        uint8_t *p_extra;
528
        vlc_bool_t b_store_size = VLC_TRUE;
529

530
        p_stream->i_packets_backup++;
531
        switch( p_stream->fmt.i_codec )
532 533
        {
        case VLC_FOURCC( 'v','o','r','b' ):
534
        case VLC_FOURCC( 's','p','x',' ' ):
535
        case VLC_FOURCC( 't','h','e','o' ):
536 537
            if( p_stream->i_packets_backup == 3 ) p_stream->b_force_backup = 0;
            break;
538

539
        case VLC_FOURCC( 'f','l','a','c' ):
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
            if( !p_stream->fmt.audio.i_rate && p_stream->i_packets_backup == 2 )
            {
                Ogg_ReadFlacHeader( p_demux, p_stream, p_oggpacket );
                p_stream->b_force_backup = 0;
            }
            else if( p_stream->fmt.audio.i_rate )
            {
                p_stream->b_force_backup = 0;
                if( p_oggpacket->bytes >= 9 )
                {
                    p_oggpacket->packet += 9;
                    p_oggpacket->bytes -= 9;
                }
            }
            b_store_size = VLC_FALSE;
            break;
556

557
        default:
558 559
            p_stream->b_force_backup = 0;
            break;
560 561 562
        }

        /* Backup the ogg packet (likely an header packet) */
563 564 565 566 567
        p_stream->p_headers =
            realloc( p_stream->p_headers, p_stream->i_headers +
                     p_oggpacket->bytes + (b_store_size ? 2 : 0) );
        p_extra = p_stream->p_headers + p_stream->i_headers;
        if( b_store_size )
568
        {
569 570
            *(p_extra++) = p_oggpacket->bytes >> 8;
            *(p_extra++) = p_oggpacket->bytes & 0xFF;
571
        }
572 573
        memcpy( p_extra, p_oggpacket->packet, p_oggpacket->bytes );
        p_stream->i_headers += p_oggpacket->bytes + (b_store_size ? 2 : 0);
574

575 576
        if( !p_stream->b_force_backup )
        {
577 578 579 580
            /* Last header received, commit changes */
            p_stream->fmt.i_extra = p_stream->i_headers;
            p_stream->fmt.p_extra =
                realloc( p_stream->fmt.p_extra, p_stream->i_headers );
581 582
            memcpy( p_stream->fmt.p_extra, p_stream->p_headers,
                    p_stream->i_headers );
583 584
            es_out_Control( p_demux->out, ES_OUT_SET_FMT,
                            p_stream->p_es, &p_stream->fmt );
585
        }
586 587

        b_selected = VLC_FALSE; /* Discard the header packet */
588 589
    }

590
    /* Convert the pcr into a pts */
591 592 593
    if( p_stream->fmt.i_codec == VLC_FOURCC( 'v','o','r','b' ) ||
        p_stream->fmt.i_codec == VLC_FOURCC( 's','p','x',' ' ) ||
        p_stream->fmt.i_codec == VLC_FOURCC( 'f','l','a','c' ) )
594
    {
595 596 597 598 599
        if( p_stream->i_pcr >= 0 )
        {
            /* This is for streams where the granulepos of the header packets
             * doesn't match these of the data packets (eg. ogg web radios). */
            if( p_stream->i_previous_pcr == 0 &&
600 601
                p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
            {
602
                es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
603

604
                /* Call the pace control */
605 606
                es_out_Control( p_demux->out, ES_OUT_SET_PCR,
                                p_stream->i_pcr );
607
            }
608

609
            p_stream->i_previous_pcr = p_stream->i_pcr;
610

611
            /* The granulepos is the end date of the sample */
612
            i_pts =  p_stream->i_pcr;
613
        }
614
    }
615

616
    /* Convert the granulepos into the next pcr */
617
    i_interpolated_pts = p_stream->i_interpolated_pcr;
618
    Ogg_UpdatePCR( p_stream, p_oggpacket );
619

620 621 622 623 624
    if( p_stream->i_pcr >= 0 )
    {
        /* This is for streams where the granulepos of the header packets
         * doesn't match these of the data packets (eg. ogg web radios). */
        if( p_stream->i_previous_pcr == 0 &&
625 626
            p_stream->i_pcr  > 3 * DEFAULT_PTS_DELAY )
        {
627
            es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
628 629

            /* Call the pace control */
630
            es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_stream->i_pcr );
631
        }
632
    }
633

634 635 636
    if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
        p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
        p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
637 638 639
        p_stream->i_pcr >= 0 )
    {
        p_stream->i_previous_pcr = p_stream->i_pcr;
640 641

        /* The granulepos is the start date of the sample */
642
        i_pts = p_stream->i_pcr;
643
    }
644

645
    if( !b_selected )
646 647 648 649 650 651
    {
        /* This stream isn't currently selected so we don't need to decode it,
         * but we did need to store its pcr as it might be selected later on */
        return;
    }

652 653 654
    if( p_oggpacket->bytes <= 0 )
        return;

655
    if( !( p_block = block_New( p_demux, p_oggpacket->bytes ) ) ) return;
656

657 658 659 660 661
    /* Normalize PTS */
    if( i_pts == 0 ) i_pts = 1;
    else if( i_pts == -1 && i_interpolated_pts == 0 ) i_pts = 1;
    else if( i_pts == -1 ) i_pts = 0;

662 663 664 665
    if( p_stream->fmt.i_cat == AUDIO_ES )
        p_block->i_dts = p_block->i_pts = i_pts;
    else if( p_stream->fmt.i_cat == SPU_ES )
    {
666 667
        p_block->i_dts = p_block->i_pts = i_pts;
        p_block->i_length = 0;
668 669 670 671 672 673 674 675
    }
    else if( p_stream->fmt.i_codec == VLC_FOURCC( 't','h','e','o' ) )
        p_block->i_dts = p_block->i_pts = i_pts;
    else
    {
        p_block->i_dts = i_pts;
        p_block->i_pts = 0;
    }
676

677 678 679 680
    if( p_stream->fmt.i_codec != VLC_FOURCC( 'v','o','r','b' ) &&
        p_stream->fmt.i_codec != VLC_FOURCC( 's','p','x',' ' ) &&
        p_stream->fmt.i_codec != VLC_FOURCC( 'f','l','a','c' ) &&
        p_stream->fmt.i_codec != VLC_FOURCC( 't','a','r','k' ) &&
681 682
        p_stream->fmt.i_codec != VLC_FOURCC( 't','h','e','o' ) &&
        p_stream->fmt.i_codec != VLC_FOURCC( 'c','m','m','l' ) )
683
    {
684
        /* We remove the header from the packet */
685 686
        i_header_len = (*p_oggpacket->packet & PACKET_LEN_BITS01) >> 6;
        i_header_len |= (*p_oggpacket->packet & PACKET_LEN_BITS2) << 1;
687

688 689 690
        if( p_stream->fmt.i_codec == VLC_FOURCC( 's','u','b','t' ))
        {
            /* But with subtitles we need to retrieve the duration first */
691
            int i, lenbytes = 0;
692

693
            if( i_header_len > 0 && p_oggpacket->bytes >= i_header_len + 1 )
694 695 696 697
            {
                for( i = 0, lenbytes = 0; i < i_header_len; i++ )
                {
                    lenbytes = lenbytes << 8;
698
                    lenbytes += *(p_oggpacket->packet + i_header_len - i);
699 700
                }
            }
701 702
            if( p_oggpacket->bytes - 1 - i_header_len > 2 ||
                ( p_oggpacket->packet[i_header_len + 1] != ' ' &&
703
                  p_oggpacket->packet[i_header_len + 1] != 0 &&
704 705
                  p_oggpacket->packet[i_header_len + 1] != '\n' &&
                  p_oggpacket->packet[i_header_len + 1] != '\r' ) )
706
            {
707
                p_block->i_length = (mtime_t)lenbytes * 1000;
708 709
            }
        }
710

711
        i_header_len++;
712 713 714 715
        if( p_block->i_buffer >= i_header_len )
            p_block->i_buffer -= i_header_len;
        else
            p_block->i_buffer = 0;
716 717
    }

718
    if( p_stream->fmt.i_codec == VLC_FOURCC( 't','a','r','k' ) )
719 720
    {
        /* FIXME: the biggest hack I've ever done */
721
        msg_Warn( p_demux, "tarkin pts: "I64Fd", granule: "I64Fd,
722
                  p_block->i_pts, p_block->i_dts );
723
        msleep(10000);
724 725
    }

726
    memcpy( p_block->p_buffer, p_oggpacket->packet + i_header_len,
727 728
            p_oggpacket->bytes - i_header_len );

729
    es_out_Send( p_demux->out, p_stream->p_es, p_block );
730 731 732 733 734 735 736 737 738 739 740 741
}

/****************************************************************************
 * Ogg_FindLogicalStreams: Find the logical streams embedded in the physical
 *                         stream and fill p_ogg.
 *****************************************************************************
 * The initial page of a logical stream is marked as a 'bos' page.
 * Furthermore, the Ogg specification mandates that grouped bitstreams begin
 * together and all of the initial pages must appear before any data pages.
 *
 * On success this function returns VLC_SUCCESS.
 ****************************************************************************/
742
static int Ogg_FindLogicalStreams( demux_t *p_demux )
743
{
744
    demux_sys_t *p_ogg = p_demux->p_sys  ;
745 746 747 748
    ogg_packet oggpacket;
    ogg_page oggpage;
    int i_stream;

749 750
#define p_stream p_ogg->pp_stream[p_ogg->i_streams - 1]

751
    while( Ogg_ReadPage( p_demux, &oggpage ) == VLC_SUCCESS )
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
    {
        if( ogg_page_bos( &oggpage ) )
        {

            /* All is wonderful in our fine fine little world.
             * We found the beginning of our first logical stream. */
            while( ogg_page_bos( &oggpage ) )
            {
                p_ogg->i_streams++;
                p_ogg->pp_stream =
                    realloc( p_ogg->pp_stream, p_ogg->i_streams *
                             sizeof(logical_stream_t *) );

                p_stream = malloc( sizeof(logical_stream_t) );
                memset( p_stream, 0, sizeof(logical_stream_t) );
767
                p_stream->p_headers = 0;
768
                p_stream->secondary_header_packets = 0;
769

770 771
                es_format_Init( &p_stream->fmt, 0, 0 );

772 773 774 775 776 777 778 779 780
                /* Setup the logical stream */
                p_stream->i_serial_no = ogg_page_serialno( &oggpage );
                ogg_stream_init( &p_stream->os, p_stream->i_serial_no );

                /* Extract the initial header from the first page and verify
                 * the codec type of tis Ogg bitstream */
                if( ogg_stream_pagein( &p_stream->os, &oggpage ) < 0 )
                {
                    /* error. stream version mismatch perhaps */
781
                    msg_Err( p_demux, "error reading first page of "
782 783 784 785 786 787 788 789
                             "Ogg bitstream data" );
                    return VLC_EGENERIC;
                }

                /* FIXME: check return value */
                ogg_stream_packetpeek( &p_stream->os, &oggpacket );

                /* Check for Vorbis header */
790
                if( oggpacket.bytes >= 7 &&
791
                    ! memcmp( &oggpacket.packet[1], "vorbis", 6 ) )
792
                {
793
                    Ogg_ReadVorbisHeader( p_stream, &oggpacket );
794
                    msg_Dbg( p_demux, "found vorbis header" );
795
                }
796
                /* Check for Speex header */
797
                else if( oggpacket.bytes >= 7 &&
798
                    ! memcmp( &oggpacket.packet[0], "Speex", 5 ) )
799
                {
800
                    Ogg_ReadSpeexHeader( p_stream, &oggpacket );
801
                    msg_Dbg( p_demux, "found speex header, channels: %i, "
802 803 804
                             "rate: %i,  bitrate: %i",
                             p_stream->fmt.audio.i_channels,
                             (int)p_stream->f_rate, p_stream->fmt.i_bitrate );
805
                }
806
                /* Check for Flac header (< version 1.1.1) */
807
                else if( oggpacket.bytes >= 4 &&
808
                    ! memcmp( &oggpacket.packet[0], "fLaC", 4 ) )
809
                {
810
                    msg_Dbg( p_demux, "found FLAC header" );
811 812 813 814 815 816

                    /* Grrrr!!!! Did they really have to put all the
                     * important info in the second header packet!!!
                     * (STREAMINFO metadata is in the following packet) */
                    p_stream->b_force_backup = 1;

817 818
                    p_stream->fmt.i_cat = AUDIO_ES;
                    p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
819
                }
820 821
                /* Check for Flac header (>= version 1.1.1) */
                else if( oggpacket.bytes >= 13 && oggpacket.packet[0] ==0x7F &&
822 823
                    ! memcmp( &oggpacket.packet[1], "FLAC", 4 ) &&
                    ! memcmp( &oggpacket.packet[9], "fLaC", 4 ) )
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
                {
                    int i_packets = ((int)oggpacket.packet[7]) << 8 |
                        oggpacket.packet[8];
                    msg_Dbg( p_demux, "found FLAC header version %i.%i "
                             "(%i header packets)",
                             oggpacket.packet[5], oggpacket.packet[6],
                             i_packets );

                    p_stream->b_force_backup = 1;

                    p_stream->fmt.i_cat = AUDIO_ES;
                    p_stream->fmt.i_codec = VLC_FOURCC( 'f','l','a','c' );
                    oggpacket.packet += 13; oggpacket.bytes -= 13;
                    Ogg_ReadFlacHeader( p_demux, p_stream, &oggpacket );
                }
839 840
                /* Check for Theora header */
                else if( oggpacket.bytes >= 7 &&
841
                         ! memcmp( &oggpacket.packet[1], "theora", 6 ) )
842
                {
843
                    Ogg_ReadTheoraHeader( p_stream, &oggpacket );
844

845
                    msg_Dbg( p_demux,
846
                             "found theora header, bitrate: %i, rate: %f",
847
                             p_stream->fmt.i_bitrate, p_stream->f_rate );
848 849 850
                }
                /* Check for Tarkin header */
                else if( oggpacket.bytes >= 7 &&
851
                         ! memcmp( &oggpacket.packet[1], "tarkin", 6 ) )
852 853 854
                {
                    oggpack_buffer opb;

855
                    msg_Dbg( p_demux, "found tarkin header" );
856 857
                    p_stream->fmt.i_cat = VIDEO_ES;
                    p_stream->fmt.i_codec = VLC_FOURCC( 't','a','r','k' );
858 859 860 861 862

                    /* Cheat and get additionnal info ;) */
                    oggpack_readinit( &opb, oggpacket.packet, oggpacket.bytes);
                    oggpack_adv( &opb, 88 );
                    oggpack_adv( &opb, 104 );
863
                    p_stream->fmt.i_bitrate = oggpack_read( &opb, 32 );
864
                    p_stream->f_rate = 2; /* FIXME */
865
                    msg_Dbg( p_demux,
866
                             "found tarkin header, bitrate: %i, rate: %f",
867
                             p_stream->fmt.i_bitrate, p_stream->f_rate );
868
                }
869 870
                /* Check for Annodex header */
                else if( oggpacket.bytes >= 7 &&
871
                         ! memcmp( &oggpacket.packet[0], "Annodex", 7 ) )
872
                {
873
                    Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
874 875 876 877 878 879 880
                                           &oggpacket );
                    /* kill annodex track */
                    free( p_stream );
                    p_ogg->i_streams--;
                }
                /* Check for Annodex header */
                else if( oggpacket.bytes >= 7 &&
881
                         ! memcmp( &oggpacket.packet[0], "AnxData", 7 ) )
882
                {
883
                    Ogg_ReadAnnodexHeader( VLC_OBJECT(p_demux), p_stream,
884 885
                                           &oggpacket );
                }
886
                else if( oggpacket.bytes >= 142 &&
887
                         !memcmp( &oggpacket.packet[1],
888 889 890 891 892 893 894 895
                                   "Direct Show Samples embedded in Ogg", 35 ))
                {
                    /* Old header type */

                    /* Check for video header (old format) */
                    if( GetDWLE((oggpacket.packet+96)) == 0x05589f80 &&
                        oggpacket.bytes >= 184 )
                    {
896 897
                        p_stream->fmt.i_cat = VIDEO_ES;
                        p_stream->fmt.i_codec =
898 899 900 901
                            VLC_FOURCC( oggpacket.packet[68],
                                        oggpacket.packet[69],
                                        oggpacket.packet[70],
                                        oggpacket.packet[71] );
902
                        msg_Dbg( p_demux, "found video header of type: %.4s",
903
                                 (char *)&p_stream->fmt.i_codec );
904

905 906 907
                        p_stream->fmt.video.i_frame_rate = 10000000;
                        p_stream->fmt.video.i_frame_rate_base =
                            GetQWLE((oggpacket.packet+164));
908 909
                        p_stream->f_rate = 10000000.0 /
                            GetQWLE((oggpacket.packet+164));
910
                        p_stream->fmt.video.i_bits_per_pixel =
911
                            GetWLE((oggpacket.packet+182));
912 913 914 915
                        if( !p_stream->fmt.video.i_bits_per_pixel )
                            /* hack, FIXME */
                            p_stream->fmt.video.i_bits_per_pixel = 24;
                        p_stream->fmt.video.i_width =
916
                            GetDWLE((oggpacket.packet+176));
917
                        p_stream->fmt.video.i_height =
918 919
                            GetDWLE((oggpacket.packet+180));

920
                        msg_Dbg( p_demux,
921 922 923 924 925 926
                                 "fps: %f, width:%i; height:%i, bitcount:%i",
                                 p_stream->f_rate,
                                 p_stream->fmt.video.i_width,
                                 p_stream->fmt.video.i_height,
                                 p_stream->fmt.video.i_bits_per_pixel);

927 928 929 930 931
                    }
                    /* Check for audio header (old format) */
                    else if( GetDWLE((oggpacket.packet+96)) == 0x05589F81 )
                    {
                        unsigned int i_extra_size;
932
                        unsigned int i_format_tag;
933

934
                        p_stream->fmt.i_cat = AUDIO_ES;
935 936

                        i_extra_size = GetWLE((oggpacket.packet+140));
937
                        if( i_extra_size )
938
                        {
939 940 941 942
                            p_stream->fmt.i_extra = i_extra_size;
                            p_stream->fmt.p_extra = malloc( i_extra_size );
                            memcpy( p_stream->fmt.p_extra,
                                    oggpacket.packet + 142, i_extra_size );
943 944
                        }

945 946
                        i_format_tag = GetWLE((oggpacket.packet+124));
                        p_stream->fmt.audio.i_channels =
947
                            GetWLE((oggpacket.packet+126));
948
                        p_stream->f_rate = p_stream->fmt.audio.i_rate =
949
                            GetDWLE((oggpacket.packet+128));
950 951 952
                        p_stream->fmt.i_bitrate =
                            GetDWLE((oggpacket.packet+132)) * 8;
                        p_stream->fmt.audio.i_blockalign =
953
                            GetWLE((oggpacket.packet+136));
954
                        p_stream->fmt.audio.i_bitspersample =
955 956
                            GetWLE((oggpacket.packet+138));

957 958 959 960 961
                        wf_tag_to_fourcc( i_format_tag,
                                          &p_stream->fmt.i_codec, 0 );

                        if( p_stream->fmt.i_codec ==
                            VLC_FOURCC('u','n','d','f') )
962
                        {
963 964 965
                            p_stream->fmt.i_codec = VLC_FOURCC( 'm', 's',
                                ( i_format_tag >> 8 ) & 0xff,
                                i_format_tag & 0xff );
966 967
                        }

968
                        msg_Dbg( p_demux, "found audio header of type: %.4s",
969
                                 (char *)&p_stream->fmt.i_codec );
970
                        msg_Dbg( p_demux, "audio:0x%4.4x channels:%d %dHz "
971
                                 "%dbits/sample %dkb/s",
972 973 974 975 976
                                 i_format_tag,
                                 p_stream->fmt.audio.i_channels,
                                 p_stream->fmt.audio.i_rate,
                                 p_stream->fmt.audio.i_bitspersample,
                                 p_stream->fmt.i_bitrate / 1024 );
977

978 979 980
                    }
                    else
                    {
981
                        msg_Dbg( p_demux, "stream %d has an old header "
982 983 984 985 986
                            "but is of an unknown type", p_ogg->i_streams-1 );
                        free( p_stream );
                        p_ogg->i_streams--;
                    }
                }
987
                else if( (*oggpacket.packet & PACKET_TYPE_BITS )
Sam Hocevar's avatar
Sam Hocevar committed
988
                         == PACKET_TYPE_HEADER &&
989 990 991 992 993 994 995
                         oggpacket.bytes >= (int)sizeof(stream_header)+1 )
                {
                    stream_header *st = (stream_header *)(oggpacket.packet+1);

                    /* Check for video header (new format) */
                    if( !strncmp( st->streamtype, "video", 5 ) )
                    {
996
                        p_stream->fmt.i_cat = VIDEO_ES;
997 998 999 1000

                        /* We need to get rid of the header packet */
                        ogg_stream_packetout( &p_stream->os, &oggpacket );

1001 1002 1003
                        p_stream->fmt.i_codec =
                            VLC_FOURCC( st->subtype[0], st->subtype[1],
                                        st->subtype[2], st->subtype[3] );
1004
                        msg_Dbg( p_demux, "found video header of type: %.4s",
1005
                                 (char *)&p_stream->fmt.i_codec );
1006

1007 1008 1009
                        p_stream->fmt.video.i_frame_rate = 10000000;
                        p_stream->fmt.video.i_frame_rate_base =
                            GetQWLE(&st->time_unit);
1010
                        p_stream->f_rate = 10000000.0 /
1011
                            GetQWLE(&st->time_unit);
1012
                        p_stream->fmt.video.i_bits_per_pixel =
1013
                            GetWLE(&st->bits_per_sample);
1014
                        p_stream->fmt.video.i_width =
1015
                            GetDWLE(&st->sh.video.width);
1016
                        p_stream->fmt.video.i_height =
1017
                            GetDWLE(&st->sh.video.height);
1018

1019
                        msg_Dbg( p_demux,
1020 1021 1022 1023 1024
                                 "fps: %f, width:%i; height:%i, bitcount:%i",
                                 p_stream->f_rate,
                                 p_stream->fmt.video.i_width,
                                 p_stream->fmt.video.i_height,
                                 p_stream->fmt.video.i_bits_per_pixel );
1025 1026 1027 1028 1029
                    }
                    /* Check for audio header (new format) */
                    else if( !strncmp( st->streamtype, "audio", 5 ) )
                    {
                        char p_buffer[5];
1030
                        int i_format_tag;
1031

1032
                        p_stream->fmt.i_cat = AUDIO_ES;
1033 1034 1035 1036

                        /* We need to get rid of the header packet */
                        ogg_stream_packetout( &p_stream->os, &oggpacket );

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
                        p_stream->fmt.i_extra = GetQWLE(&st->size) -
                            sizeof(stream_header);
                        if( p_stream->fmt.i_extra )
                        {
                            p_stream->fmt.p_extra =
                                malloc( p_stream->fmt.i_extra );
                            memcpy( p_stream->fmt.p_extra, st + 1,
                                    p_stream->fmt.i_extra );
                        }

1047 1048
                        memcpy( p_buffer, st->subtype, 4 );
                        p_buffer[4] = '\0';
1049 1050
                        i_format_tag = strtol(p_buffer,NULL,16);
                        p_stream->fmt.audio.i_channels =
1051
                            GetWLE(&st->sh.audio.channels);
1052
                        p_stream->f_rate = p_stream->fmt.audio.i_rate =
1053
                            GetQWLE(&st->samples_per_unit);
1054 1055 1056
                        p_stream->fmt.i_bitrate =
                            GetDWLE(&st->sh.audio.avgbytespersec) * 8;
                        p_stream->fmt.audio.i_blockalign =
1057
                            GetWLE(&st->sh.audio.blockalign);
1058
                        p_stream->fmt.audio.i_bitspersample =