httplive.c 39.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*****************************************************************************
 * httplive.c: HTTP Live Streaming stream filter
 *****************************************************************************
 * Copyright (C) 2010 M2X BV
 * $Id$
 *
 * Author: Jean-Paul Saman <jpsaman _AT_ videolan _DOT_ org>
 *
 * 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
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_common.h>
#include <vlc_plugin.h>

#include <assert.h>

#include <vlc_threads.h>
#include <vlc_arrays.h>
#include <vlc_stream.h>
#include <vlc_url.h>

#include <vlc_modules.h>
#include <vlc_access.h>

/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
static int  Open (vlc_object_t *);
static void Close(vlc_object_t *);

vlc_module_begin()
    set_category(CAT_INPUT)
    set_subcategory(SUBCAT_INPUT_STREAM_FILTER)
    set_description(N_("Http Live Streaming stream filter"))
    set_capability("stream_filter", 20)
    set_callbacks(Open, Close)
vlc_module_end()

/*****************************************************************************
 *
 *****************************************************************************/
typedef struct segment_s
{
    int         sequence;   /* unique sequence number */
    int         length;     /* segment duration (ms) */
    uint64_t    size;       /* segment size in bytes */

    vlc_url_t   url;
    vlc_mutex_t lock;
    block_t     *data;      /* data */
} segment_t;

typedef struct hls_stream_s
{
    int         id;         /* program id */
    int         version;    /* protocol version should be 1 */
    int         sequence;   /* media sequence number */
    int         duration;   /* maximum duration per segment (ms) */
78
79
    uint64_t    bandwidth;  /* bandwidth usage of segments (kbps)*/

80
    vlc_array_t *segments;  /* list of segments */
81
    int         segment;    /* current segment downloading */
82
83

    vlc_url_t   url;        /* uri to m3u8 */
84
    vlc_mutex_t lock;
85
86
87
88
89
90
91
92
93
    bool        b_cache;    /* allow caching */
} hls_stream_t;

typedef struct
{
    VLC_COMMON_MEMBERS

    /* */
    int         current;    /* current hls_stream  */
94
    vlc_array_t *hls_stream;/* bandwidth adaptation */
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

    stream_t    *s;
} hls_thread_t;

struct stream_sys_t
{
    access_t    *p_access;  /* HTTP access input */

    /* */
    hls_thread_t *thread;
    vlc_array_t *hls_stream;/* bandwidth adaptation */

    /* Playback */
    uint64_t    offset;     /* current offset in media */
    int         current;    /* current hls_stream  */
    int         segment;    /* current segment for playback */

    /* Playlist */
    mtime_t     last;       /* playlist last loaded */
    mtime_t     wakeup;     /* next reload time */
    int         tries;      /* times it was not changed */

    /* state */
    bool        b_cache;    /* can cache files */
    bool        b_meta;     /* meta playlist */
    bool        b_live;     /* live stream? or vod? */
    bool        b_error;    /* parsing error */
};

/****************************************************************************
 * Local prototypes
 ****************************************************************************/
static int  Read   (stream_t *, void *p_read, unsigned int i_read);
static int  Peek   (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
static int  Control(stream_t *, int i_query, va_list);

static int  AccessOpen(stream_t *s, vlc_url_t *url);
static void AccessClose(stream_t *s);
static char *AccessReadLine(access_t *p_access, uint8_t *psz_tmp, size_t i_len);
static int AccessDownload(stream_t *s, segment_t *segment);

static void* hls_Thread(vlc_object_t *);
static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls);

static void segment_Free(segment_t *segment);

/****************************************************************************
 *
 ****************************************************************************/
