]> git.sesse.net Git - vlc/blob - modules/stream_filter/httplive.c
Fixing HLS on win32.
[vlc] / modules / stream_filter / httplive.c
1 /*****************************************************************************
2  * httplive.c: HTTP Live Streaming stream filter
3  *****************************************************************************
4  * Copyright (C) 2010-2012 M2X BV
5  * $Id$
6  *
7  * Author: Jean-Paul Saman <jpsaman _AT_ videolan _DOT_ org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <limits.h>
32 #include <errno.h>
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36
37 #include <assert.h>
38 #include <gcrypt.h>
39
40 #include <vlc_threads.h>
41 #include <vlc_arrays.h>
42 #include <vlc_stream.h>
43 #include <vlc_memory.h>
44 #include <vlc_gcrypt.h>
45
46 /*****************************************************************************
47  * Module descriptor
48  *****************************************************************************/
49 static int  Open (vlc_object_t *);
50 static void Close(vlc_object_t *);
51
52 vlc_module_begin()
53     set_category(CAT_INPUT)
54     set_subcategory(SUBCAT_INPUT_STREAM_FILTER)
55     set_description(N_("Http Live Streaming stream filter"))
56     set_capability("stream_filter", 20)
57     set_callbacks(Open, Close)
58 vlc_module_end()
59
60 /*****************************************************************************
61  *
62  *****************************************************************************/
63 #define AES_BLOCK_SIZE 16 /* Only support AES-128 */
64 typedef struct segment_s
65 {
66     int         sequence;   /* unique sequence number */
67     int         duration;   /* segment duration (seconds) */
68     uint64_t    size;       /* segment size in bytes */
69     uint64_t    bandwidth;  /* bandwidth usage of segments (bits per second)*/
70
71     char        *url;
72     char       *psz_key_path;         /* url key path */
73     uint8_t     psz_AES_key[16];      /* AES-128 */
74     bool        b_key_loaded;
75
76     vlc_mutex_t lock;
77     block_t     *data;      /* data */
78 } segment_t;
79
80 typedef struct hls_stream_s
81 {
82     int         id;         /* program id */
83     int         version;    /* protocol version should be 1 */
84     int         sequence;   /* media sequence number */
85     int         duration;   /* maximum duration per segment (s) */
86     uint64_t    bandwidth;  /* bandwidth usage of segments (bits per second)*/
87     uint64_t    size;       /* stream length is calculated by taking the sum
88                                foreach segment of (segment->duration * hls->bandwidth/8) */
89
90     vlc_array_t *segments;  /* list of segments */
91     char        *url;        /* uri to m3u8 */
92     vlc_mutex_t lock;
93     bool        b_cache;    /* allow caching */
94
95     char        *psz_current_key_path;          /* URL path of the encrypted key */
96     uint8_t      psz_AES_IV[AES_BLOCK_SIZE];    /* IV used when decypher the block */
97     bool         b_iv_loaded;
98 } hls_stream_t;
99
100 struct stream_sys_t
101 {
102     char         *m3u8;         /* M3U8 url */
103     vlc_thread_t  reload;       /* HLS m3u8 reload thread */
104     vlc_thread_t  thread;       /* HLS segment download thread */
105
106     block_t      *peeked;
107
108     /* */
109     vlc_array_t  *hls_stream;   /* bandwidth adaptation */
110     uint64_t      bandwidth;    /* measured bandwidth (bits per second) */
111
112     /* Download */
113     struct hls_download_s
114     {
115         int         stream;     /* current hls_stream  */
116         int         segment;    /* current segment for downloading */
117         int         seek;       /* segment requested by seek (default -1) */
118         vlc_mutex_t lock_wait;  /* protect segment download counter */
119         vlc_cond_t  wait;       /* some condition to wait on */
120     } download;
121
122     /* Playback */
123     struct hls_playback_s
124     {
125         uint64_t    offset;     /* current offset in media */
126         int         stream;     /* current hls_stream  */
127         int         segment;    /* current segment for playback */
128     } playback;
129
130     /* Playlist */
131     struct hls_playlist_s
132     {
133         mtime_t     last;       /* playlist last loaded */
134         mtime_t     wakeup;     /* next reload time */
135         int         tries;      /* times it was not changed */
136     } playlist;
137
138     /* state */
139     bool        b_cache;    /* can cache files */
140     bool        b_meta;     /* meta playlist */
141     bool        b_live;     /* live stream? or vod? */
142     bool        b_error;    /* parsing error */
143     bool        b_aesmsg;   /* only print one time that the media is encrypted */
144 };
145
146 /****************************************************************************
147  * Local prototypes
148  ****************************************************************************/
149 static int  Read   (stream_t *, void *p_read, unsigned int i_read);
150 static int  Peek   (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
151 static int  Control(stream_t *, int i_query, va_list);
152
153 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer);
154 static ssize_t read_M3U8_from_url(stream_t *s, const char *psz_url, uint8_t **buffer);
155 static char *ReadLine(uint8_t *buffer, uint8_t **pos, size_t len);
156
157 static int hls_Download(stream_t *s, segment_t *segment);
158
159 static void* hls_Thread(void *);
160 static void* hls_Reload(void *);
161
162 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted);
163 static void segment_Free(segment_t *segment);
164
165 /****************************************************************************
166  *
167  ****************************************************************************/
168 static const char *const ext[] = {
169     "#EXT-X-TARGETDURATION",
170     "#EXT-X-MEDIA-SEQUENCE",
171     "#EXT-X-KEY",
172     "#EXT-X-ALLOW-CACHE",
173     "#EXT-X-ENDLIST",
174     "#EXT-X-STREAM-INF",
175     "#EXT-X-DISCONTINUITY",
176     "#EXT-X-VERSION"
177 };
178
179 static bool isHTTPLiveStreaming(stream_t *s)
180 {
181     const uint8_t *peek, *peek_end;
182
183     int64_t i_size = stream_Peek(s->p_source, &peek, 46);
184     if (i_size < 1)
185         return false;
186
187     if (strncasecmp((const char*)peek, "#EXTM3U", 7) != 0)
188         return false;
189
190     /* Parse stream and search for
191      * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
192      * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
193     peek_end = peek + i_size;
194     while(peek <= peek_end)
195     {
196         if (*peek == '#')
197         {
198             for (unsigned int i = 0; i < ARRAY_SIZE(ext); i++)
199             {
200                 char *p = strstr((const char*)peek, ext[i]);
201                 if (p != NULL)
202                     return true;
203             }
204         }
205         peek++;
206     };
207
208     return false;
209 }
210
211 /* HTTP Live Streaming */
212 static hls_stream_t *hls_New(vlc_array_t *hls_stream, const int id, const uint64_t bw, const char *uri)
213 {
214     hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
215     if (hls == NULL) return NULL;
216
217     hls->id = id;
218     hls->bandwidth = bw;
219     hls->duration = -1;/* unknown */
220     hls->size = 0;
221     hls->sequence = 0; /* default is 0 */
222     hls->version = 1;  /* default protocol version */
223     hls->b_cache = true;
224     hls->url = strdup(uri);
225     if (hls->url == NULL)
226     {
227         free(hls);
228         return NULL;
229     }
230     hls->psz_current_key_path = NULL;
231     hls->segments = vlc_array_new();
232     vlc_array_append(hls_stream, hls);
233     vlc_mutex_init(&hls->lock);
234     return hls;
235 }
236
237 static void hls_Free(hls_stream_t *hls)
238 {
239     vlc_mutex_destroy(&hls->lock);
240
241     if (hls->segments)
242     {
243         for (int n = 0; n < vlc_array_count(hls->segments); n++)
244         {
245             segment_t *segment = segment_GetSegment(hls, n);
246             if (segment) segment_Free(segment);
247         }
248         vlc_array_destroy(hls->segments);
249     }
250     free(hls->url);
251     free(hls->psz_current_key_path);
252     free(hls);
253 }
254
255 static hls_stream_t *hls_Copy(hls_stream_t *src, const bool b_cp_segments)
256 {
257     assert(src);
258     assert(!b_cp_segments); /* FIXME: copying segments is not implemented */
259
260     hls_stream_t *dst = (hls_stream_t *)malloc(sizeof(hls_stream_t));
261     if (dst == NULL) return NULL;
262
263     dst->id = src->id;
264     dst->bandwidth = src->bandwidth;
265     dst->duration = src->duration;
266     dst->size = src->size;
267     dst->sequence = src->sequence;
268     dst->version = src->version;
269     dst->b_cache = src->b_cache;
270     dst->psz_current_key_path = src->psz_current_key_path ?
271                 strdup( src->psz_current_key_path ) : NULL;
272     dst->url = strdup(src->url);
273     if (dst->url == NULL)
274     {
275         free(dst);
276         return NULL;
277     }
278     if (!b_cp_segments)
279         dst->segments = vlc_array_new();
280     vlc_mutex_init(&dst->lock);
281     return dst;
282 }
283
284 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, const int wanted)
285 {
286     int count = vlc_array_count(hls_stream);
287     if (count <= 0)
288         return NULL;
289     if ((wanted < 0) || (wanted >= count))
290         return NULL;
291     return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
292 }
293
294 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
295 {
296     return hls_Get(hls_stream, 0);
297 }
298
299 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
300 {
301     int count = vlc_array_count(hls_stream);
302     if (count <= 0)
303         return NULL;
304     count--;
305     return hls_Get(hls_stream, count);
306 }
307
308 static hls_stream_t *hls_Find(vlc_array_t *hls_stream, hls_stream_t *hls_new)
309 {
310     int count = vlc_array_count(hls_stream);
311     for (int n = 0; n < count; n++)
312     {
313         hls_stream_t *hls = hls_Get(hls_stream, n);
314         if (hls)
315         {
316             /* compare */
317             if ((hls->id == hls_new->id) &&
318                 ((hls->bandwidth == hls_new->bandwidth)||(hls_new->bandwidth==0)))
319                 return hls;
320         }
321     }
322     return NULL;
323 }
324
325 static uint64_t hls_GetStreamSize(hls_stream_t *hls)
326 {
327     /* NOTE: Stream size is calculated based on segment duration and
328      * HLS stream bandwidth from the .m3u8 file. If these are not correct
329      * then the deviation from exact byte size will be big and the seek/
330      * progressbar will not behave entirely as one expects. */
331     uint64_t size = 0UL;
332
333     /* If there is no valid bandwidth yet, then there is no point in
334      * computing stream size. */
335     if (hls->bandwidth == 0)
336         return size;
337
338     int count = vlc_array_count(hls->segments);
339     for (int n = 0; n < count; n++)
340     {
341         segment_t *segment = segment_GetSegment(hls, n);
342         if (segment)
343         {
344             size += (segment->duration * (hls->bandwidth / 8));
345         }
346     }
347     return size;
348 }
349
350 /* Segment */
351 static segment_t *segment_New(hls_stream_t* hls, const int duration, const char *uri)
352 {
353     segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
354     if (segment == NULL)
355         return NULL;
356
357     segment->duration = duration; /* seconds */
358     segment->size = 0; /* bytes */
359     segment->sequence = 0;
360     segment->bandwidth = 0;
361     segment->url = strdup(uri);
362     if (segment->url == NULL)
363     {
364         free(segment);
365         return NULL;
366     }
367     segment->data = NULL;
368     vlc_array_append(hls->segments, segment);
369     vlc_mutex_init(&segment->lock);
370     segment->b_key_loaded = false;
371     segment->psz_key_path = NULL;
372     if (hls->psz_current_key_path)
373         segment->psz_key_path = strdup(hls->psz_current_key_path);
374     return segment;
375 }
376
377 static void segment_Free(segment_t *segment)
378 {
379     vlc_mutex_destroy(&segment->lock);
380
381     free(segment->url);
382     free(segment->psz_key_path);
383     if (segment->data)
384         block_Release(segment->data);
385     free(segment);
386 }
387
388 static segment_t *segment_GetSegment(hls_stream_t *hls, const int wanted)
389 {
390     assert(hls);
391
392     int count = vlc_array_count(hls->segments);
393     if (count <= 0)
394         return NULL;
395     if ((wanted < 0) || (wanted >= count))
396         return NULL;
397     return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
398 }
399
400 static segment_t *segment_Find(hls_stream_t *hls, const int sequence)
401 {
402     assert(hls);
403
404     int count = vlc_array_count(hls->segments);
405     if (count <= 0) return NULL;
406     for (int n = 0; n < count; n++)
407     {
408         segment_t *segment = segment_GetSegment(hls, n);
409         if (segment == NULL) break;
410         if (segment->sequence == sequence)
411             return segment;
412     }
413     return NULL;
414 }
415
416 static int ChooseSegment(stream_t *s, const int current)
417 {
418     stream_sys_t *p_sys = (stream_sys_t *)s->p_sys;
419     hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
420     if (hls == NULL) return 0;
421
422     /* Choose a segment to start which is no closer than
423      * 3 times the target duration from the end of the playlist.
424      */
425     int wanted = 0;
426     int duration = 0;
427     int sequence = 0;
428     int count = vlc_array_count(hls->segments);
429     int i = p_sys->b_live ? count - 1 : 0;
430
431     while((i >= 0) && (i < count))
432     {
433         segment_t *segment = segment_GetSegment(hls, i);
434         assert(segment);
435
436         if (segment->duration > hls->duration)
437         {
438             msg_Err(s, "EXTINF:%d duration is larger than EXT-X-TARGETDURATION:%d",
439                     segment->duration, hls->duration);
440         }
441
442         duration += segment->duration;
443         if (duration >= 3 * hls->duration)
444         {
445             /* Start point found */
446             wanted = p_sys->b_live ? i : 0;
447             sequence = segment->sequence;
448             break;
449         }
450
451         if (p_sys->b_live)
452             i-- ;
453         else
454             i++;
455     }
456
457     msg_Info(s, "Choose segment %d/%d (sequence=%d)", wanted, count, sequence);
458     return wanted;
459 }
460
461 /* Parsing */
462 static char *parse_Attributes(const char *line, const char *attr)
463 {
464     char *p;
465     char *begin = (char *) line;
466     char *end = begin + strlen(line);
467
468     /* Find start of attributes */
469     if ((p = strchr(begin, ':' )) == NULL)
470         return NULL;
471
472     begin = p;
473     do
474     {
475         if (strncasecmp(begin, attr, strlen(attr)) == 0)
476         {
477             /* <attr>=<value>[,]* */
478             p = strchr(begin, ',');
479             begin += strlen(attr) + 1;
480             if (begin >= end)
481                 return NULL;
482             if (p == NULL) /* last attribute */
483                 return strndup(begin, end - begin);
484             /* copy till ',' */
485             return strndup(begin, p - begin);
486         }
487         begin++;
488     } while(begin < end);
489
490     return NULL;
491 }
492
493 static int hex2int(char c)
494 {
495     if (c >= '0' && c <= '9')
496         return c - '0';
497     if (c >= 'A' && c <= 'F')
498         return c - 'A' + 10;
499     if (c >= 'a' && c <= 'f')
500         return c - 'a' + 10;
501     return -1;
502 }
503
504 static int string_to_IV(const char *string_hexa, uint8_t iv[AES_BLOCK_SIZE])
505 {
506     const char *p = string_hexa;
507     uint8_t *d = iv;
508     unsigned int c;
509
510     if (*p++ != '0')
511         return VLC_EGENERIC;
512     if (*p++ != 'x')
513         return VLC_EGENERIC;
514
515     while (*p && *(p+1))
516     {
517         c = hex2int(*p++) << 4;
518         c |= hex2int(*p++);
519         *d++ = c;
520     }
521
522     return VLC_SUCCESS;
523 }
524
525 static char *relative_URI(const char *psz_url, const char *psz_path)
526 {
527     assert(psz_url != NULL && psz_path != NULL);
528     //If the path is actually an absolute URL, don't do anything.
529     if (strncmp(psz_path, "http", 4) == 0)
530         return NULL;
531
532     char    *path_end = strrchr(psz_url, '/');
533     if (path_end == NULL)
534         return NULL;
535     unsigned int    url_length = path_end - psz_url + 1;
536     char    *psz_res = malloc(url_length + strlen(psz_path) + 1);
537     strncpy(psz_res, psz_url, url_length);
538     psz_res[url_length] = 0;
539     strcat(psz_res, psz_path);
540     return psz_res;
541 }
542
543 static int parse_SegmentInformation(hls_stream_t *hls, char *p_read, int *duration)
544 {
545     assert(hls);
546     assert(p_read);
547
548     /* strip of #EXTINF: */
549     char *p_next = NULL;
550     char *token = strtok_r(p_read, ":", &p_next);
551     if (token == NULL)
552         return VLC_EGENERIC;
553
554     /* read duration */
555     token = strtok_r(NULL, ",", &p_next);
556     if (token == NULL)
557         return VLC_EGENERIC;
558
559     int value;
560     if (hls->version < 3)
561     {
562        value = strtol(token, NULL, 10);
563        if (errno == ERANGE)
564        {
565            *duration = -1;
566            return VLC_EGENERIC;
567        }
568        *duration = value;
569     }
570     else
571     {
572         double d = strtod(token, (char **) NULL);
573         if (errno == ERANGE)
574         {
575             *duration = -1;
576             return VLC_EGENERIC;
577         }
578         if ((d) - ((int)d) >= 0.5)
579             value = ((int)d) + 1;
580         else
581             value = ((int)d);
582     }
583
584     /* Ignore the rest of the line */
585     return VLC_SUCCESS;
586 }
587
588 static int parse_AddSegment(hls_stream_t *hls, const int duration, const char *uri)
589 {
590     assert(hls);
591     assert(uri);
592
593     /* Store segment information */
594     vlc_mutex_lock(&hls->lock);
595
596     char *psz_uri = relative_URI(hls->url, uri);
597
598     segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
599     if (segment)
600         segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
601     free(psz_uri);
602
603     vlc_mutex_unlock(&hls->lock);
604
605     return segment ? VLC_SUCCESS : VLC_ENOMEM;
606 }
607
608 static int parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
609 {
610     assert(hls);
611
612     int duration = -1;
613     int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
614     if (ret != 1)
615     {
616         msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
617         return VLC_EGENERIC;
618     }
619
620     hls->duration = duration; /* seconds */
621     return VLC_SUCCESS;
622 }
623
624 static int parse_StreamInformation(stream_t *s, vlc_array_t **hls_stream,
625                                    hls_stream_t **hls, char *p_read, const char *uri)
626 {
627     int id;
628     uint64_t bw;
629     char *attr;
630
631     assert(*hls == NULL);
632
633     attr = parse_Attributes(p_read, "PROGRAM-ID");
634     if (attr == NULL)
635     {
636         msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
637         return VLC_EGENERIC;
638     }
639     id = atol(attr);
640     free(attr);
641
642     attr = parse_Attributes(p_read, "BANDWIDTH");
643     if (attr == NULL)
644     {
645         msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
646         return VLC_EGENERIC;
647     }
648     bw = atoll(attr);
649     free(attr);
650
651     if (bw == 0)
652     {
653         msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
654         return VLC_EGENERIC;
655     }
656
657     msg_Info(s, "bandwidth adaptation detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
658
659     char *psz_uri = relative_URI(s->p_sys->m3u8, uri);
660
661     *hls = hls_New(*hls_stream, id, bw, psz_uri ? psz_uri : uri);
662
663     free(psz_uri);
664
665     return (*hls == NULL) ? VLC_ENOMEM : VLC_SUCCESS;
666 }
667
668 static int parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
669 {
670     assert(hls);
671
672     int sequence;
673     int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
674     if (ret != 1)
675     {
676         msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
677         return VLC_EGENERIC;
678     }
679
680     if (hls->sequence > 0)
681     {
682         if (s->p_sys->b_live)
683         {
684             hls_stream_t *last = hls_GetLast(s->p_sys->hls_stream);
685             if ((last->sequence < sequence) && (sequence - last->sequence != 1))
686                 msg_Err(s, "EXT-X-MEDIA-SEQUENCE gap in playlist (new=%d, old=%d)",
687                             sequence, last->sequence);
688         }
689         else
690             msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist (new=%d, old=%d)",
691                         sequence, hls->sequence);
692     }
693     hls->sequence = sequence;
694     return VLC_SUCCESS;
695 }
696
697 static int parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
698 {
699     assert(hls);
700
701     /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
702     int err = VLC_SUCCESS;
703     char *attr = parse_Attributes(p_read, "METHOD");
704     if (attr == NULL)
705     {
706         msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
707         return err;
708     }
709
710     if (strncasecmp(attr, "NONE", 4) == 0)
711     {
712         char *uri = parse_Attributes(p_read, "URI");
713         if (uri != NULL)
714         {
715             msg_Err(s, "#EXT-X-KEY: URI not expected");
716             err = VLC_EGENERIC;
717         }
718         free(uri);
719         /* IV is only supported in version 2 and above */
720         if (hls->version >= 2)
721         {
722             char *iv = parse_Attributes(p_read, "IV");
723             if (iv != NULL)
724             {
725                 msg_Err(s, "#EXT-X-KEY: IV not expected");
726                 err = VLC_EGENERIC;
727             }
728             free(iv);
729         }
730     }
731     else if (strncasecmp(attr, "AES-128", 7) == 0)
732     {
733         char *value, *uri, *iv;
734         if (s->p_sys->b_aesmsg == false)
735         {
736             msg_Info(s, "playback of AES-128 encrypted HTTP Live media detected.");
737             s->p_sys->b_aesmsg = true;
738         }
739         value = uri = parse_Attributes(p_read, "URI");
740         if (value == NULL)
741         {
742             msg_Err(s, "#EXT-X-KEY: URI not found for encrypted HTTP Live media in AES-128");
743             free(attr);
744             return VLC_EGENERIC;
745         }
746
747         /* Url is put between quotes, remove them */
748         if (*value == '"')
749         {
750             /* We need to strip the "" from the attribute value */
751             uri = value + 1;
752             char* end = strchr(uri, '"');
753             if (end != NULL)
754                 *end = 0;
755         }
756         hls->psz_current_key_path = strdup(uri);
757         free(value);
758
759         value = iv = parse_Attributes(p_read, "IV");
760         if (iv == NULL)
761         {
762             /*
763             * If the EXT-X-KEY tag does not have the IV attribute, implementations
764             * MUST use the sequence number of the media file as the IV when
765             * encrypting or decrypting that media file.  The big-endian binary
766             * representation of the sequence number SHALL be placed in a 16-octet
767             * buffer and padded (on the left) with zeros.
768             */
769             hls->b_iv_loaded = false;
770         }
771         else
772         {
773             /*
774             * If the EXT-X-KEY tag has the IV attribute, implementations MUST use
775             * the attribute value as the IV when encrypting or decrypting with that
776             * key.  The value MUST be interpreted as a 128-bit hexadecimal number
777             * and MUST be prefixed with 0x or 0X.
778             */
779
780             if (string_to_IV(iv, hls->psz_AES_IV) == VLC_EGENERIC)
781                 err = VLC_EGENERIC;
782             else
783                 hls->b_iv_loaded = true;
784             free(value);
785         }
786     }
787     else
788     {
789         msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
790         err = VLC_EGENERIC;
791     }
792     free(attr);
793     return err;
794 }
795
796 static int parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
797 {
798     VLC_UNUSED(hls);
799     msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
800     return VLC_SUCCESS;
801 }
802
803 static int parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
804 {
805     assert(hls);
806
807     char answer[4] = "\0";
808     int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
809     if (ret != 1)
810     {
811         msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
812         return VLC_EGENERIC;
813     }
814
815     hls->b_cache = (strncmp(answer, "NO", 2) != 0);
816     return VLC_SUCCESS;
817 }
818
819 static int parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
820 {
821     assert(hls);
822
823     int version;
824     int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
825     if (ret != 1)
826     {
827         msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
828         return VLC_EGENERIC;
829     }
830
831     /* Check version */
832     hls->version = version;
833     if (hls->version <= 0 || hls->version > 3)
834     {
835         msg_Err(s, "#EXT-X-VERSION should be version 1, 2 or 3 iso %d", version);
836         return VLC_EGENERIC;
837     }
838     return VLC_SUCCESS;
839 }
840
841 static int parse_EndList(stream_t *s, hls_stream_t *hls)
842 {
843     assert(hls);
844
845     s->p_sys->b_live = false;
846     msg_Info(s, "video on demand (vod) mode");
847     return VLC_SUCCESS;
848 }
849
850 static int parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
851 {
852     assert(hls);
853
854     /* FIXME: Do we need to act on discontinuity ?? */
855     msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
856     return VLC_SUCCESS;
857 }
858
859 static int hls_CompareStreams( const void* a, const void* b )
860 {
861     hls_stream_t*   stream_a = *(hls_stream_t**)a;
862     hls_stream_t*   stream_b = *(hls_stream_t**)b;
863     return stream_a->bandwidth > stream_b->bandwidth;
864 }
865
866 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
867  * document defines the following new tags: EXT-X-TARGETDURATION,
868  * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
869  * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
870  * and EXT-X-VERSION.
871  */
872 static int parse_M3U8(stream_t *s, vlc_array_t *streams, uint8_t *buffer, const ssize_t len)
873 {
874     stream_sys_t *p_sys = s->p_sys;
875     uint8_t *p_read, *p_begin, *p_end;
876
877     assert(streams);
878     assert(buffer);
879
880     msg_Dbg(s, "parse_M3U8\n%s", buffer);
881     p_begin = buffer;
882     p_end = p_begin + len;
883
884     char *line = ReadLine(p_begin, &p_read, p_end - p_begin);
885     if (line == NULL)
886         return VLC_ENOMEM;
887     p_begin = p_read;
888
889     if (strncmp(line, "#EXTM3U", 7) != 0)
890     {
891         msg_Err(s, "missing #EXTM3U tag .. aborting");
892         free(line);
893         return VLC_EGENERIC;
894     }
895
896     free(line);
897     line = NULL;
898
899     /* What is the version ? */
900     int version = 1;
901     uint8_t *p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-VERSION:");
902     if (p != NULL)
903     {
904         uint8_t *tmp = NULL;
905         char *psz_version = ReadLine(p, &tmp, p_end - p);
906         if (psz_version == NULL)
907             return VLC_ENOMEM;
908         int ret = sscanf((const char*)psz_version, "#EXT-X-VERSION:%d", &version);
909         if (ret != 1)
910         {
911             msg_Warn(s, "#EXT-X-VERSION: no protocol version found, assuming version 1.");
912             version = 1;
913         }
914         free(psz_version);
915         p = NULL;
916     }
917
918     /* Is it a live stream ? */
919     p_sys->b_live = (strstr((const char *)buffer, "#EXT-X-ENDLIST") == NULL) ? true : false;
920
921     /* Is it a meta index file ? */
922     bool b_meta = (strstr((const char *)buffer, "#EXT-X-STREAM-INF") == NULL) ? false : true;
923
924     int err = VLC_SUCCESS;
925
926     if (b_meta)
927     {
928         msg_Info(s, "Meta playlist");
929
930         /* M3U8 Meta Index file */
931         do {
932             /* Next line */
933             line = ReadLine(p_begin, &p_read, p_end - p_begin);
934             if (line == NULL)
935                 break;
936             p_begin = p_read;
937
938             /* */
939             if (strncmp(line, "#EXT-X-STREAM-INF", 17) == 0)
940             {
941                 p_sys->b_meta = true;
942                 char *uri = ReadLine(p_begin, &p_read, p_end - p_begin);
943                 if (uri == NULL)
944                     err = VLC_ENOMEM;
945                 else
946                 {
947                     if (*uri == '#')
948                     {
949                         msg_Info(s, "Skipping invalid stream-inf: %s", uri);
950                         free(uri);
951                     }
952                     else
953                     {
954                         hls_stream_t *hls = NULL;
955                         err = parse_StreamInformation(s, &streams, &hls, line, uri);
956                         free(uri);
957
958                         /* Download playlist file from server */
959                         uint8_t *buf = NULL;
960                         ssize_t len = read_M3U8_from_url(s, hls->url, &buf);
961                         if (len < 0)
962                             err = VLC_EGENERIC;
963                         else
964                         {
965                             /* Parse HLS m3u8 content. */
966                             err = parse_M3U8(s, streams, buf, len);
967                             free(buf);
968                         }
969
970                         if (hls)
971                         {
972                             hls->version = version;
973                             if (!p_sys->b_live)
974                                 hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
975                         }
976                     }
977                 }
978                 p_begin = p_read;
979             }
980
981             free(line);
982             line = NULL;
983
984             if (p_begin >= p_end)
985                 break;
986
987         } while (err == VLC_SUCCESS);
988
989     }
990     else
991     {
992         msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
993
994         hls_stream_t *hls = NULL;
995         if (p_sys->b_meta)
996             hls = hls_GetLast(streams);
997         else
998         {
999             /* No Meta playlist used */
1000             hls = hls_New(streams, 0, 0, p_sys->m3u8);
1001             if (hls)
1002             {
1003                 /* Get TARGET-DURATION first */
1004                 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1005                 if (p)
1006                 {
1007                     uint8_t *p_rest = NULL;
1008                     char *psz_duration = ReadLine(p, &p_rest,  p_end - p);
1009                     if (psz_duration == NULL)
1010                         return VLC_EGENERIC;
1011                     err = parse_TargetDuration(s, hls, psz_duration);
1012                     free(psz_duration);
1013                     p = NULL;
1014                 }
1015
1016                 /* Store version */
1017                 hls->version = version;
1018             }
1019             else return VLC_ENOMEM;
1020         }
1021         assert(hls);
1022
1023         /* */
1024         int segment_duration = -1;
1025         do
1026         {
1027             /* Next line */
1028             line = ReadLine(p_begin, &p_read, p_end - p_begin);
1029             if (line == NULL)
1030                 break;
1031             p_begin = p_read;
1032
1033             if (strncmp(line, "#EXTINF", 7) == 0)
1034                 err = parse_SegmentInformation(hls, line, &segment_duration);
1035             else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1036                 err = parse_TargetDuration(s, hls, line);
1037             else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1038                 err = parse_MediaSequence(s, hls, line);
1039             else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1040                 err = parse_Key(s, hls, line);
1041             else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1042                 err = parse_ProgramDateTime(s, hls, line);
1043             else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1044                 err = parse_AllowCache(s, hls, line);
1045             else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1046                 err = parse_Discontinuity(s, hls, line);
1047             else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1048                 err = parse_Version(s, hls, line);
1049             else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1050                 err = parse_EndList(s, hls);
1051             else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1052             {
1053                 err = parse_AddSegment(hls, segment_duration, line);
1054                 segment_duration = -1; /* reset duration */
1055             }
1056
1057             free(line);
1058             line = NULL;
1059
1060             if (p_begin >= p_end)
1061                 break;
1062
1063         } while (err == VLC_SUCCESS);
1064
1065         free(line);
1066     }
1067
1068     return err;
1069 }
1070
1071
1072 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1073 {
1074     uint8_t         aeskey[32]; /* AES-512 can use up to 32 bytes */
1075     ssize_t len;
1076
1077     stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1078     if (p_m3u8 == NULL)
1079     {
1080         msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1081         return VLC_EGENERIC;
1082     }
1083
1084     len = stream_Read(p_m3u8, aeskey, sizeof(aeskey));
1085     if (len != AES_BLOCK_SIZE)
1086     {
1087         msg_Err(s, "The AES key loaded doesn't have the right size (%zd)", len);
1088         stream_Delete(p_m3u8);
1089         return VLC_EGENERIC;
1090     }
1091
1092     memcpy(seg->psz_AES_key, aeskey, AES_BLOCK_SIZE);
1093
1094     stream_Delete(p_m3u8);
1095
1096     return VLC_SUCCESS;
1097 }
1098
1099 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1100 {
1101     segment_t   *seg = NULL;
1102     segment_t   *prev_seg;
1103     int         count = vlc_array_count(hls->segments);
1104
1105     for (int i = 0; i < count; i++)
1106     {
1107         prev_seg = seg;
1108         seg = segment_GetSegment(hls, i);
1109         if (seg == NULL )
1110             continue;
1111         if (seg->psz_key_path == NULL)
1112             continue;   /* No key to load ? continue */
1113         if (seg->b_key_loaded)
1114             continue;   /* The key is already loaded */
1115
1116         /* if the key has not changed, and already available from previous segment,
1117          * try to copy it, and don't load the key */
1118         if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1119         {
1120             memcpy(seg->psz_AES_key, prev_seg->psz_AES_key, AES_BLOCK_SIZE);
1121             seg->b_key_loaded = true;
1122             continue;
1123         }
1124         if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1125             return VLC_EGENERIC;
1126        seg->b_key_loaded = true;
1127     }
1128     return VLC_SUCCESS;
1129 }
1130
1131 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1132 {
1133     /* Did the segment need to be decoded ? */
1134     if (segment->psz_key_path == NULL)
1135         return VLC_SUCCESS;
1136
1137     /* Do we have loaded the key ? */
1138     if (!segment->b_key_loaded)
1139     {
1140         /* No ? try to download it now */
1141         if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1142             return VLC_EGENERIC;
1143     }
1144
1145     /* For now, we only decode AES-128 data */
1146     gcry_error_t i_gcrypt_err;
1147     gcry_cipher_hd_t aes_ctx;
1148     /* Setup AES */
1149     i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1150                                      GCRY_CIPHER_MODE_CBC, 0);
1151     if (i_gcrypt_err)
1152     {
1153         msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1154         gcry_cipher_close(aes_ctx);
1155         return VLC_EGENERIC;
1156     }
1157
1158     /* Set key */
1159     i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->psz_AES_key,
1160                                        sizeof(segment->psz_AES_key));
1161     if (i_gcrypt_err)
1162     {
1163         msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1164         gcry_cipher_close(aes_ctx);
1165         return VLC_EGENERIC;
1166     }
1167
1168     if (hls->b_iv_loaded == false)
1169     {
1170         memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1171         hls->psz_AES_IV[15] = segment->sequence & 0xff;
1172         hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1173         hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1174         hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1175     }
1176
1177     i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1178                                       sizeof(hls->psz_AES_IV));
1179
1180     if (i_gcrypt_err)
1181     {
1182         msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1183         gcry_cipher_close(aes_ctx);
1184         return VLC_EGENERIC;
1185     }
1186
1187     i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1188                                        segment->data->p_buffer, /* out */
1189                                        segment->data->i_buffer,
1190                                        NULL, /* in */
1191                                        0);
1192     if (i_gcrypt_err)
1193     {
1194         msg_Err(s, "gcry_cipher_decrypt failed:  %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1195         gcry_cipher_close(aes_ctx);
1196         return VLC_EGENERIC;
1197     }
1198     gcry_cipher_close(aes_ctx);
1199     /* remove the PKCS#7 padding from the buffer */
1200     int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1201     if (pad <= 0 || pad > AES_BLOCK_SIZE)
1202     {
1203         msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1204         return VLC_EGENERIC;
1205     }
1206     int count = pad;
1207     while (count--)
1208     {
1209         if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1210         {
1211                 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1212                 return VLC_EGENERIC;
1213         }
1214     }
1215
1216     /* not all the data is readable because of padding */
1217     segment->data->i_buffer -= pad;
1218
1219     return VLC_SUCCESS;
1220 }
1221
1222 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1223 {
1224     stream_sys_t *p_sys = s->p_sys;
1225     assert(*streams);
1226     int err = VLC_EGENERIC;
1227
1228     /* Duplicate HLS stream META information */
1229     for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1230     {
1231         hls_stream_t *src, *dst;
1232         src = hls_Get(p_sys->hls_stream, i);
1233         if (src == NULL)
1234             return VLC_EGENERIC;
1235
1236         dst = hls_Copy(src, false);
1237         if (dst == NULL)
1238             return VLC_ENOMEM;
1239         vlc_array_append(*streams, dst);
1240
1241         /* Download playlist file from server */
1242         uint8_t *buf = NULL;
1243         ssize_t len = read_M3U8_from_url(s, dst->url, &buf);
1244         if (len < 0)
1245             err = VLC_EGENERIC;
1246         else
1247         {
1248             /* Parse HLS m3u8 content. */
1249             err = parse_M3U8(s, *streams, buf, len);
1250             free(buf);
1251         }
1252     }
1253     return err;
1254 }
1255
1256 /* Reload playlist */
1257 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t **hls)
1258 {
1259     int count = vlc_array_count(hls_new->segments);
1260
1261     msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1262              hls_new->id, hls_new->bandwidth, count);
1263
1264     for (int n = 0; n < count; n++)
1265     {
1266         segment_t *p = segment_GetSegment(hls_new, n);
1267         if (p == NULL) return VLC_EGENERIC;
1268
1269         vlc_mutex_lock(&(*hls)->lock);
1270         segment_t *segment = segment_Find(*hls, p->sequence);
1271         if (segment)
1272         {
1273             vlc_mutex_lock(&segment->lock);
1274
1275             assert(p->url);
1276             assert(segment->url);
1277
1278             /* they should be the same */
1279             if ((p->sequence != segment->sequence) ||
1280                 (p->duration != segment->duration) ||
1281                 (strcmp(p->url, segment->url) != 0))
1282             {
1283                 msg_Warn(s, "existing segment found with different content - resetting");
1284                 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1285                 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1286                 msg_Warn(s, "- file: new=%s", p->url);
1287                 msg_Warn(s, "        old=%s", segment->url);
1288
1289                 /* Resetting content */
1290                 segment->sequence = p->sequence;
1291                 segment->duration = p->duration;
1292                 free(segment->url);
1293                 segment->url = strdup(p->url);
1294                 if ( segment->url == NULL )
1295                 {
1296                     msg_Err(s, "Failed updating segment %d - skipping it",  p->sequence);
1297                     segment_Free(p);
1298                     vlc_mutex_unlock(&segment->lock);
1299                     continue;
1300                 }
1301                 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1302                 if (segment->data)
1303                 {
1304                     block_Release(segment->data);
1305                     segment->data = NULL;
1306                 }
1307                 free(segment->psz_key_path);
1308                 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1309                 segment_Free(p);
1310             }
1311             vlc_mutex_unlock(&segment->lock);
1312         }
1313         else
1314         {
1315             int last = vlc_array_count((*hls)->segments) - 1;
1316             segment_t *l = segment_GetSegment(*hls, last);
1317             if (l == NULL) goto fail_and_unlock;
1318
1319             if ((l->sequence + 1) != p->sequence)
1320             {
1321                 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1322                         p->sequence, l->sequence+1);
1323             }
1324             vlc_array_append((*hls)->segments, p);
1325             msg_Info(s, "- segment %d appended", p->sequence);
1326         }
1327         vlc_mutex_unlock(&(*hls)->lock);
1328     }
1329
1330     /* update meta information */
1331     vlc_mutex_lock(&(*hls)->lock);
1332     (*hls)->sequence = hls_new->sequence;
1333     (*hls)->duration = (hls_new->duration == -1) ? (*hls)->duration : hls_new->duration;
1334     (*hls)->b_cache = hls_new->b_cache;
1335     vlc_mutex_unlock(&(*hls)->lock);
1336     return VLC_SUCCESS;
1337
1338 fail_and_unlock:
1339     assert(0);
1340     vlc_mutex_unlock(&(*hls)->lock);
1341     return VLC_EGENERIC;
1342 }
1343
1344 static int hls_ReloadPlaylist(stream_t *s)
1345 {
1346     stream_sys_t *p_sys = s->p_sys;
1347
1348     vlc_array_t *hls_streams = vlc_array_new();
1349     if (hls_streams == NULL)
1350         return VLC_ENOMEM;
1351
1352     msg_Info(s, "Reloading HLS live meta playlist");
1353
1354     if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1355     {
1356         /* Free hls streams */
1357         for (int i = 0; i < vlc_array_count(hls_streams); i++)
1358         {
1359             hls_stream_t *hls;
1360             hls = hls_Get(hls_streams, i);
1361             if (hls) hls_Free(hls);
1362         }
1363         vlc_array_destroy(hls_streams);
1364
1365         msg_Err(s, "reloading playlist failed");
1366         return VLC_EGENERIC;
1367     }
1368
1369     /* merge playlists */
1370     int count = vlc_array_count(hls_streams);
1371     for (int n = 0; n < count; n++)
1372     {
1373         hls_stream_t *hls_new = hls_Get(hls_streams, n);
1374         if (hls_new == NULL)
1375             continue;
1376
1377         hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1378         if (hls_old == NULL)
1379         {   /* new hls stream - append */
1380             vlc_array_append(p_sys->hls_stream, hls_new);
1381             msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1382                      hls_new->id, hls_new->bandwidth);
1383         }
1384         else if (hls_UpdatePlaylist(s, hls_new, &hls_old) != VLC_SUCCESS)
1385             msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1386                      hls_new->id, hls_new->bandwidth);
1387     }
1388     vlc_array_destroy(hls_streams);
1389     return VLC_SUCCESS;
1390 }
1391
1392 /****************************************************************************
1393  * hls_Thread
1394  ****************************************************************************/
1395 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1396 {
1397     stream_sys_t *p_sys = s->p_sys;
1398     int candidate = -1;
1399     uint64_t bw = *bandwidth;
1400     uint64_t bw_candidate = 0;
1401
1402     int count = vlc_array_count(p_sys->hls_stream);
1403     for (int n = 0; n < count; n++)
1404     {
1405         /* Select best bandwidth match */
1406         hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1407         if (hls == NULL) break;
1408
1409         /* only consider streams with the same PROGRAM-ID */
1410         if (hls->id == progid)
1411         {
1412             if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1413             {
1414                 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1415                          n, bw, hls->bandwidth); /* bits / s */
1416                 bw_candidate = hls->bandwidth;
1417                 candidate = n; /* possible candidate */
1418             }
1419         }
1420     }
1421     *bandwidth = bw_candidate;
1422     return candidate;
1423 }
1424
1425 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1426 {
1427     stream_sys_t *p_sys = s->p_sys;
1428
1429     assert(hls);
1430     assert(segment);
1431
1432     vlc_mutex_lock(&segment->lock);
1433     if (segment->data != NULL)
1434     {
1435         /* Segment already downloaded */
1436         vlc_mutex_unlock(&segment->lock);
1437         return VLC_SUCCESS;
1438     }
1439
1440     /* sanity check - can we download this segment on time? */
1441     if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1442     {
1443         uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1444         int estimated = (int)(size / p_sys->bandwidth);
1445         if (estimated > segment->duration)
1446         {
1447             msg_Warn(s,"downloading of segment %d takes %ds, which is longer than its playback (%ds)",
1448                         segment->sequence, estimated, segment->duration);
1449         }
1450     }
1451
1452     mtime_t start = mdate();
1453     if (hls_Download(s, segment) != VLC_SUCCESS)
1454     {
1455         msg_Err(s, "downloaded segment %d from stream %d failed",
1456                     segment->sequence, *cur_stream);
1457         vlc_mutex_unlock(&segment->lock);
1458         return VLC_EGENERIC;
1459     }
1460     mtime_t duration = mdate() - start;
1461     if (hls->bandwidth == 0)
1462     {
1463         /* Try to estimate the bandwidth for this stream */
1464         hls->bandwidth = (uint64_t)((double)segment->size / ((double)duration / 1000000.0));
1465     }
1466
1467     /* If the segment is encrypted, decode it */
1468     if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1469     {
1470         vlc_mutex_unlock(&segment->lock);
1471         return VLC_EGENERIC;
1472     }
1473
1474     vlc_mutex_unlock(&segment->lock);
1475
1476     msg_Info(s, "downloaded segment %d from stream %d",
1477                 segment->sequence, *cur_stream);
1478
1479     /* check for division by zero */
1480     double ms = (double)duration / 1000.0; /* ms */
1481     if (ms <= 0.0)
1482         return VLC_SUCCESS;
1483
1484     uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
1485     p_sys->bandwidth = bw;
1486     if (p_sys->b_meta && (hls->bandwidth != bw))
1487     {
1488         int newstream = BandwidthAdaptation(s, hls->id, &bw);
1489
1490         /* FIXME: we need an average here */
1491         if ((newstream >= 0) && (newstream != *cur_stream))
1492         {
1493             msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1494                      (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1495             *cur_stream = newstream;
1496         }
1497     }
1498     return VLC_SUCCESS;
1499 }
1500
1501 static void* hls_Thread(void *p_this)
1502 {
1503     stream_t *s = (stream_t *)p_this;
1504     stream_sys_t *p_sys = s->p_sys;
1505
1506     int canc = vlc_savecancel();
1507
1508     while (vlc_object_alive(s))
1509     {
1510         hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1511         assert(hls);
1512
1513         /* Sliding window (~60 seconds worth of movie) */
1514         vlc_mutex_lock(&hls->lock);
1515         int count = vlc_array_count(hls->segments);
1516         vlc_mutex_unlock(&hls->lock);
1517
1518         /* Is there a new segment to process? */
1519         if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1520             (p_sys->download.segment >= count))
1521         {
1522             /* wait */
1523             vlc_mutex_lock(&p_sys->download.lock_wait);
1524             while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1525                     (p_sys->download.segment >= count)) &&
1526                    (p_sys->download.seek == -1))
1527             {
1528                 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1529                 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1530                     break;
1531                 if (!vlc_object_alive(s))
1532                     break;
1533             }
1534             /* */
1535             if (p_sys->download.seek >= 0)
1536             {
1537                 p_sys->download.segment = p_sys->download.seek;
1538                 p_sys->download.seek = -1;
1539             }
1540             vlc_mutex_unlock(&p_sys->download.lock_wait);
1541         }
1542
1543         if (!vlc_object_alive(s)) break;
1544
1545         vlc_mutex_lock(&hls->lock);
1546         segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1547         vlc_mutex_unlock(&hls->lock);
1548
1549         if ((segment != NULL) &&
1550             (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1551         {
1552             if (!vlc_object_alive(s)) break;
1553
1554             if (!p_sys->b_live)
1555             {
1556                 p_sys->b_error = true;
1557                 break;
1558             }
1559         }
1560
1561         /* download succeeded */
1562         /* determine next segment to download */
1563         vlc_mutex_lock(&p_sys->download.lock_wait);
1564         if (p_sys->download.seek >= 0)
1565         {
1566             p_sys->download.segment = p_sys->download.seek;
1567             p_sys->download.seek = -1;
1568         }
1569         else if (p_sys->download.segment < count)
1570             p_sys->download.segment++;
1571         vlc_cond_signal(&p_sys->download.wait);
1572         vlc_mutex_unlock(&p_sys->download.lock_wait);
1573     }
1574
1575     vlc_restorecancel(canc);
1576     return NULL;
1577 }
1578
1579 static void* hls_Reload(void *p_this)
1580 {
1581     stream_t *s = (stream_t *)p_this;
1582     stream_sys_t *p_sys = s->p_sys;
1583
1584     assert(p_sys->b_live);
1585
1586     int canc = vlc_savecancel();
1587
1588     double wait = 0.5;
1589     while (vlc_object_alive(s))
1590     {
1591         mtime_t now = mdate();
1592         if (now >= p_sys->playlist.wakeup)
1593         {
1594             /* reload the m3u8 */
1595             if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1596             {
1597                 /* No change in playlist, then backoff */
1598                 p_sys->playlist.tries++;
1599                 if (p_sys->playlist.tries == 1) wait = 0.5;
1600                 else if (p_sys->playlist.tries == 2) wait = 1;
1601                 else if (p_sys->playlist.tries >= 3) wait = 2;
1602
1603                 /* Can we afford to backoff? */
1604                 if (p_sys->download.segment - p_sys->playback.segment < 3)
1605                 {
1606                     p_sys->playlist.tries = 0;
1607                     wait = 0.5;
1608                 }
1609             }
1610             else
1611             {
1612                 p_sys->playlist.tries = 0;
1613                 wait = 0.5;
1614             }
1615
1616             hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1617             assert(hls);
1618
1619             /* determine next time to update playlist */
1620             p_sys->playlist.last = now;
1621             p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1622                                                    * (mtime_t)1000000);
1623         }
1624
1625         mwait(p_sys->playlist.wakeup);
1626     }
1627
1628     vlc_restorecancel(canc);
1629     return NULL;
1630 }
1631
1632 static int Prefetch(stream_t *s, int *current)
1633 {
1634     stream_sys_t *p_sys = s->p_sys;
1635     int stream = *current;
1636
1637     hls_stream_t *hls = hls_Get(p_sys->hls_stream, stream);
1638     if (hls == NULL)
1639         return VLC_EGENERIC;
1640
1641     /* Download first 2 segments of this HLS stream */
1642     for (int i = 0; i < 2; i++)
1643     {
1644         segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1645         if (segment == NULL )
1646             return VLC_EGENERIC;
1647
1648         /* It is useless to lock the segment here, as Prefetch is called before
1649            download and playlit thread are started. */
1650         if (segment->data)
1651         {
1652             p_sys->download.segment++;
1653             continue;
1654         }
1655
1656         if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1657             return VLC_EGENERIC;
1658
1659         p_sys->download.segment++;
1660
1661         /* adapt bandwidth? */
1662         if (*current != stream)
1663         {
1664             hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1665             if (hls == NULL)
1666                 return VLC_EGENERIC;
1667
1668              stream = *current;
1669         }
1670     }
1671
1672     return VLC_SUCCESS;
1673 }
1674
1675 /****************************************************************************
1676  *
1677  ****************************************************************************/
1678 static int hls_Download(stream_t *s, segment_t *segment)
1679 {
1680     assert(segment);
1681
1682     stream_t *p_ts = stream_UrlNew(s, segment->url);
1683     if (p_ts == NULL)
1684         return VLC_EGENERIC;
1685
1686     segment->size = stream_Size(p_ts);
1687     assert(segment->size > 0);
1688
1689     segment->data = block_Alloc(segment->size);
1690     if (segment->data == NULL)
1691     {
1692         stream_Delete(p_ts);
1693         return VLC_ENOMEM;
1694     }
1695
1696     assert(segment->data->i_buffer == segment->size);
1697
1698     ssize_t length = 0, curlen = 0;
1699     uint64_t size;
1700     do
1701     {
1702         size = stream_Size(p_ts);
1703         if (size > segment->size)
1704         {
1705             msg_Dbg(s, "size changed %"PRIu64, segment->size);
1706             block_t *p_block = block_Realloc(segment->data, 0, size);
1707             if (p_block == NULL)
1708             {
1709                 stream_Delete(p_ts);
1710                 block_Release(segment->data);
1711                 segment->data = NULL;
1712                 return VLC_ENOMEM;
1713             }
1714             segment->data = p_block;
1715             segment->size = size;
1716             assert(segment->data->i_buffer == segment->size);
1717             p_block = NULL;
1718         }
1719         length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1720         if (length <= 0)
1721             break;
1722         curlen += length;
1723     } while (vlc_object_alive(s));
1724
1725     stream_Delete(p_ts);
1726     return VLC_SUCCESS;
1727 }
1728
1729 /* Read M3U8 file */
1730 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1731 {
1732     int64_t total_bytes = 0;
1733     int64_t total_allocated = 0;
1734     uint8_t *p = NULL;
1735
1736     while (1)
1737     {
1738         char buf[4096];
1739         int64_t bytes;
1740
1741         bytes = stream_Read(s, buf, sizeof(buf));
1742         if (bytes == 0)
1743             break;      /* EOF ? */
1744         else if (bytes < 0)
1745             return bytes;
1746
1747         if ( (total_bytes + bytes + 1) > total_allocated )
1748         {
1749             if (total_allocated)
1750                 total_allocated *= 2;
1751             else
1752                 total_allocated = __MIN((uint64_t)bytes+1, sizeof(buf));
1753
1754             p = realloc_or_free(p, total_allocated);
1755             if (p == NULL)
1756                 return VLC_ENOMEM;
1757         }
1758
1759         memcpy(p+total_bytes, buf, bytes);
1760         total_bytes += bytes;
1761     }
1762
1763     if (total_allocated == 0)
1764         return VLC_EGENERIC;
1765
1766     p[total_bytes] = '\0';
1767     *buffer = p;
1768
1769     return total_bytes;
1770 }
1771
1772 static ssize_t read_M3U8_from_url(stream_t *s, const char* psz_url, uint8_t **buffer)
1773 {
1774     assert(*buffer == NULL);
1775
1776     /* Construct URL */
1777     stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1778     if (p_m3u8 == NULL)
1779         return VLC_EGENERIC;
1780
1781     ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1782     stream_Delete(p_m3u8);
1783
1784     return size;
1785 }
1786
1787 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1788 {
1789     assert(buffer);
1790
1791     char *line = NULL;
1792     uint8_t *begin = buffer;
1793     uint8_t *p = begin;
1794     uint8_t *end = p + len;
1795
1796     while (p < end)
1797     {
1798         if ((*p == '\n') || (*p == '\0'))
1799             break;
1800         p++;
1801     }
1802
1803     /* copy line excluding \n or \0 */
1804     line = strndup((char *)begin, p - begin);
1805
1806     if (*p == '\0')
1807         *pos = end;
1808     else
1809     {
1810         /* next pass start after \n */
1811         p++;
1812         *pos = p;
1813     }
1814
1815     return line;
1816 }
1817
1818 /****************************************************************************
1819  * Open
1820  ****************************************************************************/
1821 static int Open(vlc_object_t *p_this)
1822 {
1823     stream_t *s = (stream_t*)p_this;
1824     stream_sys_t *p_sys;
1825
1826     if (!isHTTPLiveStreaming(s))
1827         return VLC_EGENERIC;
1828
1829     msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1830
1831     /* Initialize crypto bit */
1832     vlc_gcrypt_init();
1833
1834     /* */
1835     s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1836     if (p_sys == NULL)
1837         return VLC_ENOMEM;
1838
1839     char *psz_uri = NULL;
1840     if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1841     {
1842         free(p_sys);
1843         return VLC_ENOMEM;
1844     }
1845     p_sys->m3u8 = psz_uri;
1846
1847     char *new_path;
1848     if (asprintf(&new_path, "%s.ts", s->psz_path) < 0)
1849     {
1850         free(p_sys->m3u8);
1851         free(p_sys);
1852         return VLC_ENOMEM;
1853     }
1854     free(s->psz_path);
1855     s->psz_path = new_path;
1856
1857     p_sys->bandwidth = 0;
1858     p_sys->b_live = true;
1859     p_sys->b_meta = false;
1860     p_sys->b_error = false;
1861
1862     p_sys->hls_stream = vlc_array_new();
1863     if (p_sys->hls_stream == NULL)
1864     {
1865         free(p_sys->m3u8);
1866         free(p_sys);
1867         return VLC_ENOMEM;
1868     }
1869
1870     /* */
1871     s->pf_read = Read;
1872     s->pf_peek = Peek;
1873     s->pf_control = Control;
1874
1875     /* Parse HLS m3u8 content. */
1876     uint8_t *buffer = NULL;
1877     ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1878     if (len < 0)
1879         goto fail;
1880     if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
1881     {
1882         free(buffer);
1883         goto fail;
1884     }
1885     free(buffer);
1886     /* HLS standard doesn't provide any guaranty about streams
1887        being sorted by bandwidth, so we sort them */
1888     qsort( p_sys->hls_stream->pp_elems, p_sys->hls_stream->i_count,
1889            sizeof( hls_stream_t* ), &hls_CompareStreams );
1890
1891     /* Choose first HLS stream to start with */
1892     int current = p_sys->playback.stream = 0;
1893     p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
1894
1895     /* manage encryption key if needed */
1896     hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
1897
1898     if (p_sys->b_live && (p_sys->playback.segment < 0))
1899     {
1900         msg_Warn(s, "less data than 3 times 'target duration' available for live playback, playback may stall");
1901     }
1902
1903     if (Prefetch(s, &current) != VLC_SUCCESS)
1904     {
1905         msg_Err(s, "fetching first segment failed.");
1906         goto fail;
1907     }
1908
1909     p_sys->download.stream = current;
1910     p_sys->playback.stream = current;
1911     p_sys->download.seek = -1;
1912
1913     vlc_mutex_init(&p_sys->download.lock_wait);
1914     vlc_cond_init(&p_sys->download.wait);
1915
1916     /* Initialize HLS live stream */
1917     if (p_sys->b_live)
1918     {
1919         hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
1920         p_sys->playlist.last = mdate();
1921         p_sys->playlist.wakeup = p_sys->playlist.last +
1922                 ((mtime_t)hls->duration * UINT64_C(1000000));
1923
1924         if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
1925         {
1926             goto fail_thread;
1927         }
1928     }
1929
1930     if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
1931     {
1932         if (p_sys->b_live)
1933             vlc_join(p_sys->reload, NULL);
1934         goto fail_thread;
1935     }
1936
1937     return VLC_SUCCESS;
1938
1939 fail_thread:
1940     vlc_mutex_destroy(&p_sys->download.lock_wait);
1941     vlc_cond_destroy(&p_sys->download.wait);
1942
1943 fail:
1944     /* Free hls streams */
1945     for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1946     {
1947         hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
1948         if (hls) hls_Free(hls);
1949     }
1950     vlc_array_destroy(p_sys->hls_stream);
1951
1952     /* */
1953     free(p_sys->m3u8);
1954     free(p_sys);
1955     return VLC_EGENERIC;
1956 }
1957
1958 /****************************************************************************
1959  * Close
1960  ****************************************************************************/
1961 static void Close(vlc_object_t *p_this)
1962 {
1963     stream_t *s = (stream_t*)p_this;
1964     stream_sys_t *p_sys = s->p_sys;
1965
1966     assert(p_sys->hls_stream);
1967
1968     /* */
1969     vlc_mutex_lock(&p_sys->download.lock_wait);
1970     vlc_cond_signal(&p_sys->download.wait);
1971     vlc_mutex_unlock(&p_sys->download.lock_wait);
1972
1973     /* */
1974     if (p_sys->b_live)
1975         vlc_join(p_sys->reload, NULL);
1976     vlc_join(p_sys->thread, NULL);
1977     vlc_mutex_destroy(&p_sys->download.lock_wait);
1978     vlc_cond_destroy(&p_sys->download.wait);
1979
1980     /* Free hls streams */
1981     for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1982     {
1983         hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
1984         if (hls) hls_Free(hls);
1985     }
1986     vlc_array_destroy(p_sys->hls_stream);
1987
1988     /* */
1989     free(p_sys->m3u8);
1990     if (p_sys->peeked)
1991         block_Release (p_sys->peeked);
1992     free(p_sys);
1993 }
1994
1995 /****************************************************************************
1996  * Stream filters functions
1997  ****************************************************************************/
1998 static segment_t *GetSegment(stream_t *s)
1999 {
2000     stream_sys_t *p_sys = s->p_sys;
2001     segment_t *segment = NULL;
2002
2003     /* Is this segment of the current HLS stream ready? */
2004     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2005     if (hls != NULL)
2006     {
2007         vlc_mutex_lock(&hls->lock);
2008         segment = segment_GetSegment(hls, p_sys->playback.segment);
2009         if (segment != NULL)
2010         {
2011             vlc_mutex_lock(&segment->lock);
2012             /* This segment is ready? */
2013             if (segment->data != NULL)
2014             {
2015                 vlc_mutex_unlock(&segment->lock);
2016                 p_sys->b_cache = hls->b_cache;
2017                 vlc_mutex_unlock(&hls->lock);
2018                 goto check;
2019             }
2020             vlc_mutex_unlock(&segment->lock);
2021         }
2022         vlc_mutex_unlock(&hls->lock);
2023     }
2024
2025     /* Was the HLS stream changed to another bitrate? */
2026     segment = NULL;
2027     for (int i_stream = 0; i_stream < vlc_array_count(p_sys->hls_stream); i_stream++)
2028     {
2029         /* Is the next segment ready */
2030         hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2031         if (hls == NULL)
2032             return NULL;
2033
2034         vlc_mutex_lock(&hls->lock);
2035         segment = segment_GetSegment(hls, p_sys->playback.segment);
2036         if (segment == NULL)
2037         {
2038             vlc_mutex_unlock(&hls->lock);
2039             break;
2040         }
2041
2042         vlc_mutex_lock(&p_sys->download.lock_wait);
2043         int i_segment = p_sys->download.segment;
2044         vlc_mutex_unlock(&p_sys->download.lock_wait);
2045
2046         vlc_mutex_lock(&segment->lock);
2047         /* This segment is ready? */
2048         if ((segment->data != NULL) &&
2049             (p_sys->playback.segment < i_segment))
2050         {
2051             p_sys->playback.stream = i_stream;
2052             p_sys->b_cache = hls->b_cache;
2053             vlc_mutex_unlock(&segment->lock);
2054             vlc_mutex_unlock(&hls->lock);
2055             goto check;
2056         }
2057         vlc_mutex_unlock(&segment->lock);
2058         vlc_mutex_unlock(&hls->lock);
2059
2060         if (!p_sys->b_meta)
2061             break;
2062     }
2063     /* */
2064     return NULL;
2065
2066 check:
2067     /* sanity check */
2068     assert(segment->data);
2069     if (segment->data->i_buffer == 0)
2070     {
2071         vlc_mutex_lock(&hls->lock);
2072         int count = vlc_array_count(hls->segments);
2073         vlc_mutex_unlock(&hls->lock);
2074
2075         if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2076             ((count != p_sys->download.segment) || p_sys->b_live))
2077             msg_Err(s, "playback will stall");
2078         else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2079                  ((count != p_sys->download.segment) || p_sys->b_live))
2080             msg_Warn(s, "playback in danger of stalling");
2081     }
2082     return segment;
2083 }
2084
2085 static int segment_RestorePos(segment_t *segment)
2086 {
2087     if (segment->data)
2088     {
2089         uint64_t size = segment->size - segment->data->i_buffer;
2090         if (size > 0)
2091         {
2092             segment->data->i_buffer += size;
2093             segment->data->p_buffer -= size;
2094         }
2095     }
2096     return VLC_SUCCESS;
2097 }
2098
2099 /* p_read might be NULL if caller wants to skip data */
2100 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2101 {
2102     stream_sys_t *p_sys = s->p_sys;
2103     ssize_t used = 0;
2104
2105     do
2106     {
2107         /* Determine next segment to read. If this is a meta playlist and
2108          * bandwidth conditions changed, then the stream might have switched
2109          * to another bandwidth. */
2110         segment_t *segment = GetSegment(s);
2111         if (segment == NULL)
2112             break;
2113
2114         vlc_mutex_lock(&segment->lock);
2115         if (segment->data->i_buffer == 0)
2116         {
2117             if (!p_sys->b_cache || p_sys->b_live)
2118             {
2119                 block_Release(segment->data);
2120                 segment->data = NULL;
2121             }
2122             else
2123                 segment_RestorePos(segment);
2124
2125             p_sys->playback.segment++;
2126             vlc_mutex_unlock(&segment->lock);
2127
2128             /* signal download thread */
2129             vlc_mutex_lock(&p_sys->download.lock_wait);
2130             vlc_cond_signal(&p_sys->download.wait);
2131             vlc_mutex_unlock(&p_sys->download.lock_wait);
2132             continue;
2133         }
2134
2135         if (segment->size == segment->data->i_buffer)
2136             msg_Info(s, "playing segment %d from stream %d",
2137                      segment->sequence, p_sys->playback.stream);
2138
2139         ssize_t len = -1;
2140         if (i_read <= segment->data->i_buffer)
2141             len = i_read;
2142         else if (i_read > segment->data->i_buffer)
2143             len = segment->data->i_buffer;
2144
2145         if (len > 0)
2146         {
2147             if (p_read) /* if NULL, then caller skips data */
2148                 memcpy(p_read + used, segment->data->p_buffer, len);
2149             segment->data->i_buffer -= len;
2150             segment->data->p_buffer += len;
2151             used += len;
2152             i_read -= len;
2153         }
2154         vlc_mutex_unlock(&segment->lock);
2155
2156     } while (i_read > 0);
2157
2158     return used;
2159 }
2160
2161 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2162 {
2163     stream_sys_t *p_sys = s->p_sys;
2164     ssize_t length = 0;
2165
2166     assert(p_sys->hls_stream);
2167
2168     if (p_sys->b_error)
2169         return 0;
2170
2171     /* NOTE: buffer might be NULL if caller wants to skip data */
2172     length = hls_Read(s, (uint8_t*) buffer, i_read);
2173     if (length < 0)
2174         return 0;
2175
2176     p_sys->playback.offset += length;
2177     return length;
2178 }
2179
2180 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2181 {
2182     stream_sys_t *p_sys = s->p_sys;
2183     segment_t *segment;
2184     unsigned int len = i_peek;
2185
2186     segment = GetSegment(s);
2187     if (segment == NULL)
2188     {
2189         msg_Err(s, "segment %d should have been available (stream %d)",
2190                 p_sys->playback.segment, p_sys->playback.stream);
2191         return 0; /* eof? */
2192     }
2193
2194     vlc_mutex_lock(&segment->lock);
2195
2196     size_t i_buff = segment->data->i_buffer;
2197     uint8_t *p_buff = segment->data->p_buffer;
2198
2199     if (i_peek < i_buff)
2200     {
2201         *pp_peek = p_buff;
2202         vlc_mutex_unlock(&segment->lock);
2203         return i_peek;
2204     }
2205
2206     else /* This will seldom be run */
2207     {
2208         /* remember segment to read */
2209         int peek_segment = p_sys->playback.segment;
2210         size_t curlen = 0;
2211         segment_t *nsegment;
2212         p_sys->playback.segment++;
2213         block_t *peeked = p_sys->peeked;
2214
2215         if (peeked == NULL)
2216             peeked = block_Alloc (i_peek);
2217         else if (peeked->i_buffer < i_peek)
2218             peeked = block_Realloc (peeked, 0, i_peek);
2219         if (peeked == NULL)
2220             return 0;
2221         p_sys->peeked = peeked;
2222
2223         memcpy(peeked->p_buffer, p_buff, i_buff);
2224         curlen = i_buff;
2225         len -= i_buff;
2226         vlc_mutex_unlock(&segment->lock);
2227
2228         i_buff = peeked->i_buffer;
2229         p_buff = peeked->p_buffer;
2230         *pp_peek = p_buff;
2231
2232         while (curlen < i_peek)
2233         {
2234             nsegment = GetSegment(s);
2235             if (nsegment == NULL)
2236             {
2237                 msg_Err(s, "segment %d should have been available (stream %d)",
2238                         p_sys->playback.segment, p_sys->playback.stream);
2239                 /* restore segment to read */
2240                 p_sys->playback.segment = peek_segment;
2241                 return curlen; /* eof? */
2242             }
2243
2244             vlc_mutex_lock(&nsegment->lock);
2245
2246             if (len < nsegment->data->i_buffer)
2247             {
2248                 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2249                 curlen += len;
2250             }
2251             else
2252             {
2253                 size_t i_nbuff = nsegment->data->i_buffer;
2254                 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2255                 curlen += i_nbuff;
2256                 len -= i_nbuff;
2257
2258                 p_sys->playback.segment++;
2259             }
2260
2261             vlc_mutex_unlock(&nsegment->lock);
2262         }
2263
2264         /* restore segment to read */
2265         p_sys->playback.segment = peek_segment;
2266         return curlen;
2267     }
2268 }
2269
2270 static bool hls_MaySeek(stream_t *s)
2271 {
2272     stream_sys_t *p_sys = s->p_sys;
2273
2274     if (p_sys->hls_stream == NULL)
2275         return false;
2276
2277     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2278     if (hls == NULL) return false;
2279
2280     if (p_sys->b_live)
2281     {
2282         vlc_mutex_lock(&hls->lock);
2283         int count = vlc_array_count(hls->segments);
2284         vlc_mutex_unlock(&hls->lock);
2285
2286         vlc_mutex_lock(&p_sys->download.lock_wait);
2287         bool may_seek = (p_sys->download.segment < (count - 2));
2288         vlc_mutex_unlock(&p_sys->download.lock_wait);
2289         return may_seek;
2290     }
2291     return true;
2292 }
2293
2294 static uint64_t GetStreamSize(stream_t *s)
2295 {
2296     stream_sys_t *p_sys = s->p_sys;
2297
2298     if (p_sys->b_live)
2299         return 0;
2300
2301     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2302     if (hls == NULL) return 0;
2303
2304     vlc_mutex_lock(&hls->lock);
2305     if (hls->size == 0)
2306         hls->size = hls_GetStreamSize(hls);
2307     uint64_t size = hls->size;
2308     vlc_mutex_unlock(&hls->lock);
2309
2310     return size;
2311 }
2312
2313 static int segment_Seek(stream_t *s, const uint64_t pos)
2314 {
2315     stream_sys_t *p_sys = s->p_sys;
2316
2317     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2318     if (hls == NULL)
2319         return VLC_EGENERIC;
2320
2321     vlc_mutex_lock(&hls->lock);
2322
2323     bool b_found = false;
2324     uint64_t length = 0;
2325     uint64_t size = hls->size;
2326     int count = vlc_array_count(hls->segments);
2327
2328     /* restore current segment to start position */
2329     segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2330     if (segment == NULL)
2331     {
2332         vlc_mutex_unlock(&hls->lock);
2333         return VLC_EGENERIC;
2334     }
2335     vlc_mutex_lock(&segment->lock);
2336     segment_RestorePos(segment);
2337     vlc_mutex_unlock(&segment->lock);
2338
2339     for (int n = 0; n < count; n++)
2340     {
2341         segment_t *segment = segment_GetSegment(hls, n);
2342         if (segment == NULL)
2343         {
2344             vlc_mutex_unlock(&hls->lock);
2345             return VLC_EGENERIC;
2346         }
2347
2348         vlc_mutex_lock(&segment->lock);
2349         length += segment->duration * (hls->bandwidth/8);
2350         vlc_mutex_unlock(&segment->lock);
2351
2352         if (pos <= length)
2353         {
2354             if (count - n >= 3)
2355             {
2356                 p_sys->playback.segment = n;
2357                 b_found = true;
2358                 break;
2359             }
2360             /* Do not search in last 3 segments */
2361             vlc_mutex_unlock(&hls->lock);
2362             return VLC_EGENERIC;
2363         }
2364     }
2365
2366     /* */
2367     if (!b_found && (pos >= size))
2368     {
2369         p_sys->playback.segment = count - 1;
2370         b_found = true;
2371     }
2372
2373     /* */
2374     if (b_found)
2375     {
2376         /* restore segment to start position */
2377         segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2378         if (segment == NULL)
2379         {
2380             vlc_mutex_unlock(&hls->lock);
2381             return VLC_EGENERIC;
2382         }
2383
2384         vlc_mutex_lock(&segment->lock);
2385         segment_RestorePos(segment);
2386         vlc_mutex_unlock(&segment->lock);
2387
2388         /* start download at current playback segment */
2389         vlc_mutex_unlock(&hls->lock);
2390
2391         /* Wake up download thread */
2392         vlc_mutex_lock(&p_sys->download.lock_wait);
2393         p_sys->download.seek = p_sys->playback.segment;
2394         vlc_cond_signal(&p_sys->download.wait);
2395         vlc_mutex_unlock(&p_sys->download.lock_wait);
2396
2397         /* Wait for download to be finished */
2398         vlc_mutex_lock(&p_sys->download.lock_wait);
2399         msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2400         while (((p_sys->download.seek != -1) ||
2401                 (p_sys->download.segment - p_sys->playback.segment < 3)) &&
2402                 (p_sys->download.segment < (count - 6)))
2403         {
2404             vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2405             if (!vlc_object_alive(s) || s->b_error) break;
2406         }
2407         vlc_mutex_unlock(&p_sys->download.lock_wait);
2408
2409         return VLC_SUCCESS;
2410     }
2411     vlc_mutex_unlock(&hls->lock);
2412
2413     return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2414 }
2415
2416 static int Control(stream_t *s, int i_query, va_list args)
2417 {
2418     stream_sys_t *p_sys = s->p_sys;
2419
2420     switch (i_query)
2421     {
2422         case STREAM_CAN_SEEK:
2423             *(va_arg (args, bool *)) = hls_MaySeek(s);
2424             break;
2425         case STREAM_GET_POSITION:
2426             *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2427             break;
2428         case STREAM_SET_POSITION:
2429             if (hls_MaySeek(s))
2430             {
2431                 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2432                 if (segment_Seek(s, pos) == VLC_SUCCESS)
2433                 {
2434                     p_sys->playback.offset = pos;
2435                     break;
2436                 }
2437             }
2438             return VLC_EGENERIC;
2439         case STREAM_GET_SIZE:
2440             *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2441             break;
2442         default:
2443             return VLC_EGENERIC;
2444     }
2445     return VLC_SUCCESS;
2446 }