stream.c 57.2 KB
Newer Older
1 2 3
/*****************************************************************************
 * stream.c
 *****************************************************************************
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
4
 * Copyright (C) 1999-2004 VLC authors and VideoLAN
Gildas Bazin's avatar
Gildas Bazin committed
5
 * $Id$
6 7 8
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
9 10 11
 * 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
12 13 14 15
 * (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
LGPL  
Jean-Baptiste Kempf committed
16 17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
18
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
19 20 21
 * 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.
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 )
{
211
    stream_t *s = (stream_t *)vlc_custom_create( p_obj, sizeof(*s), "stream" );
Laurent Aimar's avatar
Laurent Aimar committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229

    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;
}
230

Laurent Aimar's avatar
Laurent Aimar committed
231 232 233 234 235 236 237 238
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 );
    }
239
    free( s->psz_access );
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
    const char *psz_access, *psz_demux, *psz_path, *psz_anchor;
251 252
    access_t *p_access;
    stream_t *p_res;
253

254 255
    if( !psz_url )
        return NULL;
256

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

261
    /* Now try a real access */
262
    p_access = access_New( p_parent, NULL, psz_access, psz_demux, psz_path );
263 264 265 266 267
    if( p_access == NULL )
    {
        msg_Err( p_parent, "no suitable access module for `%s'", psz_url );
        return NULL;
    }
268

269
    if( !( p_res = stream_AccessNew( p_access, NULL ) ) )
270
    {
271
        access_Delete( p_access );
272
        return NULL;
273
    }
274 275 276

    p_res->pf_destroy = UStreamDestroy;
    return p_res;
277 278
}

279
stream_t *stream_AccessNew( access_t *p_access, char **ppsz_list )
280
{
Laurent Aimar's avatar
Laurent Aimar committed
281
    stream_t *s = stream_CommonNew( VLC_OBJECT(p_access) );
282 283
    stream_sys_t *p_sys;

284 285 286
    if( !s )
        return NULL;

287
    s->p_input = p_access->p_input;
288
    s->psz_access = strdup( p_access->psz_access );
289
    s->psz_path = strdup( p_access->psz_location );
290
    s->p_sys = p_sys = malloc( sizeof( *p_sys ) );
291
    if( !s->psz_access || !s->psz_path || !s->p_sys )
292
    {
Laurent Aimar's avatar
Laurent Aimar committed
293
        stream_CommonDelete( s );
294 295
        return NULL;
    }
296 297 298

    s->pf_read   = NULL;    /* Set up later */
    s->pf_peek   = NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
299
    s->pf_control = AStreamControl;
300
    s->pf_destroy = AStreamDestroy;
301 302 303

    /* Common field */
    p_sys->p_access = p_access;
304
    if( p_access->pf_block )
305
        p_sys->method = STREAM_METHOD_BLOCK;
306
    else
307
        p_sys->method = STREAM_METHOD_STREAM;
308

309 310 311
    p_sys->i_pos = p_access->info.i_pos;

    /* Stats */
312
    access_Control( p_access, ACCESS_CAN_FASTSEEK, &p_sys->stat.b_fastseek );
313 314 315 316 317 318
    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;

319
    TAB_INIT( p_sys->i_list, p_sys->list );
320
    p_sys->i_list_index = 0;
321
    p_sys->p_list_access = NULL;
322 323

    /* Get the additional list of inputs if any (for concatenation) */
324
    if( ppsz_list && ppsz_list[0] )
325
    {
326 327
        access_entry_t *p_entry = malloc( sizeof(*p_entry) );
        if( !p_entry )
328
            goto error;
329 330

        p_entry->i_size = p_access->info.i_size;
331
        p_entry->psz_path = strdup( p_access->psz_location );
332
        if( !p_entry->psz_path )
333 334 335 336
        {
            free( p_entry );
            goto error;
        }
337
        p_sys->p_list_access = p_access;
338
        TAB_APPEND( p_sys->i_list, p_sys->list, p_entry );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
339
        msg_Dbg( p_access, "adding file `%s', (%"PRId64" bytes)",
340 341
                 p_entry->psz_path, p_access->info.i_size );

342
        for( int i = 0; ppsz_list[i] != NULL; i++ )
343
        {
344 345 346 347 348
            char *psz_name = strdup( ppsz_list[i] );

            if( !psz_name )
                break;

349
            access_t *p_tmp = access_New( p_access, p_access->p_input,
350 351 352
                                          p_access->psz_access, "", psz_name );
            if( !p_tmp )
                continue;
353

354 355 356 357 358
            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 )
359 360 361 362 363
            {
                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 );
            }
364
            access_Delete( p_tmp );
365 366 367
        }
    }