static bool isHTTPLiveStreaming(stream_t *s)
{
    const uint8_t *peek, *peek_end;

    int64_t i_size = stream_Peek(s->p_source, &peek, 46);
    if (i_size < 1)
        return false;

    if (strncasecmp((const char*)peek, "#EXTM3U", 7) != 0)
        return false;

    /* Parse stream and search for
     * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
     * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
    peek_end = peek + i_size;
    while(peek <= peek_end)
    {
        if (*peek == '#')
        {
            if (strncasecmp((const char*)peek, "#EXT-X-TARGETDURATION", 21) == 0)
                return true;
            else if (strncasecmp((const char*)peek, "#EXT-X-STREAM-INF", 17) == 0)
                return true;
        }
        peek++;
    };

    return false;
}

/* HTTP Live Streaming */
static hls_stream_t *hls_New(vlc_array_t *hls_stream, int id, uint64_t bw, char *uri)
{
    hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
    if (hls == NULL) return NULL;

    hls->id = id;
    hls->bandwidth = bw;
182
    hls->duration = -1;/* unknown */
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
    hls->sequence = 0; /* default is 0 */
    hls->version = 1;  /* default protocol version */
    hls->segment = 0;
    hls->b_cache = true;
    vlc_UrlParse(&hls->url, uri, 0);
    hls->segments = vlc_array_new();
    vlc_array_append(hls_stream, hls);
    vlc_mutex_init(&hls->lock);
    return hls;
}

static void hls_Free(hls_stream_t *hls)
{
    vlc_mutex_destroy(&hls->lock);

    if (hls->segments)
    {
        for (int n = 0; n < vlc_array_count(hls->segments); n++)
        {
            segment_t *segment = (segment_t *)vlc_array_item_at_index(hls->segments, n);
            if (segment) segment_Free(segment);
        }
        vlc_array_destroy(hls->segments);
    }

    vlc_UrlClean(&hls->url);
    free(hls);
    hls = NULL;
}

static hls_stream_t *hls_Get(vlc_array_t *hls_stream, int wanted)
{
    int count = vlc_array_count(hls_stream);
    if (count <= 0)
        return NULL;
    if ((wanted < 0) || (wanted >= count))
        return NULL;
    return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
}

static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
{
    return (hls_stream_t*) hls_Get(hls_stream, 0);
}

static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
{
    int count = vlc_array_count(hls_stream);
    if (count <= 0)
        return NULL;
    count--;
    return (hls_stream_t *) hls_Get(hls_stream, count);
}

/* Segment */
static segment_t *segment_New(hls_stream_t* hls, int duration, char *uri)
{
    segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
    if (segment == NULL)
        return NULL;

    segment->length = duration; /* seconds */
    segment->size = 0; /* bytes */
    segment->sequence = 0;
    vlc_UrlParse(&segment->url, uri, 0);
    segment->data = NULL;
    vlc_array_append(hls->segments, segment);
    vlc_mutex_init(&segment->lock);
    return segment;
}

static void segment_Free(segment_t *segment)
{
    vlc_mutex_destroy(&segment->lock);

    vlc_UrlClean(&segment->url);
    if (segment->data)
        block_Release(segment->data);
    free(segment);
    segment = NULL;
}

static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted)
{
    assert(hls);

    int count = vlc_array_count(hls->segments);
    if (count <= 0)
        return NULL;
    if ((wanted < 0) || (wanted >= count))
        return NULL;
    return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
}

/* Parsing */
static char *parse_Attributes(const char *line, const char *attr)
{
    char *p;
    char *begin = (char *) line;
    char *end = begin + strlen(line);

    /* Find start of attributes */
    if ((p = strchr(begin, ':' )) == NULL)
        return NULL;

    begin = p;
    do
    {
        if (strncasecmp(begin, attr, strlen(attr)) == 0)
        {
            /* <attr>=<value>[,]* */
            p = strchr(begin, ',');
            begin += strlen(attr) + 1;
            if (begin >= end)
                return NULL;
            if (p == NULL) /* last attribute */
                return strndup(begin, end - begin);
            /* copy till ',' */
            return strndup(begin, p - begin);
        }
        begin++;
    } while(begin < end);

    return NULL;
}

309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
static char *relative_URI(stream_t *s, const char *uri, char *psz_uri)
{
    char *p = strchr(uri, ':');
    if (p != NULL)
        return NULL;

    char *tmp;
    if (asprintf(&tmp,"%s://%s", s->psz_access, s->psz_path) < 0)
    {
        s->p_sys->b_error = true;
        return NULL;
    }

    char *psz_path = strrchr(tmp, '/');
    if (psz_path) *psz_path = '\0';

    vlc_url_t url;
    vlc_UrlParse(&url, tmp, 0);
    if (asprintf(&psz_uri, "%s://%s%s/%s",
           url.psz_protocol, url.psz_host, url.psz_path, uri) < 0)
    {
        free(tmp);
        vlc_UrlClean(&url);
        s->p_sys->b_error = true;
        return NULL;
    }
    vlc_UrlClean(&url);
    free(tmp);
    return psz_uri;
}

340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
static void parse_SegmentInformation(stream_t *s, hls_stream_t *hls, char *p_read, char *uri)
{
    stream_sys_t *p_sys = s->p_sys;

    assert(hls);

    int duration;
    int ret = sscanf(p_read, "#EXTINF:%d,", &duration);
    if (ret != 1)
    {
        msg_Err(s, "expected #EXTINF:<s>,");
        p_sys->b_error = true;
        return;
    }

355
356
357
    char *psz_uri = NULL;
    psz_uri = relative_URI(s, uri, psz_uri);

358
    vlc_mutex_lock(&hls->lock);
359
    segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
360
361
362
363
364
365
366
367
368
369
    if (segment)
        segment->sequence = hls->sequence + vlc_array_count(hls->segments);
    if (duration > hls->duration)
    {
        msg_Err(s, "EXTINF:%d duration is larger then EXT-X-TARGETDURATION:%d",
                duration, hls->duration);
    }
    vlc_mutex_unlock(&hls->lock);
}

