oggseek.c 34.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*****************************************************************************
 * oggseek.c : ogg seeking functions for ogg demuxer vlc
 *****************************************************************************
 * Copyright (C) 2008 - 2010 Gabriel Finch <salsaman@gmail.com>
 *
 * Authors: Gabriel Finch <salsaman@gmail.com>
 * adapted from: http://lives.svn.sourceforge.net/viewvc/lives/trunk/lives-plugins
 * /plugins/decoders/ogg_theora_decoder.c
 *
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
10 11 12
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
13 14 15 16
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
17 18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
19
 *
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
20 21 22
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_common.h>
#include <vlc_demux.h>

#include <ogg/ogg.h>
37
#include <limits.h>
38

39 40
#include <assert.h>

41 42 43
#include "ogg.h"
#include "oggseek.h"

44 45 46 47 48 49 50 51 52 53 54 55 56 57
/* Theora spec 7.1 */
#define THEORA_FTYPE_NOTDATA       0x80
#define THEORA_FTYPE_INTERFRAME    0x40

#define SEGMENT_NOT_FOUND -1

#define MAX_PAGE_SIZE 65307
typedef struct packetStartCoordinates
{
    int64_t i_pos;
    int64_t i_pageno;
    int64_t i_skip;
} packetStartCoordinates;

58
//#define OGG_SEEK_DEBUG 1
59 60 61 62 63 64 65
#ifdef OGG_SEEK_DEBUG
  #define OggDebug(code) code
  #define OggNoDebug(code)
#else
  #define OggDebug(code)
  #define OggNoDebug(code) code
#endif
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
/************************************************************
* index entries
*************************************************************/

/* free all entries in index list */

void oggseek_index_entries_free ( demux_index_entry_t *idx )
{
    demux_index_entry_t *idx_next;

    while ( idx != NULL )
    {
        idx_next = idx->p_next;
        free( idx );
        idx = idx_next;
    }
}


/* internal function to create a new list member */

static demux_index_entry_t *index_entry_new( void )
{
89
    demux_index_entry_t *idx = xmalloc( sizeof( demux_index_entry_t ) );
90
    if ( !idx ) return NULL;
91 92 93 94 95
    idx->p_next = idx->p_prev = NULL;
    idx->i_pagepos_end = -1;
    return idx;
}

96 97 98 99 100 101 102 103 104 105 106
/* We insert into index, sorting by pagepos (as a page can match multiple
   time stamps) */
const demux_index_entry_t *OggSeek_IndexAdd ( logical_stream_t *p_stream,
                                             int64_t i_timestamp,
                                             int64_t i_pagepos )
{
    demux_index_entry_t *idx;
    demux_index_entry_t *last_idx = NULL;

    if ( p_stream == NULL ) return NULL;

107
    idx = p_stream->idx;
108 109 110 111 112 113 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

    if ( i_timestamp < 1 || i_pagepos < 1 ) return NULL;

    if ( idx == NULL )
    {
        demux_index_entry_t *ie = index_entry_new();
        if ( !ie ) return NULL;
        ie->i_value = i_timestamp;
        ie->i_pagepos = i_pagepos;
        p_stream->idx = ie;
        return ie;
    }

    while ( idx != NULL )
    {
        if ( idx->i_pagepos > i_pagepos ) break;
        last_idx = idx;
        idx = idx->p_next;
    }

    /* new entry; insert after last_idx */
    idx = index_entry_new();
    if ( !idx ) return NULL;
    if ( last_idx != NULL )
    {
        idx->p_next = last_idx->p_next;
        last_idx->p_next = idx;
        idx->p_prev = last_idx;
    }
    else
    {
139 140
        idx->p_next = p_stream->idx;
        p_stream->idx = idx;
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    }

    if ( idx->p_next != NULL )
    {
        idx->p_next->p_prev = idx;
    }

    idx->i_value = i_timestamp;
    idx->i_pagepos = i_pagepos;

    return idx;
}

static bool OggSeekIndexFind ( logical_stream_t *p_stream, int64_t i_timestamp,
                               int64_t *pi_pos_lower, int64_t *pi_pos_upper )
{
    demux_index_entry_t *idx = p_stream->idx;
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    while ( idx != NULL )
    {
        if ( idx->i_value <= i_timestamp )
        {
            if ( !idx->p_next ) /* found on last index */
            {
                *pi_pos_lower = idx->i_pagepos;
                return true;
            }
            if ( idx->p_next->i_value > i_timestamp )
            {
                *pi_pos_lower = idx->i_pagepos;
                *pi_pos_upper = idx->p_next->i_pagepos;
                return true;
            }
        }
        idx = idx->p_next;
    }
177

178 179
    return false;
}
180 181 182 183 184 185 186 187 188 189 190

/*********************************************************************
 * private functions
 **********************************************************************/

/* seek in ogg file to offset i_pos and update the sync */

static void seek_byte( demux_t *p_demux, int64_t i_pos )
{
    demux_sys_t *p_sys  = p_demux->p_sys;

191
    if ( ! vlc_stream_Seek( p_demux->s, i_pos ) )
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    {
        ogg_sync_reset( &p_sys->oy );

        p_sys->i_input_position = i_pos;
        p_sys->b_page_waiting = false;
    }
}



/* read bytes from the ogg file to try to find a page start */

