stream.c 56.8 KB
Newer Older
1 2 3
/*****************************************************************************
 * stream.c
 *****************************************************************************
4
 * Copyright (C) 1999-2004 the VideoLAN team
Gildas Bazin's avatar
Gildas Bazin committed
5
 * $Id$
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
 *
 * 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.
 *
 * 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
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 23
 *****************************************************************************/

24 25 26 27
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

28
#include <dirent.h>
29
#include <assert.h>
30

31
#include <vlc_common.h>
32
#include <vlc_strings.h>
33
#include <vlc_memory.h>
34

35
#include <libvlc.h>
36

37
#include "access.h"
38 39 40
#include "stream.h"

#include "input_internal.h"
41

42
// #define STREAM_DEBUG 1
43

44
/* TODO:
45
 *  - tune the 2 methods (block/stream)
46 47 48
 *  - compute cost for seek
 *  - improve stream mode seeking with closest segments
 *  - ...
49
 */
50 51 52 53 54 55

/* Two methods:
 *  - using pf_block
 *      One linked list of data read
 *  - using pf_read
 *      More complex scheme using mutliple track to avoid seeking
56 57 58
 *  - using directly the access (only indirection for peeking).
 *      This method is known to introduce much less latency.
 *      It should probably defaulted (instead of the stream method (2)).
59 60
 */

61 62
/* How many tracks we have, currently only used for stream mode */
#ifdef OPTIMIZE_MEMORY
63 64 65 66 67 68 69 70 71
#   define STREAM_CACHE_TRACK 1
    /* Max size of our cache 128Ko per track */
#   define STREAM_CACHE_SIZE  (STREAM_CACHE_TRACK*1024*128)
#else
#   define STREAM_CACHE_TRACK 3
    /* Max size of our cache 4Mo per track */
#   define STREAM_CACHE_SIZE  (4*STREAM_CACHE_TRACK*1024*1024)
#endif

72 73 74 75
/* How many data we try to prebuffer
 * XXX it should be small to avoid useless latency but big enough for
 * efficient demux probing */
#define STREAM_CACHE_PREBUFFER_SIZE (128)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

/* Method1: Simple, for pf_block.
 *  We get blocks and put them in the linked list.
 *  We release blocks once the total size is bigger than CACHE_BLOCK_SIZE
 */

/* Method2: A bit more complex, for pf_read
 *  - We use ring buffers, only one if unseekable, all if seekable
 *  - Upon seek date current ring, then search if one ring match the pos,
 *      yes: switch to it, seek the access to match the end of the ring
 *      no: search the ring with i_end the closer to i_pos,
 *          if close enough, read data and use this ring
 *          else use the oldest ring, seek and use it.
 *
 *  TODO: - with access non seekable: use all space available for only one ring, but
 *          we have to support seekable/non-seekable switch on the fly.
 *        - compute a good value for i_read_size
 *        - ?
 */
95
#define STREAM_READ_ATONCE 1024
96 97 98
#define STREAM_CACHE_TRACK_SIZE (STREAM_CACHE_SIZE/STREAM_CACHE_TRACK)

typedef struct
99
{
100
    int64_t i_date;
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
101

102 103
    uint64_t i_start;
    uint64_t i_end;
104 105

    uint8_t *p_buffer;
106

107 108
} stream_track_t;

109 110 111
typedef struct
{
    char     *psz_path;
112
    uint64_t  i_size;
113 114 115

} access_entry_t;

Laurent Aimar's avatar
Laurent Aimar committed
116
typedef enum
117
{
118 119
    STREAM_METHOD_BLOCK,
    STREAM_METHOD_STREAM
120 121
} stream_read_method_t;

122 123 124 125
struct stream_sys_t
{
    access_t    *p_access;

126
    stream_read_method_t   method;    /* method to use */
127

128
    uint64_t     i_pos;      /* Current reading offset */
129 130 131

    /* Method 1: pf_block */
    struct
132
    {
133 134
        uint64_t i_start;        /* Offset of block for p_first */
        uint64_t i_offset;       /* Offset for data in p_current */
135 136
        block_t *p_current;     /* Current block */

137
        uint64_t i_size;         /* Total amount of data in the list */
138 139
        block_t *p_first;
        block_t **pp_last;
140

141 142 143 144
    } block;

    /* Method 2: for pf_read */
    struct
145
    {
146 147
        unsigned i_offset;   /* Buffer offset in the current track */
        int      i_tk;       /* Current track */
148 149 150 151 152 153
        stream_track_t tk[STREAM_CACHE_TRACK];

        /* Global buffer */
        uint8_t *p_buffer;

        /* */
154 155
        unsigned i_used; /* Used since last read */
        unsigned i_read_size;
156

157 158 159
    } stream;