368 369 370 371
    /* Peek */
    p_sys->i_peek = 0;
    p_sys->p_peek = NULL;

372
    if( p_sys->method == STREAM_METHOD_BLOCK )
373
    {
374
        msg_Dbg( s, "Using block method for AStream*" );
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        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;
        }
    }
395
    else
396
    {
397 398
        int i;

399 400
        assert( p_sys->method == STREAM_METHOD_STREAM );

401
        msg_Dbg( s, "Using stream method for AStream*" );
402

403 404 405 406 407 408 409
        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 );
410 411
        if( p_sys->stream.p_buffer == NULL )
            goto error;
412
        p_sys->stream.i_used   = 0;
413 414 415 416
        p_sys->stream.i_read_size = STREAM_READ_ATONCE;
#if STREAM_READ_ATONCE < 256
#   error "Invalid STREAM_READ_ATONCE value"
#endif
417 418 419 420 421 422 423 424 425 426 427 428

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

430 431 432 433 434
        if( p_sys->stream.tk[p_sys->stream.i_tk].i_end <= 0 )
        {
            msg_Err( s, "cannot pre fill buffer" );
            goto error;
        }
435
    }
436

437
    return s;
438 439

error:
440
    if( p_sys->method == STREAM_METHOD_BLOCK )
441 442 443 444 445 446 447
    {
        /* Nothing yet */
    }
    else
    {
        free( p_sys->stream.p_buffer );
    }
448 449 450
    while( p_sys->i_list > 0 )
        free( p_sys->list[--(p_sys->i_list)] );
    free( p_sys->list );
451
    free( s->p_sys );
Laurent Aimar's avatar
Laurent Aimar committed
452
    stream_CommonDelete( s );
453
    return NULL;
454 455
}

456
/****************************************************************************
457
 * AStreamDestroy:
458
 ****************************************************************************/
459
static void AStreamDestroy( stream_t *s )
460
{
461 462
    stream_sys_t *p_sys = s->p_sys;

463
    if( p_sys->method == STREAM_METHOD_BLOCK )
464 465 466
        block_ChainRelease( p_sys->block.p_first );
    else
        free( p_sys->stream.p_buffer );
467

468
    free( p_sys->p_peek );
469 470

    if( p_sys->p_list_access && p_sys->p_list_access != p_sys->p_access )
471
        access_Delete( p_sys->p_list_access );
472 473

    while( p_sys->i_list-- )
474
    {
475 476
        free( p_sys->list[p_sys->i_list]->psz_path );
        free( p_sys->list[p_sys->i_list] );
477 478
    }

479 480 481
    free( p_sys->list );
    free( p_sys );

Laurent Aimar's avatar
Laurent Aimar committed
482
    stream_CommonDelete( s );
483 484
}

485 486
static void UStreamDestroy( stream_t *s )
{
487
    access_t *p_access = (access_t *)s->p_parent;
488
    AStreamDestroy( s );
489
    access_Delete( p_access );
490 491
}

492
/****************************************************************************
493
 * AStreamControlReset:
494
 ****************************************************************************/
495
static void AStreamControlReset( stream_t *s )
496 497 498 499 500
{
    stream_sys_t *p_sys = s->p_sys;

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

501
    if( p_sys->method == STREAM_METHOD_BLOCK )
502 503 504 505 506 507 508 509 510 511 512 513 514 515
    {
        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 );
    }
516
    else
517 518 519
    {
        int i;

520 521
        assert( p_sys->method == STREAM_METHOD_STREAM );

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
        /* 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 );
    }
}
538

539
/****************************************************************************
540
 * AStreamControlUpdate:
541
 ****************************************************************************/
542
static void AStreamControlUpdate( stream_t *s )
543 544
{
    stream_sys_t *p_sys = s->p_sys;
545

546
    p_sys->i_pos = p_sys->p_access->info.i_pos;
547 548 549 550 551 552 553 554 555

    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;
        }
    }
