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