    /* Peek temporary buffer */
160
    unsigned int i_peek;
161 162 163 164
    uint8_t *p_peek;

    /* Stat for both method */
    struct
165
    {
166
        bool b_fastseek;  /* From access */
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
167

168
        /* Stat about reading data */
169 170 171
        uint64_t i_read_count;
        uint64_t i_bytes;
        uint64_t i_read_time;
172

173
        /* Stat about seek */
174 175
        unsigned i_seek_count;
        uint64_t i_seek_time;
176

177
    } stat;
178

179 180 181 182 183
    /* Streams list */
    int            i_list;
    access_entry_t **list;
    int            i_list_index;
    access_t       *p_list_access;
184
};
185

186
/* Method 1: */
187 188
static int  AStreamReadBlock( stream_t *s, void *p_read, unsigned int i_read );
static int  AStreamPeekBlock( stream_t *s, const uint8_t **p_peek, unsigned int i_read );
189
static int  AStreamSeekBlock( stream_t *s, uint64_t i_pos );
190
static void AStreamPrebufferBlock( stream_t *s );
191
static block_t *AReadBlock( stream_t *s, bool *pb_eof );
192

193
/* Method 2 */
194 195
static int  AStreamReadStream( stream_t *s, void *p_read, unsigned int i_read );
static int  AStreamPeekStream( stream_t *s, const uint8_t **pp_peek, unsigned int i_read );
196
static int  AStreamSeekStream( stream_t *s, uint64_t i_pos );
197
static void AStreamPrebufferStream( stream_t *s );
198
static int  AReadStream( stream_t *s, void *p_read, unsigned int i_read );
199

200
/* Common */
201
static int AStreamControl( stream_t *s, int i_query, va_list );
202 203
static void AStreamDestroy( stream_t *s );
static void UStreamDestroy( stream_t *s );
204
static int  ASeek( stream_t *s, uint64_t i_pos );
205

Laurent Aimar's avatar
Laurent Aimar committed
206 207 208 209 210
/****************************************************************************
 * stream_CommonNew: create an empty stream structure
 ****************************************************************************/
stream_t *stream_CommonNew( vlc_object_t *p_obj )
{
Laurent Aimar's avatar
Laurent Aimar committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    stream_t *s = (stream_t *)vlc_custom_create( p_obj, sizeof(*s),
                                                 VLC_OBJECT_GENERIC, "stream" );

    if( !s )
        return NULL;

    s->p_text = malloc( sizeof(*s->p_text) );
    if( !s->p_text )
    {
        vlc_object_release( s );
        return NULL;
    }

    /* UTF16 and UTF32 text file conversion */
    s->p_text->conv = (vlc_iconv_t)(-1);
    s->p_text->i_char_width = 1;
    s->p_text->b_little_endian = false;

    return s;
}
231

Laurent Aimar's avatar
Laurent Aimar committed
232 233 234 235 236 237 238 239
void stream_CommonDelete( stream_t *s )
{
    if( s->p_text )
    {
        if( s->p_text->conv != (vlc_iconv_t)(-1) )
            vlc_iconv_close( s->p_text->conv );
        free( s->p_text );
    }
240
    free( s->psz_path );
Laurent Aimar's avatar
Laurent Aimar committed
241
    vlc_object_release( s );
Laurent Aimar's avatar
Laurent Aimar committed
242 243
}

244
#undef stream_UrlNew
245
/****************************************************************************
246
 * stream_UrlNew: create a stream from a access
247
 ****************************************************************************/
248
stream_t *stream_UrlNew( vlc_object_t *p_parent, const char *psz_url )
249
{
250 251
    const char *psz_access, *psz_demux;
    char *psz_path;
252 253
    access_t *p_access;
    stream_t *p_res;
254

255 256
    if( !psz_url )
        return NULL;
257

258 259 260
    char psz_dup[strlen( psz_url ) + 1];
    strcpy( psz_dup, psz_url );
    input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_dup );
261

262 263 264 265
    /* Get a weak link to the parent input */
    /* FIXME: This should probably be removed in favor of a NULL input. */
    input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_parent, VLC_OBJECT_INPUT, FIND_PARENT );
    
266
    /* Now try a real access */
267 268 269 270
    p_access = access_New( p_parent, p_input, psz_access, psz_demux, psz_path );

    if(p_input)
        vlc_object_release((vlc_object_t*)p_input);
