]> git.sesse.net Git - vlc/blob - modules/stream_filter/httplive.c
hls: Fix vod
[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                     hls_stream_t *hls = NULL;
1038                     err = parse_StreamInformation(s, &streams, &hls, line, uri);
1039                     free(uri);
1040
1041                     /* Download playlist file from server */
1042                     uint8_t *buf = NULL;
1043                     ssize_t len = read_M3U8_from_url(s, &hls->url, &buf);
1044                     if (len < 0)
1045                         err = VLC_EGENERIC;
1046                     else
1047                     {
1048                         /* Parse HLS m3u8 content. */
1049                         err = parse_M3U8(s, streams, buf, len);
1050                         free(buf);
1051                     }
1052
1053                     if (hls)
1054                     {
1055                         hls->version = version;
1056                         if (!p_sys->b_live)
1057                             hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
1058                     }
1059                 }
1060                 p_begin = p_read;
1061             }
1062
1063             free(line);
1064             line = NULL;
1065
1066             if (p_begin >= p_end)
1067                 break;
1068
1069         } while ((err == VLC_SUCCESS) && vlc_object_alive(s));
1070
1071     }
1072     else
1073     {
1074         msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
1075
1076         hls_stream_t *hls = NULL;
1077         if (p_sys->b_meta)
1078             hls = hls_GetLast(streams);
1079         else
1080         {
1081             /* No Meta playlist used */
1082             hls = hls_New(streams, 0, 0, NULL);
1083             if (hls)
1084             {
1085                 /* Get TARGET-DURATION first */
1086                 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1087                 if (p)
1088                 {
1089                     uint8_t *p_rest = NULL;
1090                     char *psz_duration = ReadLine(p, &p_rest,  p_end - p);
1091                     if (psz_duration == NULL)
1092                         return VLC_EGENERIC;
1093                     err = parse_TargetDuration(s, hls, psz_duration);
1094                     free(psz_duration);
1095                     p = NULL;
1096                 }
1097
1098                 /* Store version */
1099                 hls->version = version;
1100             }
1101             else return VLC_ENOMEM;
1102         }
1103         assert(hls);
1104
1105         /* */
1106         int segment_duration = -1;
1107         do
1108         {
1109             /* Next line */
1110             line = ReadLine(p_begin, &p_read, p_end - p_begin);
1111             if (line == NULL)
1112                 break;
1113             p_begin = p_read;
1114
1115             if (strncmp(line, "#EXTINF", 7) == 0)
1116                 err = parse_SegmentInformation(hls, line, &segment_duration);
1117             else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1118                 err = parse_TargetDuration(s, hls, line);
1119             else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1120                 err = parse_MediaSequence(s, hls, line);
1121             else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1122                 err = parse_Key(s, hls, line);
1123             else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1124                 err = parse_ProgramDateTime(s, hls, line);
1125             else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1126                 err = parse_AllowCache(s, hls, line);
1127             else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1128                 err = parse_Discontinuity(s, hls, line);
1129             else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1130                 err = parse_Version(s, hls, line);
1131             else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1132                 err = parse_EndList(s, hls);
1133             else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1134             {
1135                 err = parse_AddSegment(s, hls, segment_duration, line);
1136                 segment_duration = -1; /* reset duration */
1137             }
1138
1139             free(line);
1140             line = NULL;
1141
1142             if (p_begin >= p_end)
1143                 break;
1144
1145         } while ((err == VLC_SUCCESS) && vlc_object_alive(s));
1146
1147         free(line);
1148     }
1149
1150     return err;
1151 }
1152
1153
1154 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1155 {
1156     uint8_t         aeskey[32]; /* AES-512 can use up to 32 bytes */
1157     ssize_t len;
1158
1159     stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1160     if (p_m3u8 == NULL)
1161     {
1162         msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1163         return VLC_EGENERIC;
1164     }
1165
1166     len = stream_Read(p_m3u8, aeskey, sizeof(aeskey));
1167     if (len != AES_BLOCK_SIZE)
1168     {
1169         msg_Err(s, "The AES key loaded doesn't have the right size (%d)", len);
1170         stream_Delete(p_m3u8);
1171         return VLC_EGENERIC;
1172     }
1173
1174     memcpy(seg->psz_AES_key, aeskey, AES_BLOCK_SIZE);
1175
1176     stream_Delete(p_m3u8);
1177
1178     return VLC_SUCCESS;
1179 }
1180
1181 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1182 {
1183     segment_t   *seg = NULL;
1184     segment_t   *prev_seg;
1185     int         count = vlc_array_count(hls->segments);
1186
1187     for (int i = 0; i < count; i++)
1188     {
1189         prev_seg = seg;
1190         seg = segment_GetSegment(hls, i);
1191         if (seg->psz_key_path == NULL)
1192             continue;   /* No key to load ? continue */
1193         if (seg->b_key_loaded)
1194             continue;   /* The key is already loaded */
1195
1196         /* if the key has not changed, and already available from previous segment,
1197          * try to copy it, and don't load the key */
1198         if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1199         {
1200             memcpy(seg->psz_AES_key, prev_seg->psz_AES_key, AES_BLOCK_SIZE);
1201             seg->b_key_loaded = true;
1202             continue;
1203         }
1204         if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1205             return VLC_EGENERIC;
1206        seg->b_key_loaded = true;
1207     }
1208     return VLC_SUCCESS;
1209 }
1210
1211 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1212 {
1213     /* Did the segment need to be decoded ? */
1214     if (segment->psz_key_path == NULL)
1215         return VLC_SUCCESS;
1216
1217     /* Do we have loaded the key ? */
1218     if (!segment->b_key_loaded)
1219     {
1220         /* No ? try to download it now */
1221         if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1222             return VLC_EGENERIC;
1223     }
1224
1225     /* For now, we only decode AES-128 data */
1226     gcry_error_t i_gcrypt_err;
1227     gcry_cipher_hd_t aes_ctx;
1228     /* Setup AES */
1229     i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1230                                      GCRY_CIPHER_MODE_CBC, 0);
1231     if (i_gcrypt_err)
1232     {
1233         msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1234         gcry_cipher_close(aes_ctx);
1235         return VLC_EGENERIC;
1236     }
1237
1238     /* Set key */
1239     i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->psz_AES_key,
1240                                        sizeof(segment->psz_AES_key));
1241     if (i_gcrypt_err)
1242     {
1243         msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1244         gcry_cipher_close(aes_ctx);
1245         return VLC_EGENERIC;
1246     }
1247
1248     if (hls->b_iv_loaded == false)
1249     {
1250         memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1251         hls->psz_AES_IV[15] = segment->sequence & 0xff;
1252         hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1253         hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1254         hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1255     }
1256
1257     i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1258                                       sizeof(hls->psz_AES_IV));
1259
1260     if (i_gcrypt_err)
1261     {
1262         msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1263         gcry_cipher_close(aes_ctx);
1264         return VLC_EGENERIC;
1265     }
1266
1267     i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1268                                        segment->data->p_buffer, /* out */
1269                                        segment->data->i_buffer,
1270                                        NULL, /* in */
1271                                        0);
1272     if (i_gcrypt_err)
1273     {
1274         msg_Err(s, "gcry_cipher_decrypt failed:  %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1275         gcry_cipher_close(aes_ctx);
1276         return VLC_EGENERIC;
1277     }
1278     gcry_cipher_close(aes_ctx);
1279     /* remove the PKCS#7 padding from the buffer */
1280     int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1281     if (pad <= 0 || pad > AES_BLOCK_SIZE)
1282     {
1283         msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1284         return VLC_EGENERIC;
1285     }
1286     int count = pad;
1287     while (count--)
1288     {
1289         if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1290         {
1291                 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1292                 return VLC_EGENERIC;
1293         }
1294     }
1295
1296     /* not all the data is readable because of padding */
1297     segment->data->i_buffer -= pad;
1298
1299     return VLC_SUCCESS;
1300 }
1301
1302 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1303 {
1304     stream_sys_t *p_sys = s->p_sys;
1305     assert(*streams);
1306     int err = VLC_EGENERIC;
1307
1308     /* Duplicate HLS stream META information */
1309     for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1310     {
1311         hls_stream_t *src, *dst;
1312         src = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
1313         if (src == NULL)
1314             return VLC_EGENERIC;
1315
1316         dst = hls_Copy(src, false);
1317         if (dst == NULL)
1318             return VLC_ENOMEM;
1319
1320         vlc_array_append(*streams, dst);
1321     }
1322
1323     /* Download new playlist file from server */
1324     for (int i = 0; i < vlc_array_count(*streams); i++)
1325     {
1326         hls_stream_t *hls;
1327         hls = (hls_stream_t *)vlc_array_item_at_index(*streams, i);
1328         if (hls == NULL)
1329             return VLC_EGENERIC;
1330
1331         /* Download playlist file from server */
1332         uint8_t *buf = NULL;
1333         ssize_t len = read_M3U8_from_url(s, &hls->url, &buf);
1334         if (len < 0)
1335             err = VLC_EGENERIC;
1336         else
1337         {
1338             /* Parse HLS m3u8 content. */
1339             err = parse_M3U8(s, *streams, buf, len);
1340             free(buf);
1341         }
1342     }
1343     return err;
1344 }
1345
1346 /* Reload playlist */
1347 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t **hls)
1348 {
1349     int count = vlc_array_count(hls_new->segments);
1350
1351     msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1352              hls_new->id, hls_new->bandwidth, count);
1353
1354     for (int n = 0; n < count; n++)
1355     {
1356         segment_t *p = segment_GetSegment(hls_new, n);
1357         if (p == NULL) return VLC_EGENERIC;
1358
1359         vlc_mutex_lock(&(*hls)->lock);
1360         segment_t *segment = segment_Find(*hls, p->sequence);
1361         if (segment)
1362         {
1363             vlc_mutex_lock(&segment->lock);
1364
1365             assert(p->url.psz_path);
1366             assert(segment->url.psz_path);
1367
1368             /* they should be the same */
1369             if ((p->sequence != segment->sequence) ||
1370                 (p->duration != segment->duration) ||
1371                 (strcmp(p->url.psz_path, segment->url.psz_path) != 0))
1372             {
1373                 msg_Warn(s, "existing segment found with different content - resetting");
1374                 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1375                 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1376                 msg_Warn(s, "- file: new=%s", p->url.psz_path);
1377                 msg_Warn(s, "        old=%s", segment->url.psz_path);
1378
1379                 /* Resetting content */
1380                 char *psz_url = ConstructUrl(&p->url);
1381                 if (psz_url == NULL)
1382                 {
1383                     msg_Err(s, "Failed updating segment %d - skipping it",  p->sequence);
1384                     segment_Free(p);
1385                     vlc_mutex_unlock(&segment->lock);
1386                     continue;
1387                 }
1388                 segment->sequence = p->sequence;
1389                 segment->duration = p->duration;
1390                 vlc_UrlClean(&segment->url);
1391                 vlc_UrlParse(&segment->url, psz_url, 0);
1392                 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1393                 if (segment->data)
1394                 {
1395                     block_Release(segment->data);
1396                     segment->data = NULL;
1397                 }
1398                 free(segment->psz_key_path);
1399                 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1400                 vlc_mutex_unlock(&segment->lock);
1401                 segment_Free(p);
1402                 free(psz_url);
1403             }
1404         }
1405         else
1406         {
1407             int last = vlc_array_count((*hls)->segments) - 1;
1408             segment_t *l = segment_GetSegment(*hls, last);
1409             if (l == NULL) goto fail_and_unlock;
1410
1411             if ((l->sequence + 1) != p->sequence)
1412             {
1413                 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1414                         p->sequence, l->sequence+1);
1415             }
1416             vlc_array_append((*hls)->segments, p);
1417             msg_Info(s, "- segment %d appended", p->sequence);
1418         }
1419         vlc_mutex_unlock(&(*hls)->lock);
1420     }
1421
1422     /* update meta information */
1423     vlc_mutex_lock(&(*hls)->lock);
1424     (*hls)->sequence = hls_new->sequence;
1425     (*hls)->duration = (hls_new->duration == -1) ? (*hls)->duration : hls_new->duration;
1426     (*hls)->b_cache = hls_new->b_cache;
1427     vlc_mutex_unlock(&(*hls)->lock);
1428     return VLC_SUCCESS;
1429
1430 fail_and_unlock:
1431     assert(0);
1432     vlc_mutex_unlock(&(*hls)->lock);
1433     return VLC_EGENERIC;
1434 }
1435
1436 static int hls_ReloadPlaylist(stream_t *s)
1437 {
1438     stream_sys_t *p_sys = s->p_sys;
1439
1440     vlc_array_t *hls_streams = vlc_array_new();
1441     if (hls_streams == NULL)
1442         return VLC_ENOMEM;
1443
1444     msg_Info(s, "Reloading HLS live meta playlist");
1445
1446     if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1447     {
1448         /* Free hls streams */
1449         for (int i = 0; i < vlc_array_count(hls_streams); i++)
1450         {
1451             hls_stream_t *hls;
1452             hls = (hls_stream_t *)vlc_array_item_at_index(hls_streams, i);
1453             if (hls) hls_Free(hls);
1454         }
1455         vlc_array_destroy(hls_streams);
1456
1457         msg_Err(s, "reloading playlist failed");
1458         return VLC_EGENERIC;
1459     }
1460
1461     /* merge playlists */
1462     int count = vlc_array_count(hls_streams);
1463     for (int n = 0; n < count; n++)
1464     {
1465         hls_stream_t *hls_new = hls_Get(hls_streams, n);
1466         if (hls_new == NULL)
1467             continue;
1468
1469         hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1470         if (hls_old == NULL)
1471         {   /* new hls stream - append */
1472             vlc_array_append(p_sys->hls_stream, hls_new);
1473             msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1474                      hls_new->id, hls_new->bandwidth);
1475         }
1476         else if (hls_UpdatePlaylist(s, hls_new, &hls_old) != VLC_SUCCESS)
1477             msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1478                      hls_new->id, hls_new->bandwidth);
1479     }
1480     vlc_array_destroy(hls_streams);
1481     return VLC_SUCCESS;
1482 }
1483
1484 /****************************************************************************
1485  * hls_Thread
1486  ****************************************************************************/
1487 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1488 {
1489     stream_sys_t *p_sys = s->p_sys;
1490     int candidate = -1;
1491     uint64_t bw = *bandwidth;
1492     uint64_t bw_candidate = 0;
1493
1494     int count = vlc_array_count(p_sys->hls_stream);
1495     for (int n = 0; n < count; n++)
1496     {
1497         /* Select best bandwidth match */
1498         hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1499         if (hls == NULL) break;
1500
1501         /* only consider streams with the same PROGRAM-ID */
1502         if (hls->id == progid)
1503         {
1504             if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1505             {
1506                 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1507                          n, bw, hls->bandwidth); /* bits / s */
1508                 bw_candidate = hls->bandwidth;
1509                 candidate = n; /* possible candidate */
1510             }
1511         }
1512     }
1513     *bandwidth = bw_candidate;
1514     return candidate;
1515 }
1516
1517 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1518 {
1519     stream_sys_t *p_sys = s->p_sys;
1520
1521     assert(hls);
1522     assert(segment);
1523
1524     vlc_mutex_lock(&segment->lock);
1525     if (segment->data != NULL)
1526     {
1527         /* Segment already downloaded */
1528         vlc_mutex_unlock(&segment->lock);
1529         return VLC_SUCCESS;
1530     }
1531
1532     /* sanity check - can we download this segment on time? */
1533     if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1534     {
1535         uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1536         int estimated = (int)(size / p_sys->bandwidth);
1537         if (estimated > segment->duration)
1538         {
1539             msg_Warn(s,"downloading of segment %d takes %ds, which is longer than its playback (%ds)",
1540                         segment->sequence, estimated, segment->duration);
1541         }
1542     }
1543
1544     mtime_t start = mdate();
1545     if (hls_Download(s, segment) != VLC_SUCCESS)
1546     {
1547         msg_Err(s, "downloaded segment %d from stream %d failed",
1548                     segment->sequence, *cur_stream);
1549         vlc_mutex_unlock(&segment->lock);
1550         return VLC_EGENERIC;
1551     }
1552     mtime_t duration = mdate() - start;
1553
1554     /* If the segment is encrypted, decode it */
1555     if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1556     {
1557         vlc_mutex_unlock(&segment->lock);
1558         return VLC_EGENERIC;
1559     }
1560
1561     vlc_mutex_unlock(&segment->lock);
1562
1563     msg_Info(s, "downloaded segment %d from stream %d",
1564                 segment->sequence, *cur_stream);
1565
1566     /* check for division by zero */
1567     double ms = (double)duration / 1000.0; /* ms */
1568     if (ms <= 0.0)
1569         return VLC_SUCCESS;
1570
1571     uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
1572     p_sys->bandwidth = bw;
1573     if (p_sys->b_meta && (hls->bandwidth != bw))
1574     {
1575         int newstream = BandwidthAdaptation(s, hls->id, &bw);
1576
1577         /* FIXME: we need an average here */
1578         if ((newstream >= 0) && (newstream != *cur_stream))
1579         {
1580             msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1581                      (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1582             *cur_stream = newstream;
1583         }
1584     }
1585     return VLC_SUCCESS;
1586 }
1587
1588 static void* hls_Thread(void *p_this)
1589 {
1590     stream_t *s = (stream_t *)p_this;
1591     stream_sys_t *p_sys = s->p_sys;
1592
1593     int canc = vlc_savecancel();
1594
1595     while (vlc_object_alive(s))
1596     {
1597         hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1598         assert(hls);
1599
1600         /* Sliding window (~60 seconds worth of movie) */
1601         vlc_mutex_lock(&hls->lock);
1602         int count = vlc_array_count(hls->segments);
1603         vlc_mutex_unlock(&hls->lock);
1604
1605         /* Is there a new segment to process? */
1606         if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1607             (p_sys->download.segment >= count))
1608         {
1609             /* wait */
1610             vlc_mutex_lock(&p_sys->download.lock_wait);
1611             while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1612                     (p_sys->download.segment >= count)) &&
1613                    (p_sys->download.seek == -1))
1614             {
1615                 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1616                 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1617                     break;
1618                 if (!vlc_object_alive(s))
1619                     break;
1620             }
1621             /* */
1622             if (p_sys->download.seek >= 0)
1623             {
1624                 p_sys->download.segment = p_sys->download.seek;
1625                 p_sys->download.seek = -1;
1626             }
1627             vlc_mutex_unlock(&p_sys->download.lock_wait);
1628         }
1629
1630         if (!vlc_object_alive(s)) break;
1631
1632         vlc_mutex_lock(&hls->lock);
1633         segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1634         vlc_mutex_unlock(&hls->lock);
1635
1636         if ((segment != NULL) &&
1637             (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1638         {
1639             if (!vlc_object_alive(s)) break;
1640
1641             if (!p_sys->b_live)
1642             {
1643                 p_sys->b_error = true;
1644                 break;
1645             }
1646         }
1647
1648         /* download succeeded */
1649         /* determine next segment to download */
1650         vlc_mutex_lock(&p_sys->download.lock_wait);
1651         if (p_sys->download.seek >= 0)
1652         {
1653             p_sys->download.segment = p_sys->download.seek;
1654             p_sys->download.seek = -1;
1655         }
1656         else if (p_sys->download.segment < count)
1657             p_sys->download.segment++;
1658         vlc_cond_signal(&p_sys->download.wait);
1659         vlc_mutex_unlock(&p_sys->download.lock_wait);
1660     }
1661
1662     vlc_restorecancel(canc);
1663     return NULL;
1664 }
1665
1666 static void* hls_Reload(void *p_this)
1667 {
1668     stream_t *s = (stream_t *)p_this;
1669     stream_sys_t *p_sys = s->p_sys;
1670
1671     assert(p_sys->b_live);
1672
1673     int canc = vlc_savecancel();
1674
1675     double wait = 0.5;
1676     while (vlc_object_alive(s))
1677     {
1678         mtime_t now = mdate();
1679         if (now >= p_sys->playlist.wakeup)
1680         {
1681             /* reload the m3u8 */
1682             if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1683             {
1684                 /* No change in playlist, then backoff */
1685                 p_sys->playlist.tries++;
1686                 if (p_sys->playlist.tries == 1) wait = 0.5;
1687                 else if (p_sys->playlist.tries == 2) wait = 1;
1688                 else if (p_sys->playlist.tries >= 3) wait = 2;
1689
1690                 /* Can we afford to backoff? */
1691                 if (p_sys->download.segment - p_sys->playback.segment < 3)
1692                 {
1693                     p_sys->playlist.tries = 0;
1694                     wait = 0.5;
1695                 }
1696             }
1697             else
1698             {
1699                 p_sys->playlist.tries = 0;
1700                 wait = 0.5;
1701             }
1702
1703             hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1704             assert(hls);
1705
1706             /* determine next time to update playlist */
1707             p_sys->playlist.last = now;
1708             p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1709                                                    * (mtime_t)1000000);
1710         }
1711
1712         mwait(p_sys->playlist.wakeup);
1713     }
1714
1715     vlc_restorecancel(canc);
1716     return NULL;
1717 }
1718
1719 static int Prefetch(stream_t *s, int *current)
1720 {
1721     stream_sys_t *p_sys = s->p_sys;
1722     int stream;
1723
1724     /* Try to pick best matching stream */;
1725 again:
1726     stream = *current;
1727
1728     hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1729     if (hls == NULL)
1730         return VLC_EGENERIC;
1731
1732     segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1733     if (segment == NULL )
1734         return VLC_EGENERIC;
1735
1736     if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1737         return VLC_EGENERIC;
1738
1739     /* Found better bandwidth match, try again */
1740     if (*current != stream)
1741         goto again;
1742
1743     /* Download first 2 segments of this HLS stream */
1744     stream = *current;
1745     for (int i = 0; i < 2; i++)
1746     {
1747         segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1748         if (segment == NULL )
1749             return VLC_EGENERIC;
1750
1751         if (segment->data)
1752         {
1753             p_sys->download.segment++;
1754             continue;
1755         }
1756
1757         if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1758             return VLC_EGENERIC;
1759
1760         p_sys->download.segment++;
1761
1762         /* adapt bandwidth? */
1763         if (*current != stream)
1764         {
1765             hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1766             if (hls == NULL)
1767                 return VLC_EGENERIC;
1768
1769              stream = *current;
1770         }
1771     }
1772
1773     return VLC_SUCCESS;
1774 }
1775
1776 /****************************************************************************
1777  *
1778  ****************************************************************************/
1779 static int hls_Download(stream_t *s, segment_t *segment)
1780 {
1781     assert(segment);
1782
1783     /* Construct URL */
1784     char *psz_url = ConstructUrl(&segment->url);
1785     if (psz_url == NULL)
1786            return VLC_ENOMEM;
1787
1788     stream_t *p_ts = stream_UrlNew(s, psz_url);
1789     free(psz_url);
1790     if (p_ts == NULL)
1791         return VLC_EGENERIC;
1792
1793     segment->size = stream_Size(p_ts);
1794     assert(segment->size > 0);
1795
1796     segment->data = block_Alloc(segment->size);
1797     if (segment->data == NULL)
1798     {
1799         stream_Delete(p_ts);
1800         return VLC_ENOMEM;
1801     }
1802
1803     assert(segment->data->i_buffer == segment->size);
1804
1805     ssize_t length = 0, curlen = 0;
1806     uint64_t size;
1807     do
1808     {
1809         size = stream_Size(p_ts);
1810         if (size > segment->size)
1811         {
1812             msg_Dbg(s, "size changed %"PRIu64, segment->size);
1813             block_t *p_block = block_Realloc(segment->data, 0, size);
1814             if (p_block == NULL)
1815             {
1816                 stream_Delete(p_ts);
1817                 block_Release(segment->data);
1818                 segment->data = NULL;
1819                 return VLC_ENOMEM;
1820             }
1821             segment->data = p_block;
1822             segment->size = size;
1823             assert(segment->data->i_buffer == segment->size);
1824             p_block = NULL;
1825         }
1826         length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1827         if (length <= 0)
1828             break;
1829         curlen += length;
1830     } while (vlc_object_alive(s));
1831
1832     stream_Delete(p_ts);
1833     return VLC_SUCCESS;
1834 }
1835
1836 /* Read M3U8 file */
1837 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1838 {
1839     int64_t total_bytes = 0;
1840     int64_t total_allocated = 0;
1841     uint8_t *p = NULL;
1842
1843     while (1)
1844     {
1845         char buf[4096];
1846         int64_t bytes;
1847
1848         bytes = stream_Read(s, buf, sizeof(buf));
1849         if (bytes == 0)
1850             break;      /* EOF ? */
1851         else if (bytes < 0)
1852             return bytes;
1853
1854         if ( (total_bytes + bytes + 1) > total_allocated )
1855         {
1856             if (total_allocated)
1857                 total_allocated *= 2;
1858             else
1859                 total_allocated = __MIN(bytes+1, sizeof(buf));
1860
1861             p = realloc_or_free(p, total_allocated);
1862             if (p == NULL)
1863                 return VLC_ENOMEM;
1864         }
1865
1866         memcpy(p+total_bytes, buf, bytes);
1867         total_bytes += bytes;
1868     }
1869
1870     if (total_allocated == 0)
1871         return VLC_EGENERIC;
1872
1873     p[total_bytes] = '\0';
1874     *buffer = p;
1875
1876     return total_bytes;
1877 }
1878
1879 static ssize_t read_M3U8_from_url(stream_t *s, vlc_url_t *url, uint8_t **buffer)
1880 {
1881     assert(*buffer == NULL);
1882
1883     /* Construct URL */
1884     char *psz_url = ConstructUrl(url);
1885     if (psz_url == NULL)
1886            return VLC_ENOMEM;
1887
1888     stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1889     free(psz_url);
1890     if (p_m3u8 == NULL)
1891         return VLC_EGENERIC;
1892
1893     ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1894     stream_Delete(p_m3u8);
1895
1896     return size;
1897 }
1898
1899 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1900 {
1901     assert(buffer);
1902
1903     char *line = NULL;
1904     uint8_t *begin = buffer;
1905     uint8_t *p = begin;
1906     uint8_t *end = p + len;
1907
1908     while (p < end)
1909     {
1910         if ((*p == '\n') || (*p == '\0'))
1911             break;
1912         p++;
1913     }
1914
1915     /* copy line excluding \n or \0 */
1916     line = strndup((char *)begin, p - begin);
1917
1918     if (*p == '\0')
1919         *pos = end;
1920     else
1921     {
1922         /* next pass start after \n */
1923         p++;
1924         *pos = p;
1925     }
1926
1927     return line;
1928 }
1929
1930 /****************************************************************************
1931  * Open
1932  ****************************************************************************/
1933 static int Open(vlc_object_t *p_this)
1934 {
1935     stream_t *s = (stream_t*)p_this;
1936     stream_sys_t *p_sys;
1937
1938     if (!isHTTPLiveStreaming(s))
1939         return VLC_EGENERIC;
1940
1941     msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1942
1943     /* Initialize crypto bit */
1944     vlc_gcrypt_init();
1945
1946     /* */
1947     s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1948     if (p_sys == NULL)
1949         return VLC_ENOMEM;
1950
1951     char *psz_uri = NULL;
1952     if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1953     {
1954         free(p_sys);
1955         return VLC_ENOMEM;
1956     }
1957     vlc_UrlParse(&p_sys->m3u8, psz_uri, 0);
1958     free(psz_uri);
1959
1960     p_sys->bandwidth = 0;
1961     p_sys->b_live = true;
1962     p_sys->b_meta = false;
1963     p_sys->b_error = false;
1964
1965     p_sys->hls_stream = vlc_array_new();
1966     if (p_sys->hls_stream == NULL)
1967     {
1968         vlc_UrlClean(&p_sys->m3u8);
1969         free(p_sys);
1970         return VLC_ENOMEM;
1971     }
1972
1973     /* */
1974     s->pf_read = Read;
1975     s->pf_peek = Peek;
1976     s->pf_control = Control;
1977
1978     /* Parse HLS m3u8 content. */
1979     uint8_t *buffer = NULL;
1980     ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1981     if (len < 0)
1982         goto fail;
1983     if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
1984     {
1985         free(buffer);
1986         goto fail;
1987     }
1988     free(buffer);
1989
1990     /* Choose first HLS stream to start with */
1991     int current = p_sys->playback.stream = 0;
1992     p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
1993
1994     /* manage encryption key if needed */
1995     hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
1996
1997     if (p_sys->b_live && (p_sys->playback.segment < 0))
1998     {
1999         msg_Warn(s, "less data than 3 times 'target duration' available for live playback, playback may stall");
2000     }
2001
2002     if (Prefetch(s, &current) != VLC_SUCCESS)
2003     {
2004         msg_Err(s, "fetching first segment failed.");
2005         goto fail;
2006     }
2007
2008
2009     p_sys->download.stream = current;
2010     p_sys->playback.stream = current;
2011     p_sys->download.seek = -1;
2012
2013     vlc_mutex_init(&p_sys->download.lock_wait);
2014     vlc_cond_init(&p_sys->download.wait);
2015
2016     /* Initialize HLS live stream */
2017     if (p_sys->b_live)
2018     {
2019         hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
2020         p_sys->playlist.last = mdate();
2021         p_sys->playlist.wakeup = p_sys->playlist.last +
2022                 ((mtime_t)hls->duration * UINT64_C(1000000));
2023
2024         if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
2025         {
2026             goto fail_thread;
2027         }
2028     }
2029
2030     if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
2031     {
2032         if (p_sys->b_live)
2033             vlc_join(p_sys->reload, NULL);
2034         goto fail_thread;
2035     }
2036
2037     return VLC_SUCCESS;
2038
2039 fail_thread:
2040     vlc_mutex_destroy(&p_sys->download.lock_wait);
2041     vlc_cond_destroy(&p_sys->download.wait);
2042
2043 fail:
2044     /* Free hls streams */
2045     for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2046     {
2047         hls_stream_t *hls;
2048         hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
2049         if (hls) hls_Free(hls);
2050     }
2051     vlc_array_destroy(p_sys->hls_stream);
2052
2053     /* */
2054     vlc_UrlClean(&p_sys->m3u8);
2055     free(p_sys);
2056     return VLC_EGENERIC;
2057 }
2058
2059 /****************************************************************************
2060  * Close
2061  ****************************************************************************/
2062 static void Close(vlc_object_t *p_this)
2063 {
2064     stream_t *s = (stream_t*)p_this;
2065     stream_sys_t *p_sys = s->p_sys;
2066
2067     assert(p_sys->hls_stream);
2068
2069     /* */
2070     vlc_mutex_lock(&p_sys->download.lock_wait);
2071     vlc_cond_signal(&p_sys->download.wait);
2072     vlc_mutex_unlock(&p_sys->download.lock_wait);
2073
2074     /* */
2075     if (p_sys->b_live)
2076         vlc_join(p_sys->reload, NULL);
2077     vlc_join(p_sys->thread, NULL);
2078     vlc_mutex_destroy(&p_sys->download.lock_wait);
2079     vlc_cond_destroy(&p_sys->download.wait);
2080
2081     /* Free hls streams */
2082     for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2083     {
2084         hls_stream_t *hls;
2085         hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
2086         if (hls) hls_Free(hls);
2087     }
2088     vlc_array_destroy(p_sys->hls_stream);
2089
2090     /* */
2091     vlc_UrlClean(&p_sys->m3u8);
2092     if (p_sys->peeked)
2093         block_Release (p_sys->peeked);
2094     free(p_sys);
2095 }
2096
2097 /****************************************************************************
2098  * Stream filters functions
2099  ****************************************************************************/
2100 static segment_t *GetSegment(stream_t *s)
2101 {
2102     stream_sys_t *p_sys = s->p_sys;
2103     segment_t *segment = NULL;
2104
2105     /* Is this segment of the current HLS stream ready? */
2106     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2107     if (hls != NULL)
2108     {
2109         vlc_mutex_lock(&hls->lock);
2110         segment = segment_GetSegment(hls, p_sys->playback.segment);
2111         if (segment != NULL)
2112         {
2113             /* This segment is ready? */
2114             if (segment->data != NULL)
2115             {
2116                 p_sys->b_cache = hls->b_cache;
2117                 vlc_mutex_unlock(&hls->lock);
2118                 goto check;
2119             }
2120         }
2121         vlc_mutex_unlock(&hls->lock);
2122     }
2123
2124     /* Was the HLS stream changed to another bitrate? */
2125     int i_stream = 0;
2126     segment = NULL;
2127     while(vlc_object_alive(s))
2128     {
2129         /* Is the next segment ready */
2130         hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2131         if (hls == NULL)
2132             return NULL;
2133
2134         vlc_mutex_lock(&hls->lock);
2135         segment = segment_GetSegment(hls, p_sys->playback.segment);
2136         if (segment == NULL)
2137         {
2138             vlc_mutex_unlock(&hls->lock);
2139             break;
2140         }
2141
2142         vlc_mutex_lock(&p_sys->download.lock_wait);
2143         int i_segment = p_sys->download.segment;
2144         vlc_mutex_unlock(&p_sys->download.lock_wait);
2145
2146         /* This segment is ready? */
2147         if ((segment->data != NULL) &&
2148             (p_sys->playback.segment < i_segment))
2149         {
2150             p_sys->playback.stream = i_stream;
2151             p_sys->b_cache = hls->b_cache;
2152             vlc_mutex_unlock(&hls->lock);
2153             goto check;
2154         }
2155         vlc_mutex_unlock(&hls->lock);
2156
2157         if (!p_sys->b_meta)
2158             break;
2159
2160         /* Was the stream changed to another bitrate? */
2161         i_stream++;
2162         if (i_stream >= vlc_array_count(p_sys->hls_stream))
2163             break;
2164     }
2165     /* */
2166     return NULL;
2167
2168 check:
2169     /* sanity check */
2170     if (segment->data->i_buffer == 0)
2171     {
2172         vlc_mutex_lock(&hls->lock);
2173         int count = vlc_array_count(hls->segments);
2174         vlc_mutex_unlock(&hls->lock);
2175
2176         if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2177             ((count != p_sys->download.segment) || p_sys->b_live))
2178             msg_Err(s, "playback will stall");
2179         else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2180                  ((count != p_sys->download.segment) || p_sys->b_live))
2181             msg_Warn(s, "playback in danger of stalling");
2182     }
2183     return segment;
2184 }
2185
2186 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2187 {
2188     stream_sys_t *p_sys = s->p_sys;
2189     ssize_t copied = 0;
2190
2191     do
2192     {
2193         /* Determine next segment to read. If this is a meta playlist and
2194          * bandwidth conditions changed, then the stream might have switched
2195          * to another bandwidth. */
2196         segment_t *segment = GetSegment(s);
2197         if (segment == NULL)
2198             break;
2199
2200         vlc_mutex_lock(&segment->lock);
2201         if (segment->data->i_buffer == 0)
2202         {
2203             if (!p_sys->b_cache || p_sys->b_live)
2204             {
2205                 block_Release(segment->data);
2206                 segment->data = NULL;
2207             }
2208             else
2209             {   /* reset playback pointer to start of buffer */
2210                 uint64_t size = segment->size - segment->data->i_buffer;
2211                 if (size > 0)
2212                 {
2213                     segment->data->i_buffer += size;
2214                     segment->data->p_buffer -= size;
2215                 }
2216             }
2217             p_sys->playback.segment++;
2218             vlc_mutex_unlock(&segment->lock);
2219
2220             /* signal download thread */
2221             vlc_mutex_lock(&p_sys->download.lock_wait);
2222             vlc_cond_signal(&p_sys->download.wait);
2223             vlc_mutex_unlock(&p_sys->download.lock_wait);
2224             continue;
2225         }
2226
2227         if (segment->size == segment->data->i_buffer)
2228             msg_Info(s, "playing segment %d from stream %d",
2229                      segment->sequence, p_sys->playback.stream);
2230
2231         ssize_t len = -1;
2232         if (i_read <= segment->data->i_buffer)
2233             len = i_read;
2234         else if (i_read > segment->data->i_buffer)
2235             len = segment->data->i_buffer;
2236
2237         if (len > 0)
2238         {
2239             memcpy(p_read + copied, segment->data->p_buffer, len);
2240             segment->data->i_buffer -= len;
2241             segment->data->p_buffer += len;
2242             copied += len;
2243             i_read -= len;
2244         }
2245         vlc_mutex_unlock(&segment->lock);
2246
2247     } while ((i_read > 0) && vlc_object_alive(s));
2248
2249     return copied;
2250 }
2251
2252 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2253 {
2254     stream_sys_t *p_sys = s->p_sys;
2255     ssize_t length = 0;
2256
2257     assert(p_sys->hls_stream);
2258
2259     if (p_sys->b_error)
2260         return 0;
2261
2262     if (buffer == NULL)
2263     {
2264         /* caller skips data, get big enough buffer */
2265         msg_Warn(s, "buffer is NULL (allocate %d)", i_read);
2266         buffer = calloc(1, i_read);
2267         if (buffer == NULL)
2268             return 0; /* NO MEMORY left*/
2269     }
2270
2271     length = hls_Read(s, (uint8_t*) buffer, i_read);
2272     if (length < 0)
2273         return 0;
2274
2275     p_sys->playback.offset += length;
2276     return length;
2277 }
2278
2279 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2280 {
2281     stream_sys_t *p_sys = s->p_sys;
2282     segment_t *segment;
2283     unsigned int len = i_peek;
2284
2285     segment = GetSegment(s);
2286     if (segment == NULL)
2287     {
2288         msg_Err(s, "segment %d should have been available (stream %d)",
2289                 p_sys->playback.segment, p_sys->playback.stream);
2290         return 0; /* eof? */
2291     }
2292
2293     vlc_mutex_lock(&segment->lock);
2294
2295     size_t i_buff = segment->data->i_buffer;
2296     uint8_t *p_buff = segment->data->p_buffer;
2297
2298     if (i_peek < i_buff)
2299     {
2300         *pp_peek = p_buff;
2301         vlc_mutex_unlock(&segment->lock);
2302         return i_peek;
2303     }
2304
2305     else /* This will seldom be run */
2306     {
2307         /* remember segment to read */
2308         int peek_segment = p_sys->playback.segment;
2309         size_t curlen = 0;
2310         segment_t *nsegment;
2311         p_sys->playback.segment++;
2312         block_t *peeked = p_sys->peeked;
2313
2314         if (peeked == NULL)
2315             peeked = block_Alloc (i_peek);
2316         else if (peeked->i_buffer < i_peek)
2317             peeked = block_Realloc (peeked, 0, i_peek);
2318         if (peeked == NULL)
2319             return 0;
2320
2321         memcpy(peeked->p_buffer, p_buff, i_buff);
2322         curlen = i_buff;
2323         len -= i_buff;
2324         vlc_mutex_unlock(&segment->lock);
2325
2326         i_buff = peeked->i_buffer;
2327         p_buff = peeked->p_buffer;
2328         *pp_peek = p_buff;
2329
2330         while ((curlen < i_peek) && vlc_object_alive(s))
2331         {
2332             nsegment = GetSegment(s);
2333             if (nsegment == NULL)
2334             {
2335                 msg_Err(s, "segment %d should have been available (stream %d)",
2336                         p_sys->playback.segment, p_sys->playback.stream);
2337                 /* restore segment to read */
2338                 p_sys->playback.segment = peek_segment;
2339                 return curlen; /* eof? */
2340             }
2341
2342             vlc_mutex_lock(&nsegment->lock);
2343
2344             if (len < nsegment->data->i_buffer)
2345             {
2346                 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2347                 curlen += len;
2348             }
2349             else
2350             {
2351                 size_t i_nbuff = nsegment->data->i_buffer;
2352                 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2353                 curlen += i_nbuff;
2354                 len -= i_nbuff;
2355
2356                 p_sys->playback.segment++;
2357             }
2358
2359             vlc_mutex_unlock(&nsegment->lock);
2360         }
2361
2362         /* restore segment to read */
2363         p_sys->playback.segment = peek_segment;
2364         return curlen;
2365     }
2366 }
2367
2368 static bool hls_MaySeek(stream_t *s)
2369 {
2370     stream_sys_t *p_sys = s->p_sys;
2371
2372     if (p_sys->hls_stream == NULL)
2373         return false;
2374
2375     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2376     if (hls == NULL) return false;
2377
2378     if (p_sys->b_live)
2379     {
2380         vlc_mutex_lock(&hls->lock);
2381         int count = vlc_array_count(hls->segments);
2382         vlc_mutex_unlock(&hls->lock);
2383
2384         vlc_mutex_lock(&p_sys->download.lock_wait);
2385         bool may_seek = (p_sys->download.segment < (count - 2));
2386         vlc_mutex_unlock(&p_sys->download.lock_wait);
2387         return may_seek;
2388     }
2389     return true;
2390 }
2391
2392 static uint64_t GetStreamSize(stream_t *s)
2393 {
2394     stream_sys_t *p_sys = s->p_sys;
2395
2396     if (p_sys->b_live)
2397         return 0;
2398
2399     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2400     if (hls == NULL) return 0;
2401
2402     vlc_mutex_lock(&hls->lock);
2403     if (hls->size == 0)
2404         hls->size = hls_GetStreamSize(hls);
2405     uint64_t size = hls->size;
2406     vlc_mutex_unlock(&hls->lock);
2407
2408     return size;
2409 }
2410
2411 static int segment_Seek(stream_t *s, const uint64_t pos)
2412 {
2413     stream_sys_t *p_sys = s->p_sys;
2414
2415     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2416     if (hls == NULL)
2417         return VLC_EGENERIC;
2418
2419     vlc_mutex_lock(&hls->lock);
2420
2421     bool b_found = false;
2422     uint64_t length = 0;
2423     uint64_t size = hls->size;
2424     int count = vlc_array_count(hls->segments);
2425
2426     for (int n = 0; n < count; n++)
2427     {
2428         segment_t *segment = vlc_array_item_at_index(hls->segments, n);
2429         if (segment == NULL)
2430         {
2431             vlc_mutex_unlock(&hls->lock);
2432             return VLC_EGENERIC;
2433         }
2434
2435         vlc_mutex_lock(&segment->lock);
2436         length += segment->duration * (hls->bandwidth/8);
2437         vlc_mutex_unlock(&segment->lock);
2438
2439         if (!b_found && (pos <= length))
2440         {
2441             if (count - n >= 3)
2442             {
2443                 p_sys->playback.segment = n;
2444                 b_found = true;
2445                 break;
2446             }
2447             /* Do not search in last 3 segments */
2448             vlc_mutex_unlock(&hls->lock);
2449             return VLC_EGENERIC;
2450         }
2451     }
2452
2453     /* */
2454     if (!b_found && (pos >= size))
2455     {
2456         p_sys->playback.segment = count - 1;
2457         b_found = true;
2458     }
2459
2460     /* */
2461     if (b_found)
2462     {
2463         /* restore segment to start position */
2464         segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2465         if (segment == NULL)
2466         {
2467             vlc_mutex_unlock(&hls->lock);
2468             return VLC_EGENERIC;
2469         }
2470
2471         vlc_mutex_lock(&segment->lock);
2472         if (segment->data)
2473         {
2474             uint64_t size = segment->size -segment->data->i_buffer;
2475             if (size > 0)
2476             {
2477                 segment->data->i_buffer += size;
2478                 segment->data->p_buffer -= size;
2479             }
2480         }
2481         vlc_mutex_unlock(&segment->lock);
2482
2483         /* start download at current playback segment */
2484         vlc_mutex_unlock(&hls->lock);
2485
2486         /* Wake up download thread */
2487         vlc_mutex_lock(&p_sys->download.lock_wait);
2488         p_sys->download.seek = p_sys->playback.segment;
2489         vlc_cond_signal(&p_sys->download.wait);
2490         vlc_mutex_unlock(&p_sys->download.lock_wait);
2491
2492         /* Wait for download to be finished */
2493         vlc_mutex_lock(&p_sys->download.lock_wait);
2494         msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2495         while (((p_sys->download.seek != -1) ||
2496                 (p_sys->download.segment - p_sys->playback.segment < 3)) &&
2497                 (p_sys->download.segment < (count - 6)))
2498         {
2499             vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2500             if (!vlc_object_alive(s) || s->b_error) break;
2501         }
2502         vlc_mutex_unlock(&p_sys->download.lock_wait);
2503
2504         return VLC_SUCCESS;
2505     }
2506     vlc_mutex_unlock(&hls->lock);
2507
2508     return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2509 }
2510
2511 static int Control(stream_t *s, int i_query, va_list args)
2512 {
2513     stream_sys_t *p_sys = s->p_sys;
2514
2515     switch (i_query)
2516     {
2517         case STREAM_CAN_SEEK:
2518             *(va_arg (args, bool *)) = hls_MaySeek(s);
2519             break;
2520         case STREAM_GET_POSITION:
2521             *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2522             break;
2523         case STREAM_SET_POSITION:
2524             if (hls_MaySeek(s))
2525             {
2526                 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2527                 if (segment_Seek(s, pos) == VLC_SUCCESS)
2528                 {
2529                     p_sys->playback.offset = pos;
2530                     break;
2531                 }
2532             }
2533             return VLC_EGENERIC;
2534         case STREAM_GET_SIZE:
2535             *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2536             break;
2537         default:
2538             return VLC_EGENERIC;
2539     }
2540     return VLC_SUCCESS;
2541 }