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