271 272 273 274 275 276

    if( p_access == NULL )
    {
        msg_Err( p_parent, "no suitable access module for `%s'", psz_url );
        return NULL;
    }
277

278
    if( !( p_res = stream_AccessNew( p_access, NULL ) ) )
279
    {
280
        access_Delete( p_access );
281
        return NULL;
282
    }
283 284 285

    p_res->pf_destroy = UStreamDestroy;
    return p_res;
286 287
}

288
stream_t *stream_AccessNew( access_t *p_access, char **ppsz_list )
289
{
Laurent Aimar's avatar
Laurent Aimar committed
290
    stream_t *s = stream_CommonNew( VLC_OBJECT(p_access) );
291 292
    stream_sys_t *p_sys;

293 294 295
    if( !s )
        return NULL;

296
    s->p_input = p_access->p_input;
297
    s->psz_path = strdup( p_access->psz_location );
298
    s->p_sys = p_sys = malloc( sizeof( *p_sys ) );
299
    if( !s->psz_path || !s->p_sys )
300
    {
Laurent Aimar's avatar
Laurent Aimar committed
301
        stream_CommonDelete( s );
302 303
        return NULL;
    }
304 305 306 307 308 309

    /* Attach it now, needed for b_die */
    vlc_object_attach( s, p_access );

    s->pf_read   = NULL;    /* Set up later */
    s->pf_peek   = NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
310
    s->pf_control = AStreamControl;
311
    s->pf_destroy = AStreamDestroy;
312 313 314

    /* Common field */
    p_sys->p_access = p_access;
315
    if( p_access->pf_block )
316
        p_sys->method = STREAM_METHOD_BLOCK;
317
    else
318
        p_sys->method = STREAM_METHOD_STREAM;
319

320 321 322
    p_sys->i_pos = p_access->info.i_pos;

    /* Stats */
323
    access_Control( p_access, ACCESS_CAN_FASTSEEK, &p_sys->stat.b_fastseek );
324 325 326 327 328 329
    p_sys->stat.i_bytes = 0;
    p_sys->stat.i_read_time = 0;
    p_sys->stat.i_read_count = 0;
    p_sys->stat.i_seek_count = 0;
    p_sys->stat.i_seek_time = 0;

330
    TAB_INIT( p_sys->i_list, p_sys->list );
331
    p_sys->i_list_index = 0;
332
    p_sys->p_list_access = NULL;
333 334

    /* Get the additional list of inputs if any (for concatenation) */
335
    if( ppsz_list && ppsz_list[0] )
336
    {
337 338
        access_entry_t *p_entry = malloc( sizeof(*p_entry) );
        if( !p_entry )
339
            goto error;
340 341

        p_entry->i_size = p_access->info.i_size;
342
        p_entry->psz_path = strdup( p_access->psz_location );
343
        if( !p_entry->psz_path )
344 345 346 347
        {
            free( p_entry );
            goto error;
        }
348
        p_sys->p_list_access = p_access;
349
        TAB_APPEND( p_sys->i_list, p_sys->list, p_entry );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
350
        msg_Dbg( p_access, "adding file `%s', (%"PRId64" bytes)",
351 352
                 p_entry->psz_path, p_access->info.i_size );

353
        for( int i = 0; ppsz_list[i] != NULL; i++ )
354
        {
355 356 357 358 359
            char *psz_name = strdup( ppsz_list[i] );

            if( !psz_name )
                break;

360
            access_t *p_tmp = access_New( p_access, p_access->p_input,
361 362 363
                                          p_access->psz_access, "", psz_name );
            if( !p_tmp )
                continue;
364

365 366 367 368 369
            msg_Dbg( p_access, "adding file `%s', (%"PRId64" bytes)",
                     psz_name, p_tmp->info.i_size );

            p_entry = malloc( sizeof(*p_entry) );
            if( p_entry )
370 371 372 373 374
            {
                p_entry->i_size = p_tmp->info.i_size;
                p_entry->psz_path = psz_name;
                TAB_APPEND( p_sys->i_list, p_sys->list, p_entry );
            }
375
            access_Delete( p_tmp );
376 377 378
        }
    }

379 380 381 382
    /* Peek */
    p_sys->i_peek = 0;
    p_sys->p_peek = NULL;

383
    if( p_sys->method == STREAM_METHOD_BLOCK )
384
    {
385
        msg_Dbg( s, "Using AStream*Block" );
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
        s->pf_read = AStreamReadBlock;
        s->pf_peek = AStreamPeekBlock;

        /* Init all fields of p_sys->block */
        p_sys->block.i_start = p_sys->i_pos;
        p_sys->block.i_offset = 0;
        p_sys->block.p_current = NULL;
        p_sys->block.i_size = 0;
        p_sys->block.p_first = NULL;
        p_sys->block.pp_last = &p_sys->block.p_first;

        /* Do the prebuffering */
        AStreamPrebufferBlock( s );

        if( p_sys->block.i_size <= 0 )
        {
            msg_Err( s, "cannot pre fill buffer" );
            goto error;
        }
    }
406
    else
407
    {
408 409
        int i;

410 411
        assert( p_sys->method == STREAM_METHOD_STREAM );

412 413
        msg_Dbg( s, "Using AStream*Stream" );

414 415 416 417 418 419 420
        s->pf_read = AStreamReadStream;
        s->pf_peek = AStreamPeekStream;

        /* Allocate/Setup our tracks */
        p_sys->stream.i_offset = 0;
        p_sys->stream.i_tk     = 0;
        p_sys->stream.p_buffer = malloc( STREAM_CACHE_SIZE );
421 422
        if( p_sys->stream.p_buffer == NULL )
            goto error;
423
        p_sys->stream.i_used   = 0;
424 425 426 427
        p_sys->stream.i_read_size = STREAM_READ_ATONCE;
#if STREAM_READ_ATONCE < 256
#   error "Invalid STREAM_READ_ATONCE value"
#endif
428 429 430 431 432 433 434 435 436 437 438 439

        for( i = 0; i < STREAM_CACHE_TRACK; i++ )
        {
            p_sys->stream.tk[i].i_date  = 0;
            p_sys->stream.tk[i].i_start = p_sys->i_pos;
            p_sys->stream.tk[i].i_end   = p_sys->i_pos;
            p_sys->stream.tk[i].p_buffer=
                &p_sys->stream.p_buffer[i * STREAM_CACHE_TRACK_SIZE];
        }

        /* Do the prebuffering */
        AStreamPrebufferStream( s );
440

441 442 443 444 445
        if( p_sys->stream.tk[p_sys->stream.i_tk].i_end <= 0 )
        {
            msg_Err( s, "cannot pre fill buffer" );
            goto error;
        }
446
    }
447

448
    return s;
449 450

error:
451
    if( p_sys->method == STREAM_METHOD_BLOCK )
452 453 454 455 456 457 458
    {
        /* Nothing yet */
    }
    else
    {
        free( p_sys->stream.p_buffer );
    }
459 460 461
    while( p_sys->i_list > 0 )
        free( p_sys->list[--(p_sys->i_list)] );
    free( p_sys->list );
462
    free( s->p_sys );
Laurent Aimar's avatar
Laurent Aimar committed
463
    stream_CommonDelete( s );
464
    return NULL;
465 466
}