556 557
}

558
/****************************************************************************
559
 * AStreamControl:
560
 ****************************************************************************/
561
static int AStreamControl( stream_t *s, int i_query, va_list args )
562
{
563 564
    stream_sys_t *p_sys = s->p_sys;
    access_t     *p_access = p_sys->p_access;
565

566 567 568
    bool     *p_bool;
    uint64_t *pi_64, i_64;
    int      i_int;
569 570 571 572

    switch( i_query )
    {
        case STREAM_GET_SIZE:
573
            pi_64 = va_arg( args, uint64_t * );
574 575 576 577 578 579 580 581
            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;
            }
582 583
            *pi_64 = p_access->info.i_size;
            break;
584 585

        case STREAM_CAN_SEEK:
586
            p_bool = (bool*)va_arg( args, bool * );
587
            access_Control( p_access, ACCESS_CAN_SEEK, p_bool );
588
            break;
589 590

        case STREAM_CAN_FASTSEEK:
591
            p_bool = (bool*)va_arg( args, bool * );
592
            access_Control( p_access, ACCESS_CAN_FASTSEEK, p_bool );
593
            break;
594 595

        case STREAM_GET_POSITION:
596
            pi_64 = va_arg( args, uint64_t * );
597 598
            *pi_64 = p_sys->i_pos;
            break;
599 600

        case STREAM_SET_POSITION:
601
            i_64 = va_arg( args, uint64_t );
602 603 604
            switch( p_sys->method )
            {
            case STREAM_METHOD_BLOCK:
605
                return AStreamSeekBlock( s, i_64 );
606
            case STREAM_METHOD_STREAM:
607
                return AStreamSeekStream( s, i_64 );
608 609 610 611
            default:
                assert(0);
                return VLC_EGENERIC;
            }
612

613
        case STREAM_CONTROL_ACCESS:
614
        {
615
            i_int = (int) va_arg( args, int );
616 617
            if( i_int != ACCESS_SET_PRIVATE_ID_STATE &&
                i_int != ACCESS_SET_PRIVATE_ID_CA &&
618 619 620
                i_int != ACCESS_GET_PRIVATE_ID_STATE &&
                i_int != ACCESS_SET_TITLE &&
                i_int != ACCESS_SET_SEEKPOINT )
621 622 623 624 625
            {
                msg_Err( s, "Hey, what are you thinking ?"
                            "DON'T USE STREAM_CONTROL_ACCESS !!!" );
                return VLC_EGENERIC;
            }
626 627 628 629 630 631 632 633 634
            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;
635

636
        case STREAM_GET_CONTENT_TYPE:
637
            return access_Control( p_access, ACCESS_GET_CONTENT_TYPE,
638
                                    va_arg( args, char ** ) );
639
        case STREAM_SET_RECORD_STATE:
640 641 642 643
        default:
            msg_Err( s, "invalid stream_vaControl query=0x%x", i_query );
            return VLC_EGENERIC;
    }
644
    return VLC_SUCCESS;
645 646
}

647
/****************************************************************************
648
 * Method 1:
649
 ****************************************************************************/
650
static void AStreamPrebufferBlock( stream_t *s )
651
{
652
    stream_sys_t *p_sys = s->p_sys;
653

654 655
    int64_t i_first = 0;
    int64_t i_start;
656

657
    msg_Dbg( s, "starting pre-buffering" );
658 659
    i_start = mdate();
    for( ;; )
660
    {
661
        const int64_t i_date = mdate();
662
        bool b_eof;
663
        block_t *b;
664

665
        if( s->b_die || p_sys->block.i_size > STREAM_CACHE_PREBUFFER_SIZE )
666 667 668 669 670 671
        {
            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
672
            i_byterate = ( INT64_C(1000000) * p_sys->stat.i_bytes ) /
673
                         (p_sys->stat.i_read_time + 1);
674

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
675
            msg_Dbg( s, "prebuffering done %"PRId64" bytes in %"PRId64"s - "
676
                     "%"PRId64" KiB/s",
677
                     p_sys->stat.i_bytes,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
678
                     p_sys->stat.i_read_time / INT64_C(1000000),
679 680 681
                     i_byterate / 1024 );
            break;
        }
682

683
        /* Fetch a block */
684
        if( ( b = AReadBlock( s, &b_eof ) ) == NULL )
685
        {
686 687
            if( b_eof )
                break;
688
            continue;
689
        }
690

691 692 693 694 695 696
        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;
697

698 699 700
            p_sys->stat.i_read_count++;
            b = b->p_next;
        }
701 702 703 704

        if( i_first == 0 )
        {
            i_first = mdate();
705 706
            msg_Dbg( s, "received first data after %d ms",
                     (int)((i_first-i_start)/1000) );
707
        }
708 709
    }

