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>
39 #include <vlc_input.h>
41 #include <vlc_network.h>
44 #include <vlc_modules.h>
45 #include <vlc_access.h>
47 /*****************************************************************************
49 *****************************************************************************/
50 static int Open (vlc_object_t *);
51 static void Close(vlc_object_t *);
54 set_category(CAT_INPUT)
55 set_subcategory(SUBCAT_INPUT_STREAM_FILTER)
56 set_description(N_("Http Live Streaming stream filter"))
57 set_capability("stream_filter", 20)
58 set_callbacks(Open, Close)
61 /*****************************************************************************
63 *****************************************************************************/
64 typedef struct segment_s
66 int sequence; /* unique sequence number */
67 int length; /* segment duration (ms) */
68 uint64_t size; /* segment size in bytes */
72 block_t *data; /* data */
75 typedef struct hls_stream_s
77 int id; /* program id */
78 uint64_t bandwidth; /* bandwidth usage of segments (kbps)*/
79 int version; /* protocol version should be 1 */
80 int sequence; /* media sequence number */
81 int duration; /* maximum duration per segment (ms) */
82 int segment; /* current segment downloading */
83 vlc_array_t *segments; /* list of segments */
86 vlc_url_t url; /* uri to m3u8 */
87 bool b_cache; /* allow caching */
95 vlc_array_t *hls_stream;/* bandwidth adaptation */
96 int current; /* current hls_stream */
103 access_t *p_access; /* HTTP access input */
106 hls_thread_t *thread;
107 vlc_array_t *hls_stream;/* bandwidth adaptation */
110 uint64_t offset; /* current offset in media */
111 int current; /* current hls_stream */
112 int segment; /* current segment for playback */
115 mtime_t last; /* playlist last loaded */
116 mtime_t wakeup; /* next reload time */
117 int tries; /* times it was not changed */
120 bool b_cache; /* can cache files */
121 bool b_meta; /* meta playlist */
122 bool b_live; /* live stream? or vod? */
123 bool b_error; /* parsing error */
126 /****************************************************************************
128 ****************************************************************************/
129 static int Read (stream_t *, void *p_read, unsigned int i_read);
130 static int Peek (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
131 static int Control(stream_t *, int i_query, va_list);
133 static int AccessOpen(stream_t *s, vlc_url_t *url);
134 static void AccessClose(stream_t *s);
135 static char *AccessReadLine(access_t *p_access, uint8_t *psz_tmp, size_t i_len);
136 static int AccessDownload(stream_t *s, segment_t *segment);
138 static void* hls_Thread(vlc_object_t *);
139 static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls);
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->sequence = 0; /* default is 0 */
185 hls->version = 1; /* default protocol version */
188 vlc_UrlParse(&hls->url, uri, 0);
189 hls->segments = vlc_array_new();
190 vlc_array_append(hls_stream, hls);
191 vlc_mutex_init(&hls->lock);
195 static void hls_Free(hls_stream_t *hls)
197 vlc_mutex_destroy(&hls->lock);
201 for (int n = 0; n < vlc_array_count(hls->segments); n++)
203 segment_t *segment = (segment_t *)vlc_array_item_at_index(hls->segments, n);
204 if (segment) segment_Free(segment);
206 vlc_array_destroy(hls->segments);
209 vlc_UrlClean(&hls->url);
214 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, int wanted)
216 int count = vlc_array_count(hls_stream);
219 if ((wanted < 0) || (wanted >= count))
221 return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
224 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
226 return (hls_stream_t*) hls_Get(hls_stream, 0);
229 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
231 int count = vlc_array_count(hls_stream);
235 return (hls_stream_t *) hls_Get(hls_stream, count);
239 static segment_t *segment_New(hls_stream_t* hls, int duration, char *uri)
241 segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
245 segment->length = duration; /* seconds */
246 segment->size = 0; /* bytes */
247 segment->sequence = 0;
248 vlc_UrlParse(&segment->url, uri, 0);
249 segment->data = NULL;
250 vlc_array_append(hls->segments, segment);
251 vlc_mutex_init(&segment->lock);
255 static void segment_Free(segment_t *segment)
257 vlc_mutex_destroy(&segment->lock);
259 vlc_UrlClean(&segment->url);
261 block_Release(segment->data);
266 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted)
270 int count = vlc_array_count(hls->segments);
273 if ((wanted < 0) || (wanted >= count))
275 return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
279 static char *parse_Attributes(const char *line, const char *attr)
282 char *begin = (char *) line;
283 char *end = begin + strlen(line);
285 /* Find start of attributes */
286 if ((p = strchr(begin, ':' )) == NULL)
292 if (strncasecmp(begin, attr, strlen(attr)) == 0)
294 /* <attr>=<value>[,]* */
295 p = strchr(begin, ',');
296 begin += strlen(attr) + 1;
299 if (p == NULL) /* last attribute */
300 return strndup(begin, end - begin);
302 return strndup(begin, p - begin);
305 } while(begin < end);
310 static void parse_SegmentInformation(stream_t *s, hls_stream_t *hls, char *p_read, char *uri)
312 stream_sys_t *p_sys = s->p_sys;
317 int ret = sscanf(p_read, "#EXTINF:%d,", &duration);
320 msg_Err(s, "expected #EXTINF:<s>,");
321 p_sys->b_error = true;
325 vlc_mutex_lock(&hls->lock);
326 segment_t *segment = segment_New(hls, duration, uri);
328 segment->sequence = hls->sequence + vlc_array_count(hls->segments);
329 if (duration > hls->duration)
331 msg_Err(s, "EXTINF:%d duration is larger then EXT-X-TARGETDURATION:%d",
332 duration, hls->duration);
334 vlc_mutex_unlock(&hls->lock);
337 static void parse_TargetDuration(stream_t *s, char *p_read)
339 stream_sys_t *p_sys = s->p_sys;
342 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
345 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
346 p_sys->b_error = true;
350 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
352 hls->duration = duration; /* seconds */
355 static void parse_StreamInformation(stream_t *s, char *p_read, char *uri)
357 stream_sys_t *p_sys = s->p_sys;
362 attr = parse_Attributes(p_read, "PROGRAM-ID");
365 msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
366 p_sys->b_error = true;
372 attr = parse_Attributes(p_read, "BANDWIDTH");
375 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
376 p_sys->b_error = true;
384 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
385 p_sys->b_error = true;
389 msg_Info(s, "bandwidth adaption detected (program-id=%d, bandwidth=%d).", id, bw);
391 hls_stream_t *hls = hls_New(p_sys->hls_stream, id, bw, uri);
393 p_sys->b_error = true;
396 static void parse_MediaSequence(stream_t *s, char *p_read)
398 stream_sys_t *p_sys = s->p_sys;
401 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
404 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
405 p_sys->b_error = true;
409 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
411 if (hls->sequence > 0)
412 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist");
414 hls->sequence = sequence;
417 static void parse_Key(stream_t *s, char *p_read)
419 stream_sys_t *p_sys = s->p_sys;
421 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
423 attr = parse_Attributes(p_read, "METHOD");
426 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
427 p_sys->b_error = true;
429 else if (strncasecmp(attr, "NONE", 4) == 0)
431 char *uri = parse_Attributes(p_read, "URI");
432 char *iv = parse_Attributes(p_read, "IV");
433 if ((iv != NULL) || (uri != NULL))
435 msg_Err(s, "#EXT-X-KEY: URI and IV not expected");
436 p_sys->b_error = true;
444 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
445 p_sys->b_error = true;
450 static void parse_ProgramDateTime(stream_t *s, char *p_read)
452 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
455 static void parse_AllowCache(stream_t *s, char *p_read)
457 stream_sys_t *p_sys = s->p_sys;
459 char answer[4] = "\0";
460 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
463 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
464 p_sys->b_error = true;
468 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
471 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
474 static void parse_Version(stream_t *s, char *p_read)
476 stream_sys_t *p_sys = s->p_sys;
479 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
482 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
483 p_sys->b_error = true;
487 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
491 hls->version = version;
492 if (hls->version != 1)
494 msg_Err(s, "#EXT-X-VERSION should be version 1 iso %d", version);
495 p_sys->b_error = true;
499 static void parse_EndList(stream_t *s)
501 stream_sys_t *p_sys = s->p_sys;
502 p_sys->b_live = false;
504 msg_Info(s, "video on demand (vod) mode");
507 static void parse_Discontinuity(stream_t *s, char *p_read)
509 /* FIXME: Do we need to act on discontinuity ?? */
510 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
513 static void parse_M3U8ExtLine(stream_t *s, char *line)
517 if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
518 parse_TargetDuration(s, line);
519 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 22) == 0)
520 parse_MediaSequence(s, line);
521 else if (strncmp(line, "#EXT-X-KEY", 11) == 0)
523 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 25) == 0)
524 parse_ProgramDateTime(s, line);
525 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 17) == 0)
526 parse_AllowCache(s, line);
527 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
528 parse_Discontinuity(s, line);
529 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
530 parse_Version(s, line);
531 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
536 #define HTTPLIVE_MAX_LINE 4096
537 static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls)
539 stream_sys_t *p_sys = s->p_sys;
541 /* Download new playlist file from server */
542 if (AccessOpen(s, &hls->url) != VLC_SUCCESS)
545 /* Parse the rest of the reply */
546 uint8_t *tmp = calloc(1, HTTPLIVE_MAX_LINE);
553 char *line = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
554 if (strncmp(line, "#EXTM3U", 7) != 0)
556 msg_Err(s, "missing #EXTM3U tag");
564 line = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
567 msg_Dbg(s, "end of data");
571 if (!vlc_object_alive(s))
574 /* some more checks for actual data */
575 if (strncmp(line, "#EXTINF", 7) == 0)
577 char *uri = AccessReadLine(p_sys->p_access, tmp, HTTPLIVE_MAX_LINE);
579 p_sys->b_error = true;
582 parse_SegmentInformation(s, hls, line, uri);
588 parse_M3U8ExtLine(s, line);
591 /* Error during m3u8 parsing abort */
609 #undef HTTPLIVE_MAX_LINE
611 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
612 * document defines the following new tags: EXT-X-TARGETDURATION,
613 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
614 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
617 static int parse_HTTPLiveStreaming(stream_t *s)
619 stream_sys_t *p_sys = s->p_sys;
620 char *p_read, *p_begin, *p_end;
622 assert(p_sys->hls_stream);
624 p_begin = p_read = stream_ReadLine(s->p_source);
629 int i_len = strlen(p_begin);
630 p_end = p_read + i_len;
632 if (strncmp(p_read, "#EXTM3U", 7) != 0)
634 msg_Err(s, "missing #EXTM3U tag .. aborting");
646 p_begin = stream_ReadLine(s->p_source);
650 i_len = strlen(p_begin);
652 p_end = p_read + i_len;
654 if (strncmp(p_read, "#EXT-X-STREAM-INF", 17) == 0)
656 p_sys->b_meta = true;
657 char *uri = stream_ReadLine(s->p_source);
659 p_sys->b_error = true;
662 parse_StreamInformation(s, p_read, uri);
666 else if (strncmp(p_read, "#EXTINF", 7) == 0)
668 char *uri = stream_ReadLine(s->p_source);
670 p_sys->b_error = true;
673 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
675 parse_SegmentInformation(s, hls, p_read, uri);
677 p_sys->b_error = true;
685 hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
688 hls = hls_New(p_sys->hls_stream, -1, -1, NULL);
691 p_sys->b_error = true;
696 /* Parse M3U8 Ext Line */
697 parse_M3U8ExtLine(s, p_read);
699 } while(p_read < p_end);
704 int count = vlc_array_count(p_sys->hls_stream);
705 for (int n = 0; n < count; n++)
707 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
708 if (hls == NULL) break;
710 /* Is it a meta playlist? */
713 if (get_HTTPLivePlaylist(s, hls) != VLC_SUCCESS)
715 msg_Err(s, "could not parse playlist file from meta index." );
722 /* There should at least be 3 segments of hls->duration */
724 int num = vlc_array_count(hls->segments);
725 for (int i = 0; i < num; i++)
727 segment_t *segment = segment_GetSegment(hls, i);
728 if (segment && segment->length >= hls->duration)
733 msg_Err(s, "cannot start live playback at this time, try again later.");
736 /* Determine next time to reload playlist */
737 p_sys->wakeup = p_sys->last + (hls->duration * 2 * (mtime_t)1000000);
739 /* Can we cache files after playback */
740 p_sys->b_cache = hls->b_cache;
746 /****************************************************************************
748 ****************************************************************************/
749 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
751 stream_sys_t *p_sys = s->p_sys;
753 uint64_t bw = *bandwidth;
755 msg_Dbg(s, "bandwidth (bits/s) %"PRIu64, bw * 1000); /* bits / s */
757 int count = vlc_array_count(p_sys->hls_stream);
758 for (int n = 0; n < count; n++)
760 /* Select best bandwidth match */
761 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
762 if (hls == NULL) break;
764 /* only consider streams with the same PROGRAM-ID */
765 if (hls->id == progid)
767 if (bw <= hls->bandwidth)
769 *bandwidth = hls->bandwidth;
770 candidate = n; /* possible candidate */
777 static int Download(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
782 vlc_mutex_lock(&segment->lock);
783 if (segment->data != NULL)
785 /* Segment already downloaded */
786 vlc_mutex_unlock(&segment->lock);
790 mtime_t start = mdate();
791 if (AccessDownload(s, segment) != VLC_SUCCESS)
793 vlc_mutex_unlock(&segment->lock);
796 mtime_t duration = mdate() - start;
798 vlc_mutex_unlock(&segment->lock);
800 uint64_t bw = (segment->size * 8) / (duration/1000); /* bits / ms */
801 if (hls->bandwidth != bw)
803 int newstream = BandwidthAdaptation(s, hls->id, &bw);
804 if ((newstream > 0) && (newstream != *cur_stream))
806 msg_Info(s, "switching to %s bandwidth (%"PRIu64") stream",
807 (hls->bandwidth <= bw) ? "faster" : "lower", bw);
808 *cur_stream = newstream;
814 static void* hls_Thread(vlc_object_t *p_this)
816 hls_thread_t *client = (hls_thread_t *) p_this;
817 stream_t *s = client->s;
818 stream_sys_t *p_sys = s->p_sys;
820 int canc = vlc_savecancel();
822 while (vlc_object_alive(p_this))
824 hls_stream_t *hls = hls_Get(client->hls_stream, client->current);
827 vlc_mutex_lock(&hls->lock);
828 segment_t *segment = segment_GetSegment(hls, hls->segment);
829 if (segment) hls->segment++;
830 vlc_mutex_unlock(&hls->lock);
832 /* Is there a new segment to process? */
835 if (!p_sys->b_live) break;
836 mwait(p_sys->wakeup);
838 else if (Download(client->s, hls, segment, &client->current) != VLC_SUCCESS)
840 if (!p_sys->b_live) break;
843 /* FIXME: Reread the m3u8 index file */
847 mtime_t now = mdate();
848 if (now >= p_sys->wakeup)
851 /** FIXME: Implement m3u8 playlist reloading */
852 if (!hls_ReloadPlaylist(client->s))
854 /* No change in playlist, then backoff */
856 if (p_sys->tries == 1) wait = 0.5;
857 else if (p_sys->tries == 2) wait = 1;
858 else if (p_sys->tries >= 3) wait = 3;
861 /* determine next time to update playlist */
863 p_sys->wakeup = now + ((mtime_t)(hls->duration * wait) * (mtime_t)1000000);
868 vlc_restorecancel(canc);
872 static int Prefetch(stream_t *s)
874 stream_sys_t *p_sys = s->p_sys;
878 current = p_sys->current;
880 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
884 segment_t *segment = segment_GetSegment(hls, hls->segment);
885 if (segment == NULL )
888 if (Download(s, hls, segment, &p_sys->current) != VLC_SUCCESS)
891 /* Bandwidth changed? */
892 if (current != p_sys->current)
898 /****************************************************************************
900 ****************************************************************************/
901 static int AccessOpen(stream_t *s, vlc_url_t *url)
903 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
905 if ((url->psz_protocol == NULL) ||
906 (url->psz_path == NULL))
909 p_sys->p_access = vlc_object_create(s, sizeof(access_t));
912 p_sys->p_access->psz_access = strdup(url->psz_protocol);
913 p_sys->p_access->psz_filepath = strdup(url->psz_path);
914 if (url->psz_password || url->psz_username)
916 if (asprintf(&p_sys->p_access->psz_location, "%s:%s@%s%s",
917 url->psz_username, url->psz_password,
918 url->psz_host, url->psz_path) < 0)
920 msg_Err(s, "creating http access module");
926 if (asprintf(&p_sys->p_access->psz_location, "%s%s",
927 url->psz_host, url->psz_path) < 0)
929 msg_Err(s, "creating http access module");
933 vlc_object_attach(p_sys->p_access, s);
934 p_sys->p_access->p_module =
935 module_need(p_sys->p_access, "access", "http", true);
936 if (p_sys->p_access->p_module == NULL)
938 msg_Err(s, "could not load http access module");
946 vlc_object_release(p_sys->p_access);
947 p_sys->p_access = NULL;
951 static void AccessClose(stream_t *s)
953 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
957 vlc_object_kill(p_sys->p_access);
958 free(p_sys->p_access->psz_access);
959 if (p_sys->p_access->p_module)
960 module_unneed(p_sys->p_access,
961 p_sys->p_access->p_module);
963 vlc_object_release(p_sys->p_access);
964 p_sys->p_access = NULL;
968 static char *AccessReadLine(access_t *p_access, uint8_t *psz_tmp, size_t i_len)
971 char *begin = (char *)psz_tmp;
975 int skip = strlen(begin);
976 ssize_t len = p_access->pf_read(p_access, psz_tmp + skip, i_len - skip);
977 if (len < 0) return NULL;
978 if ((len == 0) && (skip == 0))
982 char *end = p + len + skip;
993 line = calloc(1, p - begin + 1);
996 /* copy line excluding \n */
997 line = strndup(begin, p - begin);
1002 psz_tmp = memmove(begin, p, end - p);
1003 psz_tmp[end - p] = '\0';
1005 else memset(psz_tmp, 0, i_len);
1010 static int AccessDownload(stream_t *s, segment_t *segment)
1012 stream_sys_t *p_sys = (stream_sys_t *) s->p_sys;
1016 /* Download new playlist file from server */
1017 if (AccessOpen(s, &segment->url) != VLC_SUCCESS)
1018 return VLC_EGENERIC;
1020 segment->size = p_sys->p_access->info.i_size;
1021 assert(segment->size > 0);
1023 segment->data = block_Alloc(segment->size);
1024 if (segment->data == NULL)
1030 assert(segment->data->i_buffer == segment->size);
1032 ssize_t length = 0, curlen = 0;
1035 if (p_sys->p_access->info.i_size > segment->size)
1037 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1038 segment->data = block_Realloc(segment->data, 0, p_sys->p_access->info.i_size);
1040 segment->size = p_sys->p_access->info.i_size;
1041 assert(segment->data->i_buffer == segment->size);
1043 length = p_sys->p_access->pf_read(p_sys->p_access,
1044 segment->data->p_buffer + curlen, segment->size - curlen);
1045 if ((length <= 0) || ((uint64_t)length >= segment->size))
1048 } while (vlc_object_alive(s));
1050 assert(curlen == (ssize_t)segment->size);
1056 /****************************************************************************
1058 ****************************************************************************/
1059 static int Open(vlc_object_t *p_this)
1061 stream_t *s = (stream_t*)p_this;
1062 stream_sys_t *p_sys;
1064 if (!isHTTPLiveStreaming(s))
1065 return VLC_EGENERIC;
1067 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1070 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1074 p_sys->b_live = true;
1075 p_sys->b_meta = false;
1077 p_sys->hls_stream = vlc_array_new();
1078 if (p_sys->hls_stream == NULL)
1087 s->pf_control = Control;
1089 /* Select first segment to play */
1090 p_sys->last = mdate();
1091 if (parse_HTTPLiveStreaming(s) != VLC_SUCCESS)
1100 if (Prefetch(s) != VLC_SUCCESS)
1102 msg_Err(s, "fetching first segment.");
1106 p_sys->thread = vlc_object_create(s, sizeof(hls_thread_t));
1107 if( p_sys->thread == NULL )
1109 msg_Err(s, "creating HTTP Live Streaming client thread");
1113 p_sys->thread->hls_stream = p_sys->hls_stream;
1114 p_sys->thread->current = p_sys->current;
1115 p_sys->thread->s = s;
1117 if (vlc_thread_create(p_sys->thread, "HTTP Live Streaming client",
1118 hls_Thread, VLC_THREAD_PRIORITY_INPUT))
1123 vlc_object_attach(p_sys->thread, s);
1129 return VLC_EGENERIC;
1132 /****************************************************************************
1134 ****************************************************************************/
1135 static void Close(vlc_object_t *p_this)
1137 stream_t *s = (stream_t*)p_this;
1138 stream_sys_t *p_sys = s->p_sys;
1140 assert(p_sys->hls_stream);
1145 vlc_object_kill(p_sys->thread);
1146 vlc_thread_join(p_sys->thread);
1147 vlc_object_release(p_sys->thread);
1150 /* Free hls streams */
1151 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1154 hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
1155 if (hls) hls_Free(hls);
1157 vlc_array_destroy(p_sys->hls_stream);
1163 /****************************************************************************
1164 * Stream filters functions
1165 ****************************************************************************/
1166 static segment_t *NextSegment(stream_t *s)
1168 stream_sys_t *p_sys = s->p_sys;
1173 /* Is the next segment ready */
1174 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1175 if (hls == NULL) return NULL;
1177 segment = segment_GetSegment(hls, p_sys->segment);
1178 if (segment == NULL) return NULL;
1180 /* This segment is ready? */
1181 if (segment->data != NULL)
1184 /* Was the stream changed to another bitrate? */
1185 if (!p_sys->b_meta) return NULL;
1187 if (p_sys->current != p_sys->thread->current)
1190 p_sys->current = p_sys->thread->current;
1195 /* Not downloaded yet, do it here */
1196 if (Download(s, hls, segment, &p_sys->current) != VLC_SUCCESS)
1203 while(vlc_object_alive(s));
1208 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
1210 stream_sys_t *p_sys = s->p_sys;
1215 /* Determine next segment to read. If this is a meta playlist and
1216 * bandwidth conditions changed, then the stream might have switched
1217 * to another bandwidth. */
1218 segment_t *segment = NextSegment(s);
1219 if (segment == NULL)
1222 vlc_mutex_lock(&segment->lock);
1223 if (segment->data->i_buffer == 0)
1225 if (!p_sys->b_cache)
1227 block_Release(segment->data);
1228 segment->data = NULL;
1230 msg_Dbg(s, "switching to segment %d", p_sys->segment);
1232 vlc_mutex_unlock(&segment->lock);
1237 if (i_read <= segment->data->i_buffer)
1239 else if (i_read > segment->data->i_buffer)
1240 len = segment->data->i_buffer;
1244 memcpy(p_read + copied, segment->data->p_buffer, len);
1245 segment->data->i_buffer -= len;
1246 segment->data->p_buffer += len;
1250 vlc_mutex_unlock(&segment->lock);
1252 } while ((i_read > 0) && vlc_object_alive(s));
1257 static int Read(stream_t *s, void *buffer, unsigned int i_read)
1259 stream_sys_t *p_sys = s->p_sys;
1262 assert(p_sys->hls_stream);
1266 /* caller skips data, get big enough buffer */
1267 msg_Warn(s, "buffer is NULL (allocate %d)", i_read);
1268 buffer = calloc(1, i_read);
1270 return 0; /* NO MEMORY left*/
1273 length = hls_Read(s, (uint8_t*) buffer, i_read);
1277 p_sys->offset += length;
1281 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
1283 stream_sys_t *p_sys = s->p_sys;
1286 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1290 int peek_segment = p_sys->segment;
1293 segment_t *segment = segment_GetSegment(hls, peek_segment);
1294 if (segment == NULL) return 0;
1296 vlc_mutex_lock(&segment->lock);
1297 if (i_peek < segment->data->i_buffer)
1299 *pp_peek = segment->data->p_buffer;
1306 vlc_mutex_unlock(&segment->lock);
1307 } while ((curlen < i_peek) && vlc_object_alive(s));
1312 static bool hls_MaySeek(stream_t *s)
1314 stream_sys_t *p_sys = s->p_sys;
1316 if (p_sys->hls_stream == NULL)
1319 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1320 if (hls == NULL) return false;
1324 int count = vlc_array_count(hls->segments);
1325 vlc_mutex_lock(&hls->lock);
1326 bool may_seek = (hls->segment < count - 2);
1327 vlc_mutex_unlock(&hls->lock);
1333 static uint64_t GetStreamSize(stream_t *s)
1335 stream_sys_t *p_sys = s->p_sys;
1340 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1341 if (hls == NULL) return 0;
1343 /* FIXME: Stream size is not entirely exacts at this point */
1344 uint64_t length = 0UL;
1345 int count = vlc_array_count(hls->segments);
1346 for (int n = 0; n < count; n++)
1348 segment_t *segment = segment_GetSegment(hls, n);
1351 length += (segment->size > 0) ? segment->size :
1352 (segment->length * hls->bandwidth);
1358 static int segment_Seek(stream_t *s, uint64_t pos)
1360 stream_sys_t *p_sys = s->p_sys;
1362 /* Find the right offset */
1363 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
1365 return VLC_EGENERIC;
1367 uint64_t length = 0;
1368 bool b_found = false;
1370 int count = vlc_array_count(hls->segments);
1371 for (int n = 0; n < count; n++)
1373 /* FIXME: Seeking in segments not dowloaded is not supported. */
1374 if (n >= hls->segment)
1376 msg_Err(s, "seeking in segment not downloaded yet.");
1377 return VLC_EGENERIC;
1380 segment_t *segment = vlc_array_item_at_index(hls->segments, n);
1381 if (segment == NULL)
1382 return VLC_EGENERIC;
1384 vlc_mutex_lock(&segment->lock);
1385 length += segment->size;
1386 uint64_t size = segment->size -segment->data->i_buffer;
1389 segment->data->i_buffer += size;
1390 segment->data->p_buffer -= size;
1393 if (!b_found && (pos <= length))
1395 uint64_t used = length - pos;
1396 segment->data->i_buffer -= used;
1397 segment->data->p_buffer += used;
1399 count = p_sys->segment;
1403 vlc_mutex_unlock(&segment->lock);
1408 static int Control(stream_t *s, int i_query, va_list args)
1410 stream_sys_t *p_sys = s->p_sys;
1414 case STREAM_CAN_SEEK:
1415 case STREAM_CAN_FASTSEEK:
1416 *(va_arg (args, bool *)) = hls_MaySeek(s);
1418 case STREAM_GET_POSITION:
1419 *(va_arg (args, uint64_t *)) = p_sys->offset;
1421 case STREAM_SET_POSITION:
1424 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
1425 if (segment_Seek(s, pos) == VLC_SUCCESS)
1427 p_sys->offset = pos;
1431 return VLC_EGENERIC;
1432 case STREAM_GET_SIZE:
1433 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
1436 return VLC_EGENERIC;