467
/****************************************************************************
468
 * AStreamDestroy:
469
 ****************************************************************************/
470
static void AStreamDestroy( stream_t *s )
471
{
472 473
    stream_sys_t *p_sys = s->p_sys;

474
    if( p_sys->method == STREAM_METHOD_BLOCK )
475 476 477
        block_ChainRelease( p_sys->block.p_first );
    else
        free( p_sys->stream.p_buffer );
478

479
    free( p_sys->p_peek );
480 481

    if( p_sys->p_list_access && p_sys->p_list_access != p_sys->p_access )
482
        access_Delete( p_sys->p_list_access );
483 484

    while( p_sys->i_list-- )
485
    {
486 487
        free( p_sys->list[p_sys->i_list]->psz_path );
        free( p_sys->list[p_sys->i_list] );
488 489
    }

490 491 492
    free( p_sys->list );
    free( p_sys );

Laurent Aimar's avatar
Laurent Aimar committed
493
    stream_CommonDelete( s );
494 495
}

496 497
static void UStreamDestroy( stream_t *s )
{
498
    access_t *p_access = (access_t *)s->p_parent;
499
    AStreamDestroy( s );
500
    access_Delete( p_access );
501 502
}

503
/****************************************************************************
504
 * AStreamControlReset:
505
 ****************************************************************************/
