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