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 duration; /* 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)*/
80 uint64_t size; /* stream length (segment->duration * hls->bandwidth/8) */
82 vlc_array_t *segments; /* list of segments */
83 vlc_url_t url; /* uri to m3u8 */
85 bool b_cache; /* allow caching */
93 int current; /* current hls_stream */
94 int segment; /* current segment for downloading */
95 vlc_array_t *hls_stream;/* bandwidth adaptation */
102 access_t *p_access; /* HTTP access input */
105 hls_thread_t *thread;
106 vlc_array_t *hls_stream;/* bandwidth adaptation */
109 uint64_t offset; /* current offset in media */
110 int current; /* current hls_stream */
111 int segment; /* current segment for playback */
114 mtime_t last; /* playlist last loaded */
115 mtime_t wakeup; /* next reload time */
116 int tries; /* times it was not changed */
119 bool b_cache; /* can cache files */
120 bool b_meta; /* meta playlist */
121 bool b_live; /* live stream? or vod? */
122 bool b_error; /* parsing error */
125 /****************************************************************************
127 ****************************************************************************/
128 static int Read (stream_t *, void *p_read, unsigned int i_read);
129 static int Peek (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
130 static int Control(stream_t *, int i_query, va_list);
132 static int AccessOpen(stream_t *s, vlc_url_t *url);
133 static void AccessClose(stream_t *s);
134 static char *AccessReadLine(access_t *p_access, uint8_t *psz_tmp, size_t i_len);
135 static int AccessDownload(stream_t *s, segment_t *segment);
137 static void* hls_Thread(vlc_object_t *);
138 static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls);
140 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted);
141 static void segment_Free(segment_t *segment);
143 /****************************************************************************
145 ****************************************************************************/
146 static bool isHTTPLiveStreaming(stream_t *s)
148 const uint8_t *peek, *peek_end;
150 int64_t i_size = stream_Peek(s->p_source, &peek, 46);
154 if (strncasecmp((const char*)peek, "#EXTM3U", 7) != 0)
157 /* Parse stream and search for
158 * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
159 * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
160 peek_end = peek + i_size;
161 while(peek <= peek_end)
165 if (strncasecmp((const char*)peek, "#EXT-X-TARGETDURATION", 21) == 0)
167 else if (strncasecmp((const char*)peek, "#EXT-X-STREAM-INF", 17) == 0)
176 /* HTTP Live Streaming */
177 static hls_stream_t *hls_New(vlc_array_t *hls_stream, int id, uint64_t bw, char *uri)
179 hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
180 if (hls == NULL) return NULL;
184 hls->duration = -1;/* unknown */
186 hls->sequence = 0; /* default is 0 */
187 hls->version = 1; /* default protocol version */
189 vlc_UrlParse(&hls->url, uri, 0);
190 hls->segments = vlc_array_new();
191 vlc_array_append(hls_stream, hls);
192 vlc_mutex_init(&hls->lock);
196 static void hls_Free(hls_stream_t *hls)
198 vlc_mutex_destroy(&hls->lock);
202 for (int n = 0; n < vlc_array_count(hls->segments); n++)
204 segment_t *segment = (segment_t *)vlc_array_item_at_index(hls->segments, n);
205 if (segment) segment_Free(segment);
207 vlc_array_destroy(hls->segments);
210 vlc_UrlClean(&hls->url);
215 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, int wanted)
217 int count = vlc_array_count(hls_stream);
220 if ((wanted < 0) || (wanted >= count))
222 return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
225 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
227 return (hls_stream_t*) hls_Get(hls_stream, 0);
230 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
232 int count = vlc_array_count(hls_stream);
236 return (hls_stream_t *) hls_Get(hls_stream, count);
239 static uint64_t hls_GetStreamSize(hls_stream_t *hls)
241 /* NOTE: Stream size is calculated based on segment duration and
242 * HLS stream bandwidth from the .m3u8 file. If these are not correct
243 * then the deviation from exact byte size will be big and the seek/
244 * progressbar will not behave entirely as one expects. */
246 int count = vlc_array_count(hls->segments);
247 for (int n = 0; n < count; n++)
249 segment_t *segment = segment_GetSegment(hls, n);
252 size += (segment->duration * (hls->bandwidth / 8));
259 static segment_t *segment_New(hls_stream_t* hls, int duration, char *uri)
261 segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
265 segment->duration = duration; /* seconds */
266 segment->size = 0; /* bytes */
267 segment->sequence = 0;
268 segment->bandwidth = 0;
269 vlc_UrlParse(&segment->url, uri, 0);
270 segment->data = NULL;
271 vlc_array_append(hls->segments, segment);
272 vlc_mutex_init(&segment->lock);
276 static void segment_Free(segment_t *segment)
278 vlc_mutex_destroy(&segment->lock);
280 vlc_UrlClean(&segment->url);
282 block_Release(segment->data);
287 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted)
291 int count = vlc_array_count(hls->segments);
294 if ((wanted < 0) || (wanted >= count))
296 return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
300 static char *parse_Attributes(const char *line, const char *attr)
303 char *begin = (char *) line;
304 char *end = begin + strlen(line);
306 /* Find start of attributes */
307 if ((p = strchr(begin, ':' )) == NULL)
313 if (strncasecmp(begin, attr, strlen(attr)) == 0)
315 /* <attr>=<value>[,]* */
316 p = strchr(begin, ',');
317 begin += strlen(attr) + 1;
320 if (p == NULL) /* last attribute */
321 return strndup(begin, end - begin);
323 return strndup(begin, p - begin);
326 } while(begin < end);
331 static char *relative_URI(stream_t *s, const char *uri, char *psz_uri)
333 char *p = strchr(uri, ':');
338 if (asprintf(&tmp,"%s://%s", s->psz_access, s->psz_path) < 0)
340 s->p_sys->b_error = true;
344 char *psz_path = strrchr(tmp, '/');
345 if (psz_path) *psz_path = '\0';
348 vlc_UrlParse(&url, tmp, 0);
349 if (asprintf(&psz_uri, "%s://%s%s/%s",
350 url.psz_protocol, url.psz_host, url.psz_path, uri) < 0)
354 s->p_sys->b_error = true;
362 static void parse_SegmentInformation(stream_t *s, hls_stream_t *hls, char *p_read, char *uri)
364 stream_sys_t *p_sys = s->p_sys;
369 int ret = sscanf(p_read, "#EXTINF:%d,", &duration);
372 msg_Err(s, "expected #EXTINF:<s>,");
373 p_sys->b_error = true;
377 char *psz_uri = NULL;
378 psz_uri = relative_URI(s, uri, psz_uri);
380 vlc_mutex_lock(&hls->lock);
381 segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
383 segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
384 if (duration > hls->duration)
386 msg_Err(s, "EXTINF:%d duration is larger then EXT-X-TARGETDURATION:%d",
387 duration, hls->duration);
389 vlc_mutex_unlock(&hls->lock);
394 static void parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
396 stream_sys_t *p_sys = s->p_sys;
401 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
404 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
405 p_sys->b_error = true;
409 hls->duration = duration; /* seconds */
412 static void parse_StreamInformation(stream_t *s, char *p_read, char *uri)
414 stream_sys_t *p_sys = s->p_sys;
420 attr = parse_Attributes(p_read, "PROGRAM-ID");
423 msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
424 p_sys->b_error = true;
430 attr = parse_Attributes(p_read, "BANDWIDTH");
433 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
434 p_sys->b_error = true;
442 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
443 p_sys->b_error = true;
447 msg_Info(s, "bandwidth adaption detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
449 char *psz_uri = NULL;
450 psz_uri = relative_URI(s, uri, psz_uri);
452 hls_stream_t *hls = hls_New(p_sys->hls_stream, id, bw, psz_uri ? psz_uri : uri);
454 p_sys->b_error = true;
459 static void parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
461 stream_sys_t *p_sys = s->p_sys;
466 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
469 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
470 p_sys->b_error = true;
474 if (hls->sequence > 0)
475 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist");
477 hls->sequence = sequence;
480 static void parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
482 stream_sys_t *p_sys = s->p_sys;
486 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
488 attr = parse_Attributes(p_read, "METHOD");
491 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
492 p_sys->b_error = true;
494 else if (strncasecmp(attr, "NONE", 4) == 0)
496 char *uri = parse_Attributes(p_read, "URI");
499 msg_Err(s, "#EXT-X-KEY: URI not expected");
500 p_sys->b_error = true;
503 /* IV is only supported in version 2 and above */
504 if (hls->version >= 2)
506 char *iv = parse_Attributes(p_read, "IV");
509 msg_Err(s, "#EXT-X-KEY: IV not expected");
510 p_sys->b_error = true;
517 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
518 p_sys->b_error = true;
523 static void parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
526 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
529 static void parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
531 stream_sys_t *p_sys = s->p_sys;
535 char answer[4] = "\0";
536 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
539 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
540 p_sys->b_error = true;
544 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
547 static void parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
549 stream_sys_t *p_sys = s->p_sys;
554 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
557 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
558 p_sys->b_error = true;
563 hls->version = version;
564 if (hls->version != 1)
566 msg_Err(s, "#EXT-X-VERSION should be version 1 iso %d", version);
567 p_sys->b_error = true;
571 static void parse_EndList(stream_t *s, hls_stream_t *hls)
573 stream_sys_t *p_sys = s->p_sys;
577 p_sys->b_live = false;
578 msg_Info(s, "video on demand (vod) mode");
581 static void parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
585 /* FIXME: Do we need to act on discontinuity ?? */
586 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
589 static void parse_M3U8ExtLine(stream_t *s, hls_stream_t *hls, char *line)
593 if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
594 parse_TargetDuration(s, hls, line);
595 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 22) == 0)
596 parse_MediaSequence(s, hls, line);
597 else if (strncmp(line, "#EXT-X-KEY", 11) == 0)
598 parse_Key(s, hls, line);
599 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 25) == 0)
600 parse_ProgramDateTime(s, hls, line);
601 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 17) == 0)
602 parse_AllowCache(s, hls, line);
603 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
604 parse_Discontinuity(s, hls, line);
605 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
606 parse_Version(s, hls, line);
607 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
608 parse_EndList(s, hls);
612 #define HTTPLIVE_MAX_LINE 4096
613 static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls)
615 stream_sys_t *p_sys = s->p_sys;
617 /* Download new playlist file from server */
618 if (AccessOpen(s, &hls->url) != VLC_SUCCESS)
621 /* Parse the rest of the reply */
622 uint8_t *tmp = calloc(1, HTTPLIVE_MAX_LINE);
629 char *line = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
630 if (strncmp(line, "#EXTM3U", 7) != 0)
632 msg_Err(s, "missing #EXTM3U tag");
640 line = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
643 msg_Dbg(s, "end of data");
647 if (!vlc_object_alive(s))
650 /* some more checks for actual data */
651 if (strncmp(line, "#EXTINF", 7) == 0)
653 char *uri = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
655 p_sys->b_error = true;
658 parse_SegmentInformation(s, hls, line, uri);
664 parse_M3U8ExtLine(s, hls, line);
667 /* Error during m3u8 parsing abort */
685 #undef HTTPLIVE_MAX_LINE
687 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
688 * document defines the following new tags: EXT-X-TARGETDURATION,
689 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
690 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
693 static int parse_HTTPLiveStreaming(stream_t *s)
695 stream_sys_t *p_sys = s->p_sys;
696 char *p_read, *p_begin, *p_end;
698 assert(p_sys->hls_stream);
700 p_begin = p_read = stream_ReadLine(s->p_source);
705 int i_len = strlen(p_begin);
706 p_end = p_read + i_len;
708 if (strncmp(p_read, "#EXTM3U", 7) != 0)
710 msg_Err(s, "missing #EXTM3U tag .. aborting");
722 p_begin = stream_ReadLine(s->p_source);
726 i_len = strlen(p_begin);
728 p_end = p_read + i_len;
730 if (strncmp(p_read, "#EXT-X-STREAM-INF", 17) == 0)
732 p_sys->b_meta = true;
733 char *uri = stream_ReadLine(s->p_source);
735 p_sys->b_error = true;
738 parse_StreamInformation(s, p_read, uri);
742 else if (strncmp(p_read, "#EXTINF", 7) == 0)
744 char *uri = stream_ReadLine(s->p_source);
746 p_sys->b_error = true;
749 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
751 parse_SegmentInformation(s, hls, p_read, uri);
753 p_sys->b_error = true;
759 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
764 hls = hls_New(p_sys->hls_stream, -1, -1, NULL);
767 p_sys->b_error = true;
772 /* Parse M3U8 Ext Line */
773 parse_M3U8ExtLine(s, hls, p_read);
775 } while(p_read < p_end);
780 int count = vlc_array_count(p_sys->hls_stream);
781 for (int n = 0; n < count; n++)
783 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
784 if (hls == NULL) break;
786 /* Is it a meta playlist? */
789 msg_Dbg(s, "parsing %s", hls->url.psz_path);
790 if (get_HTTPLivePlaylist(s, hls) != VLC_SUCCESS)
792 msg_Err(s, "could not parse playlist file from meta index." );
797 vlc_mutex_lock(&hls->lock);
801 /* There should at least be 3 segments of hls->duration */
803 int num = vlc_array_count(hls->segments);
804 for (int i = 0; i < num; i++)
806 segment_t *segment = segment_GetSegment(hls, i);
807 if (segment && segment->duration >= hls->duration)
812 msg_Err(s, "cannot start live playback at this time, try again later.");
813 vlc_mutex_unlock(&hls->lock);
817 /* Determine next time to reload playlist */
818 p_sys->wakeup = p_sys->last + (hls->duration * 2 * (mtime_t)1000000);
821 /* Stream size (approximate) */
822 hls->size = hls_GetStreamSize(hls);
824 /* Can we cache files after playback */
825 p_sys->b_cache = hls->b_cache;
827 vlc_mutex_unlock(&hls->lock);
833 /****************************************************************************
835 ****************************************************************************/
836 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
838 stream_sys_t *p_sys = s->p_sys;
840 uint64_t bw = *bandwidth;
841 uint64_t bw_candidate = 0;
843 int count = vlc_array_count(p_sys->hls_stream);
844 for (int n = 0; n < count; n++)
846 /* Select best bandwidth match */
847 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
848 if (hls == NULL) break;
850 /* only consider streams with the same PROGRAM-ID */
851 if (hls->id == progid)
853 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
855 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
856 n, bw, hls->bandwidth); /* bits / s */
857 bw_candidate = hls->bandwidth;
858 candidate = n; /* possible candidate */
862 *bandwidth = bw_candidate;
866 static int Download(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
871 vlc_mutex_lock(&segment->lock);
872 if (segment->data != NULL)
874 /* Segment already downloaded */
875 vlc_mutex_unlock(&segment->lock);
879 mtime_t start = mdate();
880 if (AccessDownload(s, segment) != VLC_SUCCESS)
882 vlc_mutex_unlock(&segment->lock);
885 mtime_t duration = mdate() - start;
887 vlc_mutex_unlock(&segment->lock);
889 msg_Info(s, "downloaded segment %d from stream %d",
890 segment->sequence, *cur_stream);
892 /* check for division by zero */
893 double ms = (double)duration / 1000.0; /* ms */
897 uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
898 segment->bandwidth = bw;
899 if (hls->bandwidth != bw)
901 int newstream = BandwidthAdaptation(s, hls->id, &bw);
903 /* FIXME: we need an average here */
904 if ((newstream >= 0) && (newstream != *cur_stream))
906 msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
907 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
908 *cur_stream = newstream;
914 static void* hls_Thread(vlc_object_t *p_this)
916 hls_thread_t *client = (hls_thread_t *) p_this;
917 stream_t *s = client->s;
918 stream_sys_t *p_sys = s->p_sys;
920 int canc = vlc_savecancel();
922 while (vlc_object_alive(p_this))
924 hls_stream_t *hls = hls_Get(client->hls_stream, client->current);
927 vlc_mutex_lock(&hls->lock);
928 segment_t *segment = segment_GetSegment(hls, client->segment);
929 vlc_mutex_unlock(&hls->lock);
931 /* Is there a new segment to process? */
934 if (!p_sys->b_live) break;
935 mwait(p_sys->wakeup);
937 else if (Download(client->s, hls, segment, &client->current) != VLC_SUCCESS)
939 if (!p_sys->b_live) break;
942 /* download succeeded */
945 /* FIXME: Reread the m3u8 index file */
949 mtime_t now = mdate();
950 if (now >= p_sys->wakeup)
953 /** FIXME: Implement m3u8 playlist reloading */
954 if (!hls_ReloadPlaylist(client->s))
956 /* No change in playlist, then backoff */
958 if (p_sys->tries == 1) wait = 0.5;
959 else if (p_sys->tries == 2) wait = 1;
960 else if (p_sys->tries >= 3) wait = 3;
963 /* determine next time to update playlist */
965 p_sys->wakeup = now + ((mtime_t)(hls->duration * wait) * (mtime_t)1000000);
970 vlc_restorecancel(canc);
974 static int Prefetch(stream_t *s, int *current)
976 stream_sys_t *p_sys = s->p_sys;
979 /* Try to pick best matching stream */
983 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
987 segment_t *segment = segment_GetSegment(hls, p_sys->segment);
988 if (segment == NULL )
991 if (Download(s, hls, segment, current) != VLC_SUCCESS)
994 /* Found better bandwidth match, try again */
995 if (*current != stream)
998 /* Download first 2 segments of this HLS stream */
999 for (int i = 0; i < 2; i++)
1001 segment_t *segment = segment_GetSegment(hls, p_sys->segment);
1002 if (segment == NULL )
1003 return VLC_EGENERIC;
1011 if (Download(s, hls, segment, current) != VLC_SUCCESS)
1012 return VLC_EGENERIC;
1020 /****************************************************************************
1022 ****************************************************************************/
1023 static int AccessOpen(stream_t *s, vlc_url_t *url)
1025 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
1027 if ((url->psz_protocol == NULL) ||
1028 (url->psz_path == NULL))
1029 return VLC_EGENERIC;
1031 p_sys->p_access = vlc_object_create(s, sizeof(access_t));
1032 if (p_sys->p_access == NULL)
1035 p_sys->p_access->psz_access = strdup(url->psz_protocol);
1036 p_sys->p_access->psz_filepath = strdup(url->psz_path);
1037 if (url->psz_password || url->psz_username)
1039 if (asprintf(&p_sys->p_access->psz_location, "%s:%s@%s%s",
1040 url->psz_username, url->psz_password,
1041 url->psz_host, url->psz_path) < 0)
1043 msg_Err(s, "creating http access module");
1049 if (asprintf(&p_sys->p_access->psz_location, "%s%s",
1050 url->psz_host, url->psz_path) < 0)
1052 msg_Err(s, "creating http access module");
1056 vlc_object_attach(p_sys->p_access, s);
1057 p_sys->p_access->p_module =
1058 module_need(p_sys->p_access, "access", "http", true);
1059 if (p_sys->p_access->p_module == NULL)
1061 msg_Err(s, "could not load http access module");
1068 vlc_object_release(p_sys->p_access);
1069 p_sys->p_access = NULL;
1070 return VLC_EGENERIC;
1073 static void AccessClose(stream_t *s)
1075 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
1077 if (p_sys->p_access)
1079 vlc_object_kill(p_sys->p_access);
1080 free(p_sys->p_access->psz_access);
1081 if (p_sys->p_access->p_module)
1082 module_unneed(p_sys->p_access,
1083 p_sys->p_access->p_module);
1085 vlc_object_release(p_sys->p_access);
1086 p_sys->p_access = NULL;
1090 static char *AccessReadLine(access_t *p_access, uint8_t *psz_tmp, size_t i_len)
1093 char *begin = (char *)psz_tmp;
1097 int skip = strlen(begin);
1098 ssize_t len = p_access->pf_read(p_access, psz_tmp + skip, i_len - skip);
1099 if (len < 0) return NULL;
1100 if ((len == 0) && (skip == 0))
1104 char *end = p + len + skip;
1114 /* copy line excluding \n */
1115 line = strndup(begin, p - begin);
1120 psz_tmp = memmove(begin, p, end - p);
1121 psz_tmp[end - p] = '\0';
1123 else memset(psz_tmp, 0, i_len);
1128 static int AccessDownload(stream_t *s, segment_t *segment)
1130 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
1134 /* Download new playlist file from server */
1135 if (AccessOpen(s, &segment->url) != VLC_SUCCESS)
1136 return VLC_EGENERIC;
1138 segment->size = p_sys->p_access->info.i_size;
1139 assert(segment->size > 0);
1141 segment->data = block_Alloc(segment->size);
1142 if (segment->data == NULL)
1148 assert(segment->data->i_buffer == segment->size);
1150 ssize_t length = 0, curlen = 0;
1153 if (p_sys->p_access->info.i_size > segment->size)
1155 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1156 segment->data = block_Realloc(segment->data, 0, p_sys->p_access->info.i_size);
1157 if (segment->data == NULL)
1162 segment->size = p_sys->p_access->info.i_size;
1163 assert(segment->data->i_buffer == segment->size);
1165 length = p_sys->p_access->pf_read(p_sys->p_access,
1166 segment->data->p_buffer + curlen, segment->size - curlen);
1167 if ((length <= 0) || ((uint64_t)length >= segment->size))
1170 } while (vlc_object_alive(s));
1176 /****************************************************************************
1178 ****************************************************************************/
1179 static int Open(vlc_object_t *p_this)
1181 stream_t *s = (stream_t*)p_this;
1182 stream_sys_t *p_sys;
1184 if (!isHTTPLiveStreaming(s))
1185 return VLC_EGENERIC;
1187 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1190 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1194 p_sys->b_live = true;
1195 p_sys->b_meta = false;
1197 p_sys->hls_stream = vlc_array_new();
1198 if (p_sys->hls_stream == NULL)
1207 s->pf_control = Control;
1209 /* Select first segment to play */
1210 p_sys->last = mdate();
1211 if (parse_HTTPLiveStreaming(s) != VLC_SUCCESS)
1216 /* Choose first HLS stream to start with */
1217 int current = p_sys->current = 0;
1220 if (Prefetch(s, ¤t) != VLC_SUCCESS)
1222 msg_Err(s, "fetching first segment.");
1226 p_sys->thread = vlc_object_create(s, sizeof(hls_thread_t));
1227 if( p_sys->thread == NULL )
1229 msg_Err(s, "creating HTTP Live Streaming client thread");
1233 p_sys->thread->hls_stream = p_sys->hls_stream;
1234 p_sys->thread->current = current;
1235 p_sys->current = current;
1236 p_sys->thread->segment = p_sys->segment;
1237 p_sys->segment = 0; /* reset to first segment */
1238 p_sys->thread->s = s;
1240 if (vlc_thread_create(p_sys->thread, "HTTP Live Streaming client",
1241 hls_Thread, VLC_THREAD_PRIORITY_INPUT))
1246 vlc_object_attach(p_sys->thread, s);
1252 return VLC_EGENERIC;
1255 /****************************************************************************
1257 ****************************************************************************/
1258 static void Close(vlc_object_t *p_this)
1260 stream_t *s = (stream_t*)p_this;
1261 stream_sys_t *p_sys = s->p_sys;
1263 assert(p_sys->hls_stream);
1268 vlc_object_kill(p_sys->thread);
1269 vlc_thread_join(p_sys->thread);
1270 vlc_object_release(p_sys->thread);
1273 /* Free hls streams */
1274 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1277 hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
1278 if (hls) hls_Free(hls);
1280 vlc_array_destroy(p_sys->hls_stream);
1286 /****************************************************************************
1287 * Stream filters functions
1288 ****************************************************************************/
1289 static segment_t *NextSegment(stream_t *s)
1291 stream_sys_t *p_sys = s->p_sys;
1292 segment_t *segment = NULL;
1294 /* Is the next segment of the current HLS stream ready? */
1295 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1298 vlc_mutex_lock(&hls->lock);
1299 segment = segment_GetSegment(hls, p_sys->segment);
1300 if (segment != NULL)
1302 /* This segment is ready? */
1303 if (segment->data != NULL)
1305 vlc_mutex_unlock(&hls->lock);
1309 vlc_mutex_unlock(&hls->lock);
1312 /* Was the HLS stream changed to another bitrate? */
1315 while(vlc_object_alive(s))
1317 /* Is the next segment ready */
1318 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
1322 vlc_mutex_lock(&hls->lock);
1323 segment = segment_GetSegment(hls, p_sys->segment);
1324 if (segment == NULL)
1326 vlc_mutex_unlock(&hls->lock);
1330 /* This segment is ready? */
1331 if ((segment->data != NULL) &&
1332 (p_sys->segment < p_sys->thread->segment))
1334 p_sys->current = i_stream;
1335 vlc_mutex_unlock(&hls->lock);
1338 vlc_mutex_unlock(&hls->lock);
1343 /* Was the stream changed to another bitrate? */
1345 if (i_stream >= vlc_array_count(p_sys->hls_stream))
1352 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
1354 stream_sys_t *p_sys = s->p_sys;
1359 /* Determine next segment to read. If this is a meta playlist and
1360 * bandwidth conditions changed, then the stream might have switched
1361 * to another bandwidth. */
1362 segment_t *segment = NextSegment(s);
1363 if (segment == NULL)
1366 vlc_mutex_lock(&segment->lock);
1367 if (segment->data->i_buffer == 0)
1369 if (!p_sys->b_cache)
1371 block_Release(segment->data);
1372 segment->data = NULL;
1375 vlc_mutex_unlock(&segment->lock);
1379 if (segment->size == segment->data->i_buffer)
1380 msg_Info(s, "playing segment %d from stream %d",
1381 p_sys->segment, p_sys->current);
1384 if (i_read <= segment->data->i_buffer)
1386 else if (i_read > segment->data->i_buffer)
1387 len = segment->data->i_buffer;
1391 memcpy(p_read + copied, segment->data->p_buffer, len);
1392 segment->data->i_buffer -= len;
1393 segment->data->p_buffer += len;
1397 vlc_mutex_unlock(&segment->lock);
1399 } while ((i_read > 0) && vlc_object_alive(s));
1404 static int Read(stream_t *s, void *buffer, unsigned int i_read)
1406 stream_sys_t *p_sys = s->p_sys;
1409 assert(p_sys->hls_stream);
1413 /* caller skips data, get big enough buffer */
1414 msg_Warn(s, "buffer is NULL (allocate %d)", i_read);
1415 buffer = calloc(1, i_read);
1417 return 0; /* NO MEMORY left*/
1420 length = hls_Read(s, (uint8_t*) buffer, i_read);
1424 p_sys->offset += length;
1428 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
1430 stream_sys_t *p_sys = s->p_sys;
1435 segment = NextSegment(s);
1436 if (segment == NULL)
1438 msg_Err(s, "segment should have been available");
1439 return 0; /* eof? */
1442 vlc_mutex_lock(&segment->lock);
1444 /* remember segment to peek */
1445 int peek_segment = p_sys->segment;
1448 if (i_peek < segment->data->i_buffer)
1450 *pp_peek = segment->data->p_buffer;
1456 vlc_mutex_unlock(&segment->lock);
1459 } while ((curlen < i_peek) && vlc_object_alive(s));
1461 /* restore segment to read */
1462 p_sys->segment = peek_segment;
1464 vlc_mutex_unlock(&segment->lock);
1469 static bool hls_MaySeek(stream_t *s)
1471 stream_sys_t *p_sys = s->p_sys;
1473 if (p_sys->hls_stream == NULL)
1476 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1477 if (hls == NULL) return false;
1481 vlc_mutex_lock(&hls->lock);
1482 int count = vlc_array_count(hls->segments);
1483 bool may_seek = (p_sys->thread == NULL) ? false :
1484 (p_sys->thread->segment < count - 2);
1485 vlc_mutex_unlock(&hls->lock);
1491 static uint64_t GetStreamSize(stream_t *s)
1493 stream_sys_t *p_sys = s->p_sys;
1498 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1499 if (hls == NULL) return 0;
1501 vlc_mutex_lock(&hls->lock);
1502 uint64_t size = hls->size;
1503 vlc_mutex_unlock(&hls->lock);
1508 static int segment_Seek(stream_t *s, uint64_t pos)
1510 stream_sys_t *p_sys = s->p_sys;
1512 /* Find the right offset */
1513 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1515 return VLC_EGENERIC;
1517 uint64_t length = 0;
1518 bool b_found = false;
1520 vlc_mutex_lock(&hls->lock);
1521 int count = vlc_array_count(hls->segments);
1522 vlc_mutex_unlock(&hls->lock);
1524 for (int n = 0; n < count; n++)
1526 /* FIXME: Seeking in segments not dowloaded is not supported. */
1527 if (n >= p_sys->thread->segment)
1529 msg_Err(s, "seeking in segment not downloaded yet.");
1530 return VLC_EGENERIC;
1533 segment_t *segment = vlc_array_item_at_index(hls->segments, n);
1534 if (segment == NULL)
1535 return VLC_EGENERIC;
1537 vlc_mutex_lock(&segment->lock);
1540 length += segment->size;
1541 uint64_t size = segment->size -segment->data->i_buffer;
1544 segment->data->i_buffer += size;
1545 segment->data->p_buffer -= size;
1548 if (!b_found && (pos <= length))
1550 uint64_t used = length - pos;
1551 segment->data->i_buffer -= used;
1552 segment->data->p_buffer += used;
1554 count = p_sys->segment;
1561 /* FIXME: seeking is weird when seeking in segments
1562 that have not been downloaded yet */
1563 length += segment->duration * hls->bandwidth;
1565 if (!b_found && (pos <= length))
1567 count = p_sys->segment;
1572 vlc_mutex_unlock(&segment->lock);
1577 static int Control(stream_t *s, int i_query, va_list args)
1579 stream_sys_t *p_sys = s->p_sys;
1583 case STREAM_CAN_SEEK:
1584 case STREAM_CAN_FASTSEEK:
1585 *(va_arg (args, bool *)) = hls_MaySeek(s);
1587 case STREAM_GET_POSITION:
1588 *(va_arg (args, uint64_t *)) = p_sys->offset;
1590 case STREAM_SET_POSITION:
1593 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
1594 if (segment_Seek(s, pos) == VLC_SUCCESS)
1596 p_sys->offset = pos;
1600 return VLC_EGENERIC;
1601 case STREAM_GET_SIZE:
1602 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
1605 return VLC_EGENERIC;