506
static void AStreamControlReset( stream_t *s )
507 508 509 510 511
{
    stream_sys_t *p_sys = s->p_sys;

    p_sys->i_pos = p_sys->p_access->info.i_pos;

512
    if( p_sys->method == STREAM_METHOD_BLOCK )
513 514 515 516 517 518 519 520 521 522 523 524 525 526
    {
        block_ChainRelease( p_sys->block.p_first );

        /* Init all fields of p_sys->block */
        p_sys->block.i_start = p_sys->i_pos;
        p_sys->block.i_offset = 0;
        p_sys->block.p_current = NULL;
        p_sys->block.i_size = 0;
        p_sys->block.p_first = NULL;
        p_sys->block.pp_last = &p_sys->block.p_first;

        /* Do the prebuffering */
        AStreamPrebufferBlock( s );
    }
527
    else
528 529 530
    {
        int i;

531 532
        assert( p_sys->method == STREAM_METHOD_STREAM );

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
        /* Setup our tracks */
        p_sys->stream.i_offset = 0;
        p_sys->stream.i_tk     = 0;
        p_sys->stream.i_used   = 0;

        for( i = 0; i < STREAM_CACHE_TRACK; i++ )
        {
            p_sys->stream.tk[i].i_date  = 0;
            p_sys->stream.tk[i].i_start = p_sys->i_pos;
            p_sys->stream.tk[i].i_end   = p_sys->i_pos;
        }

        /* Do the prebuffering */
        AStreamPrebufferStream( s );
    }
}
549

550
/****************************************************************************
551
 * AStreamControlUpdate:
552
 ****************************************************************************/
553
static void AStreamControlUpdate( stream_t *s )
554 555
{
    stream_sys_t *p_sys = s->p_sys;
556

557
    p_sys->i_pos = p_sys->p_access->info.i_pos;
558 559 560 561 562 563 564 565 566

    if( p_sys->i_list )
    {
        int i;
        for( i = 0; i < p_sys->i_list_index; i++ )
        {
            p_sys->i_pos += p_sys->list[i]->i_size;
        }
    }
567 568
}

569
/****************************************************************************
570
 * AStreamControl:
571
 ****************************************************************************/
572
static int AStreamControl( stream_t *s, int i_query, va_list args )
573
{
574 575
    stream_sys_t *p_sys = s->p_sys;
    access_t     *p_access = p_sys->p_access;
576

577 578 579
    bool     *p_bool;
    uint64_t *pi_64, i_64;
    int      i_int;
580 581 582 583

    switch( i_query )
    {
        case STREAM_GET_SIZE:
584
            pi_64 = va_arg( args, uint64_t * );
585 586 587 588 589 590 591 592
            if( s->p_sys->i_list )
            {
                int i;
                *pi_64 = 0;
                for( i = 0; i < s->p_sys->i_list; i++ )
                    *pi_64 += s->p_sys->list[i]->i_size;
                break;
            }
593 594
            *pi_64 = p_access->info.i_size;
            break;
595 596

        case STREAM_CAN_SEEK:
597
            p_bool = (bool*)va_arg( args, bool * );
598
            access_Control( p_access, ACCESS_CAN_SEEK, p_bool );
599
            break;
600 601

        case STREAM_CAN_FASTSEEK:
602
            p_bool = (bool*)va_arg( args, bool * );
603
            access_Control( p_access, ACCESS_CAN_FASTSEEK, p_bool );
604
            break;
605 606

        case STREAM_GET_POSITION:
607
            pi_64 = va_arg( args, uint64_t * );
608 609
            *pi_64 = p_sys->i_pos;
            break;
610 611

        case STREAM_SET_POSITION:
612
            i_64 = va_arg( args, uint64_t );
613 614 615
            switch( p_sys->method )
            {
            case STREAM_METHOD_BLOCK:
616
                return AStreamSeekBlock( s, i_64 );
617
            case STREAM_METHOD_STREAM:
618
                return AStreamSeekStream( s, i_64 );
619 620 621 622
            default:
                assert(0);
                return VLC_EGENERIC;
            }
623

624
        case STREAM_CONTROL_ACCESS:
625
        {
626
            i_int = (int) va_arg( args, int );
627 628
            if( i_int != ACCESS_SET_PRIVATE_ID_STATE &&
                i_int != ACCESS_SET_PRIVATE_ID_CA &&
629 630 631
                i_int != ACCESS_GET_PRIVATE_ID_STATE &&
                i_int != ACCESS_SET_TITLE &&
                i_int != ACCESS_SET_SEEKPOINT )
632 633 634 635 636
            {
                msg_Err( s, "Hey, what are you thinking ?"
                            "DON'T USE STREAM_CONTROL_ACCESS !!!" );
                return VLC_EGENERIC;
            }
637 638 639 640 641 642 643 644 645
            int i_ret = access_vaControl( p_access, i_int, args );
            if( i_int == ACCESS_SET_TITLE || i_int == ACCESS_SET_SEEKPOINT )
                AStreamControlReset( s );
            return i_ret;
        }

        case STREAM_UPDATE_SIZE:
            AStreamControlUpdate( s );
            return VLC_SUCCESS;
646

647
        case STREAM_GET_CONTENT_TYPE:
648
            return access_Control( p_access, ACCESS_GET_CONTENT_TYPE,
649
                                    va_arg( args, char ** ) );
650
        case STREAM_SET_RECORD_STATE:
651 652 653 654
        default:
            msg_Err( s, "invalid stream_vaControl query=0x%x", i_query );
            return VLC_EGENERIC;
    }
655
    return VLC_SUCCESS;
656 657
}

