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