1 /*****************************************************************************
2 * httplive.c: HTTP Live Streaming stream filter
3 *****************************************************************************
4 * Copyright (C) 2010 M2X BV
7 * Author: Jean-Paul Saman <jpsaman _AT_ videolan _DOT_ org>
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.
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.
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 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
36 #include <vlc_threads.h>
37 #include <vlc_arrays.h>
38 #include <vlc_stream.h>
41 #include <vlc_modules.h>
42 #include <vlc_access.h>
44 /*****************************************************************************
46 *****************************************************************************/
47 static int Open (vlc_object_t *);
48 static void Close(vlc_object_t *);
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)
58 /*****************************************************************************
60 *****************************************************************************/
61 typedef struct segment_s
63 int sequence; /* unique sequence number */
64 int length; /* segment duration (seconds) */
65 uint64_t size; /* segment size in bytes */
66 uint64_t bandwidth; /* bandwidth usage of segments (bits per second)*/
70 block_t *data; /* data */
73 typedef struct hls_stream_s
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)*/
81 vlc_array_t *segments; /* list of segments */
82 vlc_url_t url; /* uri to m3u8 */
84 bool b_cache; /* allow caching */
92 int current; /* current hls_stream */
93 int segment; /* current segment for downloading */
94 vlc_array_t *hls_stream;/* bandwidth adaptation */
101 access_t *p_access; /* HTTP access input */
104 hls_thread_t *thread;
105 vlc_array_t *hls_stream;/* bandwidth adaptation */
108 uint64_t offset; /* current offset in media */
109 int current; /* current hls_stream */
110 int segment; /* current segment for playback */
113 mtime_t last; /* playlist last loaded */
114 mtime_t wakeup; /* next reload time */
115 int tries; /* times it was not changed */
118 bool b_cache; /* can cache files */
119 bool b_meta; /* meta playlist */
120 bool b_live; /* live stream? or vod? */
121 bool b_error; /* parsing error */
124 /****************************************************************************
126 ****************************************************************************/
127 static int Read (stream_t *, void *p_read, unsigned int i_read);
128 static int Peek (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
129 static int Control(stream_t *, int i_query, va_list);
131 static int AccessOpen(stream_t *s, vlc_url_t *url);
132 static void AccessClose(stream_t *s);
133 static char *AccessReadLine(access_t *p_access, uint8_t *psz_tmp, size_t i_len);
134 static int AccessDownload(stream_t *s, segment_t *segment);
136 static void* hls_Thread(vlc_object_t *);
137 static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls);
139 static void segment_Free(segment_t *segment);
141 /****************************************************************************
143 ****************************************************************************/
144 static bool isHTTPLiveStreaming(stream_t *s)
146 const uint8_t *peek, *peek_end;
148 int64_t i_size = stream_Peek(s->p_source, &peek, 46);
152 if (strncasecmp((const char*)peek, "#EXTM3U", 7) != 0)
155 /* Parse stream and search for
156 * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
157 * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
158 peek_end = peek + i_size;
159 while(peek <= peek_end)
163 if (strncasecmp((const char*)peek, "#EXT-X-TARGETDURATION", 21) == 0)
165 else if (strncasecmp((const char*)peek, "#EXT-X-STREAM-INF", 17) == 0)
174 /* HTTP Live Streaming */
175 static hls_stream_t *hls_New(vlc_array_t *hls_stream, int id, uint64_t bw, char *uri)
177 hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
178 if (hls == NULL) return NULL;
182 hls->duration = -1;/* unknown */
183 hls->sequence = 0; /* default is 0 */
184 hls->version = 1; /* default protocol version */
186 vlc_UrlParse(&hls->url, uri, 0);
187 hls->segments = vlc_array_new();
188 vlc_array_append(hls_stream, hls);
189 vlc_mutex_init(&hls->lock);
193 static void hls_Free(hls_stream_t *hls)
195 vlc_mutex_destroy(&hls->lock);
199 for (int n = 0; n < vlc_array_count(hls->segments); n++)
201 segment_t *segment = (segment_t *)vlc_array_item_at_index(hls->segments, n);
202 if (segment) segment_Free(segment);
204 vlc_array_destroy(hls->segments);
207 vlc_UrlClean(&hls->url);
212 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, int wanted)
214 int count = vlc_array_count(hls_stream);
217 if ((wanted < 0) || (wanted >= count))
219 return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
222 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
224 return (hls_stream_t*) hls_Get(hls_stream, 0);
227 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
229 int count = vlc_array_count(hls_stream);
233 return (hls_stream_t *) hls_Get(hls_stream, count);
236 static int hls_LowestBandwidthStream(vlc_array_t *hls_stream)
238 int count = vlc_array_count(hls_stream);
242 for (int i = 0; i < count; i++)
244 hls_stream_t *hls = (hls_stream_t *) vlc_array_item_at_index(hls_stream, i);
247 lowest = hls->bandwidth;
250 else if (hls->bandwidth < lowest)
252 lowest = hls->bandwidth;
260 static segment_t *segment_New(hls_stream_t* hls, int duration, char *uri)
262 segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
266 segment->length = duration; /* seconds */
267 segment->size = 0; /* bytes */
268 segment->sequence = 0;
269 segment->bandwidth = 0;
270 vlc_UrlParse(&segment->url, uri, 0);
271 segment->data = NULL;
272 vlc_array_append(hls->segments, segment);
273 vlc_mutex_init(&segment->lock);
277 static void segment_Free(segment_t *segment)
279 vlc_mutex_destroy(&segment->lock);
281 vlc_UrlClean(&segment->url);
283 block_Release(segment->data);
288 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted)
292 int count = vlc_array_count(hls->segments);
295 if ((wanted < 0) || (wanted >= count))
297 return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
301 static char *parse_Attributes(const char *line, const char *attr)
304 char *begin = (char *) line;
305 char *end = begin + strlen(line);
307 /* Find start of attributes */
308 if ((p = strchr(begin, ':' )) == NULL)
314 if (strncasecmp(begin, attr, strlen(attr)) == 0)
316 /* <attr>=<value>[,]* */
317 p = strchr(begin, ',');
318 begin += strlen(attr) + 1;
321 if (p == NULL) /* last attribute */
322 return strndup(begin, end - begin);
324 return strndup(begin, p - begin);
327 } while(begin < end);
332 static char *relative_URI(stream_t *s, const char *uri, char *psz_uri)
334 char *p = strchr(uri, ':');
339 if (asprintf(&tmp,"%s://%s", s->psz_access, s->psz_path) < 0)
341 s->p_sys->b_error = true;
345 char *psz_path = strrchr(tmp, '/');
346 if (psz_path) *psz_path = '\0';
349 vlc_UrlParse(&url, tmp, 0);
350 if (asprintf(&psz_uri, "%s://%s%s/%s",
351 url.psz_protocol, url.psz_host, url.psz_path, uri) < 0)
355 s->p_sys->b_error = true;
363 static void parse_SegmentInformation(stream_t *s, hls_stream_t *hls, char *p_read, char *uri)
365 stream_sys_t *p_sys = s->p_sys;
370 int ret = sscanf(p_read, "#EXTINF:%d,", &duration);
373 msg_Err(s, "expected #EXTINF:<s>,");
374 p_sys->b_error = true;
378 char *psz_uri = NULL;
379 psz_uri = relative_URI(s, uri, psz_uri);
381 vlc_mutex_lock(&hls->lock);
382 segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
384 segment->sequence = hls->sequence + vlc_array_count(hls->segments);
385 if (duration > hls->duration)
387 msg_Err(s, "EXTINF:%d duration is larger then EXT-X-TARGETDURATION:%d",
388 duration, hls->duration);
390 vlc_mutex_unlock(&hls->lock);
393 static void parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
395 stream_sys_t *p_sys = s->p_sys;
400 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
403 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
404 p_sys->b_error = true;
408 hls->duration = duration; /* seconds */
411 static void parse_StreamInformation(stream_t *s, char *p_read, char *uri)
413 stream_sys_t *p_sys = s->p_sys;
419 attr = parse_Attributes(p_read, "PROGRAM-ID");
422 msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
423 p_sys->b_error = true;
429 attr = parse_Attributes(p_read, "BANDWIDTH");
432 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
433 p_sys->b_error = true;
441 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
442 p_sys->b_error = true;
446 msg_Info(s, "bandwidth adaption detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
448 char *psz_uri = NULL;
449 psz_uri = relative_URI(s, uri, psz_uri);
451 hls_stream_t *hls = hls_New(p_sys->hls_stream, id, bw, psz_uri ? psz_uri : uri);
453 p_sys->b_error = true;
456 static void parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
458 stream_sys_t *p_sys = s->p_sys;
463 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
466 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
467 p_sys->b_error = true;
471 if (hls->sequence > 0)
472 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist");
474 hls->sequence = sequence;
477 static void parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
479 stream_sys_t *p_sys = s->p_sys;
483 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
485 attr = parse_Attributes(p_read, "METHOD");
488 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
489 p_sys->b_error = true;
491 else if (strncasecmp(attr, "NONE", 4) == 0)
493 char *uri = parse_Attributes(p_read, "URI");
496 msg_Err(s, "#EXT-X-KEY: URI not expected");
497 p_sys->b_error = true;
500 /* IV is only supported in version 2 and above */
501 if (hls->version >= 2)
503 char *iv = parse_Attributes(p_read, "IV");
506 msg_Err(s, "#EXT-X-KEY: IV not expected");
507 p_sys->b_error = true;
514 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
515 p_sys->b_error = true;
520 static void parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
523 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
526 static void parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
528 stream_sys_t *p_sys = s->p_sys;
532 char answer[4] = "\0";
533 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
536 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
537 p_sys->b_error = true;
541 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
544 static void parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
546 stream_sys_t *p_sys = s->p_sys;
551 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
554 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
555 p_sys->b_error = true;
560 hls->version = version;
561 if (hls->version != 1)
563 msg_Err(s, "#EXT-X-VERSION should be version 1 iso %d", version);
564 p_sys->b_error = true;
568 static void parse_EndList(stream_t *s, hls_stream_t *hls)
570 stream_sys_t *p_sys = s->p_sys;
574 p_sys->b_live = false;
575 msg_Info(s, "video on demand (vod) mode");
578 static void parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
582 /* FIXME: Do we need to act on discontinuity ?? */
583 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
586 static void parse_M3U8ExtLine(stream_t *s, hls_stream_t *hls, char *line)
590 if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
591 parse_TargetDuration(s, hls, line);
592 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 22) == 0)
593 parse_MediaSequence(s, hls, line);
594 else if (strncmp(line, "#EXT-X-KEY", 11) == 0)
595 parse_Key(s, hls, line);
596 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 25) == 0)
597 parse_ProgramDateTime(s, hls, line);
598 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 17) == 0)
599 parse_AllowCache(s, hls, line);
600 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
601 parse_Discontinuity(s, hls, line);
602 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
603 parse_Version(s, hls, line);
604 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
605 parse_EndList(s, hls);
609 #define HTTPLIVE_MAX_LINE 4096
610 static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls)
612 stream_sys_t *p_sys = s->p_sys;
614 /* Download new playlist file from server */
615 if (AccessOpen(s, &hls->url) != VLC_SUCCESS)
618 /* Parse the rest of the reply */
619 uint8_t *tmp = calloc(1, HTTPLIVE_MAX_LINE);
626 char *line = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
627 if (strncmp(line, "#EXTM3U", 7) != 0)
629 msg_Err(s, "missing #EXTM3U tag");
637 line = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
640 msg_Dbg(s, "end of data");
644 if (!vlc_object_alive(s))
647 /* some more checks for actual data */
648 if (strncmp(line, "#EXTINF", 7) == 0)
650 char *uri = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
652 p_sys->b_error = true;
655 parse_SegmentInformation(s, hls, line, uri);
661 parse_M3U8ExtLine(s, hls, line);
664 /* Error during m3u8 parsing abort */
682 #undef HTTPLIVE_MAX_LINE
684 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
685 * document defines the following new tags: EXT-X-TARGETDURATION,
686 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
687 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
690 static int parse_HTTPLiveStreaming(stream_t *s)
692 stream_sys_t *p_sys = s->p_sys;
693 char *p_read, *p_begin, *p_end;
695 assert(p_sys->hls_stream);
697 p_begin = p_read = stream_ReadLine(s->p_source);
702 int i_len = strlen(p_begin);
703 p_end = p_read + i_len;
705 if (strncmp(p_read, "#EXTM3U", 7) != 0)
707 msg_Err(s, "missing #EXTM3U tag .. aborting");
719 p_begin = stream_ReadLine(s->p_source);
723 i_len = strlen(p_begin);
725 p_end = p_read + i_len;
727 if (strncmp(p_read, "#EXT-X-STREAM-INF", 17) == 0)
729 p_sys->b_meta = true;
730 char *uri = stream_ReadLine(s->p_source);
732 p_sys->b_error = true;
735 parse_StreamInformation(s, p_read, uri);
739 else if (strncmp(p_read, "#EXTINF", 7) == 0)
741 char *uri = stream_ReadLine(s->p_source);
743 p_sys->b_error = true;
746 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
748 parse_SegmentInformation(s, hls, p_read, uri);
750 p_sys->b_error = true;
756 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
761 hls = hls_New(p_sys->hls_stream, -1, -1, NULL);
764 p_sys->b_error = true;
769 /* Parse M3U8 Ext Line */
770 parse_M3U8ExtLine(s, hls, p_read);
772 } while(p_read < p_end);
777 int count = vlc_array_count(p_sys->hls_stream);
778 for (int n = 0; n < count; n++)
780 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
781 if (hls == NULL) break;
783 /* Is it a meta playlist? */
786 msg_Dbg(s, "parsing %s", hls->url.psz_path);
787 if (get_HTTPLivePlaylist(s, hls) != VLC_SUCCESS)
789 msg_Err(s, "could not parse playlist file from meta index." );
796 /* There should at least be 3 segments of hls->duration */
798 int num = vlc_array_count(hls->segments);
799 for (int i = 0; i < num; i++)
801 segment_t *segment = segment_GetSegment(hls, i);
802 if (segment && segment->length >= hls->duration)
807 msg_Err(s, "cannot start live playback at this time, try again later.");
810 /* Determine next time to reload playlist */
811 p_sys->wakeup = p_sys->last + (hls->duration * 2 * (mtime_t)1000000);
813 /* Can we cache files after playback */
814 p_sys->b_cache = hls->b_cache;
820 /****************************************************************************
822 ****************************************************************************/
823 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
825 stream_sys_t *p_sys = s->p_sys;
827 uint64_t bw = *bandwidth;
828 uint64_t bw_candidate = 0;
830 int count = vlc_array_count(p_sys->hls_stream);
831 for (int n = 0; n < count; n++)
833 /* Select best bandwidth match */
834 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
835 if (hls == NULL) break;
837 /* only consider streams with the same PROGRAM-ID */
838 if (hls->id == progid)
840 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
842 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
843 n, bw, hls->bandwidth); /* bits / s */
844 bw_candidate = hls->bandwidth;
845 candidate = n; /* possible candidate */
849 *bandwidth = bw_candidate;
853 static int Download(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
855 stream_sys_t *p_sys = s->p_sys;
860 vlc_mutex_lock(&segment->lock);
861 if (segment->data != NULL)
863 /* Segment already downloaded */
864 vlc_mutex_unlock(&segment->lock);
868 mtime_t start = mdate();
869 if (AccessDownload(s, segment) != VLC_SUCCESS)
871 vlc_mutex_unlock(&segment->lock);
874 mtime_t duration = mdate() - start;
876 vlc_mutex_unlock(&segment->lock);
878 /* thread is not started yet */
879 if (p_sys->thread == NULL)
881 msg_Info(s, "downloaded segment %d from stream %d",
882 p_sys->segment, p_sys->current);
887 /* Do bandwidth calculations when there are at least 3 segments
889 msg_Info(s, "downloaded segment %d from stream %d",
890 p_sys->thread->segment, p_sys->thread->current);
892 if (p_sys->thread->segment - p_sys->segment < 3)
896 /* check for division by zero */
897 double ms = (double)duration / 1000.0; /* ms */
901 uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
902 segment->bandwidth = bw;
903 if (hls->bandwidth != bw)
905 int newstream = BandwidthAdaptation(s, hls->id, &bw);
907 /* FIXME: we need an average here */
908 if ((newstream >= 0) && (newstream != *cur_stream))
910 msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
911 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
912 *cur_stream = newstream;
918 static void* hls_Thread(vlc_object_t *p_this)
920 hls_thread_t *client = (hls_thread_t *) p_this;
921 stream_t *s = client->s;
922 stream_sys_t *p_sys = s->p_sys;
924 int canc = vlc_savecancel();
926 while (vlc_object_alive(p_this))
928 hls_stream_t *hls = hls_Get(client->hls_stream, client->current);
931 vlc_mutex_lock(&hls->lock);
932 segment_t *segment = segment_GetSegment(hls, client->segment);
933 vlc_mutex_unlock(&hls->lock);
935 /* Is there a new segment to process? */
938 if (!p_sys->b_live) break;
939 mwait(p_sys->wakeup);
941 else if (Download(client->s, hls, segment, &client->current) != VLC_SUCCESS)
943 if (!p_sys->b_live) break;
946 /* download succeeded */
949 /* FIXME: Reread the m3u8 index file */
953 mtime_t now = mdate();
954 if (now >= p_sys->wakeup)
957 /** FIXME: Implement m3u8 playlist reloading */
958 if (!hls_ReloadPlaylist(client->s))
960 /* No change in playlist, then backoff */
962 if (p_sys->tries == 1) wait = 0.5;
963 else if (p_sys->tries == 2) wait = 1;
964 else if (p_sys->tries >= 3) wait = 3;
967 /* determine next time to update playlist */
969 p_sys->wakeup = now + ((mtime_t)(hls->duration * wait) * (mtime_t)1000000);
974 vlc_restorecancel(canc);
978 static int Prefetch(stream_t *s, int *current)
980 stream_sys_t *p_sys = s->p_sys;
982 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
986 /* Download first 3 segments of this HLS stream */
987 for (int i = 0; i < 3; i++)
989 segment_t *segment = segment_GetSegment(hls, p_sys->segment);
990 if (segment == NULL )
993 if (Download(s, hls, segment, current) != VLC_SUCCESS)
1002 /****************************************************************************
1004 ****************************************************************************/
1005 static int AccessOpen(stream_t *s, vlc_url_t *url)
1007 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
1009 if ((url->psz_protocol == NULL) ||
1010 (url->psz_path == NULL))
1011 return VLC_EGENERIC;
1013 p_sys->p_access = vlc_object_create(s, sizeof(access_t));
1014 if (p_sys->p_access == NULL)
1017 p_sys->p_access->psz_access = strdup(url->psz_protocol);
1018 p_sys->p_access->psz_filepath = strdup(url->psz_path);
1019 if (url->psz_password || url->psz_username)
1021 if (asprintf(&p_sys->p_access->psz_location, "%s:%s@%s%s",
1022 url->psz_username, url->psz_password,
1023 url->psz_host, url->psz_path) < 0)
1025 msg_Err(s, "creating http access module");
1031 if (asprintf(&p_sys->p_access->psz_location, "%s%s",
1032 url->psz_host, url->psz_path) < 0)
1034 msg_Err(s, "creating http access module");
1038 vlc_object_attach(p_sys->p_access, s);
1039 p_sys->p_access->p_module =
1040 module_need(p_sys->p_access, "access", "http", true);
1041 if (p_sys->p_access->p_module == NULL)
1043 msg_Err(s, "could not load http access module");
1050 vlc_object_release(p_sys->p_access);
1051 p_sys->p_access = NULL;
1052 return VLC_EGENERIC;
1055 static void AccessClose(stream_t *s)
1057 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
1059 if (p_sys->p_access)
1061 vlc_object_kill(p_sys->p_access);
1062 free(p_sys->p_access->psz_access);
1063 if (p_sys->p_access->p_module)
1064 module_unneed(p_sys->p_access,
1065 p_sys->p_access->p_module);
1067 vlc_object_release(p_sys->p_access);
1068 p_sys->p_access = NULL;
1072 static char *AccessReadLine(access_t *p_access, uint8_t *psz_tmp, size_t i_len)
1075 char *begin = (char *)psz_tmp;
1079 int skip = strlen(begin);
1080 ssize_t len = p_access->pf_read(p_access, psz_tmp + skip, i_len - skip);
1081 if (len < 0) return NULL;
1082 if ((len == 0) && (skip == 0))
1086 char *end = p + len + skip;
1096 /* copy line excluding \n */
1097 line = strndup(begin, p - begin);
1102 psz_tmp = memmove(begin, p, end - p);
1103 psz_tmp[end - p] = '\0';
1105 else memset(psz_tmp, 0, i_len);
1110 static int AccessDownload(stream_t *s, segment_t *segment)
1112 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
1116 /* Download new playlist file from server */
1117 if (AccessOpen(s, &segment->url) != VLC_SUCCESS)
1118 return VLC_EGENERIC;
1120 segment->size = p_sys->p_access->info.i_size;
1121 assert(segment->size > 0);
1123 segment->data = block_Alloc(segment->size);
1124 if (segment->data == NULL)
1130 assert(segment->data->i_buffer == segment->size);
1132 ssize_t length = 0, curlen = 0;
1135 if (p_sys->p_access->info.i_size > segment->size)
1137 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1138 segment->data = block_Realloc(segment->data, 0, p_sys->p_access->info.i_size);
1139 if (segment->data == NULL)
1144 segment->size = p_sys->p_access->info.i_size;
1145 assert(segment->data->i_buffer == segment->size);
1147 length = p_sys->p_access->pf_read(p_sys->p_access,
1148 segment->data->p_buffer + curlen, segment->size - curlen);
1149 if ((length <= 0) || ((uint64_t)length >= segment->size))
1152 } while (vlc_object_alive(s));
1158 /****************************************************************************
1160 ****************************************************************************/
1161 static int Open(vlc_object_t *p_this)
1163 stream_t *s = (stream_t*)p_this;
1164 stream_sys_t *p_sys;
1166 if (!isHTTPLiveStreaming(s))
1167 return VLC_EGENERIC;
1169 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1172 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1176 p_sys->b_live = true;
1177 p_sys->b_meta = false;
1179 p_sys->hls_stream = vlc_array_new();
1180 if (p_sys->hls_stream == NULL)
1189 s->pf_control = Control;
1191 /* Select first segment to play */
1192 p_sys->last = mdate();
1193 if (parse_HTTPLiveStreaming(s) != VLC_SUCCESS)
1199 int current = p_sys->current = hls_LowestBandwidthStream(p_sys->hls_stream);
1202 if (Prefetch(s, ¤t) != VLC_SUCCESS)
1204 msg_Err(s, "fetching first segment.");
1208 p_sys->thread = vlc_object_create(s, sizeof(hls_thread_t));
1209 if( p_sys->thread == NULL )
1211 msg_Err(s, "creating HTTP Live Streaming client thread");
1215 p_sys->thread->hls_stream = p_sys->hls_stream;
1216 p_sys->thread->current = current;
1217 p_sys->thread->segment = p_sys->segment;
1218 p_sys->segment = 0; /* reset to first segment */
1219 p_sys->thread->s = s;
1221 if (vlc_thread_create(p_sys->thread, "HTTP Live Streaming client",
1222 hls_Thread, VLC_THREAD_PRIORITY_INPUT))
1227 vlc_object_attach(p_sys->thread, s);
1233 return VLC_EGENERIC;
1236 /****************************************************************************
1238 ****************************************************************************/
1239 static void Close(vlc_object_t *p_this)
1241 stream_t *s = (stream_t*)p_this;
1242 stream_sys_t *p_sys = s->p_sys;
1244 assert(p_sys->hls_stream);
1249 vlc_object_kill(p_sys->thread);
1250 vlc_thread_join(p_sys->thread);
1251 vlc_object_release(p_sys->thread);
1254 /* Free hls streams */
1255 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1258 hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
1259 if (hls) hls_Free(hls);
1261 vlc_array_destroy(p_sys->hls_stream);
1267 /****************************************************************************
1268 * Stream filters functions
1269 ****************************************************************************/
1270 static segment_t *NextSegment(stream_t *s)
1272 stream_sys_t *p_sys = s->p_sys;
1273 segment_t *segment = NULL;
1276 while(vlc_object_alive(s))
1278 /* Is the next segment ready */
1279 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
1280 if (hls == NULL) return NULL;
1282 segment = segment_GetSegment(hls, p_sys->segment);
1283 if (segment == NULL) return NULL;
1285 /* This segment is ready? */
1286 if (segment->data != NULL)
1289 if (!p_sys->b_meta) return NULL;
1291 /* Was the stream changed to another bitrate? */
1293 if (i_stream >= vlc_array_count(p_sys->hls_stream))
1296 msg_Info(s, "playback is switching from stream %d to %d",
1297 p_sys->current, i_stream);
1299 p_sys->current = i_stream;
1305 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
1307 stream_sys_t *p_sys = s->p_sys;
1312 /* Determine next segment to read. If this is a meta playlist and
1313 * bandwidth conditions changed, then the stream might have switched
1314 * to another bandwidth. */
1315 segment_t *segment = NextSegment(s);
1316 if (segment == NULL)
1319 vlc_mutex_lock(&segment->lock);
1320 if (segment->data->i_buffer == 0)
1322 if (!p_sys->b_cache)
1324 block_Release(segment->data);
1325 segment->data = NULL;
1328 vlc_mutex_unlock(&segment->lock);
1332 if (segment->size == segment->data->i_buffer)
1333 msg_Info(s, "playing segment %d from stream %d",
1334 p_sys->segment, p_sys->current);
1337 if (i_read <= segment->data->i_buffer)
1339 else if (i_read > segment->data->i_buffer)
1340 len = segment->data->i_buffer;
1344 memcpy(p_read + copied, segment->data->p_buffer, len);
1345 segment->data->i_buffer -= len;
1346 segment->data->p_buffer += len;
1350 vlc_mutex_unlock(&segment->lock);
1352 } while ((i_read > 0) && vlc_object_alive(s));
1357 static int Read(stream_t *s, void *buffer, unsigned int i_read)
1359 stream_sys_t *p_sys = s->p_sys;
1362 assert(p_sys->hls_stream);
1366 /* caller skips data, get big enough buffer */
1367 msg_Warn(s, "buffer is NULL (allocate %d)", i_read);
1368 buffer = calloc(1, i_read);
1370 return 0; /* NO MEMORY left*/
1373 length = hls_Read(s, (uint8_t*) buffer, i_read);
1377 p_sys->offset += length;
1381 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
1383 stream_sys_t *p_sys = s->p_sys;
1388 segment = NextSegment(s);
1389 if (segment == NULL)
1391 msg_Err(s, "segment should have been available");
1392 return 0; /* eof? */
1395 vlc_mutex_lock(&segment->lock);
1397 /* remember segment to peek */
1398 int peek_segment = p_sys->segment;
1401 if (i_peek < segment->data->i_buffer)
1403 *pp_peek = segment->data->p_buffer;
1409 vlc_mutex_unlock(&segment->lock);
1412 } while ((curlen < i_peek) && vlc_object_alive(s));
1414 /* restore segment to read */
1415 p_sys->segment = peek_segment;
1417 vlc_mutex_unlock(&segment->lock);
1422 static bool hls_MaySeek(stream_t *s)
1424 stream_sys_t *p_sys = s->p_sys;
1426 if (p_sys->hls_stream == NULL)
1429 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1430 if (hls == NULL) return false;
1434 vlc_mutex_lock(&hls->lock);
1435 int count = vlc_array_count(hls->segments);
1436 bool may_seek = (p_sys->thread == NULL) ? false :
1437 (p_sys->thread->segment < count - 2);
1438 vlc_mutex_unlock(&hls->lock);
1444 static uint64_t GetStreamSize(stream_t *s)
1446 stream_sys_t *p_sys = s->p_sys;
1451 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1452 if (hls == NULL) return 0;
1454 /* FIXME: Stream size is not entirely exacts at this point */
1455 uint64_t length = 0UL;
1456 int count = vlc_array_count(hls->segments);
1457 for (int n = 0; n < count; n++)
1459 segment_t *segment = segment_GetSegment(hls, n);
1462 length += (segment->size > 0) ? segment->size :
1463 (segment->length * hls->bandwidth);
1469 static int segment_Seek(stream_t *s, uint64_t pos)
1471 stream_sys_t *p_sys = s->p_sys;
1473 /* Find the right offset */
1474 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1476 return VLC_EGENERIC;
1478 uint64_t length = 0;
1479 bool b_found = false;
1481 int count = vlc_array_count(hls->segments);
1482 for (int n = 0; n < count; n++)
1484 /* FIXME: Seeking in segments not dowloaded is not supported. */
1485 if (n >= p_sys->thread->segment)
1487 msg_Err(s, "seeking in segment not downloaded yet.");
1488 return VLC_EGENERIC;
1491 segment_t *segment = vlc_array_item_at_index(hls->segments, n);
1492 if (segment == NULL)
1493 return VLC_EGENERIC;
1495 vlc_mutex_lock(&segment->lock);
1498 length += segment->size;
1499 uint64_t size = segment->size -segment->data->i_buffer;
1502 segment->data->i_buffer += size;
1503 segment->data->p_buffer -= size;
1506 if (!b_found && (pos <= length))
1508 uint64_t used = length - pos;
1509 segment->data->i_buffer -= used;
1510 segment->data->p_buffer += used;
1512 count = p_sys->segment;
1519 /* FIXME: seeking is weird when seeking in segments
1520 that have not been downloaded yet */
1521 length += segment->length * hls->bandwidth;
1523 if (!b_found && (pos <= length))
1525 count = p_sys->segment;
1530 vlc_mutex_unlock(&segment->lock);
1535 static int Control(stream_t *s, int i_query, va_list args)
1537 stream_sys_t *p_sys = s->p_sys;
1541 case STREAM_CAN_SEEK:
1542 case STREAM_CAN_FASTSEEK:
1543 *(va_arg (args, bool *)) = hls_MaySeek(s);
1545 case STREAM_GET_POSITION:
1546 *(va_arg (args, uint64_t *)) = p_sys->offset;
1548 case STREAM_SET_POSITION:
1551 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
1552 if (segment_Seek(s, pos) == VLC_SUCCESS)
1554 p_sys->offset = pos;
1558 return VLC_EGENERIC;
1559 case STREAM_GET_SIZE:
1560 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
1563 return VLC_EGENERIC;