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