static int64_t get_data( demux_t *p_demux, int64_t i_bytes_to_read )
{
    demux_sys_t *p_sys  = p_demux->p_sys;

    char *buf;
    int64_t i_result;

    if ( p_sys->i_total_length > 0 )
    {
        if ( p_sys->i_input_position + i_bytes_to_read > p_sys->i_total_length )
        {
            i_bytes_to_read = p_sys->i_total_length - p_sys->i_input_position;
            if ( i_bytes_to_read <= 0 ) {
                return 0;
            }
        }
    }

222 223
    i_bytes_to_read = __MIN( i_bytes_to_read, INT_MAX );

224 225 226 227
    seek_byte ( p_demux, p_sys->i_input_position );

    buf = ogg_sync_buffer( &p_sys->oy, i_bytes_to_read );

228
    i_result = vlc_stream_Read( p_demux->s, buf, i_bytes_to_read );
229 230 231 232 233

    ogg_sync_wrote( &p_sys->oy, i_result );
    return i_result;
}

234

235
void Oggseek_ProbeEnd( demux_t *p_demux )
236
{
237 238 239 240 241 242 243
    /* Temporary state */
    ogg_stream_state os;
    ogg_sync_state oy;
    ogg_page page;
    demux_sys_t *p_sys = p_demux->p_sys;
    int64_t i_pos, i_startpos, i_result, i_granule, i_lowerbound;
    int64_t i_length = 0;
244
    int64_t i_backup_pos = vlc_stream_Tell( p_demux->s );
245 246 247
    int64_t i_upperbound = stream_Size( p_demux->s );
    unsigned int i_backoffset = OGGSEEK_BYTES_TO_READ;
    assert( OGGSEEK_BYTES_TO_READ < UINT_MAX );
248

249
    const char *buffer;
250

251 252
    ogg_stream_init( &os, -1 );
    ogg_sync_init( &oy );
253

254 255 256
    /* Try to lookup last granule from each logical stream */
    i_lowerbound = stream_Size( p_demux->s ) - p_sys->i_streams * MAX_PAGE_SIZE * 2;
    i_lowerbound = __MAX( 0, i_lowerbound );
257

258
    i_pos = i_startpos = __MAX( i_lowerbound, i_upperbound - i_backoffset );
259

260
    if ( vlc_stream_Seek( p_demux->s, i_pos ) )
261
    {
262 263 264 265
        ogg_sync_clear( &oy );
        ogg_stream_clear( &os );
        return;
    }
266

267 268
    while( i_pos >= i_lowerbound )
    {
269

270
        while( i_pos < i_upperbound )
271
        {
272 273 274 275 276
            if ( oy.unsynced )
                i_result = ogg_sync_pageseek( &oy, &page );

            buffer = ogg_sync_buffer( &oy, OGGSEEK_BYTES_TO_READ );
            if ( buffer == NULL ) goto clean;
277
            i_result = vlc_stream_Read( p_demux->s, (void*) buffer, OGGSEEK_BYTES_TO_READ );
278 279 280 281 282
            if ( i_result < 1 ) goto clean;
            i_pos += i_result;
            ogg_sync_wrote( &oy, i_result );

            while( ogg_sync_pageout( &oy, &page ) == 1 )
283
            {
284 285 286 287 288 289 290 291 292 293 294 295
                i_granule = ogg_page_granulepos( &page );
                if ( i_granule == -1 ) continue;

                for ( int i=0; i< p_sys->i_streams; i++ )
                {
                    if ( p_sys->pp_stream[i]->i_serial_no != ogg_page_serialno( &page ) )
                        continue;

                    i_length = Oggseek_GranuleToAbsTimestamp( p_sys->pp_stream[i], i_granule, false );
                    p_sys->i_length = __MAX( p_sys->i_length, i_length / 1000000 );
                    break;
                }
296
            }
297 298
            if ( i_length > 0 ) break;
        }
299

300 301 302 303 304 305 306 307
        /* We found at least a page with valid granule */
        if ( i_length > 0 ) break;

        /* Otherwise increase read size, starting earlier */
        if ( i_backoffset <= ( UINT_MAX >> 1 ) )
        {
            i_backoffset <<= 1;
            i_startpos = i_upperbound - i_backoffset;
308 309 310
        }
        else
        {
311
            i_startpos -= i_backoffset;
312
        }
313
        i_pos = i_startpos;
314

315
        if ( vlc_stream_Seek( p_demux->s, i_pos ) )
316 317
            break;
    }
318

319
clean:
320
    vlc_stream_Seek( p_demux->s, i_backup_pos );
321

322 323 324
    ogg_sync_clear( &oy );
    ogg_stream_clear( &os );
}
325 326


