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