658
/****************************************************************************
659
 * Method 1:
660
 ****************************************************************************/
661
static void AStreamPrebufferBlock( stream_t *s )
662
{
663
    stream_sys_t *p_sys = s->p_sys;
664

665 666
    int64_t i_first = 0;
    int64_t i_start;
667

668 669 670
    msg_Dbg( s, "pre buffering" );
    i_start = mdate();
    for( ;; )
671
    {
672
        const int64_t i_date = mdate();
673
        bool b_eof;
674
        block_t *b;
675

676
        if( s->b_die || p_sys->block.i_size > STREAM_CACHE_PREBUFFER_SIZE )
677 678 679 680 681 682
        {
            int64_t i_byterate;

            /* Update stat */
            p_sys->stat.i_bytes = p_sys->block.i_size;
            p_sys->stat.i_read_time = i_date - i_start;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
683
            i_byterate = ( INT64_C(1000000) * p_sys->stat.i_bytes ) /
684
                         (p_sys->stat.i_read_time + 1);
685

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
686
            msg_Dbg( s, "prebuffering done %"PRId64" bytes in %"PRId64"s - "
687
                     "%"PRId64" KiB/s",
688
                     p_sys->stat.i_bytes,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
689
                     p_sys->stat.i_read_time / INT64_C(1000000),
690 691 692
                     i_byterate / 1024 );
            break;
        }
693

694
        /* Fetch a block */
695
        if( ( b = AReadBlock( s, &b_eof ) ) == NULL )
696
        {
697 698
            if( b_eof )
                break;
699
            continue;
700
        }
701

702 703 704 705 706 707
        while( b )
        {
            /* Append the block */
            p_sys->block.i_size += b->i_buffer;
            *p_sys->block.pp_last = b;
            p_sys->block.pp_last = &b->p_next;
708

709 710 711
            p_sys->stat.i_read_count++;
            b = b->p_next;
        }
712 713 714 715

        if( i_first == 0 )
        {
            i_first = mdate();
716 717
            msg_Dbg( s, "received first data after %d ms",
                     (int)((i_first-i_start)/1000) );
718
        }
719 720
    }

721 722 723 724 725
    p_sys->block.p_current = p_sys->block.p_first;
}

static int AStreamRefillBlock( stream_t *s );

726
static int AStreamReadBlock( stream_t *s, void *p_read, unsigned int i_read )
727 728 729
{
    stream_sys_t *p_sys = s->p_sys;

730
    uint8_t *p_data = p_read;
731
    unsigned int i_data = 0;
732 733 734 735 736

    /* It means EOF */
    if( p_sys->block.p_current == NULL )
        return 0;

737
    if( p_data == NULL )
Damien Fouilleul's avatar
 
Damien Fouilleul committed
738
    {
739
        /* seek within this stream if possible, else use plain old read and discard */
Damien Fouilleul's avatar
 
Damien Fouilleul committed
740 741
        stream_sys_t *p_sys = s->p_sys;
        access_t     *p_access = p_sys->p_access;
742
        bool   b_aseek;
743
        access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
Damien Fouilleul's avatar
 
Damien Fouilleul committed
744 745 746
        if( b_aseek )
            return AStreamSeekBlock( s, p_sys->i_pos + i_read ) ? 0 : i_read;
    }
747

748
    while( i_data < i_read )
749
    {
750 751
        int i_current =
            p_sys->block.p_current->i_buffer - p_sys->block.i_offset;
752
        unsigned int i_copy = __MIN( (unsigned int)__MAX(i_current,0), i_read - i_data);
Gildas Bazin's avatar
 
Gildas Bazin committed
753

754
        /* Copy data */
755 756 757
        if( p_data )
        {
            memcpy( p_data,
758 759
                    &p_sys->block.p_current->p_buffer[p_sys->block.i_offset],
                    i_copy );
760 761
            p_data += i_copy;
        }
762
        i_data += i_copy;
763

764 765 766 767 768 769 770 771 772
        p_sys->block.i_offset += i_copy;
        if( p_sys->block.i_offset >= p_sys->block.p_current->i_buffer )
        {
            /* Current block is now empty, switch to next */
            if( p_sys->block.p_current )
            {
                p_sys->block.i_offset = 0;
                p_sys->block.p_current = p_sys->block.p_current->p_next;
            }
Rafaël Carré's avatar
Rafaël Carré committed
773 774
            /*Get a new block if needed */
            if( !p_sys->block.p_current && AStreamRefillBlock( s ) )
Gildas Bazin's avatar
Gildas Bazin committed
775 776 777
            {
                break;
            }
778 779 780
        }
    }

781 782
    p_sys->i_pos += i_data;
    return i_data;
783
}
Gildas Bazin's avatar
Gildas Bazin committed
784