327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
static int64_t find_first_page_granule( demux_t *p_demux,
                                int64_t i_pos1, int64_t i_pos2,
                                logical_stream_t *p_stream,
                                int64_t *i_granulepos )
{
    int64_t i_result;
    *i_granulepos = -1;
    int64_t i_bytes_to_read = i_pos2 - i_pos1 + 1;
    int64_t i_bytes_read;
    int64_t i_packets_checked;

    demux_sys_t *p_sys  = p_demux->p_sys;

    ogg_packet op;

    seek_byte( p_demux, i_pos1 );

    if ( i_pos1 == p_stream->i_data_start )
        return p_sys->i_input_position;

    if ( i_bytes_to_read > OGGSEEK_BYTES_TO_READ ) i_bytes_to_read = OGGSEEK_BYTES_TO_READ;

    while ( 1 )
    {

        if ( p_sys->i_input_position >= i_pos2 )
        {
            /* we reached the end and found no pages */
            return -1;
        }

        /* read next chunk */
        if ( ! ( i_bytes_read = get_data( p_demux, i_bytes_to_read ) ) )
        {
            /* EOF */
            return -1;
        }

        i_bytes_to_read = OGGSEEK_BYTES_TO_READ;

        i_result = ogg_sync_pageseek( &p_sys->oy, &p_sys->current_page );

        if ( i_result < 0 )
        {
            /* found a page, sync to page start */
            p_sys->i_input_position -= i_result;
            i_pos1 = p_sys->i_input_position;
            continue;
        }

        if ( i_result > 0 || ( i_result == 0 && p_sys->oy.fill > 3 &&
                               ! strncmp( (char *)p_sys->oy.data, "OggS" , 4 ) ) )
        {
            i_pos1 = p_sys->i_input_position;
            break;
        }

        p_sys->i_input_position += i_bytes_read;

    };

    seek_byte( p_demux, p_sys->i_input_position );
    ogg_stream_reset( &p_stream->os );

    while( 1 )
    {

        if ( p_sys->i_input_position >= i_pos2 )
        {
            /* reached the end of the search region and nothing was found */
            return p_sys->i_input_position;
        }

        p_sys->b_page_waiting = false;

        if ( ! ( i_result = oggseek_read_page( p_demux ) ) )
        {
            /* EOF */
            return p_sys->i_input_position;
        }

408 409
        // found a page
        if ( ogg_stream_pagein( &p_stream->os, &p_sys->current_page ) != 0 )
410
        {
411
            /* page is not for this stream or incomplete */
412 413 414 415
            p_sys->i_input_position += i_result;
            continue;
        }

416
        if ( ogg_page_granulepos( &p_sys->current_page ) <= 0 )
417
        {
418 419
            /* A negative granulepos means that the packet continues on the
             * next page => read the next page */
420 421 422 423 424
            p_sys->i_input_position += i_result;
            continue;
        }

        i_packets_checked = 0;
425

426
        while ( ogg_stream_packetout( &p_stream->os, &op ) > 0 )
427 428 429
        {
            i_packets_checked++;
        }
430

431 432 433 434 435
        if ( i_packets_checked )
        {
            *i_granulepos = ogg_page_granulepos( &p_sys->current_page );
            return i_pos1;
        }
436

437 438
        /*  -> start of next page */
        p_sys->i_input_position += i_result;
439
        i_pos1 = p_sys->i_input_position;
440 441
    }
}
442

443 444
/* Checks if current packet matches codec keyframe */
bool Ogg_IsKeyFrame( logical_stream_t *p_stream, ogg_packet *p_packet )
445
{
446 447 448 449
    if ( p_stream->b_oggds )
    {
        return ( p_packet->bytes > 0 && p_packet->packet[0] & PACKET_IS_SYNCPOINT );
    }
450
    else switch ( p_stream->fmt.i_codec )
451
    {
452
    case VLC_CODEC_THEORA:
453
    case VLC_CODEC_DAALA: /* Same convention used in daala */
454 455 456 457
        if ( p_packet->bytes <= 0 || p_packet->packet[0] & THEORA_FTYPE_NOTDATA )
            return false;
        else
            return !( p_packet->packet[0] & THEORA_FTYPE_INTERFRAME );
458
    case VLC_CODEC_VP8:
459
        return ( ( ( p_packet->granulepos >> 3 ) & 0x07FFFFFF ) == 0 );
460 461 462 463
    case VLC_CODEC_DIRAC:
        return ( p_packet->granulepos & 0xFF8000FF );
    default:
        return true;
464
    }
465
}
466

467 468 469 470 471 472
int64_t Ogg_GetKeyframeGranule( logical_stream_t *p_stream, int64_t i_granule )
{
    if ( p_stream->b_oggds )
    {
           return -1; /* We have no way to know */
    }
473 474
    else if( p_stream->fmt.i_codec == VLC_CODEC_THEORA ||
             p_stream->fmt.i_codec == VLC_CODEC_DAALA )
475 476 477 478 479 480 481 482 483 484
    {
        return ( i_granule >> p_stream->i_granule_shift ) << p_stream->i_granule_shift;
    }
    else if( p_stream->fmt.i_codec == VLC_CODEC_DIRAC )
    {
        return ( i_granule >> 31 ) << 31;
    }
    /* No change, that's keyframe or it can't be shifted out (oggds) */
    return i_granule;
}
485