370
static void parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
371
372
373
{
    stream_sys_t *p_sys = s->p_sys;

374
375
    assert(hls);

376
    int duration = -1;
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
    if (ret != 1)
    {
        msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
        p_sys->b_error = true;
        return;
    }

    hls->duration = duration; /* seconds */
}

static void parse_StreamInformation(stream_t *s, char *p_read, char *uri)
{
    stream_sys_t *p_sys = s->p_sys;

392
393
    int id;
    uint64_t bw;
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
    char *attr;

    attr = parse_Attributes(p_read, "PROGRAM-ID");
    if (attr == NULL)
    {
        msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
        p_sys->b_error = true;
        return;
    }
    id = atol(attr);
    free(attr);

    attr = parse_Attributes(p_read, "BANDWIDTH");
    if (attr == NULL)
    {
        msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
        p_sys->b_error = true;
        return;
    }
    bw = atoll(attr);
    free(attr);

    if (bw == 0)
    {
        msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
        p_sys->b_error = true;
        return;
    }

423
    msg_Info(s, "bandwidth adaption detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
424

425
426
427
428
    char *psz_uri = NULL;
    psz_uri = relative_URI(s, uri, psz_uri);

    hls_stream_t *hls = hls_New(p_sys->hls_stream, id, bw, psz_uri ? psz_uri : uri);
429
430
431
432
    if (hls == NULL)
        p_sys->b_error = true;
}

433
static void parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
434
435
436
{
    stream_sys_t *p_sys = s->p_sys;

437
438
    assert(hls);

439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
    int sequence;
    int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
    if (ret != 1)
    {
        msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
        p_sys->b_error = true;
        return;
    }

    if (hls->sequence > 0)
        msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist");

    hls->sequence = sequence;
}

454
static void parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
455
456
457
{
    stream_sys_t *p_sys = s->p_sys;

458
459
    assert(hls);

460
461
462
463
464
465
466
467
468
469
470
    /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
    char *attr;
    attr = parse_Attributes(p_read, "METHOD");
    if (attr == NULL)
    {
        msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
        p_sys->b_error = true;
    }
    else if (strncasecmp(attr, "NONE", 4) == 0)
    {
        char *uri = parse_Attributes(p_read, "URI");
471
        if (uri != NULL)
472
        {
473
            msg_Err(s, "#EXT-X-KEY: URI not expected");
474
            p_sys->b_error = true;
475
476
477
478
479
480
481
482
483
484
485
        }
        free(uri);
        /* IV is only supported in version 2 and above */
        if (hls->version >= 2)
        {
            char *iv = parse_Attributes(p_read, "IV");
            if (iv != NULL)
            {
                msg_Err(s, "#EXT-X-KEY: IV not expected");
                p_sys->b_error = true;
            }
486
487
488
489
490
491
492
493
494
495
496
            free(iv);
        }
    }
    else
    {
        msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
        p_sys->b_error = true;
    }
    free(attr);
}

497
static void parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
498
{
499
    VLC_UNUSED(hls);
500
501
502
    msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
}

503
static void parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
504
505
506
{
    stream_sys_t *p_sys = s->p_sys;

507
508
    assert(hls);

509
510
511
512
513
514
515
516
517
518
519
520
    char answer[4] = "\0";
    int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
    if (ret != 1)
    {
        msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
        p_sys->b_error = true;
        return;
    }

    hls->b_cache = (strncmp(answer, "NO", 2) != 0);
}

521
static void parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
522
523
524
{
    stream_sys_t *p_sys = s->p_sys;

525
526
    assert(hls);

527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
    int version;
    int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
    if (ret != 1)
    {
        msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
        p_sys->b_error = true;
        return;
    }

    /* Check version */
    hls->version = version;
    if (hls->version != 1)
    {
        msg_Err(s, "#EXT-X-VERSION should be version 1 iso %d", version);
        p_sys->b_error = true;
    }
}

545
static void parse_EndList(stream_t *s, hls_stream_t *hls)
546
547
548
{
    stream_sys_t *p_sys = s->p_sys;

549
550
551
    assert(hls);

    p_sys->b_live = false;
552
553
554
    msg_Info(s, "video on demand (vod) mode");
}

555
static void parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
556
{
557
558
    assert(hls);

559
560
561
562
    /* FIXME: Do we need to act on discontinuity ?? */
    msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
}

563
static void parse_M3U8ExtLine(stream_t *s, hls_stream_t *hls, char *line)
564
565
566
567
{
    if (*line == '#')
    {
        if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
568
            parse_TargetDuration(s, hls, line);
569
        else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 22) == 0)
570
            parse_MediaSequence(s, hls, line);
571
        else if (strncmp(line, "#EXT-X-KEY", 11) == 0)
572
            parse_Key(s, hls, line);
573
        else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 25) == 0)