785
static int AStreamPeekBlock( stream_t *s, const uint8_t **pp_peek, unsigned int i_read )
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
786
{
787 788
    stream_sys_t *p_sys = s->p_sys;
    uint8_t *p_data;
789
    unsigned int i_data = 0;
790
    block_t *b;
791
    unsigned int i_offset;
792

793
    if( p_sys->block.p_current == NULL ) return 0; /* EOF */
794 795 796 797 798 799 800 801 802 803 804

    /* We can directly give a pointer over our buffer */
    if( i_read <= p_sys->block.p_current->i_buffer - p_sys->block.i_offset )
    {
        *pp_peek = &p_sys->block.p_current->p_buffer[p_sys->block.i_offset];
        return i_read;
    }

    /* We need to create a local copy */
    if( p_sys->i_peek < i_read )
    {
805
        p_sys->p_peek = realloc_or_free( p_sys->p_peek, i_read );
806 807 808 809 810
        if( !p_sys->p_peek )
        {
            p_sys->i_peek = 0;
            return 0;
        }
811 812 813 814
        p_sys->i_peek = i_read;
    }

    /* Fill enough data */
815 816
    while( p_sys->block.i_size - (p_sys->i_pos - p_sys->block.i_start)
           < i_read )
817 818 819
    {
        block_t **pp_last = p_sys->block.pp_last;

820
        if( AStreamRefillBlock( s ) ) break;
821 822

        /* Our buffer are probably filled enough, don't try anymore */
823
        if( pp_last == p_sys->block.pp_last ) break;
824 825 826 827 828 829 830 831 832
    }

    /* Copy what we have */
    b = p_sys->block.p_current;
    i_offset = p_sys->block.i_offset;
    p_data = p_sys->p_peek;

    while( b && i_data < i_read )
    {
833
        unsigned int i_current = __MAX(b->i_buffer - i_offset,0);
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
        int i_copy = __MIN( i_current, i_read - i_data );

        memcpy( p_data, &b->p_buffer[i_offset], i_copy );
        i_data += i_copy;
        p_data += i_copy;
        i_offset += i_copy;

        if( i_offset >= b->i_buffer )
        {
            i_offset = 0;
            b = b->p_next;
        }
    }

    *pp_peek = p_sys->p_peek;
    return i_data;
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
850
}
851