486 487 488 489 490 491
static bool OggSeekToPacket( demux_t *p_demux, logical_stream_t *p_stream,
            int64_t i_granulepos, packetStartCoordinates *p_lastpacketcoords,
            bool b_exact )
{
    ogg_packet op;
    demux_sys_t *p_sys  = p_demux->p_sys;
492 493 494
    if ( ogg_stream_pagein( &p_stream->os, &p_sys->current_page ) != 0 )
        return false;
    p_sys->b_page_waiting = true;
495
    int i=0;
496

497 498 499 500
    int64_t itarget_frame = Ogg_GetKeyframeGranule( p_stream, i_granulepos );
    int64_t iframe = Ogg_GetKeyframeGranule( p_stream, ogg_page_granulepos( &p_sys->current_page ) );

    if ( ! ogg_page_continued( &p_sys->current_page ) )
501
    {
502 503 504 505 506 507 508 509 510
        /* Start of frame, not continued page, but no packet. */
        p_lastpacketcoords->i_pageno = ogg_page_pageno( &p_sys->current_page );
        p_lastpacketcoords->i_pos = p_sys->i_input_position;
        p_lastpacketcoords->i_skip = 0;
    }

    if ( b_exact && iframe > itarget_frame )
    {
        while( ogg_stream_packetout( &p_stream->os, &op ) > 0 ) {};
511
        p_sys->b_page_waiting = false;
512 513 514 515 516 517
        return false;
    }

    while( ogg_stream_packetpeek( &p_stream->os, &op ) > 0 )
    {
        if ( ( !b_exact || itarget_frame == iframe ) && Ogg_IsKeyFrame( p_stream, &op ) )
518
        {
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
            OggDebug(
                msg_Dbg(p_demux, "** KEYFRAME **" );
                msg_Dbg(p_demux, "** KEYFRAME PACKET START pageno %"PRId64" OFFSET %"PRId64" skip %"PRId64" **", p_lastpacketcoords->i_pageno, p_lastpacketcoords->i_pos, p_lastpacketcoords->i_skip );
                msg_Dbg(p_demux, "KEYFRAME PACKET IS at pageno %"PRId64" OFFSET %"PRId64" with skip %d packet (%d / %d) ",
                    ogg_page_pageno( &p_sys->current_page ), p_sys->i_input_position, i, i+1, ogg_page_packets( &p_sys->current_page ) );
                DemuxDebug( p_sys->b_seeked = true; )
            );

            if ( i != 0 ) /* Not continued packet */
            {
                /* We need to handle the case when the packet spans onto N
                       previous page(s). packetout() will be valid only when
                       all segments are assembled.
                       Keyframe flag is only available after assembling last part
                       (when packetout() becomes valid). We have no way to guess
                       keyframe at earlier time.
                    */
                p_lastpacketcoords->i_pageno = ogg_page_pageno( &p_sys->current_page );
                p_lastpacketcoords->i_pos = p_sys->i_input_position;
                p_lastpacketcoords->i_skip = i;
            }
            return true;
        }

        p_lastpacketcoords->i_pageno = ogg_page_pageno( &p_sys->current_page );
        p_lastpacketcoords->i_pos = p_sys->i_input_position;
        p_lastpacketcoords->i_skip = i + 1;
        i++;
        /* remove that packet and go sync to next */
        ogg_stream_packetout( &p_stream->os, &op );
    }
550

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    return false;
}

static int64_t OggForwardSeekToFrame( demux_t *p_demux, int64_t i_pos1, int64_t i_pos2,
                logical_stream_t *p_stream, int64_t i_granulepos, bool b_fastseek )
{
    int64_t i_result;
    int64_t i_bytes_to_read;
    int64_t i_bytes_read;

    demux_sys_t *p_sys  = p_demux->p_sys;

    i_bytes_to_read = i_pos2 - i_pos1 + 1;
    seek_byte( p_demux, i_pos1 );
    if ( i_bytes_to_read > OGGSEEK_BYTES_TO_READ ) i_bytes_to_read = OGGSEEK_BYTES_TO_READ;

    OggDebug(
        msg_Dbg( p_demux, "Probing Fwd %"PRId64" %"PRId64" for granule %"PRId64,
        i_pos1, i_pos2, i_granulepos );
    );

    while ( 1 )
    {

        if ( p_sys->i_input_position >= i_pos2 )
            return SEGMENT_NOT_FOUND;

        /* read next chunk */
        if ( ! ( i_bytes_read = get_data( p_demux, i_bytes_to_read ) ) )
            return SEGMENT_NOT_FOUND;

        i_bytes_to_read = OGGSEEK_BYTES_TO_READ;

        i_result = ogg_sync_pageseek( &p_sys->oy, &p_sys->current_page );

        if ( i_result < 0 )
        {
            /* found a page, sync to page start */
            p_sys->i_input_position -= i_result;
            i_pos1 = p_sys->i_input_position;
591 592 593
            continue;
        }

594 595
        if ( i_result > 0 || ( i_result == 0 && p_sys->oy.fill > 3 &&
                               ! strncmp( (char *)p_sys->oy.data, "OggS" , 4 ) ) )
596
        {
597 598
            i_pos1 = p_sys->i_input_position;
            break;
599 600
        }

601 602 603 604 605 606
        p_sys->i_input_position += i_bytes_read;
    };

    seek_byte( p_demux, p_sys->i_input_position );
    ogg_stream_reset( &p_stream->os );

607 608 609
    ogg_packet op;
    while( ogg_stream_packetout( &p_stream->os, &op ) > 0 ) {};

610
    packetStartCoordinates lastpacket = { -1, -1, -1 };
611

612 613 614 615
    while( 1 )
    {

        if ( p_sys->i_input_position >= i_pos2 )
616
        {
617 618
            /* reached the end of the search region and nothing was found */
            break;
619 620
        }

621 622 623
        p_sys->b_page_waiting = false;

        if ( ! ( i_result = oggseek_read_page( p_demux ) ) )
624
        {
625 626 627 628 629 630 631 632 633
            /* EOF */
            break;
        }

        // found a page
        if ( p_stream->os.serialno != ogg_page_serialno( &p_sys->current_page ) )
        {
            /* page is not for this stream */
            p_sys->i_input_position += i_result;
634
            continue;
635 636
        }

637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
        if ( OggSeekToPacket( p_demux, p_stream, i_granulepos, &lastpacket, b_fastseek ) )
        {
            p_sys->i_input_position = lastpacket.i_pos;
            p_stream->i_skip_frames = 0;
            return p_sys->i_input_position;
        }

        /*  -> start of next page */
        p_sys->i_input_position += i_result;
    }

    return SEGMENT_NOT_FOUND;
}

