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