574
            parse_ProgramDateTime(s, hls, line);
575
        else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 17) == 0)
576
            parse_AllowCache(s, hls, line);
577
        else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
578
            parse_Discontinuity(s, hls, line);
579
        else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
580
            parse_Version(s, hls, line);
581
        else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
582
            parse_EndList(s, hls);
583
584
585
586
587
588
589
590
591
592
    }
}

#define HTTPLIVE_MAX_LINE 4096
static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls)
{
    stream_sys_t *p_sys = s->p_sys;

    /* Download new playlist file from server */
    if (AccessOpen(s, &hls->url) != VLC_SUCCESS)
593
        return VLC_EGENERIC;
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637

    /* Parse the rest of the reply */
    uint8_t *tmp = calloc(1, HTTPLIVE_MAX_LINE);
    if (tmp == NULL)
    {
        AccessClose(s);
        return VLC_ENOMEM;
    }

    char *line = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
    if (strncmp(line, "#EXTM3U", 7) != 0)
    {
        msg_Err(s, "missing #EXTM3U tag");
        goto error;
    }
    free(line);
    line = NULL;

    for( ; ; )
    {
        line = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
        if (line == NULL)
        {
            msg_Dbg(s, "end of data");
            break;
        }

        if (!vlc_object_alive(s))
            goto error;

        /* some more checks for actual data */
        if (strncmp(line, "#EXTINF", 7) == 0)
        {
            char *uri = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
            if (uri == NULL)
                p_sys->b_error = true;
            else
            {
                parse_SegmentInformation(s, hls, line, uri);
                free(uri);
            }
        }
        else
        {
638
            parse_M3U8ExtLine(s, hls, line);
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
        }

        /* Error during m3u8 parsing abort */
        if (p_sys->b_error)
            goto error;

        free(line);
    }

    free(line);
    free(tmp);
    AccessClose(s);
    return VLC_SUCCESS;

error:
    free(line);
    free(tmp);
    AccessClose(s);
    return VLC_EGENERIC;
}
#undef HTTPLIVE_MAX_LINE

/* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
 * document defines the following new tags: EXT-X-TARGETDURATION,
 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
 * and EXT-X-VERSION.
 */
static int parse_HTTPLiveStreaming(stream_t *s)
{
    stream_sys_t *p_sys = s->p_sys;
    char *p_read, *p_begin, *p_end;

    assert(p_sys->hls_stream);

    p_begin = p_read = stream_ReadLine(s->p_source);
    if (!p_begin)
        return VLC_ENOMEM;

    /* */
    int i_len = strlen(p_begin);
    p_end = p_read + i_len;

    if (strncmp(p_read, "#EXTM3U", 7) != 0)
    {
        msg_Err(s, "missing #EXTM3U tag .. aborting");
        free(p_begin);
        return VLC_EGENERIC;
    }

    do {
        free(p_begin);

        if (p_sys->b_error)
            return VLC_EGENERIC;

        /* Next line */
        p_begin = stream_ReadLine(s->p_source);
        if (p_begin == NULL)
            break;

        i_len = strlen(p_begin);
        p_read = p_begin;
        p_end = p_read + i_len;

        if (strncmp(p_read, "#EXT-X-STREAM-INF", 17) == 0)
        {
            p_sys->b_meta = true;
            char *uri = stream_ReadLine(s->p_source);
            if (uri == NULL)
                p_sys->b_error = true;
            else
            {
                parse_StreamInformation(s, p_read, uri);
                free(uri);
            }
        }
        else if (strncmp(p_read, "#EXTINF", 7) == 0)
        {
            char *uri = stream_ReadLine(s->p_source);
            if (uri == NULL)
                p_sys->b_error = true;
            else
            {
                hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
                if (hls)
                    parse_SegmentInformation(s, hls, p_read, uri);
                else
                    p_sys->b_error = true;
                free(uri);
            }
        }
        else
        {
733
734
            hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
            if (hls == NULL)
735
            {
736
                if (!p_sys->b_meta)
737
738
739
740
741
742
743
744
745
746
                {
                    hls = hls_New(p_sys->hls_stream, -1, -1, NULL);
                    if (hls == NULL)
                    {
                        p_sys->b_error = true;
                        return VLC_ENOMEM;
                    }
                }
            }
            /* Parse M3U8 Ext Line */
747
            parse_M3U8ExtLine(s, hls, p_read);
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
        }
    } while(p_read < p_end);

    free(p_begin);

    /* */
    int count = vlc_array_count(p_sys->hls_stream);
    for (int n = 0; n < count; n++)
    {
        hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
        if (hls == NULL) break;

        /* Is it a meta playlist? */
        if (p_sys->b_meta)
        {
763
            msg_Dbg(s, "parsing %s", hls->url.psz_path);
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
            if (get_HTTPLivePlaylist(s, hls) != VLC_SUCCESS)
            {
                msg_Err(s, "could not parse playlist file from meta index." );
                return VLC_EGENERIC;
            }
        }

        if (p_sys->b_live)
        {
            /* There should at least be 3 segments of hls->duration */
            int ok = 0;
            int num = vlc_array_count(hls->segments);
            for (int i = 0; i < num; i++)
            {
                segment_t *segment = segment_GetSegment(hls, i);
                if (segment && segment->length >= hls->duration)
                    ok++;
            }
            if (ok < 3)
            {
                msg_Err(s, "cannot start live playback at this time, try again later.");
                return VLC_EGENERIC;
            }
            /* Determine next time to reload playlist */
            p_sys->wakeup = p_sys->last + (hls->duration * 2 * (mtime_t)1000000);
        }
        /* Can we cache files after playback */
        p_sys->b_cache = hls->b_cache;
    }

    return VLC_SUCCESS;
}