static int64_t OggBackwardSeekToFrame( demux_t *p_demux, int64_t i_pos1, int64_t i_pos2,
                               logical_stream_t *p_stream, int64_t i_granulepos )
{
    int64_t i_result;
    int64_t i_offset = __MAX( 1 + ( (i_pos2 - i_pos1) >> 1 ), OGGSEEK_BYTES_TO_READ );

restart:

    OggDebug(
        msg_Dbg( p_demux, "Probing Back %"PRId64" %"PRId64" for granule %"PRId64,
        i_pos1, i_pos2, i_granulepos );
    );

    i_result = OggForwardSeekToFrame( p_demux, i_pos1, i_pos2, p_stream,
                                      i_granulepos, true );

    if ( i_result == SEGMENT_NOT_FOUND && i_pos1 > p_stream->i_data_start )
    {
        i_pos1 = __MAX( p_stream->i_data_start, i_pos1 - i_offset );
        goto restart;
671
    }
672

673
    return i_result;
674 675
}

676 677 678 679 680
/* Dont use b_presentation with frames granules ! */
int64_t Oggseek_GranuleToAbsTimestamp( logical_stream_t *p_stream,
                                       int64_t i_granule, bool b_presentation )
{
    int64_t i_timestamp = -1;
681
    if ( i_granule < 1 )
682
        return -1;
683 684 685

    if ( p_stream->b_oggds )
    {
686
        if ( b_presentation ) i_granule--;
Tristan Matthews's avatar
Tristan Matthews committed
687
        i_timestamp = i_granule * CLOCK_FREQ / p_stream->f_rate;
688
    }
689 690 691
    else  switch( p_stream->fmt.i_codec )
    {
    case VLC_CODEC_THEORA:
692
    case VLC_CODEC_DAALA:
693
    case VLC_CODEC_KATE:
694 695 696 697 698
    {
        ogg_int64_t iframe = i_granule >> p_stream->i_granule_shift;
        ogg_int64_t pframe = i_granule - ( iframe << p_stream->i_granule_shift );
        /* See Theora A.2.3 */
        if ( b_presentation ) pframe -= p_stream->i_keyframe_offset;
Tristan Matthews's avatar
Tristan Matthews committed
699
        i_timestamp = ( iframe + pframe ) * CLOCK_FREQ / p_stream->f_rate;
700
        break;
701
    }
702
    case VLC_CODEC_VP8:
703 704 705 706
    {
        ogg_int64_t frame = i_granule >> p_stream->i_granule_shift;
        if ( b_presentation ) frame--;
        i_timestamp = frame * CLOCK_FREQ / p_stream->f_rate;
707
        break;
708
    }
709
    case VLC_CODEC_DIRAC:
710 711
    {
        ogg_int64_t i_dts = i_granule >> 31;
712
        ogg_int64_t delay = (i_granule >> 9) & 0x1fff;
713
        /* NB, OggDirac granulepos values are in units of 2*picturerate */
714 715 716 717 718
        double f_rate = p_stream->f_rate;
        if ( !p_stream->special.dirac.b_interlaced ) f_rate *= 2;
        if ( b_presentation ) i_dts += delay;
        i_timestamp = i_dts * CLOCK_FREQ / f_rate;
        break;
719
    }
720
    case VLC_CODEC_OPUS:
721
    {
722
        if ( b_presentation ) return VLC_TS_INVALID;
723
        i_timestamp = ( i_granule - p_stream->i_pre_skip ) * CLOCK_FREQ / 48000;
724
        break;
725
    }
726 727
    case VLC_CODEC_VORBIS:
    case VLC_CODEC_FLAC:
728
    {
729
        if ( b_presentation ) return VLC_TS_INVALID;
Tristan Matthews's avatar
Tristan Matthews committed
730
        i_timestamp = i_granule * CLOCK_FREQ / p_stream->f_rate;
731
        break;
732
    }
733 734 735 736 737 738 739 740
    case VLC_CODEC_SPEEX:
    {
        if ( b_presentation )
            i_granule -= p_stream->special.speex.i_framesize *
                         p_stream->special.speex.i_framesperpacket;
        i_timestamp = i_granule * CLOCK_FREQ / p_stream->f_rate;
        break;
    }
741 742 743 744 745 746 747
    case VLC_CODEC_OGGSPOTS:
    {
        if ( b_presentation ) return VLC_TS_INVALID;
        i_timestamp = ( i_granule >> p_stream->i_granule_shift )
                * CLOCK_FREQ / p_stream->f_rate;
        break;
    }
748
    }
749

750
    return i_timestamp;
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
}

