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