/****************************************************************************
 * hls_Thread
 ****************************************************************************/
static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
{
    stream_sys_t *p_sys = s->p_sys;
    int candidate = -1;
    uint64_t bw = *bandwidth;

    msg_Dbg(s, "bandwidth (bits/s) %"PRIu64, bw * 1000); /* bits / s */

    int count = vlc_array_count(p_sys->hls_stream);
    for (int n = 0; n < count; n++)
    {
        /* Select best bandwidth match */
        hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
        if (hls == NULL) break;

        /* only consider streams with the same PROGRAM-ID */
        if (hls->id == progid)
        {
            if (bw <= hls->bandwidth)
            {
                *bandwidth = hls->bandwidth;
                candidate = n; /* possible candidate */
            }
        }
    }
    return candidate;
}

static int Download(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
{
    assert(hls);
    assert(segment);

    vlc_mutex_lock(&segment->lock);
    if (segment->data != NULL)
    {
        /* Segment already downloaded */
        vlc_mutex_unlock(&segment->lock);
        return VLC_SUCCESS;
    }

    mtime_t start = mdate();
    if (AccessDownload(s, segment) != VLC_SUCCESS)
    {
        vlc_mutex_unlock(&segment->lock);
        return VLC_EGENERIC;
    }
    mtime_t duration = mdate() - start;

    vlc_mutex_unlock(&segment->lock);

    uint64_t bw = (segment->size * 8) / (duration/1000);      /* bits / ms */
    if (hls->bandwidth != bw)
    {
        int newstream = BandwidthAdaptation(s, hls->id, &bw);
        if ((newstream > 0) && (newstream != *cur_stream))
        {
            msg_Info(s, "switching to %s bandwidth (%"PRIu64") stream",
                     (hls->bandwidth <= bw) ? "faster" : "lower", bw);
            *cur_stream = newstream;
        }
    }
    return VLC_SUCCESS;
}

static void* hls_Thread(vlc_object_t *p_this)
{
    hls_thread_t *client = (hls_thread_t *) p_this;
    stream_t *s = client->s;
    stream_sys_t *p_sys = s->p_sys;

    int canc = vlc_savecancel();

    while (vlc_object_alive(p_this))
    {
        hls_stream_t *hls = hls_Get(client->hls_stream, client->current);
        assert(hls);

        vlc_mutex_lock(&hls->lock);
        segment_t *segment = segment_GetSegment(hls, hls->segment);
        if (segment) hls->segment++;
        vlc_mutex_unlock(&hls->lock);

        /* Is there a new segment to process? */
        if (segment == NULL)
        {
            if (!p_sys->b_live) break;
            mwait(p_sys->wakeup);
        }
        else if (Download(client->s, hls, segment, &client->current) != VLC_SUCCESS)
        {
            if (!p_sys->b_live) break;
        }

        /* FIXME: Reread the m3u8 index file */
        if (p_sys->b_live)
        {
            double wait = 1;
            mtime_t now = mdate();
            if (now >= p_sys->wakeup)
            {
#if 0
                /** FIXME: Implement m3u8 playlist reloading */
                if (!hls_ReloadPlaylist(client->s))
                {
                    /* No change in playlist, then backoff */
                    p_sys->tries++;
                    if (p_sys->tries == 1) wait = 0.5;
                    else if (p_sys->tries == 2) wait = 1;
                    else if (p_sys->tries >= 3) wait = 3;
                }
#endif
                /* determine next time to update playlist */
                p_sys->last = now;
                p_sys->wakeup = now + ((mtime_t)(hls->duration * wait) * (mtime_t)1000000);
            }
        }
    }

    vlc_restorecancel(canc);
    return NULL;
}

static int Prefetch(stream_t *s)
{
    stream_sys_t *p_sys = s->p_sys;
    int current;

again:
    current = p_sys->current;

    hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
    if (hls == NULL)
        return VLC_EGENERIC;

    segment_t *segment = segment_GetSegment(hls, hls->segment);
    if (segment == NULL )
        return VLC_EGENERIC;

    if (Download(s, hls, segment, &p_sys->current) != VLC_SUCCESS)
        return VLC_EGENERIC;

    /* Bandwidth changed? */
    if (current != p_sys->current)
        goto again;

    return VLC_SUCCESS;
}

/****************************************************************************
 * Access
 ****************************************************************************/
static int AccessOpen(stream_t *s, vlc_url_t *url)
{
    stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;

    if ((url->psz_protocol == NULL) ||
        (url->psz_path == NULL))
        return VLC_EGENERIC;

    p_sys->p_access = vlc_object_create(s, sizeof(access_t));
961
962
963
964
965
966
    if (p_sys->p_access == NULL)
        return VLC_ENOMEM;

    p_sys->p_access->psz_access = strdup(url->psz_protocol);
    p_sys->p_access->psz_filepath = strdup(url->psz_path);
    if (url->psz_password || url->psz_username)
967
    {
968
969
970
        if (asprintf(&p_sys->p_access->psz_location, "%s:%s@%s%s",
                     url->psz_username, url->psz_password,
                     url->psz_host, url->psz_path) < 0)
971
        {
972
973
            msg_Err(s, "creating http access module");
            goto fail;
974
        }
975
976
977
978
979
    }
    else
    {
        if (asprintf(&p_sys->p_access->psz_location, "%s%s",
                     url->psz_host, url->psz_path) < 0)
980
        {
981
            msg_Err(s, "creating http access module");
982
983
984
            goto fail;
        }
    }
985
986
987
988
989
990
991
992
993
994
    vlc_object_attach(p_sys->p_access, s);
    p_sys->p_access->p_module =
        module_need(p_sys->p_access, "access", "http", true);
    if (p_sys->p_access->p_module == NULL)
    {
        msg_Err(s, "could not load http access module");
        goto fail;
    }

    return VLC_SUCCESS;
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089

fail:
    vlc_object_release(p_sys->p_access);
    p_sys->p_access = NULL;
    return VLC_EGENERIC;
}

static void AccessClose(stream_t *s)
{
    stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;

    if (p_sys->p_access)
    {
        vlc_object_kill(p_sys->p_access);
        free(p_sys->p_access->psz_access);
        if (p_sys->p_access->p_module)
            module_unneed(p_sys->p_access,
                          p_sys->p_access->p_module);

        vlc_object_release(p_sys->p_access);
        p_sys->p_access = NULL;
    }
}

static char *AccessReadLine(access_t *p_access, uint8_t *psz_tmp, size_t i_len)
{
    char *line = NULL;
    char *begin = (char *)psz_tmp;

    assert(psz_tmp);

    int skip = strlen(begin);
    ssize_t len = p_access->pf_read(p_access, psz_tmp + skip, i_len - skip);
    if (len < 0) return NULL;
    if ((len == 0) && (skip == 0))
        return NULL;

    char *p = begin;
    char *end = p + len + skip;

    while (p < end)
    {
        if (*p == '\n')
            break;

        p++;
    }

    /* EOL */
    line = calloc(1, p - begin + 1);
    if (line == NULL)
        return NULL;
    /* copy line excluding \n */
    line = strndup(begin, p - begin);

    p++;
    if (p < end)
    {
        psz_tmp = memmove(begin, p, end - p);
        psz_tmp[end - p] = '\0';
    }
    else memset(psz_tmp, 0, i_len);

    return line;
}

static int AccessDownload(stream_t *s, segment_t *segment)
{
    stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;

    assert(segment);

    /* Download new playlist file from server */
    if (AccessOpen(s, &segment->url) != VLC_SUCCESS)
        return VLC_EGENERIC;

    segment->size = p_sys->p_access->info.i_size;
    assert(segment->size > 0);

    segment->data = block_Alloc(segment->size);
    if (segment->data == NULL)
    {
        AccessClose(s);
        return VLC_ENOMEM;
    }

    assert(segment->data->i_buffer == segment->size);

    ssize_t length = 0, curlen = 0;
    do
    {
        if (p_sys->p_access->info.i_size > segment->size)
        {
            msg_Dbg(s, "size changed %"PRIu64, segment->size);
            segment->data = block_Realloc(segment->data, 0, p_sys->p_access->info.i_size);
1090
1091
1092
1093
1094
1095
            if (segment->data == NULL)
            {
                AccessClose(s);
                return VLC_ENOMEM;
            }
            segment->size = p_sys->p_access->info.i_size;
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
            assert(segment->data->i_buffer == segment->size);
        }
        length = p_sys->p_access->pf_read(p_sys->p_access,
                    segment->data->p_buffer + curlen, segment->size - curlen);
        if ((length <= 0) || ((uint64_t)length >= segment->size))
            break;
        curlen += length;
    } while (vlc_object_alive(s));

    AccessClose(s);
    return VLC_SUCCESS;
}

/****************************************************************************
 * Open
 ****************************************************************************/
static int Open(vlc_object_t *p_this)
{
    stream_t *s = (stream_t*)p_this;
    stream_sys_t *p_sys;

    if (!isHTTPLiveStreaming(s))
        return VLC_EGENERIC;

    msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);

    /* */
    s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
    if (p_sys == NULL)
        return VLC_ENOMEM;

    p_sys->b_live = true;
    p_sys->b_meta = false;

    p_sys->hls_stream = vlc_array_new();
    if (p_sys->hls_stream == NULL)
    {
        free(p_sys);
        return VLC_ENOMEM;
    }

    /* */
    s->pf_read = Read;
    s->pf_peek = Peek;
    s->pf_control = Control;

    /* Select first segment to play */
    p_sys->last = mdate();
    if (parse_HTTPLiveStreaming(s) != VLC_SUCCESS)
    {
        goto fail;
    }

    /* */
    p_sys->segment = 0;
    p_sys->current = 0;

    if (Prefetch(s) != VLC_SUCCESS)
    {
        msg_Err(s, "fetching first segment.");
        goto fail;
    }

    p_sys->thread = vlc_object_create(s, sizeof(hls_thread_t));
    if( p_sys->thread == NULL )
    {
        msg_Err(s, "creating HTTP Live Streaming client thread");
        goto fail;
    }

    p_sys->thread->hls_stream = p_sys->hls_stream;
    p_sys->thread->current = p_sys->current;
    p_sys->thread->s = s;

    if (vlc_thread_create(p_sys->thread, "HTTP Live Streaming client",
                          hls_Thread, VLC_THREAD_PRIORITY_INPUT))
    {
        goto fail;
    }

    vlc_object_attach(p_sys->thread, s);

    return VLC_SUCCESS;

fail:
    Close(p_this);
    return VLC_EGENERIC;
}