/* returns pos */
static int64_t OggBisectSearchByTime( demux_t *p_demux, logical_stream_t *p_stream,
            int64_t i_targettime, int64_t i_pos_lower, int64_t i_pos_upper)
{
    int64_t i_start_pos;
    int64_t i_end_pos;
    int64_t i_segsize;

    struct
    {
        int64_t i_pos;
        int64_t i_timestamp;
        int64_t i_granule;
766
    } bestlower = { p_stream->i_data_start, -1, -1 },
767 768
      current = { -1, -1, -1 },
      lowestupper = { -1, -1, -1 };
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

    demux_sys_t *p_sys  = p_demux->p_sys;

    i_pos_lower = __MAX( i_pos_lower, p_stream->i_data_start );
    i_pos_upper = __MIN( i_pos_upper, p_sys->i_total_length );
    if ( i_pos_upper < 0 ) i_pos_upper = p_sys->i_total_length;

    i_start_pos = i_pos_lower;
    i_end_pos = i_pos_upper;

    i_segsize = ( i_end_pos - i_start_pos + 1 ) >> 1;
    i_start_pos += i_segsize;

    OggDebug( msg_Dbg(p_demux, "Bisecting for time=%"PRId64" between %"PRId64" and %"PRId64,
            i_targettime, i_pos_lower, i_pos_upper ) );

    do
    {
        /* see if the frame lies in current segment */
        i_start_pos = __MAX( i_start_pos, i_pos_lower );
        i_end_pos = __MIN( i_end_pos, i_pos_upper );

        if ( i_start_pos >= i_end_pos )
        {
            if ( i_start_pos == i_pos_lower)
            {
                return i_start_pos;
            }
            return -1;
        }


        current.i_pos = find_first_page_granule( p_demux,
                                                 i_start_pos, i_end_pos,
                                                 p_stream,
                                                 &current.i_granule );

        current.i_timestamp = Oggseek_GranuleToAbsTimestamp( p_stream,
                                                             current.i_granule, false );

809
        if ( current.i_timestamp == -1 && current.i_granule > 0 )
810 811 812 813
        {
            msg_Err( p_demux, "Unmatched granule. New codec ?" );
            return -1;
        }
814 815 816 817
        else if ( current.i_timestamp < -1 )  /* due to preskip with some codecs */
        {
            current.i_timestamp = 0;
        }
818 819 820 821 822 823 824 825 826 827 828 829 830 831

        if ( current.i_pos != -1 && current.i_granule != -1 )
        {
            /* found a page */

            if ( current.i_timestamp <= i_targettime )
            {
                /* set our lower bound */
                if ( current.i_timestamp > bestlower.i_timestamp )
                    bestlower = current;
                i_start_pos = current.i_pos;
            }
            else if ( current.i_timestamp > i_targettime )
            {
832 833
                if ( lowestupper.i_timestamp == -1 || current.i_timestamp < lowestupper.i_timestamp )
                    lowestupper = current;
834 835 836 837 838 839 840 841 842 843 844 845
                /* check lower half of segment */
                i_start_pos -= i_segsize;
                i_end_pos -= i_segsize;
            }
        }
        else
        {
            /* no keyframe found, check lower segment */
            i_end_pos -= i_segsize;
            i_start_pos -= i_segsize;
        }

846 847 848
        OggDebug( msg_Dbg(p_demux, "Bisect restart i_segsize=%"PRId64" between %"PRId64
                                   " and %"PRId64 " bl %"PRId64" lu %"PRId64,
                i_segsize, i_start_pos, i_end_pos, bestlower.i_granule, lowestupper.i_granule  ) );
849 850 851 852

        i_segsize = ( i_end_pos - i_start_pos + 1 ) >> 1;
        i_start_pos += i_segsize;

853
    } while ( i_segsize > 64 );
854

855 856 857 858 859 860 861
    if ( bestlower.i_granule == -1 )
    {
        if ( lowestupper.i_granule == -1 )
            return -1;
        else
            bestlower = lowestupper;
    }
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

    if ( p_stream->b_oggds )
    {
        int64_t a = OggBackwardSeekToFrame( p_demux,
                __MAX ( bestlower.i_pos - OGGSEEK_BYTES_TO_READ, p_stream->i_data_start ),
                bestlower.i_pos,
                p_stream, bestlower.i_granule /* unused */ );
        return a;
    }
    /* If not each packet is usable as keyframe, query the codec for keyframe */
    else if ( Ogg_GetKeyframeGranule( p_stream, bestlower.i_granule ) != bestlower.i_granule )
    {
        int64_t i_keyframegranule = Ogg_GetKeyframeGranule( p_stream, bestlower.i_granule );

        OggDebug( msg_Dbg( p_demux, "Need to reseek to keyframe (%"PRId64") granule (%"PRId64"!=%"PRId64") to t=%"PRId64,
                           i_keyframegranule >> p_stream->i_granule_shift,
                           bestlower.i_granule,
                           i_pos_upper,
880
                           Oggseek_GranuleToAbsTimestamp( p_stream, i_keyframegranule, false ) ) );
881 882 883 884 885 886 887 888 889 890 891

        OggDebug( msg_Dbg( p_demux, "Seeking back to %"PRId64, __MAX ( bestlower.i_pos - OGGSEEK_BYTES_TO_READ, p_stream->i_data_start ) ) );

        int64_t a = OggBackwardSeekToFrame( p_demux,
            __MAX ( bestlower.i_pos - OGGSEEK_BYTES_TO_READ, p_stream->i_data_start ),
            stream_Size( p_demux->s ), p_stream, i_keyframegranule );
        return a;
    }

    return bestlower.i_pos;
}
892

