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