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