893

894 895 896 897
/************************************************************************
 * public functions
 *************************************************************************/

898 899 900 901
int Oggseek_BlindSeektoAbsoluteTime( demux_t *p_demux, logical_stream_t *p_stream,
                                     int64_t i_time, bool b_fastseek )
{
    demux_sys_t *p_sys  = p_demux->p_sys;
902 903
    int64_t i_lowerpos = -1;
    int64_t i_upperpos = -1;
904 905 906
    bool b_found = false;

    /* Search in skeleton */
907 908
    Ogg_GetBoundsUsingSkeletonIndex( p_stream, i_time, &i_lowerpos, &i_upperpos );
    if ( i_lowerpos != -1 ) b_found = true;
909 910

    /* And also search in our own index */
911
    if ( !b_found && OggSeekIndexFind( p_stream, i_time, &i_lowerpos, &i_upperpos ) )
912 913 914 915 916 917 918 919 920 921
    {
        b_found = true;
    }

    /* Or try to be smart with audio fixed bitrate streams */
    if ( !b_found && p_stream->fmt.i_cat == AUDIO_ES && p_sys->i_streams == 1
         && p_sys->i_bitrate && Ogg_GetKeyframeGranule( p_stream, 0xFF00FF00 ) == 0xFF00FF00 )
    {
        /* But only if there's no keyframe/preload requirements */
        /* FIXME: add function to get preload time by codec, ex: opus */
922
        i_lowerpos = i_time * p_sys->i_bitrate / INT64_C(8000000);
923 924 925 926 927 928
        b_found = true;
    }

    /* or search */
    if ( !b_found && b_fastseek )
    {
929 930 931
        i_lowerpos = OggBisectSearchByTime( p_demux, p_stream, i_time,
                                            p_stream->i_data_start, p_sys->i_total_length );
        b_found = ( i_lowerpos != -1 );
932 933 934 935
    }

    if ( !b_found ) return -1;

936
    if ( i_lowerpos < p_stream->i_data_start || i_upperpos > p_sys->i_total_length )
937 938 939
        return -1;

    /* And really do seek */
940
    p_sys->i_input_position = i_lowerpos;
941 942 943
    seek_byte( p_demux, p_sys->i_input_position );
    ogg_stream_reset( &p_stream->os );

944
    return i_lowerpos;
945
}
946

947 948
int Oggseek_BlindSeektoPosition( demux_t *p_demux, logical_stream_t *p_stream,
                                 double f, bool b_canfastseek )
949
{
950
    demux_sys_t *p_sys = p_demux->p_sys;
951 952 953
    OggDebug( msg_Dbg( p_demux, "=================== Seeking To Blind Pos" ) );
    int64_t i_size = stream_Size( p_demux->s );
    int64_t i_granule;
954 955
    int64_t i_pagepos;

956 957 958 959
    i_size = find_first_page_granule( p_demux,
                                             i_size * f, i_size,
                                             p_stream,
                                             &i_granule );
960

961
    OggDebug( msg_Dbg( p_demux, "Seek start pos is %"PRId64" granule %"PRId64, i_size, i_granule ) );
962

963
    i_granule = Ogg_GetKeyframeGranule( p_stream, i_granule );
964

965
    if ( b_canfastseek )
966
    {
967 968 969 970
        /* Peek back until we meet a keyframe to start our decoding up to our
         * final seek time */
        i_pagepos = OggBackwardSeekToFrame( p_demux,
                __MAX ( i_size - MAX_PAGE_SIZE, p_stream->i_data_start ),
971
                __MIN ( i_size + MAX_PAGE_SIZE, p_sys->i_total_length ),
972
                p_stream, i_granule );
973 974
    }
    else
975
    {
976 977 978 979 980
        /* Otherwise, we just sync to the next keyframe we meet */
        i_pagepos = OggForwardSeekToFrame( p_demux,
                __MAX ( i_size - MAX_PAGE_SIZE, p_stream->i_data_start ),
                stream_Size( p_demux->s ),
                p_stream, i_granule, false );
981 982
    }

983 984 985
    OggDebug( msg_Dbg( p_demux, "=================== Seeked To %"PRId64" granule %"PRId64, i_pagepos, i_granule ) );
    return i_pagepos;
}
986