/****************************************************************************
 * Close
 ****************************************************************************/
static void Close(vlc_object_t *p_this)
{
    stream_t *s = (stream_t*)p_this;
    stream_sys_t *p_sys = s->p_sys;

    assert(p_sys->hls_stream);

    /* */
    if (p_sys->thread)
    {
        vlc_object_kill(p_sys->thread);
        vlc_thread_join(p_sys->thread);
        vlc_object_release(p_sys->thread);
    }

    /* Free hls streams */
    for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
    {
        hls_stream_t *hls;
        hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
        if (hls) hls_Free(hls);
    }
    vlc_array_destroy(p_sys->hls_stream);

    /* */
    free(p_sys);
}

/****************************************************************************
 * Stream filters functions
 ****************************************************************************/
static segment_t *NextSegment(stream_t *s)
{
    stream_sys_t *p_sys = s->p_sys;
    segment_t *segment;

    do
    {
        /* Is the next segment ready */
        hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
        if (hls == NULL) return NULL;

        segment = segment_GetSegment(hls, p_sys->segment);
        if (segment == NULL) return NULL;

        /* This segment is ready? */
        if (segment->data != NULL)
            return segment;

        /* Was the stream changed to another bitrate? */
        if (!p_sys->b_meta) return NULL;

        if (p_sys->current != p_sys->thread->current)
        {
            /* YES it was */
            p_sys->current = p_sys->thread->current;
        }
        else
        {
#if 0
            /* Not downloaded yet, do it here */
            if (Download(s, hls, segment, &p_sys->current) != VLC_SUCCESS)
                return segment;
            else
#endif
                return NULL;
        }
    }
    while(vlc_object_alive(s));

    return segment;
}