710 711 712 713 714
    p_sys->block.p_current = p_sys->block.p_first;
}

static int AStreamRefillBlock( stream_t *s );

715
static int AStreamReadBlock( stream_t *s, void *p_read, unsigned int i_read )
716 717 718
{
    stream_sys_t *p_sys = s->p_sys;

719
    uint8_t *p_data = p_read;
720
    unsigned int i_data = 0;
721 722 723 724 725

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

726
    if( p_data == NULL )
Damien Fouilleul's avatar
 
Damien Fouilleul committed
727
    {
728
        /* seek within this stream if possible, else use plain old read and discard */
Damien Fouilleul's avatar
 
Damien Fouilleul committed
729 730
        stream_sys_t *p_sys = s->p_sys;
        access_t     *p_access = p_sys->p_access;
731
        bool   b_aseek;
732
        access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
Damien Fouilleul's avatar
 
Damien Fouilleul committed
733 734 735
        if( b_aseek )
            return AStreamSeekBlock( s, p_sys->i_pos + i_read ) ? 0 : i_read;
    }
736

737
    while( i_data < i_read )
738
    {
739 740
        int i_current =
            p_sys->block.p_current->i_buffer - p_sys->block.i_offset;
741
        unsigned int i_copy = VLC_CLIP( (unsigned int)i_current, 0, i_read - i_data);
Gildas Bazin's avatar
 
Gildas Bazin committed
742

743
        /* Copy data */
744 745 746
        if( p_data )
        {
            memcpy( p_data,
747 748
                    &p_sys->block.p_current->p_buffer[p_sys->block.i_offset],
                    i_copy );
749 750
            p_data += i_copy;
        }
751
        i_data += i_copy;
752

753 754 755 756 757 758 759 760 761
        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
762 763
            /*Get a new block if needed */
            if( !p_sys->block.p_current && AStreamRefillBlock( s ) )
Gildas Bazin's avatar
Gildas Bazin committed
764 765 766
            {
                break;
            }
767 768 769
        }
    }

770 771
    p_sys->i_pos += i_data;
    return i_data;
772
}
Gildas Bazin's avatar
Gildas Bazin committed
773