987 988 989 990
int Oggseek_SeektoAbsolutetime( demux_t *p_demux, logical_stream_t *p_stream,
                                int64_t i_time )
{
    demux_sys_t *p_sys  = p_demux->p_sys;
991

992
    OggDebug( msg_Dbg( p_demux, "=================== Seeking To Absolute Time %"PRId64, i_time ) );
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    int64_t i_offset_lower = -1;
    int64_t i_offset_upper = -1;

    if ( Ogg_GetBoundsUsingSkeletonIndex( p_stream, i_time, &i_offset_lower, &i_offset_upper ) )
    {
        /* Exact match */
        OggDebug( msg_Dbg( p_demux, "Found keyframe at %"PRId64" using skeleton index", i_offset_lower ) );
        if ( i_offset_lower == -1 ) i_offset_lower = p_stream->i_data_start;
        p_sys->i_input_position = i_offset_lower;
        seek_byte( p_demux, p_sys->i_input_position );
        ogg_stream_reset( &p_stream->os );
        return i_offset_lower;
    }
    OggDebug( msg_Dbg( p_demux, "Search bounds set to %"PRId64" %"PRId64" using skeleton index", i_offset_lower, i_offset_upper ) );
1007

1008 1009 1010
    OggNoDebug(
        OggSeekIndexFind( p_stream, i_time, &i_offset_lower, &i_offset_upper )
    );
1011

1012 1013
    i_offset_lower = __MAX( i_offset_lower, p_stream->i_data_start );
    i_offset_upper = __MIN( i_offset_upper, p_sys->i_total_length );
1014

1015 1016
    int64_t i_pagepos = OggBisectSearchByTime( p_demux, p_stream, i_time,
                                       i_offset_lower, i_offset_upper);
1017 1018 1019 1020
    if ( i_pagepos >= 0 )
    {
        /* be sure to clear any state or read+pagein() will fail on same # */
        ogg_stream_reset( &p_stream->os );
1021
        p_sys->i_input_position = i_pagepos;
1022 1023
        seek_byte( p_demux, p_sys->i_input_position );
    }
1024 1025 1026 1027 1028
    /* Insert keyframe position into index */
    OggNoDebug(
    if ( i_pagepos >= p_stream->i_data_start )
        OggSeek_IndexAdd( p_stream, i_time, i_pagepos )
    );
1029

1030 1031 1032
    OggDebug( msg_Dbg( p_demux, "=================== Seeked To %"PRId64" time %"PRId64, i_pagepos, i_time ) );
    return i_pagepos;
}
1033 1034 1035 1036 1037 1038 1039 1040

/****************************************************************************
 * oggseek_read_page: Read a full Ogg page from the physical bitstream.
 ****************************************************************************
 * Returns number of bytes read. This should always be > 0
 * unless we are at the end of stream.
 *
 ****************************************************************************/
1041

1042 1043 1044 1045 1046 1047
int64_t oggseek_read_page( demux_t *p_demux )
{
    demux_sys_t *p_ogg = p_demux->p_sys  ;
    uint8_t header[PAGE_HEADER_BYTES+255];
    int i_nsegs;
    int i;
1048
    int64_t i_in_pos;
1049 1050 1051 1052 1053 1054 1055
    int64_t i_result;
    int i_page_size;
    char *buf;

    demux_sys_t *p_sys  = p_demux->p_sys;

    /* store position of this page */
1056
    i_in_pos = p_ogg->i_input_position = vlc_stream_Tell( p_demux->s );
1057 1058 1059 1060 1061 1062

    if ( p_sys->b_page_waiting) {
        msg_Warn( p_demux, "Ogg page already loaded" );
        return 0;
    }

1063
    if ( vlc_stream_Read ( p_demux->s, header, PAGE_HEADER_BYTES ) < PAGE_HEADER_BYTES )
1064
    {
1065
        vlc_stream_Seek( p_demux->s, i_in_pos );
1066 1067 1068 1069 1070 1071
        msg_Dbg ( p_demux, "Reached clean EOF in ogg file" );
        return 0;
    }

    i_nsegs = header[ PAGE_HEADER_BYTES - 1 ];

1072
    if ( vlc_stream_Read ( p_demux->s, header+PAGE_HEADER_BYTES, i_nsegs ) < i_nsegs )
1073
    {
1074
        vlc_stream_Seek( p_demux->s, i_in_pos );
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
        msg_Warn ( p_demux, "Reached broken EOF in ogg file" );
        return 0;
    }

    i_page_size = PAGE_HEADER_BYTES + i_nsegs;

    for ( i = 0; i < i_nsegs; i++ )
    {
        i_page_size += header[ PAGE_HEADER_BYTES + i ];
    }

    ogg_sync_reset( &p_ogg->oy );

    buf = ogg_sync_buffer( &p_ogg->oy, i_page_size );

    memcpy( buf, header, PAGE_HEADER_BYTES + i_nsegs );

1092
    i_result = vlc_stream_Read ( p_demux->s, (uint8_t*)buf + PAGE_HEADER_BYTES + i_nsegs,
1093 1094 1095 1096 1097 1098 1099 1100 1101
                             i_page_size - PAGE_HEADER_BYTES - i_nsegs );

    ogg_sync_wrote( &p_ogg->oy, i_result + PAGE_HEADER_BYTES + i_nsegs );




    if ( ogg_sync_pageout( &p_ogg->oy, &p_ogg->current_page ) != 1 )
    {
1102 1103
        msg_Err( p_demux , "Got invalid packet, read %"PRId64" of %i: %s %"PRId64,
                 i_result, i_page_size, buf, i_in_pos );
1104 1105 1106 1107 1108 1109
        return 0;
    }

    return i_result + PAGE_HEADER_BYTES + i_nsegs;
}