static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
{
    stream_sys_t *p_sys = s->p_sys;
    ssize_t copied = 0;

    do
    {
        /* Determine next segment to read. If this is a meta playlist and
         * bandwidth conditions changed, then the stream might have switched
         * to another bandwidth. */
        segment_t *segment = NextSegment(s);
        if (segment == NULL)
            break;

        vlc_mutex_lock(&segment->lock);
        if (segment->data->i_buffer == 0)
        {
            if (!p_sys->b_cache)
            {
                block_Release(segment->data);
                segment->data = NULL;
            }
            msg_Dbg(s, "switching to segment %d", p_sys->segment);
            p_sys->segment++;
            vlc_mutex_unlock(&segment->lock);
            continue;
        }

        ssize_t len = -1;
        if (i_read <= segment->data->i_buffer)
            len = i_read;
        else if (i_read > segment->data->i_buffer)
            len = segment->data->i_buffer;

        if (len > 0)
        {
            memcpy(p_read + copied, segment->data->p_buffer, len);
            segment->data->i_buffer -= len;
            segment->data->p_buffer += len;
            copied += len;
            i_read -= len;
        }
        vlc_mutex_unlock(&segment->lock);

    } while ((i_read > 0) && vlc_object_alive(s));

    return copied;
}

static int Read(stream_t *s, void *buffer, unsigned int i_read)
{
    stream_sys_t *p_sys = s->p_sys;
    ssize_t length = 0;

    assert(p_sys->hls_stream);

    if (buffer == NULL)
    {
        /* caller skips data, get big enough buffer */
        msg_Warn(s, "buffer is NULL (allocate %d)", i_read);
        buffer = calloc(1, i_read);
        if (buffer == NULL)
            return 0; /* NO MEMORY left*/
    }

    length = hls_Read(s, (uint8_t*) buffer, i_read);
    if (length < 0)
        return 0;

    p_sys->offset += length;
    return length;
}

