stream.c 56.6 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 33
#include <vlc_strings.h>
#include <vlc_osd.h>
34
#include <vlc_charset.h>
35
#include <vlc_memory.h>
36

37
#include <libvlc.h>
38

39
#include "access.h"
40 41 42
#include "stream.h"

#include "input_internal.h"
43

44
// #define STREAM_DEBUG 1
45

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

/* Two methods:
 *  - using pf_block
 *      One linked list of data read
 *  - using pf_read
 *      More complex scheme using mutliple track to avoid seeking
58 59 60
 *  - 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)).
61 62
 */

63 64
/* How many tracks we have, currently only used for stream mode */
#ifdef OPTIMIZE_MEMORY
65 66 67 68 69 70 71 72 73
#   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

74 75 76 77
/* 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)
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

/* 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
 *        - ?
 */
97
#define STREAM_READ_ATONCE 1024
98 99 100
#define STREAM_CACHE_TRACK_SIZE (STREAM_CACHE_SIZE/STREAM_CACHE_TRACK)

typedef struct
101
{
102
    int64_t i_date;
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
103

104 105
    uint64_t i_start;
    uint64_t i_end;
106 107

    uint8_t *p_buffer;
108

109 110
} stream_track_t;

111 112 113
typedef struct
{
    char     *psz_path;
114
    uint64_t  i_size;
115 116 117

} access_entry_t;

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

124 125 126 127
struct stream_sys_t
{
    access_t    *p_access;

128
    stream_read_method_t   method;    /* method to use */
129

130
    uint64_t     i_pos;      /* Current reading offset */
131 132 133

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

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

143 144 145 146
    } block;

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

        /* Global buffer */
        uint8_t *p_buffer;

        /* */
156 157
        unsigned i_used; /* Used since last read */
        unsigned i_read_size;
158

159 160 161
    } stream;

    /* Peek temporary buffer */
162
    unsigned int i_peek;
163 164 165 166
    uint8_t *p_peek;

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

170
        /* Stat about reading data */
171 172 173
        uint64_t i_read_count;
        uint64_t i_bytes;
        uint64_t i_read_time;
174

175
        /* Stat about seek */
176 177
        unsigned i_seek_count;
        uint64_t i_seek_time;
178

179
    } stat;
180

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

188
/* Method 1: */
189 190
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 );
191
static int  AStreamSeekBlock( stream_t *s, uint64_t i_pos );
192
static void AStreamPrebufferBlock( stream_t *s );
193
static block_t *AReadBlock( stream_t *s, bool *pb_eof );
194

195
/* Method 2 */
196 197
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 );
198
static int  AStreamSeekStream( stream_t *s, uint64_t i_pos );
199
static void AStreamPrebufferStream( stream_t *s );
200
static int  AReadStream( stream_t *s, void *p_read, unsigned int i_read );
201

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

Laurent Aimar's avatar
Laurent Aimar committed
208 209 210 211 212
/****************************************************************************
 * stream_CommonNew: create an empty stream structure
 ****************************************************************************/
stream_t *stream_CommonNew( vlc_object_t *p_obj )
{
Laurent Aimar's avatar
Laurent Aimar committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    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;
}
233

Laurent Aimar's avatar
Laurent Aimar committed
234 235 236 237 238 239 240 241
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 );
    }
242
    free( s->psz_path );
Laurent Aimar's avatar
Laurent Aimar committed
243
    vlc_object_release( s );
Laurent Aimar's avatar
Laurent Aimar committed
244 245
}

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

256 257
    if( !psz_url )
        return NULL;
258

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

263 264 265 266
    /* 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 );
    
267
    /* Now try a real access */
268 269 270 271
    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);
272 273 274 275 276 277

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

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

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

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

294 295 296
    if( !s )
        return NULL;

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

    /* 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
311
    s->pf_control = AStreamControl;
312
    s->pf_destroy = AStreamDestroy;
313 314 315

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

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

    /* Stats */
324
    access_Control( p_access, ACCESS_CAN_FASTSEEK, &p_sys->stat.b_fastseek );
325 326 327 328 329 330
    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;

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

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

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

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

            if( !psz_name )
                break;

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