852
static int AStreamSeekBlock( stream_t *s, uint64_t i_pos )
853
{
854 855 856
    stream_sys_t *p_sys = s->p_sys;
    access_t   *p_access = p_sys->p_access;
    int64_t    i_offset = i_pos - p_sys->block.i_start;
857
    bool b_seek;
858

859
    /* We already have thoses data, just update p_current/i_offset */
860
    if( i_offset >= 0 && (uint64_t)i_offset < p_sys->block.i_size )
861 862 863
    {
        block_t *b = p_sys->block.p_first;
        int i_current = 0;
864

865
        while( i_current + b->i_buffer < (uint64_t)i_offset )
866 867 868 869
        {
            i_current += b->i_buffer;
            b = b->p_next;
        }
870

871 872
        p_sys->block.p_current = b;
        p_sys->block.i_offset = i_offset - i_current;
873

874
        p_sys->i_pos = i_pos;
875

876 877
        return VLC_SUCCESS;
    }
878

879 880
    /* We may need to seek or to read data */
    if( i_offset < 0 )
881
    {
882
        bool b_aseek;
883
        access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
884 885 886

        if( !b_aseek )
        {
887
            msg_Err( s, "backward seeking impossible (access not seekable)" );
888 889 890
            return VLC_EGENERIC;
        }

891
        b_seek = true;
892
    }
893 894
    else
    {
895
        bool b_aseek, b_aseekfast;
896

897 898
        access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
        access_Control( p_access, ACCESS_CAN_FASTSEEK, &b_aseekfast );
899 900 901

        if( !b_aseek )
        {
902
            b_seek = false;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
903
            msg_Warn( s, "%"PRId64" bytes need to be skipped "
904
                      "(access non seekable)",
905 906 907 908 909 910 911 912 913 914 915 916 917
                      i_offset - p_sys->block.i_size );
        }
        else
        {
            int64_t i_skip = i_offset - p_sys->block.i_size;

            /* Avg bytes per packets */
            int i_avg = p_sys->stat.i_bytes / p_sys->stat.i_read_count;
            /* TODO compute a seek cost instead of fixed threshold */
            int i_th = b_aseekfast ? 1 : 5;

            if( i_skip <= i_th * i_avg &&
                i_skip < STREAM_CACHE_SIZE )
918
                b_seek = false;
919
            else
920
                b_seek = true;
921

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
922
            msg_Dbg( s, "b_seek=%d th*avg=%d skip=%"PRId64,
923 924
                     b_seek, i_th*i_avg, i_skip );
        }
925 926
    }

927 928 929 930 931
    if( b_seek )
    {
        int64_t i_start, i_end;
        /* Do the access seek */
        i_start = mdate();
932
        if( ASeek( s, i_pos ) ) return VLC_EGENERIC;
933
        i_end = mdate();
934

935 936 937 938 939 940 941 942 943 944
        /* Release data */
        block_ChainRelease( p_sys->block.p_first );

        /* Reinit */
        p_sys->block.i_start = p_sys->i_pos = i_pos;
        p_sys->block.i_offset = 0;
        p_sys->block.p_current = NULL;
        p_sys->block.i_size = 0;
        p_sys->block.p_first = NULL;
        p_sys->block.pp_last = &p_sys->block.p_first;
945

946 947 948
        /* Refill a block */
        if( AStreamRefillBlock( s ) )
            return VLC_EGENERIC;
949

950 951 952 953 954 955
        /* Update stat */
        p_sys->stat.i_seek_time += i_end - i_start;
        p_sys->stat.i_seek_count++;
        return VLC_SUCCESS;
    }
    else
956
    {
957
        do
958
        {
959
            while( p_sys->block.p_current &&
960
                   p_sys->i_pos + p_sys->block.p_current->i_buffer - p_sys->block.i_offset <= i_pos )
961
            {
962
                p_sys->i_pos += p_sys->block.p_current->i_buffer - p_sys->block.i_offset;
963
                p_sys->block.p_current = p_sys->block.p_current->p_next;
964
                p_sys->block.i_offset = 0;
965
            }
966 967 968 969 970
            if( !p_sys->block.p_current && AStreamRefillBlock( s ) )
            {
                if( p_sys->i_pos != i_pos )
                    return VLC_EGENERIC;
            }
971
        }
972
        while( p_sys->block.i_start + p_sys->block.i_size < i_pos );
973

974
        p_sys->block.i_offset += i_pos - p_sys->i_pos;
975
        p_sys->i_pos = i_pos;
976

977
        return VLC_SUCCESS;
978 979
    }

980
    return VLC_EGENERIC;
981 982
}

983
static int AStreamRefillBlock( stream_t *s )
984
{
985 986 987 988 989 990 991 992
    stream_sys_t *p_sys = s->p_sys;
    block_t      *b;

    /* Release data */
    while( p_sys->block.i_size >= STREAM_CACHE_SIZE &&
           p_sys->block.p_first != p_sys->block.p_current )
    {
        block_t *b = p_sys->block.p_first;
993

994 995 996
        p_sys->block.i_start += b->i_buffer;
        p_sys->block.i_size  -= b->i_buffer;
        p_sys->block.p_first  = b->p_next;
997

998 999 1000 1001 1002
        block_Release( b );
    }
    if( p_sys->block.i_size >= STREAM_CACHE_SIZE &&
        p_sys->block.p_current == p_sys->block.p_first &&
        p_sys->block.p_current->p_next )    /* At least 2 packets */
1003
    {
1004 1005
        /* Enough data, don't read more */
        return VLC_SUCCESS;
1006 1007
    }

1008
    /* Now read a new block */
1009
    const int64_t i_start = mdate();