static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
{
    stream_sys_t *p_sys = s->p_sys;
    size_t curlen = 0;

    hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
    if (hls == NULL)
        return 0;

    int peek_segment = p_sys->segment;
    do
    {
        segment_t *segment = segment_GetSegment(hls, peek_segment);
        if (segment == NULL) return 0;

        vlc_mutex_lock(&segment->lock);
        if (i_peek < segment->data->i_buffer)
        {
            *pp_peek = segment->data->p_buffer;
            curlen += i_peek;
        }
        else
        {
             peek_segment++;
        }
        vlc_mutex_unlock(&segment->lock);
    } while ((curlen < i_peek) && vlc_object_alive(s));

    return curlen;
}

static bool hls_MaySeek(stream_t *s)
{
    stream_sys_t *p_sys = s->p_sys;

    if (p_sys->hls_stream == NULL)
        return false;

    hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
    if (hls == NULL) return false;

    if (p_sys->b_live)
    {
       int count = vlc_array_count(hls->segments);
       vlc_mutex_lock(&hls->lock);
       bool may_seek = (hls->segment < count - 2);
       vlc_mutex_unlock(&hls->lock);
       return may_seek;
    }
    return true;
}

static uint64_t GetStreamSize(stream_t *s)
{
    stream_sys_t *p_sys = s->p_sys;

    if (p_sys->b_live)
        return 0;

    hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
    if (hls == NULL) return 0;

    /* FIXME: Stream size is not entirely exacts at this point */
    uint64_t length = 0UL;
    int count = vlc_array_count(hls->segments);
    for (int n = 0; n < count; n++)
    {
        segment_t *segment = segment_GetSegment(hls, n);
        if (segment)
        {
            length += (segment->size > 0) ? segment->size :
                        (segment->length * hls->bandwidth);
        }
    }
    return length;
}

static int segment_Seek(stream_t *s, uint64_t pos)
{
    stream_sys_t *p_sys = s->p_sys;

    /* Find the right offset */
    hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
    if (hls == NULL)
        return VLC_EGENERIC;

    uint64_t length = 0;
    bool b_found = false;

    int count = vlc_array_count(hls->segments);
    for (int n = 0; n < count; n++)
    {
        /* FIXME: Seeking in segments not dowloaded is not supported. */
        if (n >= hls->segment)
        {
            msg_Err(s, "seeking in segment not downloaded yet.");
            return VLC_EGENERIC;
        }

        segment_t *segment = vlc_array_item_at_index(hls->segments, n);
        if (segment == NULL)
            return VLC_EGENERIC;

        vlc_mutex_lock(&segment->lock);
        length += segment->size;
        uint64_t size = segment->size -segment->data->i_buffer;
        if (size > 0)
        {
            segment->data->i_buffer += size;
            segment->data->p_buffer -= size;
        }

        if (!b_found && (pos <= length))
        {
            uint64_t used = length - pos;
            segment->data->i_buffer -= used;
            segment->data->p_buffer += used;

            count = p_sys->segment;
            p_sys->segment = n;
            b_found = true;
        }
        vlc_mutex_unlock(&segment->lock);
    }
    return VLC_SUCCESS;
}

static int Control(stream_t *s, int i_query, va_list args)
{
    stream_sys_t *p_sys = s->p_sys;

    switch (i_query)
    {
        case STREAM_CAN_SEEK:
        case STREAM_CAN_FASTSEEK:
            *(va_arg (args, bool *)) = hls_MaySeek(s);
            break;
        case STREAM_GET_POSITION:
            *(va_arg (args, uint64_t *)) = p_sys->offset;
            break;
        case STREAM_SET_POSITION:
            if (hls_MaySeek(s))
            {
                uint64_t pos = (uint64_t)va_arg(args, uint64_t);
                if (segment_Seek(s, pos) == VLC_SUCCESS)
                {
                    p_sys->offset = pos;
                    break;
                }
            }
            return VLC_EGENERIC;
        case STREAM_GET_SIZE:
            *(va_arg (args, uint64_t *)) = GetStreamSize(s);
            break;
        default:
            return VLC_EGENERIC;
    }
    return VLC_SUCCESS;
}