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