366 367 368 369 370
            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 )
371 372 373 374 375
            {
                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 );
            }
376
            access_Delete( p_tmp );
377 378 379
        }
    }

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

384
    if( p_sys->method == STREAM_METHOD_BLOCK )
385
    {
386
        msg_Dbg( s, "Using AStream*Block" );
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
        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;
        }
    }
407
    else
408
    {
409 410
        int i;

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

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

415 416 417 418 419 420 421
        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 );
422 423
        if( p_sys->stream.p_buffer == NULL )
            goto error;
424
        p_sys->stream.i_used   = 0;
425 426 427 428
        p_sys->stream.i_read_size = STREAM_READ_ATONCE;
#if STREAM_READ_ATONCE < 256
#   error "Invalid STREAM_READ_ATONCE value"
#endif
429 430 431 432 433 434 435 436 437 438 439 440

        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 );
441

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

449
    return s;
450 451

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

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

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

480
    free( p_sys->p_peek );
481 482

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

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

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

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

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

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

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

513
    if( p_sys->method == STREAM_METHOD_BLOCK )
514 515 516 517 518 519 520 521 522 523 524 525 526 527
    {
        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 );
    }
528
    else
529 530 531
    {
        int i;

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

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
        /* 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 );
    }
}
550

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

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

    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;
        }
    }
568 569
}

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

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

    switch( i_query )
    {
        case STREAM_GET_SIZE:
585
            pi_64 = va_arg( args, uint64_t * );
586 587 588 589 590 591 592 593
            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;
            }
594 595
            *pi_64 = p_access->info.i_size;
            break;
596 597

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

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

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

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

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

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

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

666 667
    int64_t i_first = 0;
    int64_t i_start;
668

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

677
        if( s->b_die || p_sys->block.i_size > STREAM_CACHE_PREBUFFER_SIZE )
678 679 680 681 682 683
        {
            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
684
            i_byterate = ( INT64_C(1000000) * p_sys->stat.i_bytes ) /
685
                         (p_sys->stat.i_read_time + 1);
686

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

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

703 704 705 706 707 708
        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;
709

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

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

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

static int AStreamRefillBlock( stream_t *s );

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

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

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

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

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

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

765 766 767 768 769 770 771 772 773
        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
774 775
            /*Get a new block if needed */
            if( !p_sys->block.p_current && AStreamRefillBlock( s ) )
Gildas Bazin's avatar
Gildas Bazin committed
776 777 778
            {
                break;
            }
779 780 781
        }
    }

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

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

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

    /* 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 )
    {
806
        p_sys->p_peek = realloc_or_free( p_sys->p_peek, i_read );
807 808 809 810 811
        if( !p_sys->p_peek )
        {
            p_sys->i_peek = 0;
            return 0;
        }
812 813 814 815
        p_sys->i_peek = i_read;
    }

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

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

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

    /* 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 )
    {
834
        unsigned int i_current = __MAX(b->i_buffer - i_offset,0);
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
        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
851
}
852

853
static int AStreamSeekBlock( stream_t *s, uint64_t i_pos )
854
{
855 856 857
    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;
858
    bool b_seek;
859

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

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

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

875
        p_sys->i_pos = i_pos;
876

877 878
        return VLC_SUCCESS;
    }
879

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

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

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

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

        if( !b_aseek )
        {
903
            b_seek = false;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
904
            msg_Warn( s, "%"PRId64" bytes need to be skipped "
905
                      "(access non seekable)",
906 907 908 909 910 911 912 913 914 915 916 917 918
                      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 )
919
                b_seek = false;
920
            else
921
                b_seek = true;
922

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

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

936 937 938 939 940 941 942 943 944 945
        /* 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;
946

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

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

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

978
        return VLC_SUCCESS;
979 980
    }

981
    return VLC_EGENERIC;
982 983
}

984
static int AStreamRefillBlock( stream_t *s )
985
{
986 987 988 989 990 991 992 993
    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;
994

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

999 1000 1001 1002 1003
        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 */
1004
    {
1005 1006
        /* Enough data, don't read more */
        return VLC_SUCCESS;
1007 1008
    }

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