774
static int AStreamPeekBlock( stream_t *s, const uint8_t **pp_peek, unsigned int i_read )
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
775
{
776 777
    stream_sys_t *p_sys = s->p_sys;
    uint8_t *p_data;
778
    unsigned int i_data = 0;
779
    block_t *b;
780
    unsigned int i_offset;
781

782
    if( p_sys->block.p_current == NULL ) return 0; /* EOF */
783 784 785 786 787 788 789 790 791 792 793

    /* 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 )
    {
794
        p_sys->p_peek = realloc_or_free( p_sys->p_peek, i_read );
795 796 797 798 799
        if( !p_sys->p_peek )
        {
            p_sys->i_peek = 0;
            return 0;
        }
800 801 802 803
        p_sys->i_peek = i_read;
    }

    /* Fill enough data */
804 805
    while( p_sys->block.i_size - (p_sys->i_pos - p_sys->block.i_start)
           < i_read )
806 807 808
    {
        block_t **pp_last = p_sys->block.pp_last;

809
        if( AStreamRefillBlock( s ) ) break;
810 811

        /* Our buffer are probably filled enough, don't try anymore */
812
        if( pp_last == p_sys->block.pp_last ) break;
813 814 815 816 817 818 819 820 821
    }

    /* 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 )
    {
822
        unsigned int i_current = __MAX(b->i_buffer - i_offset,0);
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
        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
839
}
840

841
static int AStreamSeekBlock( stream_t *s, uint64_t i_pos )
842
{
843 844 845
    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;
846
    bool b_seek;
847

848
    /* We already have thoses data, just update p_current/i_offset */
849
    if( i_offset >= 0 && (uint64_t)i_offset < p_sys->block.i_size )
850 851 852
    {
        block_t *b = p_sys->block.p_first;
        int i_current = 0;
853

854
        while( i_current + b->i_buffer < (uint64_t)i_offset )
855 856 857 858
        {
            i_current += b->i_buffer;
            b = b->p_next;
        }
859

860 861
        p_sys->block.p_current = b;
        p_sys->block.i_offset = i_offset - i_current;
862

863
        p_sys->i_pos = i_pos;
864

865 866
        return VLC_SUCCESS;
    }
867

868 869
    /* We may need to seek or to read data */
    if( i_offset < 0 )
870
    {
871
        bool b_aseek;
872
        access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
873 874 875

        if( !b_aseek )
        {
876
            msg_Err( s, "backward seeking impossible (access not seekable)" );
877 878 879
            return VLC_EGENERIC;
        }

880
        b_seek = true;
881
    }
882 883
    else
    {
884
        bool b_aseek, b_aseekfast;
885

886 887
        access_Control( p_access, ACCESS_CAN_SEEK, &b_aseek );
        access_Control( p_access, ACCESS_CAN_FASTSEEK, &b_aseekfast );
888 889 890

        if( !b_aseek )
        {
891
            b_seek = false;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
892
            msg_Warn( s, "%"PRId64" bytes need to be skipped "
893
                      "(access non seekable)",
894 895 896 897 898 899 900 901 902 903 904 905 906
                      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 )
907
                b_seek = false;
908
            else
909
                b_seek = true;
910

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
911
            msg_Dbg( s, "b_seek=%d th*avg=%d skip=%"PRId64,
912 913
                     b_seek, i_th*i_avg, i_skip );
        }
914 915
    }

916 917 918 919 920
    if( b_seek )
    {
        int64_t i_start, i_end;
        /* Do the access seek */
        i_start = mdate();
921
        if( ASeek( s, i_pos ) ) return VLC_EGENERIC;
922
        i_end = mdate();
923

924 925 926 927 928 929 930 931 932 933
        /* 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;
934

935 936 937
        /* Refill a block */
        if( AStreamRefillBlock( s ) )
            return VLC_EGENERIC;
938

939 940 941 942 943 944
        /* Update stat */
        p_sys->stat.i_seek_time += i_end - i_start;
        p_sys->stat.i_seek_count++;
        return VLC_SUCCESS;
    }
    else
945
    {
946
        do
947
        {
948
            while( p_sys->block.p_current &&
949
                   p_sys->i_pos + p_sys->block.p_current->i_buffer - p_sys->block.i_offset <= i_pos )
950
            {
951
                p_sys->i_pos += p_sys->block.p_current->i_buffer - p_sys->block.i_offset;
952
                p_sys->block.p_current = p_sys->block.p_current->p_next;
953
                p_sys->block.i_offset = 0;
954
            }
955 956 957 958 959
            if( !p_sys->block.p_current && AStreamRefillBlock( s ) )
            {
                if( p_sys->i_pos != i_pos )
                    return VLC_EGENERIC;
            }
960
        }
961
        while( p_sys->block.i_start + p_sys->block.i_size < i_pos );
962

963
        p_sys->block.i_offset += i_pos - p_sys->i_pos;
964
        p_sys->i_pos = i_pos;
965

966
        return VLC_SUCCESS;
967 968
    }

969
    return VLC_EGENERIC;
970 971
}

972
static int AStreamRefillBlock( stream_t *s )
973
{
974 975 976 977 978 979 980 981
    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;
982

983 984 985
        p_sys->block.i_start += b->i_buffer;
        p_sys->block.i_size  -= b->i_buffer;
        p_sys->block.p_first  = b->p_next;
986

987 988 989 990 991
        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 */
Laurent Aimar's avatar