]> git.sesse.net Git - vlc/blob - modules/stream_filter/httplive.c
httplive module takes all cpu power when playing live stream
[vlc] / modules / stream_filter / httplive.c
1 /*****************************************************************************
2  * httplive.c: HTTP Live Streaming stream filter
3  *****************************************************************************
4  * Copyright (C) 2010-2011 M2X BV
5  * $Id$
6  *
7  * Author: Jean-Paul Saman <jpsaman _AT_ videolan _DOT_ org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <limits.h>
32 #include <errno.h>
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36
37 #include <assert.h>
38
39 #include <vlc_threads.h>
40 #include <vlc_arrays.h>
41 #include <vlc_stream.h>
42 #include <vlc_url.h>
43 #include <vlc_memory.h>
44
45 /*****************************************************************************
46  * Module descriptor
47  *****************************************************************************/
48 static int  Open (vlc_object_t *);
49 static void Close(vlc_object_t *);
50
51 vlc_module_begin()
52     set_category(CAT_INPUT)
53     set_subcategory(SUBCAT_INPUT_STREAM_FILTER)
54     set_description(N_("Http Live Streaming stream filter"))
55     set_capability("stream_filter", 20)
56     set_callbacks(Open, Close)
57 vlc_module_end()
58
59 /*****************************************************************************
60  *
61  *****************************************************************************/
62 typedef struct segment_s
63 {
64     int         sequence;   /* unique sequence number */
65     int         duration;   /* segment duration (seconds) */
66     uint64_t    size;       /* segment size in bytes */
67     uint64_t    bandwidth;  /* bandwidth usage of segments (bits per second)*/
68
69     vlc_url_t   url;
70     vlc_mutex_t lock;
71     block_t     *data;      /* data */
72 } segment_t;
73
74 typedef struct hls_stream_s
75 {
76     int         id;         /* program id */
77     int         version;    /* protocol version should be 1 */
78     int         sequence;   /* media sequence number */
79     int         duration;   /* maximum duration per segment (ms) */
80     uint64_t    bandwidth;  /* bandwidth usage of segments (bits per second)*/
81     uint64_t    size;       /* stream length (segment->duration * hls->bandwidth/8) */
82
83     vlc_array_t *segments;  /* list of segments */
84     vlc_url_t   url;        /* uri to m3u8 */
85     vlc_mutex_t lock;
86     bool        b_cache;    /* allow caching */
87 } hls_stream_t;
88
89 struct stream_sys_t
90 {
91     vlc_url_t     m3u8;         /* M3U8 url */
92     vlc_thread_t  reload;       /* HLS m3u8 reload thread */
93     vlc_thread_t  thread;       /* HLS segment download thread */
94
95     /* */
96     vlc_array_t  *hls_stream;   /* bandwidth adaptation */
97     uint64_t      bandwidth;    /* measured bandwidth (bits per second) */
98
99     /* Download */
100     struct hls_download_s
101     {
102         int         stream;     /* current hls_stream  */
103         int         segment;    /* current segment for downloading */
104         int         seek;       /* segment requested by seek (default -1) */
105         vlc_mutex_t lock_wait;  /* protect segment download counter */
106         vlc_cond_t  wait;       /* some condition to wait on */
107     } download;
108
109     /* Playback */
110     struct hls_playback_s
111     {
112         uint64_t    offset;     /* current offset in media */
113         int         stream;     /* current hls_stream  */
114         int         segment;    /* current segment for playback */
115     } playback;
116
117     /* Playlist */
118     struct hls_playlist_s
119     {
120         mtime_t     last;       /* playlist last loaded */
121         mtime_t     wakeup;     /* next reload time */
122         int         tries;      /* times it was not changed */
123     } playlist;
124
125     /* state */
126     bool        b_cache;    /* can cache files */
127     bool        b_meta;     /* meta playlist */
128     bool        b_live;     /* live stream? or vod? */
129     bool        b_error;    /* parsing error */
130 };
131
132 /****************************************************************************
133  * Local prototypes
134  ****************************************************************************/
135 static int  Read   (stream_t *, void *p_read, unsigned int i_read);
136 static int  Peek   (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
137 static int  Control(stream_t *, int i_query, va_list);
138
139 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer);
140 static ssize_t read_M3U8_from_url(stream_t *s, vlc_url_t *url, uint8_t **buffer);
141 static char *ReadLine(uint8_t *buffer, uint8_t **pos, size_t len);
142
143 static int hls_Download(stream_t *s, segment_t *segment);
144
145 static void* hls_Thread(void *);
146 static void* hls_Reload(void *);
147
148 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted);
149 static void segment_Free(segment_t *segment);
150
151 /****************************************************************************
152  *
153  ****************************************************************************/
154 static const char *const ext[] = {
155     "#EXT-X-TARGETDURATION",
156     "#EXT-X-MEDIA-SEQUENCE",
157     "#EXT-X-KEY",
158     "#EXT-X-ALLOW-CACHE",
159     "#EXT-X-ENDLIST",
160     "#EXT-X-STREAM-INF",
161     "#EXT-X-DISCONTINUITY",
162     "#EXT-X-VERSION"
163 };
164
165 static bool isHTTPLiveStreaming(stream_t *s)
166 {
167     const uint8_t *peek, *peek_end;
168
169     int64_t i_size = stream_Peek(s->p_source, &peek, 46);
170     if (i_size < 1)
171         return false;
172
173     if (strncasecmp((const char*)peek, "#EXTM3U", 7) != 0)
174         return false;
175
176     /* Parse stream and search for
177      * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
178      * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
179     peek_end = peek + i_size;
180     while(peek <= peek_end)
181     {
182         if (*peek == '#')
183         {
184             for (unsigned int i = 0; i < ARRAY_SIZE(ext); i++)
185             {
186                 char *p = strstr((const char*)peek, ext[i]);
187                 if (p != NULL)
188                     return true;
189             }
190         }
191         peek++;
192     };
193
194     return false;
195 }
196
197 /* HTTP Live Streaming */
198 static hls_stream_t *hls_New(vlc_array_t *hls_stream, const int id, const uint64_t bw, const char *uri)
199 {
200     hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
201     if (hls == NULL) return NULL;
202
203     hls->id = id;
204     hls->bandwidth = bw;
205     hls->duration = -1;/* unknown */
206     hls->size = 0;
207     hls->sequence = 0; /* default is 0 */
208     hls->version = 1;  /* default protocol version */
209     hls->b_cache = true;
210     vlc_UrlParse(&hls->url, uri, 0);
211     hls->segments = vlc_array_new();
212     vlc_array_append(hls_stream, hls);
213     vlc_mutex_init(&hls->lock);
214     return hls;
215 }
216
217 static void hls_Free(hls_stream_t *hls)
218 {
219     vlc_mutex_destroy(&hls->lock);
220
221     if (hls->segments)
222     {
223         for (int n = 0; n < vlc_array_count(hls->segments); n++)
224         {
225             segment_t *segment = (segment_t *)vlc_array_item_at_index(hls->segments, n);
226             if (segment) segment_Free(segment);
227         }
228         vlc_array_destroy(hls->segments);
229     }
230
231     vlc_UrlClean(&hls->url);
232     free(hls);
233     hls = NULL;
234 }
235
236 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, const int wanted)
237 {
238     int count = vlc_array_count(hls_stream);
239     if (count <= 0)
240         return NULL;
241     if ((wanted < 0) || (wanted >= count))
242         return NULL;
243     return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
244 }
245
246 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
247 {
248     return (hls_stream_t*) hls_Get(hls_stream, 0);
249 }
250
251 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
252 {
253     int count = vlc_array_count(hls_stream);
254     if (count <= 0)
255         return NULL;
256     count--;
257     return (hls_stream_t *) hls_Get(hls_stream, count);
258 }
259
260 static hls_stream_t *hls_Find(vlc_array_t *hls_stream, hls_stream_t *hls_new)
261 {
262     int count = vlc_array_count(hls_stream);
263     for (int n = 0; n < count; n++)
264     {
265         hls_stream_t *hls = vlc_array_item_at_index(hls_stream, n);
266         if (hls)
267         {
268             /* compare */
269             if ((hls->id == hls_new->id) &&
270                 (hls->bandwidth == hls_new->bandwidth))
271                 return hls;
272         }
273     }
274     return NULL;
275 }
276
277 static uint64_t hls_GetStreamSize(hls_stream_t *hls)
278 {
279     /* NOTE: Stream size is calculated based on segment duration and
280      * HLS stream bandwidth from the .m3u8 file. If these are not correct
281      * then the deviation from exact byte size will be big and the seek/
282      * progressbar will not behave entirely as one expects. */
283     uint64_t size = 0UL;
284     int count = vlc_array_count(hls->segments);
285     for (int n = 0; n < count; n++)
286     {
287         segment_t *segment = segment_GetSegment(hls, n);
288         if (segment)
289         {
290             size += (segment->duration * (hls->bandwidth / 8));
291         }
292     }
293     return size;
294 }
295
296 /* Segment */
297 static segment_t *segment_New(hls_stream_t* hls, const int duration, const char *uri)
298 {
299     segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
300     if (segment == NULL)
301         return NULL;
302
303     segment->duration = duration; /* seconds */
304     segment->size = 0; /* bytes */
305     segment->sequence = 0;
306     segment->bandwidth = 0;
307     vlc_UrlParse(&segment->url, uri, 0);
308     segment->data = NULL;
309     vlc_array_append(hls->segments, segment);
310     vlc_mutex_init(&segment->lock);
311     return segment;
312 }
313
314 static void segment_Free(segment_t *segment)
315 {
316     vlc_mutex_destroy(&segment->lock);
317
318     vlc_UrlClean(&segment->url);
319     if (segment->data)
320         block_Release(segment->data);
321     free(segment);
322     segment = NULL;
323 }
324
325 static segment_t *segment_GetSegment(hls_stream_t *hls, const int wanted)
326 {
327     assert(hls);
328
329     int count = vlc_array_count(hls->segments);
330     if (count <= 0)
331         return NULL;
332     if ((wanted < 0) || (wanted >= count))
333         return NULL;
334     return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
335 }
336
337 static segment_t *segment_Find(hls_stream_t *hls, const int sequence)
338 {
339     assert(hls);
340
341     int count = vlc_array_count(hls->segments);
342     if (count <= 0) return NULL;
343     for (int n = 0; n < count; n++)
344     {
345         segment_t *segment = vlc_array_item_at_index(hls->segments, n);
346         if (segment == NULL) break;
347         if (segment->sequence == sequence)
348             return segment;
349     }
350     return NULL;
351 }
352
353 static int ChooseSegment(stream_t *s, const int current)
354 {
355     stream_sys_t *p_sys = (stream_sys_t *)s->p_sys;
356     hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
357     if (hls == NULL) return 0;
358
359     /* Choose a segment to start which is no closer then
360      * 3 times the target duration from the end of the playlist.
361      */
362     int wanted = 0;
363     int duration = 0;
364     int sequence = 0;
365     int count = vlc_array_count(hls->segments);
366     int i = p_sys->b_live ? count - 1 : 0;
367
368     while((i >= 0) && (i < count) && vlc_object_alive(s))
369     {
370         segment_t *segment = segment_GetSegment(hls, i);
371         assert(segment);
372
373         if (segment->duration > hls->duration)
374         {
375             msg_Err(s, "EXTINF:%d duration is larger then EXT-X-TARGETDURATION:%d",
376                     segment->duration, hls->duration);
377         }
378
379         duration += segment->duration;
380         if (duration >= 3 * hls->duration)
381         {
382             /* Start point found */
383             wanted = p_sys->b_live ? i : 0;
384             sequence = segment->sequence;
385             break;
386         }
387
388         if (p_sys->b_live)
389             i-- ;
390         else
391           i++;
392     }
393
394     msg_Info(s, "Choose segment %d/%d (sequence=%d)", wanted, count, sequence);
395     return wanted;
396 }
397
398 /* Parsing */
399 static char *parse_Attributes(const char *line, const char *attr)
400 {
401     char *p;
402     char *begin = (char *) line;
403     char *end = begin + strlen(line);
404
405     /* Find start of attributes */
406     if ((p = strchr(begin, ':' )) == NULL)
407         return NULL;
408
409     begin = p;
410     do
411     {
412         if (strncasecmp(begin, attr, strlen(attr)) == 0)
413         {
414             /* <attr>=<value>[,]* */
415             p = strchr(begin, ',');
416             begin += strlen(attr) + 1;
417             if (begin >= end)
418                 return NULL;
419             if (p == NULL) /* last attribute */
420                 return strndup(begin, end - begin);
421             /* copy till ',' */
422             return strndup(begin, p - begin);
423         }
424         begin++;
425     } while(begin < end);
426
427     return NULL;
428 }
429
430 static char *relative_URI(stream_t *s, const char *uri, const char *path)
431 {
432     stream_sys_t *p_sys = s->p_sys;
433
434     char *p = strchr(uri, ':');
435     if (p != NULL)
436         return NULL;
437
438     if (p_sys->m3u8.psz_path == NULL)
439         return NULL;
440
441     char *psz_path = strdup(p_sys->m3u8.psz_path);
442     if (psz_path == NULL) return NULL;
443     p = strrchr(psz_path, '/');
444     if (p) *p = '\0';
445
446     char *psz_uri = NULL;
447     if (p_sys->m3u8.psz_password || p_sys->m3u8.psz_username)
448     {
449         if (asprintf(&psz_uri, "%s://%s:%s@%s:%d%s/%s", p_sys->m3u8.psz_protocol,
450                      p_sys->m3u8.psz_username, p_sys->m3u8.psz_password,
451                      p_sys->m3u8.psz_host, p_sys->m3u8.i_port,
452                      path ? path : psz_path, uri) < 0)
453             goto fail;
454     }
455     else
456     {
457         if (asprintf(&psz_uri, "%s://%s:%d%s/%s", p_sys->m3u8.psz_protocol,
458                      p_sys->m3u8.psz_host, p_sys->m3u8.i_port,
459                      path ? path : psz_path, uri) < 0)
460            goto fail;
461     }
462     free(psz_path);
463     return psz_uri;
464
465 fail:
466     free(psz_path);
467     return NULL;
468 }
469
470 static char *ConstructUrl(vlc_url_t *url)
471 {
472     if ((url->psz_protocol == NULL) ||
473         (url->psz_path == NULL))
474         return NULL;
475
476     if (url->i_port <= 0)
477     {
478         if (strncmp(url->psz_protocol, "https", 5) == 0)
479             url->i_port = 443;
480         else
481             url->i_port = 80;
482     }
483
484     char *psz_url = NULL;
485     if (url->psz_password || url->psz_username)
486     {
487         if (asprintf(&psz_url, "%s://%s:%s@%s:%d%s",
488                      url->psz_protocol,
489                      url->psz_username, url->psz_password,
490                      url->psz_host, url->i_port, url->psz_path) < 0)
491             return NULL;
492     }
493     else
494     {
495         if (asprintf(&psz_url, "%s://%s:%d%s",
496                      url->psz_protocol,
497                      url->psz_host, url->i_port, url->psz_path) < 0)
498             return NULL;
499     }
500
501     return psz_url;
502 }
503
504 static int parse_SegmentInformation(hls_stream_t *hls, char *p_read, int *duration)
505 {
506     assert(hls);
507     assert(p_read);
508
509     /* strip of #EXTINF: */
510     char *p_next = NULL;
511     char *token = strtok_r(p_read, ":", &p_next);
512     if (token == NULL)
513         return VLC_EGENERIC;
514
515     /* read duration */
516     token = strtok_r(NULL, ",", &p_next);
517     if (token == NULL)
518         return VLC_EGENERIC;
519
520     int value;
521     if (hls->version < 3)
522     {
523        value = strtol(token, NULL, 10);
524        if (errno == ERANGE)
525        {
526            *duration = -1;
527            return VLC_EGENERIC;
528        }
529        *duration = value;
530     }
531     else
532     {
533         double d = strtod(token, (char **) NULL);
534         if (errno == ERANGE)
535         {
536             *duration = -1;
537             return VLC_EGENERIC;
538         }
539         if ((d) - ((int)d) >= 0.5)
540             value = ((int)d) + 1;
541         else
542             value = ((int)d);
543     }
544
545     /* Ignore the rest of the line */
546
547     return VLC_SUCCESS;
548 }
549
550 static int parse_AddSegment(stream_t *s, hls_stream_t *hls, const int duration, const char *uri)
551 {
552     assert(hls);
553     assert(uri);
554
555     /* Store segment information */
556     char *psz_path = NULL;
557     if (hls->url.psz_path != NULL)
558     {
559         psz_path = strdup(hls->url.psz_path);
560         if (psz_path == NULL)
561             return VLC_ENOMEM;
562         char *p = strrchr(psz_path, '/');
563         if (p) *p = '\0';
564     }
565     char *psz_uri = relative_URI(s, uri, psz_path);
566     free(psz_path);
567
568     vlc_mutex_lock(&hls->lock);
569     segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
570     if (segment)
571         segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
572     vlc_mutex_unlock(&hls->lock);
573
574     free(psz_uri);
575     return segment ? VLC_SUCCESS : VLC_ENOMEM;
576 }
577
578 static int parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
579 {
580     assert(hls);
581
582     int duration = -1;
583     int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
584     if (ret != 1)
585     {
586         msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
587         return VLC_EGENERIC;
588     }
589
590     hls->duration = duration; /* seconds */
591     return VLC_SUCCESS;
592 }
593
594 static int parse_StreamInformation(stream_t *s, vlc_array_t **hls_stream,
595                                    hls_stream_t **hls, char *p_read, const char *uri)
596 {
597     int id;
598     uint64_t bw;
599     char *attr;
600
601     assert(*hls == NULL);
602
603     attr = parse_Attributes(p_read, "PROGRAM-ID");
604     if (attr == NULL)
605     {
606         msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
607         return VLC_EGENERIC;
608     }
609     id = atol(attr);
610     free(attr);
611
612     attr = parse_Attributes(p_read, "BANDWIDTH");
613     if (attr == NULL)
614     {
615         msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
616         return VLC_EGENERIC;
617     }
618     bw = atoll(attr);
619     free(attr);
620
621     if (bw == 0)
622     {
623         msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
624         return VLC_EGENERIC;
625     }
626
627     msg_Info(s, "bandwidth adaption detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
628
629     char *psz_uri = relative_URI(s, uri, NULL);
630
631     *hls = hls_New(*hls_stream, id, bw, psz_uri ? psz_uri : uri);
632
633     free(psz_uri);
634
635     return (*hls == NULL) ? VLC_ENOMEM : VLC_SUCCESS;
636 }
637
638 static int parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
639 {
640     assert(hls);
641
642     int sequence;
643     int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
644     if (ret != 1)
645     {
646         msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
647         return VLC_EGENERIC;
648     }
649
650     if (hls->sequence > 0)
651         msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist (new=%d, old=%d)",
652                     sequence, hls->sequence);
653
654     hls->sequence = sequence;
655     return VLC_SUCCESS;
656 }
657
658 static int parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
659 {
660     assert(hls);
661
662     /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
663     int err = VLC_SUCCESS;
664     char *attr = parse_Attributes(p_read, "METHOD");
665     if (attr == NULL)
666     {
667         msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
668         return err;
669     }
670
671     if (strncasecmp(attr, "NONE", 4) == 0)
672     {
673
674         char *uri = parse_Attributes(p_read, "URI");
675         if (uri != NULL)
676         {
677             msg_Err(s, "#EXT-X-KEY: URI not expected");
678             err = VLC_EGENERIC;
679         }
680         free(uri);
681         /* IV is only supported in version 2 and above */
682         if (hls->version >= 2)
683         {
684             char *iv = parse_Attributes(p_read, "IV");
685             if (iv != NULL)
686             {
687                 msg_Err(s, "#EXT-X-KEY: IV not expected");
688                 err = VLC_EGENERIC;
689             }
690             free(iv);
691         }
692     }
693     else
694     {
695         msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
696         err = VLC_EGENERIC;
697     }
698     free(attr);
699     return err;
700 }
701
702 static int parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
703 {
704     VLC_UNUSED(hls);
705     msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
706     return VLC_SUCCESS;
707 }
708
709 static int parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
710 {
711     assert(hls);
712
713     char answer[4] = "\0";
714     int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
715     if (ret != 1)
716     {
717         msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
718         return VLC_EGENERIC;
719     }
720
721     hls->b_cache = (strncmp(answer, "NO", 2) != 0);
722     return VLC_SUCCESS;
723 }
724
725 static int parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
726 {
727     assert(hls);
728
729     int version;
730     int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
731     if (ret != 1)
732     {
733         msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
734         return VLC_EGENERIC;
735     }
736
737     /* Check version */
738     hls->version = version;
739     if (hls->version != 1)
740     {
741         msg_Err(s, "#EXT-X-VERSION should be version 1 iso %d", version);
742         return VLC_EGENERIC;
743     }
744     return VLC_SUCCESS;
745 }
746
747 static int parse_EndList(stream_t *s, hls_stream_t *hls)
748 {
749     assert(hls);
750
751     s->p_sys->b_live = false;
752     msg_Info(s, "video on demand (vod) mode");
753     return VLC_SUCCESS;
754 }
755
756 static int parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
757 {
758     assert(hls);
759
760     /* FIXME: Do we need to act on discontinuity ?? */
761     msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
762     return VLC_SUCCESS;
763 }
764
765 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
766  * document defines the following new tags: EXT-X-TARGETDURATION,
767  * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
768  * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
769  * and EXT-X-VERSION.
770  */
771 static int parse_M3U8(stream_t *s, vlc_array_t *streams, uint8_t *buffer, const ssize_t len)
772 {
773     stream_sys_t *p_sys = s->p_sys;
774     uint8_t *p_read, *p_begin, *p_end;
775
776     assert(streams);
777     assert(buffer);
778
779     msg_Dbg(s, "parse_M3U8\n%s", buffer);
780     p_begin = buffer;
781     p_end = p_begin + len;
782
783     char *line = ReadLine(p_begin, &p_read, p_end - p_begin);
784     if (line == NULL)
785         return VLC_ENOMEM;
786     p_begin = p_read;
787
788     if (strncmp(line, "#EXTM3U", 7) != 0)
789     {
790         msg_Err(s, "missing #EXTM3U tag .. aborting");
791         free(line);
792         return VLC_EGENERIC;
793     }
794
795     free(line);
796     line = NULL;
797
798     /* What is the version ? */
799     int version = 1;
800     uint8_t *p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-VERSION:");
801     if (p != NULL)
802     {
803         uint8_t *tmp = NULL;
804         char *psz_version = ReadLine(p, &tmp, p_end - p);
805         if (psz_version == NULL)
806             return VLC_ENOMEM;
807         int ret = sscanf((const char*)psz_version, "#EXT-X-VERSION:%d", &version);
808         if (ret != 1)
809         {
810             msg_Warn(s, "#EXT-X-VERSION: no protocol version found, assuming version 1.");
811             version = 1;
812         }
813         free(psz_version);
814         p = NULL;
815     }
816
817     /* Is it a live stream ? */
818     p_sys->b_live = (strstr((const char *)buffer, "#EXT-X-ENDLIST") == NULL) ? true : false;
819
820     /* Is it a meta index file ? */
821     bool b_meta = (strstr((const char *)buffer, "#EXT-X-STREAM-INF") == NULL) ? false : true;
822
823     int err = VLC_SUCCESS;
824
825     if (b_meta)
826     {
827         msg_Info(s, "Meta playlist");
828
829         /* M3U8 Meta Index file */
830         do {
831             /* Next line */
832             line = ReadLine(p_begin, &p_read, p_end - p_begin);
833             if (line == NULL)
834                 break;
835             p_begin = p_read;
836
837             /* */
838             if (strncmp(line, "#EXT-X-STREAM-INF", 17) == 0)
839             {
840                 p_sys->b_meta = true;
841                 char *uri = ReadLine(p_begin, &p_read, p_end - p_begin);
842                 if (uri == NULL)
843                     err = VLC_ENOMEM;
844                 else
845                 {
846                     hls_stream_t *hls = NULL;
847                     err = parse_StreamInformation(s, &streams, &hls, line, uri);
848                     free(uri);
849
850                     /* Download playlist file from server */
851                     uint8_t *buf = NULL;
852                     ssize_t len = read_M3U8_from_url(s, &hls->url, &buf);
853                     if (len < 0)
854                         err = VLC_EGENERIC;
855                     else
856                     {
857                         /* Parse HLS m3u8 content. */
858                         err = parse_M3U8(s, streams, buf, len);
859                         free(buf);
860                     }
861
862                     if (hls)
863                     {
864                         hls->version = version;
865                         if (!p_sys->b_live)
866                             hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
867                     }
868                 }
869                 p_begin = p_read;
870             }
871
872             free(line);
873             line = NULL;
874
875             if (p_begin >= p_end)
876                 break;
877
878         } while ((err == VLC_SUCCESS) && vlc_object_alive(s));
879
880     }
881     else
882     {
883         msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
884
885         hls_stream_t *hls = NULL;
886         if (p_sys->b_meta)
887             hls = hls_GetLast(streams);
888         else
889         {
890             /* No Meta playlist used */
891             hls = hls_New(streams, 0, -1, NULL);
892             if (hls)
893             {
894                 /* Get TARGET-DURATION first */
895                 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
896                 if (p)
897                 {
898                     uint8_t *p_rest = NULL;
899                     char *psz_duration = ReadLine(p, &p_rest,  p_end - p);
900                     if (psz_duration == NULL)
901                         return VLC_EGENERIC;
902                     err = parse_TargetDuration(s, hls, psz_duration);
903                     free(psz_duration);
904                     p = NULL;
905                 }
906
907                 /* Store version */
908                 hls->version = version;
909             }
910             else return VLC_ENOMEM;
911         }
912         assert(hls);
913
914         /* */
915         int segment_duration = -1;
916         do
917         {
918             /* Next line */
919             line = ReadLine(p_begin, &p_read, p_end - p_begin);
920             if (line == NULL)
921                 break;
922             p_begin = p_read;
923
924             if (strncmp(line, "#EXTINF", 7) == 0)
925                 err = parse_SegmentInformation(hls, line, &segment_duration);
926             else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
927                 err = parse_TargetDuration(s, hls, line);
928             else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
929                 err = parse_MediaSequence(s, hls, line);
930             else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
931                 err = parse_Key(s, hls, line);
932             else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
933                 err = parse_ProgramDateTime(s, hls, line);
934             else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
935                 err = parse_AllowCache(s, hls, line);
936             else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
937                 err = parse_Discontinuity(s, hls, line);
938             else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
939                 err = parse_Version(s, hls, line);
940             else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
941                 err = parse_EndList(s, hls);
942             else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
943             {
944                 err = parse_AddSegment(s, hls, segment_duration, line);
945                 segment_duration = -1; /* reset duration */
946             }
947
948             free(line);
949             line = NULL;
950
951             if (p_begin >= p_end)
952                 break;
953
954         } while ((err == VLC_SUCCESS) && vlc_object_alive(s));
955
956         free(line);
957     }
958
959     return err;
960 }
961
962 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
963 {
964     stream_sys_t *p_sys = s->p_sys;
965     assert(*streams);
966
967     /* Download new playlist file from server */
968     uint8_t *buffer = NULL;
969     ssize_t len = read_M3U8_from_url(s, &p_sys->m3u8, &buffer);
970     if (len < 0)
971         return VLC_EGENERIC;
972
973     /* Parse HLS m3u8 content. */
974     int err = parse_M3U8(s, *streams, buffer, len);
975     free(buffer);
976
977     return err;
978 }
979
980 /* Reload playlist */
981 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t **hls)
982 {
983     int count = vlc_array_count(hls_new->segments);
984
985     msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
986              hls_new->id, hls_new->bandwidth, count);
987     for (int n = 0; n < count; n++)
988     {
989         segment_t *p = segment_GetSegment(hls_new, n);
990         if (p == NULL) return VLC_EGENERIC;
991
992         vlc_mutex_lock(&(*hls)->lock);
993         segment_t *segment = segment_Find(*hls, p->sequence);
994         if (segment)
995         {
996             /* they should be the same */
997             if ((p->sequence != segment->sequence) ||
998                 (p->duration != segment->duration) ||
999                 (strcmp(p->url.psz_path, segment->url.psz_path) != 0))
1000             {
1001                 msg_Err(s, "existing segment found with different content - resetting");
1002                 msg_Err(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1003                 msg_Err(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1004                 msg_Err(s, "- file: new=%s", p->url.psz_path);
1005                 msg_Err(s, "        old=%s", segment->url.psz_path);
1006
1007                 /* Resetting content */
1008                 segment->sequence = p->sequence;
1009                 segment->duration = p->duration;
1010                 vlc_UrlClean(&segment->url);
1011                 vlc_UrlParse(&segment->url, p->url.psz_buffer, 0);
1012                 segment_Free(p);
1013             }
1014         }
1015         else
1016         {
1017             int last = vlc_array_count((*hls)->segments) - 1;
1018             segment_t *l = segment_GetSegment(*hls, last);
1019             if (l == NULL) goto fail_and_unlock;
1020
1021             if ((l->sequence + 1) != p->sequence)
1022             {
1023                 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1024                         p->sequence, l->sequence+1);
1025             }
1026             vlc_array_append((*hls)->segments, p);
1027             msg_Info(s, "- segment %d appended", p->sequence);
1028         }
1029         vlc_mutex_unlock(&(*hls)->lock);
1030     }
1031     return VLC_SUCCESS;
1032
1033 fail_and_unlock:
1034     vlc_mutex_unlock(&(*hls)->lock);
1035     return VLC_EGENERIC;
1036 }
1037
1038 static int hls_ReloadPlaylist(stream_t *s)
1039 {
1040     stream_sys_t *p_sys = s->p_sys;
1041
1042     vlc_array_t *hls_streams = vlc_array_new();
1043     if (hls_streams == NULL)
1044         return VLC_ENOMEM;
1045
1046     msg_Info(s, "Reloading HLS live meta playlist");
1047
1048     if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1049     {
1050         /* Free hls streams */
1051         for (int i = 0; i < vlc_array_count(hls_streams); i++)
1052         {
1053             hls_stream_t *hls;
1054             hls = (hls_stream_t *)vlc_array_item_at_index(hls_streams, i);
1055             if (hls) hls_Free(hls);
1056         }
1057         vlc_array_destroy(hls_streams);
1058
1059         msg_Err(s, "reloading playlist failed");
1060         return VLC_EGENERIC;
1061     }
1062
1063     /* merge playlists */
1064     int count = vlc_array_count(hls_streams);
1065     for (int n = 0; n < count; n++)
1066     {
1067         hls_stream_t *hls_new = hls_Get(hls_streams, n);
1068         if (hls_new == NULL)
1069             continue;
1070
1071         hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1072         if (hls_old == NULL)
1073         {   /* new hls stream - append */
1074             vlc_array_append(p_sys->hls_stream, hls_new);
1075             msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1076                      hls_new->id, hls_new->bandwidth);
1077         }
1078         else if (hls_UpdatePlaylist(s, hls_new, &hls_old) != VLC_SUCCESS)
1079             msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1080                      hls_new->id, hls_new->bandwidth);
1081     }
1082
1083     vlc_array_destroy(hls_streams);
1084     return VLC_SUCCESS;
1085 }
1086
1087 /****************************************************************************
1088  * hls_Thread
1089  ****************************************************************************/
1090 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1091 {
1092     stream_sys_t *p_sys = s->p_sys;
1093     int candidate = -1;
1094     uint64_t bw = *bandwidth;
1095     uint64_t bw_candidate = 0;
1096
1097     int count = vlc_array_count(p_sys->hls_stream);
1098     for (int n = 0; n < count; n++)
1099     {
1100         /* Select best bandwidth match */
1101         hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1102         if (hls == NULL) break;
1103
1104         /* only consider streams with the same PROGRAM-ID */
1105         if (hls->id == progid)
1106         {
1107             if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1108             {
1109                 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1110                          n, bw, hls->bandwidth); /* bits / s */
1111                 bw_candidate = hls->bandwidth;
1112                 candidate = n; /* possible candidate */
1113             }
1114         }
1115     }
1116     *bandwidth = bw_candidate;
1117     return candidate;
1118 }
1119
1120 static int Download(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1121 {
1122     stream_sys_t *p_sys = s->p_sys;
1123
1124     assert(hls);
1125     assert(segment);
1126
1127     vlc_mutex_lock(&segment->lock);
1128     if (segment->data != NULL)
1129     {
1130         /* Segment already downloaded */
1131         vlc_mutex_unlock(&segment->lock);
1132         return VLC_SUCCESS;
1133     }
1134
1135     /* sanity check - can we download this segment on time? */
1136     if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1137     {
1138         uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1139         int estimated = (int)(size / p_sys->bandwidth);
1140         if (estimated > segment->duration)
1141         {
1142             msg_Warn(s,"downloading of segment %d takes %ds, which is longer then its playback (%ds)",
1143                         segment->sequence, estimated, segment->duration);
1144         }
1145     }
1146
1147     mtime_t start = mdate();
1148     if (hls_Download(s, segment) != VLC_SUCCESS)
1149     {
1150         vlc_mutex_unlock(&segment->lock);
1151         return VLC_EGENERIC;
1152     }
1153     mtime_t duration = mdate() - start;
1154
1155     vlc_mutex_unlock(&segment->lock);
1156
1157     msg_Info(s, "downloaded segment %d from stream %d",
1158                 segment->sequence, *cur_stream);
1159
1160     /* check for division by zero */
1161     double ms = (double)duration / 1000.0; /* ms */
1162     if (ms <= 0.0)
1163         return VLC_SUCCESS;
1164
1165     uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
1166     p_sys->bandwidth = bw;
1167     if (p_sys->b_meta && (hls->bandwidth != bw))
1168     {
1169         int newstream = BandwidthAdaptation(s, hls->id, &bw);
1170
1171         /* FIXME: we need an average here */
1172         if ((newstream >= 0) && (newstream != *cur_stream))
1173         {
1174             msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1175                      (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1176             *cur_stream = newstream;
1177         }
1178     }
1179     return VLC_SUCCESS;
1180 }
1181
1182 static void* hls_Thread(void *p_this)
1183 {
1184     stream_t *s = (stream_t *)p_this;
1185     stream_sys_t *p_sys = s->p_sys;
1186
1187     int canc = vlc_savecancel();
1188
1189     while (vlc_object_alive(s))
1190     {
1191         hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1192         assert(hls);
1193
1194         /* Sliding window (~60 seconds worth of movie) */
1195         vlc_mutex_lock(&hls->lock);
1196         int count = vlc_array_count(hls->segments);
1197         vlc_mutex_unlock(&hls->lock);
1198
1199         /* Is there a new segment to process? */
1200         if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1201             (p_sys->download.segment >= count))
1202         {
1203             /* wait */
1204             vlc_mutex_lock(&p_sys->download.lock_wait);
1205             while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1206                     (p_sys->download.segment >= count)) &&
1207                    (p_sys->download.seek == -1))
1208             {
1209                 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1210                 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1211                     break;
1212                 if (!vlc_object_alive(s))
1213                     break;
1214             }
1215             /* */
1216             if (p_sys->download.seek >= 0)
1217             {
1218                 p_sys->download.segment = p_sys->download.seek;
1219                 p_sys->download.seek = -1;
1220             }
1221             vlc_mutex_unlock(&p_sys->download.lock_wait);
1222         }
1223
1224         if (!vlc_object_alive(s)) break;
1225
1226         vlc_mutex_lock(&hls->lock);
1227         segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1228         vlc_mutex_unlock(&hls->lock);
1229
1230         if ((segment != NULL) &&
1231             (Download(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1232         {
1233             if (!vlc_object_alive(s)) break;
1234
1235             if (!p_sys->b_live)
1236             {
1237                 p_sys->b_error = true;
1238                 break;
1239             }
1240         }
1241
1242         /* download succeeded */
1243         /* determine next segment to download */
1244         vlc_mutex_lock(&p_sys->download.lock_wait);
1245         if (p_sys->download.seek >= 0)
1246         {
1247             p_sys->download.segment = p_sys->download.seek;
1248             p_sys->download.seek = -1;
1249         }
1250         else if (p_sys->download.segment < count)
1251             p_sys->download.segment++;
1252         vlc_cond_signal(&p_sys->download.wait);
1253         vlc_mutex_unlock(&p_sys->download.lock_wait);
1254     }
1255
1256     vlc_restorecancel(canc);
1257     return NULL;
1258 }
1259
1260 static void* hls_Reload(void *p_this)
1261 {
1262     stream_t *s = (stream_t *)p_this;
1263     stream_sys_t *p_sys = s->p_sys;
1264
1265     assert(p_sys->b_live);
1266
1267     int canc = vlc_savecancel();
1268
1269     while (vlc_object_alive(s))
1270     {
1271         double wait = 1;
1272         mtime_t now = mdate();
1273         if (now >= p_sys->playlist.wakeup)
1274         {
1275             /* reload the m3u8 */
1276             if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1277             {
1278                 /* No change in playlist, then backoff */
1279                 p_sys->playlist.tries++;
1280                 if (p_sys->playlist.tries == 1) wait = 0.5;
1281                 else if (p_sys->playlist.tries == 2) wait = 1;
1282                 else if (p_sys->playlist.tries >= 3) wait = 3;
1283             }
1284             else p_sys->playlist.tries = 0;
1285
1286             hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1287             assert(hls);
1288
1289             /* determine next time to update playlist */
1290             p_sys->playlist.last = now;
1291             p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1292                                                    * (mtime_t)1000000);
1293         }
1294
1295         mwait(p_sys->playlist.wakeup);
1296     }
1297
1298     vlc_restorecancel(canc);
1299     return NULL;
1300 }
1301
1302 static int Prefetch(stream_t *s, int *current)
1303 {
1304     stream_sys_t *p_sys = s->p_sys;
1305     int stream;
1306
1307     /* Try to pick best matching stream */;
1308 again:
1309     stream = *current;
1310
1311     hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1312     if (hls == NULL)
1313         return VLC_EGENERIC;
1314
1315     segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1316     if (segment == NULL )
1317         return VLC_EGENERIC;
1318
1319     if (Download(s, hls, segment, current) != VLC_SUCCESS)
1320         return VLC_EGENERIC;
1321
1322     /* Found better bandwidth match, try again */
1323     if (*current != stream)
1324         goto again;
1325
1326     /* Download first 2 segments of this HLS stream */
1327     stream = *current;
1328     for (int i = 0; i < 2; i++)
1329     {
1330         segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1331         if (segment == NULL )
1332             return VLC_EGENERIC;
1333
1334         if (segment->data)
1335         {
1336             p_sys->download.segment++;
1337             continue;
1338         }
1339
1340         if (Download(s, hls, segment, current) != VLC_SUCCESS)
1341             return VLC_EGENERIC;
1342
1343         p_sys->download.segment++;
1344
1345         /* adapt bandwidth? */
1346         if (*current != stream)
1347         {
1348             hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1349             if (hls == NULL)
1350                 return VLC_EGENERIC;
1351
1352              stream = *current;
1353         }
1354     }
1355
1356     return VLC_SUCCESS;
1357 }
1358
1359 /****************************************************************************
1360  *
1361  ****************************************************************************/
1362 static int hls_Download(stream_t *s, segment_t *segment)
1363 {
1364     assert(segment);
1365
1366     /* Construct URL */
1367     char *psz_url = ConstructUrl(&segment->url);
1368     if (psz_url == NULL)
1369            return VLC_ENOMEM;
1370
1371     stream_t *p_ts = stream_UrlNew(s, psz_url);
1372     free(psz_url);
1373     if (p_ts == NULL)
1374         return VLC_EGENERIC;
1375
1376     segment->size = stream_Size(p_ts);
1377     assert(segment->size > 0);
1378
1379     segment->data = block_Alloc(segment->size);
1380     if (segment->data == NULL)
1381     {
1382         stream_Delete(p_ts);
1383         return VLC_ENOMEM;
1384     }
1385
1386     assert(segment->data->i_buffer == segment->size);
1387
1388     ssize_t length = 0, curlen = 0;
1389     uint64_t size;
1390     do
1391     {
1392         size = stream_Size(p_ts);
1393         if (size > segment->size)
1394         {
1395             msg_Dbg(s, "size changed %"PRIu64, segment->size);
1396             segment->data = block_Realloc(segment->data, 0, size);
1397             if (segment->data == NULL)
1398             {
1399                 stream_Delete(p_ts);
1400                 return VLC_ENOMEM;
1401             }
1402             segment->size = size;
1403             assert(segment->data->i_buffer == segment->size);
1404         }
1405         length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1406         if (length <= 0)
1407             break;
1408         curlen += length;
1409     } while (vlc_object_alive(s));
1410
1411     stream_Delete(p_ts);
1412     return VLC_SUCCESS;
1413 }
1414
1415 /* Read M3U8 file */
1416 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1417 {
1418     int64_t total_bytes = 0;
1419     int64_t total_allocated = 0;
1420     uint8_t *p = NULL;
1421
1422     while (1)
1423     {
1424         char buf[4096];
1425         int64_t bytes;
1426
1427         bytes = stream_Read(s, buf, sizeof(buf));
1428         if (bytes == 0)
1429             break;      /* EOF ? */
1430         else if (bytes < 0)
1431             return bytes;
1432
1433         if ( (total_bytes + bytes + 1) > total_allocated )
1434         {
1435             if (total_allocated)
1436                 total_allocated *= 2;
1437             else
1438                 total_allocated = __MIN(bytes+1, sizeof(buf));
1439
1440             p = realloc_or_free(p, total_allocated);
1441             if (p == NULL)
1442                 return VLC_ENOMEM;
1443         }
1444
1445         memcpy(p+total_bytes, buf, bytes);
1446         total_bytes += bytes;
1447     }
1448
1449     if (total_allocated == 0)
1450         return VLC_EGENERIC;
1451
1452     p[total_bytes] = '\0';
1453     *buffer = p;
1454
1455     return total_bytes;
1456 }
1457
1458 static ssize_t read_M3U8_from_url(stream_t *s, vlc_url_t *url, uint8_t **buffer)
1459 {
1460     assert(*buffer == NULL);
1461
1462     /* Construct URL */
1463     char *psz_url = ConstructUrl(url);
1464     if (psz_url == NULL)
1465            return VLC_ENOMEM;
1466
1467     stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1468     free(psz_url);
1469     if (p_m3u8 == NULL)
1470         return VLC_EGENERIC;
1471
1472     ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1473     stream_Delete(p_m3u8);
1474
1475     return size;
1476 }
1477
1478 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1479 {
1480     assert(buffer);
1481
1482     char *line = NULL;
1483     uint8_t *begin = buffer;
1484     uint8_t *p = begin;
1485     uint8_t *end = p + len;
1486
1487     while (p < end)
1488     {
1489         if ((*p == '\n') || (*p == '\0'))
1490             break;
1491         p++;
1492     }
1493
1494     /* copy line excluding \n or \0 */
1495     line = strndup((char *)begin, p - begin);
1496
1497     if (*p == '\0')
1498         *pos = end;
1499     else
1500     {
1501         /* next pass start after \n */
1502         p++;
1503         *pos = p;
1504     }
1505
1506     return line;
1507 }
1508
1509 /****************************************************************************
1510  * Open
1511  ****************************************************************************/
1512 static int Open(vlc_object_t *p_this)
1513 {
1514     stream_t *s = (stream_t*)p_this;
1515     stream_sys_t *p_sys;
1516
1517     if (!isHTTPLiveStreaming(s))
1518         return VLC_EGENERIC;
1519
1520     msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1521
1522     /* */
1523     s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1524     if (p_sys == NULL)
1525         return VLC_ENOMEM;
1526
1527     char *psz_uri = NULL;
1528     if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1529     {
1530         free(p_sys);
1531         return VLC_ENOMEM;
1532     }
1533     vlc_UrlParse(&p_sys->m3u8, psz_uri, 0);
1534     free(psz_uri);
1535
1536     p_sys->bandwidth = -1;
1537     p_sys->b_live = true;
1538     p_sys->b_meta = false;
1539     p_sys->b_error = false;
1540
1541     p_sys->hls_stream = vlc_array_new();
1542     if (p_sys->hls_stream == NULL)
1543     {
1544         vlc_UrlClean(&p_sys->m3u8);
1545         free(p_sys);
1546         return VLC_ENOMEM;
1547     }
1548
1549     /* */
1550     s->pf_read = Read;
1551     s->pf_peek = Peek;
1552     s->pf_control = Control;
1553
1554     /* Parse HLS m3u8 content. */
1555     uint8_t *buffer = NULL;
1556     ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1557     if (len < 0)
1558         goto fail;
1559     if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
1560     {
1561         free(buffer);
1562         goto fail;
1563     }
1564     free(buffer);
1565
1566     /* Choose first HLS stream to start with */
1567     int current = p_sys->playback.stream = 0;
1568     p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
1569
1570     if (p_sys->b_live && (p_sys->playback.segment < 0))
1571     {
1572         msg_Warn(s, "less data then 3 times 'target duration' available for live playback, playback may stall");
1573     }
1574
1575     if (Prefetch(s, &current) != VLC_SUCCESS)
1576     {
1577         msg_Err(s, "fetching first segment failed.");
1578         goto fail;
1579     }
1580
1581
1582     p_sys->download.stream = current;
1583     p_sys->playback.stream = current;
1584     p_sys->download.seek = -1;
1585
1586     vlc_mutex_init(&p_sys->download.lock_wait);
1587     vlc_cond_init(&p_sys->download.wait);
1588
1589     /* Initialize HLS live stream */
1590     if (p_sys->b_live)
1591     {
1592         hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
1593         p_sys->playlist.last = mdate();
1594         p_sys->playlist.wakeup = p_sys->playlist.last +
1595                 ((mtime_t)hls->duration * UINT64_C(1000000));
1596
1597         if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
1598         {
1599             goto fail_thread;
1600         }
1601     }
1602
1603     if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
1604     {
1605         if (p_sys->b_live)
1606             vlc_join(p_sys->reload, NULL);
1607         goto fail_thread;
1608     }
1609
1610     return VLC_SUCCESS;
1611
1612 fail_thread:
1613     vlc_mutex_destroy(&p_sys->download.lock_wait);
1614     vlc_cond_destroy(&p_sys->download.wait);
1615
1616 fail:
1617     /* Free hls streams */
1618     for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1619     {
1620         hls_stream_t *hls;
1621         hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
1622         if (hls) hls_Free(hls);
1623     }
1624     vlc_array_destroy(p_sys->hls_stream);
1625
1626     /* */
1627     vlc_UrlClean(&p_sys->m3u8);
1628     free(p_sys);
1629     return VLC_EGENERIC;
1630 }
1631
1632 /****************************************************************************
1633  * Close
1634  ****************************************************************************/
1635 static void Close(vlc_object_t *p_this)
1636 {
1637     stream_t *s = (stream_t*)p_this;
1638     stream_sys_t *p_sys = s->p_sys;
1639
1640     assert(p_sys->hls_stream);
1641
1642     /* */
1643     vlc_mutex_lock(&p_sys->download.lock_wait);
1644     vlc_cond_signal(&p_sys->download.wait);
1645     vlc_mutex_unlock(&p_sys->download.lock_wait);
1646
1647     /* */
1648     if (p_sys->b_live)
1649         vlc_join(p_sys->reload, NULL);
1650     vlc_join(p_sys->thread, NULL);
1651     vlc_mutex_destroy(&p_sys->download.lock_wait);
1652     vlc_cond_destroy(&p_sys->download.wait);
1653
1654     /* Free hls streams */
1655     for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1656     {
1657         hls_stream_t *hls;
1658         hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
1659         if (hls) hls_Free(hls);
1660     }
1661     vlc_array_destroy(p_sys->hls_stream);
1662
1663     /* */
1664     vlc_UrlClean(&p_sys->m3u8);
1665     free(p_sys);
1666 }
1667
1668 /****************************************************************************
1669  * Stream filters functions
1670  ****************************************************************************/
1671 static segment_t *GetSegment(stream_t *s)
1672 {
1673     stream_sys_t *p_sys = s->p_sys;
1674     segment_t *segment = NULL;
1675
1676     /* Is this segment of the current HLS stream ready? */
1677     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
1678     if (hls != NULL)
1679     {
1680         vlc_mutex_lock(&hls->lock);
1681         segment = segment_GetSegment(hls, p_sys->playback.segment);
1682         if (segment != NULL)
1683         {
1684             /* This segment is ready? */
1685             if (segment->data != NULL)
1686             {
1687                 p_sys->b_cache = hls->b_cache;
1688                 vlc_mutex_unlock(&hls->lock);
1689                 goto check;
1690             }
1691         }
1692         vlc_mutex_unlock(&hls->lock);
1693     }
1694
1695     /* Was the HLS stream changed to another bitrate? */
1696     int i_stream = 0;
1697     segment = NULL;
1698     while(vlc_object_alive(s))
1699     {
1700         /* Is the next segment ready */
1701         hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
1702         if (hls == NULL)
1703             return NULL;
1704
1705         vlc_mutex_lock(&hls->lock);
1706         segment = segment_GetSegment(hls, p_sys->playback.segment);
1707         if (segment == NULL)
1708         {
1709             vlc_mutex_unlock(&hls->lock);
1710             break;
1711         }
1712
1713         vlc_mutex_lock(&p_sys->download.lock_wait);
1714         int i_segment = p_sys->download.segment;
1715         vlc_mutex_unlock(&p_sys->download.lock_wait);
1716
1717         /* This segment is ready? */
1718         if ((segment->data != NULL) &&
1719             (p_sys->playback.segment < i_segment))
1720         {
1721             p_sys->playback.stream = i_stream;
1722             p_sys->b_cache = hls->b_cache;
1723             vlc_mutex_unlock(&hls->lock);
1724             goto check;
1725         }
1726         vlc_mutex_unlock(&hls->lock);
1727
1728         if (!p_sys->b_meta)
1729             break;
1730
1731         /* Was the stream changed to another bitrate? */
1732         i_stream++;
1733         if (i_stream >= vlc_array_count(p_sys->hls_stream))
1734             break;
1735     }
1736     /* */
1737     return NULL;
1738
1739 check:
1740     /* sanity check */
1741     if (segment->data->i_buffer == 0)
1742     {
1743         vlc_mutex_lock(&hls->lock);
1744         int count = vlc_array_count(hls->segments);
1745         vlc_mutex_unlock(&hls->lock);
1746
1747         if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
1748             ((count != p_sys->download.segment) || p_sys->b_live))
1749             msg_Err(s, "playback will stall");
1750         else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
1751                  ((count != p_sys->download.segment) || p_sys->b_live))
1752             msg_Warn(s, "playback in danger of stalling");
1753     }
1754     return segment;
1755 }
1756
1757 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
1758 {
1759     stream_sys_t *p_sys = s->p_sys;
1760     ssize_t copied = 0;
1761
1762     do
1763     {
1764         /* Determine next segment to read. If this is a meta playlist and
1765          * bandwidth conditions changed, then the stream might have switched
1766          * to another bandwidth. */
1767         segment_t *segment = GetSegment(s);
1768         if (segment == NULL)
1769             break;
1770
1771         vlc_mutex_lock(&segment->lock);
1772         if (segment->data->i_buffer == 0)
1773         {
1774             if (!p_sys->b_cache || p_sys->b_live)
1775             {
1776                 block_Release(segment->data);
1777                 segment->data = NULL;
1778             }
1779             else
1780             {   /* reset playback pointer to start of buffer */
1781                 uint64_t size = segment->size - segment->data->i_buffer;
1782                 if (size > 0)
1783                 {
1784                     segment->data->i_buffer += size;
1785                     segment->data->p_buffer -= size;
1786                 }
1787             }
1788             p_sys->playback.segment++;
1789             vlc_mutex_unlock(&segment->lock);
1790
1791             /* signal download thread */
1792             vlc_mutex_lock(&p_sys->download.lock_wait);
1793             vlc_cond_signal(&p_sys->download.wait);
1794             vlc_mutex_unlock(&p_sys->download.lock_wait);
1795             continue;
1796         }
1797
1798         if (segment->size == segment->data->i_buffer)
1799             msg_Info(s, "playing segment %d from stream %d",
1800                      segment->sequence, p_sys->playback.stream);
1801
1802         ssize_t len = -1;
1803         if (i_read <= segment->data->i_buffer)
1804             len = i_read;
1805         else if (i_read > segment->data->i_buffer)
1806             len = segment->data->i_buffer;
1807
1808         if (len > 0)
1809         {
1810             memcpy(p_read + copied, segment->data->p_buffer, len);
1811             segment->data->i_buffer -= len;
1812             segment->data->p_buffer += len;
1813             copied += len;
1814             i_read -= len;
1815         }
1816         vlc_mutex_unlock(&segment->lock);
1817
1818     } while ((i_read > 0) && vlc_object_alive(s));
1819
1820     return copied;
1821 }
1822
1823 static int Read(stream_t *s, void *buffer, unsigned int i_read)
1824 {
1825     stream_sys_t *p_sys = s->p_sys;
1826     ssize_t length = 0;
1827
1828     assert(p_sys->hls_stream);
1829
1830     if (p_sys->b_error)
1831         return 0;
1832
1833     if (buffer == NULL)
1834     {
1835         /* caller skips data, get big enough buffer */
1836         msg_Warn(s, "buffer is NULL (allocate %d)", i_read);
1837         buffer = calloc(1, i_read);
1838         if (buffer == NULL)
1839             return 0; /* NO MEMORY left*/
1840     }
1841
1842     length = hls_Read(s, (uint8_t*) buffer, i_read);
1843     if (length < 0)
1844         return 0;
1845
1846     p_sys->playback.offset += length;
1847     return length;
1848 }
1849
1850 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
1851 {
1852     stream_sys_t *p_sys = s->p_sys;
1853     size_t curlen = 0;
1854     segment_t *segment;
1855
1856 again:
1857     segment = GetSegment(s);
1858     if (segment == NULL)
1859     {
1860         msg_Err(s, "segment %d should have been available (stream %d)",
1861                 p_sys->playback.segment, p_sys->playback.stream);
1862         return 0; /* eof? */
1863     }
1864
1865     vlc_mutex_lock(&segment->lock);
1866
1867     /* remember segment to peek */
1868     int peek_segment = p_sys->playback.segment;
1869     do
1870     {
1871         if (i_peek < segment->data->i_buffer)
1872         {
1873             *pp_peek = segment->data->p_buffer;
1874             curlen += i_peek;
1875         }
1876         else
1877         {
1878             p_sys->playback.segment++;
1879             vlc_mutex_unlock(&segment->lock);
1880             goto again;
1881         }
1882     } while ((curlen < i_peek) && vlc_object_alive(s));
1883
1884     /* restore segment to read */
1885     p_sys->playback.segment = peek_segment;
1886
1887     vlc_mutex_unlock(&segment->lock);
1888
1889     return curlen;
1890 }
1891
1892 static bool hls_MaySeek(stream_t *s)
1893 {
1894     stream_sys_t *p_sys = s->p_sys;
1895
1896     if (p_sys->hls_stream == NULL)
1897         return false;
1898
1899     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
1900     if (hls == NULL) return false;
1901
1902     if (p_sys->b_live)
1903     {
1904         vlc_mutex_lock(&hls->lock);
1905         int count = vlc_array_count(hls->segments);
1906         vlc_mutex_unlock(&hls->lock);
1907
1908         vlc_mutex_lock(&p_sys->download.lock_wait);
1909         bool may_seek = (p_sys->download.segment < (count - 2));
1910         vlc_mutex_unlock(&p_sys->download.lock_wait);
1911         return may_seek;
1912     }
1913     return true;
1914 }
1915
1916 static uint64_t GetStreamSize(stream_t *s)
1917 {
1918     stream_sys_t *p_sys = s->p_sys;
1919
1920     if (p_sys->b_live)
1921         return 0;
1922
1923     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
1924     if (hls == NULL) return 0;
1925
1926     vlc_mutex_lock(&hls->lock);
1927     uint64_t size = hls->size;
1928     vlc_mutex_unlock(&hls->lock);
1929
1930     return size;
1931 }
1932
1933 static int segment_Seek(stream_t *s, const uint64_t pos)
1934 {
1935     stream_sys_t *p_sys = s->p_sys;
1936
1937     hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
1938     if (hls == NULL)
1939         return VLC_EGENERIC;
1940
1941     vlc_mutex_lock(&hls->lock);
1942
1943     bool b_found = false;
1944     uint64_t length = 0;
1945     uint64_t size = hls->size;
1946     int count = vlc_array_count(hls->segments);
1947
1948     for (int n = 0; n < count; n++)
1949     {
1950         segment_t *segment = vlc_array_item_at_index(hls->segments, n);
1951         if (segment == NULL)
1952         {
1953             vlc_mutex_unlock(&hls->lock);
1954             return VLC_EGENERIC;
1955         }
1956
1957         vlc_mutex_lock(&segment->lock);
1958         length += segment->duration * (hls->bandwidth/8);
1959         vlc_mutex_unlock(&segment->lock);
1960
1961         if (!b_found && (pos <= length))
1962         {
1963             if (count - n >= 3)
1964             {
1965                 p_sys->playback.segment = n;
1966                 b_found = true;
1967                 break;
1968             }
1969             /* Do not search in last 3 segments */
1970             vlc_mutex_unlock(&hls->lock);
1971             return VLC_EGENERIC;
1972         }
1973     }
1974
1975     /* */
1976     if (!b_found && (pos >= size))
1977     {
1978         p_sys->playback.segment = count - 1;
1979         b_found = true;
1980     }
1981
1982     /* */
1983     if (b_found)
1984     {
1985         /* restore segment to start position */
1986         segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
1987         if (segment == NULL)
1988         {
1989             vlc_mutex_unlock(&hls->lock);
1990             return VLC_EGENERIC;
1991         }
1992
1993         vlc_mutex_lock(&segment->lock);
1994         if (segment->data)
1995         {
1996             uint64_t size = segment->size -segment->data->i_buffer;
1997             if (size > 0)
1998             {
1999                 segment->data->i_buffer += size;
2000                 segment->data->p_buffer -= size;
2001             }
2002         }
2003         vlc_mutex_unlock(&segment->lock);
2004
2005         /* start download at current playback segment */
2006         vlc_mutex_unlock(&hls->lock);
2007
2008         /* Wake up download thread */
2009         vlc_mutex_lock(&p_sys->download.lock_wait);
2010         p_sys->download.seek = p_sys->playback.segment;
2011         vlc_cond_signal(&p_sys->download.wait);
2012         vlc_mutex_unlock(&p_sys->download.lock_wait);
2013
2014         /* Wait for download to be finished */
2015         vlc_mutex_lock(&p_sys->download.lock_wait);
2016         msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2017         while (((p_sys->download.seek != -1) ||
2018                 (p_sys->download.segment - p_sys->playback.segment < 3)) &&
2019                 (p_sys->download.segment < (count - 6)))
2020         {
2021             vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2022             if (!vlc_object_alive(s) || s->b_error) break;
2023         }
2024         vlc_mutex_unlock(&p_sys->download.lock_wait);
2025
2026         return VLC_SUCCESS;
2027     }
2028     vlc_mutex_unlock(&hls->lock);
2029
2030     return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2031 }
2032
2033 static int Control(stream_t *s, int i_query, va_list args)
2034 {
2035     stream_sys_t *p_sys = s->p_sys;
2036
2037     switch (i_query)
2038     {
2039         case STREAM_CAN_SEEK:
2040         case STREAM_CAN_FASTSEEK:
2041             *(va_arg (args, bool *)) = hls_MaySeek(s);
2042             break;
2043         case STREAM_GET_POSITION:
2044             *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2045             break;
2046         case STREAM_SET_POSITION:
2047             if (hls_MaySeek(s))
2048             {
2049                 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2050                 if (segment_Seek(s, pos) == VLC_SUCCESS)
2051                 {
2052                     p_sys->playback.offset = pos;
2053                     break;
2054                 }
2055             }
2056             return VLC_EGENERIC;
2057         case STREAM_GET_SIZE:
2058             *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2059             break;
2060         default:
2061             return VLC_EGENERIC;
2062     }
2063     return VLC_SUCCESS;
2064 }