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