1 /*****************************************************************************
2 * httplive.c: HTTP Live Streaming stream filter
3 *****************************************************************************
4 * Copyright (C) 2010-2011 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 *****************************************************************************/
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
40 #include <vlc_threads.h>
41 #include <vlc_arrays.h>
42 #include <vlc_stream.h>
44 #include <vlc_memory.h>
45 #include <vlc_gcrypt.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 #define AES_BLOCK_SIZE 16 /* Only support AES-128 */
65 typedef struct segment_s
67 int sequence; /* unique sequence number */
68 int duration; /* segment duration (seconds) */
69 uint64_t size; /* segment size in bytes */
70 uint64_t bandwidth; /* bandwidth usage of segments (bits per second)*/
73 char *psz_key_path; /* url key path */
74 uint8_t psz_AES_key[16]; /* AES-128 */
78 block_t *data; /* data */
81 typedef struct hls_stream_s
83 int id; /* program id */
84 int version; /* protocol version should be 1 */
85 int sequence; /* media sequence number */
86 int duration; /* maximum duration per segment (s) */
87 uint64_t bandwidth; /* bandwidth usage of segments (bits per second)*/
88 uint64_t size; /* stream length is calculated by taking the sum
89 foreach segment of (segment->duration * hls->bandwidth/8) */
91 vlc_array_t *segments; /* list of segments */
92 vlc_url_t url; /* uri to m3u8 */
94 bool b_cache; /* allow caching */
96 char *psz_current_key_path; /* URL path of the encrypted key */
97 uint8_t psz_AES_IV[AES_BLOCK_SIZE]; /* IV used when decypher the block */
103 vlc_url_t m3u8; /* M3U8 url */
104 vlc_thread_t reload; /* HLS m3u8 reload thread */
105 vlc_thread_t thread; /* HLS segment download thread */
110 vlc_array_t *hls_stream; /* bandwidth adaptation */
111 uint64_t bandwidth; /* measured bandwidth (bits per second) */
114 struct hls_download_s
116 int stream; /* current hls_stream */
117 int segment; /* current segment for downloading */
118 int seek; /* segment requested by seek (default -1) */
119 vlc_mutex_t lock_wait; /* protect segment download counter */
120 vlc_cond_t wait; /* some condition to wait on */
124 struct hls_playback_s
126 uint64_t offset; /* current offset in media */
127 int stream; /* current hls_stream */
128 int segment; /* current segment for playback */
132 struct hls_playlist_s
134 mtime_t last; /* playlist last loaded */
135 mtime_t wakeup; /* next reload time */
136 int tries; /* times it was not changed */
140 bool b_cache; /* can cache files */
141 bool b_meta; /* meta playlist */
142 bool b_live; /* live stream? or vod? */
143 bool b_error; /* parsing error */
144 bool b_aesmsg; /* only print one time that the media is encrypted */
147 /****************************************************************************
149 ****************************************************************************/
150 static int Read (stream_t *, void *p_read, unsigned int i_read);
151 static int Peek (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
152 static int Control(stream_t *, int i_query, va_list);
154 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer);
155 static ssize_t read_M3U8_from_url(stream_t *s, vlc_url_t *url, uint8_t **buffer);
156 static char *ReadLine(uint8_t *buffer, uint8_t **pos, size_t len);
158 static int hls_Download(stream_t *s, segment_t *segment);
160 static void* hls_Thread(void *);
161 static void* hls_Reload(void *);
163 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted);
164 static void segment_Free(segment_t *segment);
166 static char *ConstructUrl(vlc_url_t *url);
168 /****************************************************************************
170 ****************************************************************************/
171 static const char *const ext[] = {
172 "#EXT-X-TARGETDURATION",
173 "#EXT-X-MEDIA-SEQUENCE",
175 "#EXT-X-ALLOW-CACHE",
178 "#EXT-X-DISCONTINUITY",
182 static bool isHTTPLiveStreaming(stream_t *s)
184 const uint8_t *peek, *peek_end;
186 int64_t i_size = stream_Peek(s->p_source, &peek, 46);
190 if (strncasecmp((const char*)peek, "#EXTM3U", 7) != 0)
193 /* Parse stream and search for
194 * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
195 * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
196 peek_end = peek + i_size;
197 while(peek <= peek_end)
201 for (unsigned int i = 0; i < ARRAY_SIZE(ext); i++)
203 char *p = strstr((const char*)peek, ext[i]);
214 /* HTTP Live Streaming */
215 static hls_stream_t *hls_New(vlc_array_t *hls_stream, const int id, const uint64_t bw, const char *uri)
217 hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
218 if (hls == NULL) return NULL;
222 hls->duration = -1;/* unknown */
224 hls->sequence = 0; /* default is 0 */
225 hls->version = 1; /* default protocol version */
227 vlc_UrlParse(&hls->url, uri, 0);
228 hls->psz_current_key_path = NULL;
229 hls->segments = vlc_array_new();
230 vlc_array_append(hls_stream, hls);
231 vlc_mutex_init(&hls->lock);
235 static void hls_Free(hls_stream_t *hls)
237 vlc_mutex_destroy(&hls->lock);
241 for (int n = 0; n < vlc_array_count(hls->segments); n++)
243 segment_t *segment = (segment_t *)vlc_array_item_at_index(hls->segments, n);
244 if (segment) segment_Free(segment);
246 vlc_array_destroy(hls->segments);
248 vlc_UrlClean(&hls->url);
249 free(hls->psz_current_key_path);
254 static hls_stream_t *hls_Copy(hls_stream_t *src, const bool b_cp_segments)
257 assert(!b_cp_segments); /* FIXME: copying segments is not implemented */
259 hls_stream_t *dst = (hls_stream_t *)malloc(sizeof(hls_stream_t));
260 if (dst == NULL) return NULL;
263 dst->bandwidth = src->bandwidth;
264 dst->duration = src->duration;
265 dst->size = src->size;
266 dst->sequence = src->sequence;
267 dst->version = src->version;
268 dst->b_cache = src->b_cache;
269 char *uri = ConstructUrl(&src->url);
275 vlc_UrlParse(&dst->url, uri, 0);
277 dst->segments = vlc_array_new();
278 vlc_mutex_init(&dst->lock);
282 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, const int wanted)
284 int count = vlc_array_count(hls_stream);
287 if ((wanted < 0) || (wanted >= count))
289 return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
292 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
294 return (hls_stream_t*) hls_Get(hls_stream, 0);
297 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
299 int count = vlc_array_count(hls_stream);
303 return (hls_stream_t *) hls_Get(hls_stream, count);
306 static hls_stream_t *hls_Find(vlc_array_t *hls_stream, hls_stream_t *hls_new)
308 int count = vlc_array_count(hls_stream);
309 for (int n = 0; n < count; n++)
311 hls_stream_t *hls = vlc_array_item_at_index(hls_stream, n);
315 if ((hls->id == hls_new->id) &&
316 (hls->bandwidth == hls_new->bandwidth))
323 static uint64_t hls_GetStreamSize(hls_stream_t *hls)
325 /* NOTE: Stream size is calculated based on segment duration and
326 * HLS stream bandwidth from the .m3u8 file. If these are not correct
327 * then the deviation from exact byte size will be big and the seek/
328 * progressbar will not behave entirely as one expects. */
331 /* If there is no valid bandwidth yet, then there is no point in
332 * computing stream size. */
333 if (hls->bandwidth == 0)
336 int count = vlc_array_count(hls->segments);
337 for (int n = 0; n < count; n++)
339 segment_t *segment = segment_GetSegment(hls, n);
342 size += (segment->duration * (hls->bandwidth / 8));
349 static segment_t *segment_New(hls_stream_t* hls, const int duration, const char *uri)
351 segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
355 segment->duration = duration; /* seconds */
356 segment->size = 0; /* bytes */
357 segment->sequence = 0;
358 segment->bandwidth = 0;
359 vlc_UrlParse(&segment->url, uri, 0);
360 segment->data = NULL;
361 vlc_array_append(hls->segments, segment);
362 vlc_mutex_init(&segment->lock);
363 segment->b_key_loaded = false;
364 segment->psz_key_path = NULL;
365 if (hls->psz_current_key_path)
366 segment->psz_key_path = strdup(hls->psz_current_key_path);
370 static void segment_Free(segment_t *segment)
372 vlc_mutex_destroy(&segment->lock);
374 vlc_UrlClean(&segment->url);
375 free(segment->psz_key_path);
377 block_Release(segment->data);
382 static segment_t *segment_GetSegment(hls_stream_t *hls, const int wanted)
386 int count = vlc_array_count(hls->segments);
389 if ((wanted < 0) || (wanted >= count))
391 return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
394 static segment_t *segment_Find(hls_stream_t *hls, const int sequence)
398 int count = vlc_array_count(hls->segments);
399 if (count <= 0) return NULL;
400 for (int n = 0; n < count; n++)
402 segment_t *segment = vlc_array_item_at_index(hls->segments, n);
403 if (segment == NULL) break;
404 if (segment->sequence == sequence)
410 static int ChooseSegment(stream_t *s, const int current)
412 stream_sys_t *p_sys = (stream_sys_t *)s->p_sys;
413 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
414 if (hls == NULL) return 0;
416 /* Choose a segment to start which is no closer than
417 * 3 times the target duration from the end of the playlist.
422 int count = vlc_array_count(hls->segments);
423 int i = p_sys->b_live ? count - 1 : 0;
425 while((i >= 0) && (i < count) && vlc_object_alive(s))
427 segment_t *segment = segment_GetSegment(hls, i);
430 if (segment->duration > hls->duration)
432 msg_Err(s, "EXTINF:%d duration is larger than EXT-X-TARGETDURATION:%d",
433 segment->duration, hls->duration);
436 duration += segment->duration;
437 if (duration >= 3 * hls->duration)
439 /* Start point found */
440 wanted = p_sys->b_live ? i : 0;
441 sequence = segment->sequence;
451 msg_Info(s, "Choose segment %d/%d (sequence=%d)", wanted, count, sequence);
456 static char *parse_Attributes(const char *line, const char *attr)
459 char *begin = (char *) line;
460 char *end = begin + strlen(line);
462 /* Find start of attributes */
463 if ((p = strchr(begin, ':' )) == NULL)
469 if (strncasecmp(begin, attr, strlen(attr)) == 0)
471 /* <attr>=<value>[,]* */
472 p = strchr(begin, ',');
473 begin += strlen(attr) + 1;
476 if (p == NULL) /* last attribute */
477 return strndup(begin, end - begin);
479 return strndup(begin, p - begin);
482 } while(begin < end);
487 static int hex2int(char c)
489 if (c >= '0' && c <= '9')
491 if (c >= 'A' && c <= 'F')
493 if (c >= 'a' && c <= 'f')
498 static int string_to_IV(const char *string_hexa, uint8_t iv[AES_BLOCK_SIZE])
500 const char *p = string_hexa;
511 c = hex2int(*p++) << 4;
519 static char *relative_URI(stream_t *s, const char *uri, const vlc_url_t *url)
521 stream_sys_t *p_sys = s->p_sys;
522 char *psz_password = NULL;
523 char *psz_username = NULL;
524 char *psz_protocol = NULL;
525 char *psz_path = NULL;
526 char *psz_host = NULL;
527 char *psz_uri = NULL;
530 char *p = strchr(uri, ':');
534 /* Determine protocol to use */
535 if (url && url->psz_protocol)
537 psz_protocol = strdup(url->psz_protocol);
538 i_port = url->i_port;
540 else if (p_sys->m3u8.psz_protocol)
542 psz_protocol = strdup(p_sys->m3u8.psz_protocol);
543 i_port = p_sys->m3u8.i_port;
546 /* Determine host to use */
547 if (url && url->psz_host)
548 psz_host = strdup(url->psz_host);
549 else if (p_sys->m3u8.psz_host)
550 psz_host = strdup(p_sys->m3u8.psz_host);
552 /* Determine path to use */
553 if (url && url->psz_path != NULL)
554 psz_path = strdup(url->psz_path);
555 else if (p_sys->m3u8.psz_path != NULL)
556 psz_path = strdup(p_sys->m3u8.psz_path);
558 if ((psz_protocol == NULL) ||
559 (psz_path == NULL) ||
563 p = strrchr(psz_path, '/');
566 /* Determine credentials to use */
567 if (url && url->psz_username)
568 psz_username = strdup(url->psz_username);
569 else if (p_sys->m3u8.psz_username)
570 psz_username = strdup(p_sys->m3u8.psz_username);
572 if (url && url->psz_password)
573 psz_password = strdup(url->psz_password);
574 else if (p_sys->m3u8.psz_password)
575 psz_password = strdup(p_sys->m3u8.psz_password);
578 if (psz_password || psz_username)
580 if (asprintf(&psz_uri, "%s://%s:%s@%s:%d%s/%s",
582 psz_username ? psz_username : "",
583 psz_password ? psz_password : "",
590 if (asprintf(&psz_uri, "%s://%s:%d%s/%s",
591 psz_protocol, psz_host, i_port,
605 static char *ConstructUrl(vlc_url_t *url)
607 if ((url->psz_protocol == NULL) ||
608 (url->psz_path == NULL))
611 if (url->i_port <= 0)
613 if (strncmp(url->psz_protocol, "https", 5) == 0)
619 char *psz_url = NULL;
620 if (url->psz_password || url->psz_username)
622 if (asprintf(&psz_url, "%s://%s:%s@%s:%d%s",
624 url->psz_username, url->psz_password,
625 url->psz_host, url->i_port, url->psz_path) < 0)
630 if (asprintf(&psz_url, "%s://%s:%d%s",
632 url->psz_host, url->i_port, url->psz_path) < 0)
639 static int parse_SegmentInformation(hls_stream_t *hls, char *p_read, int *duration)
644 /* strip of #EXTINF: */
646 char *token = strtok_r(p_read, ":", &p_next);
651 token = strtok_r(NULL, ",", &p_next);
656 if (hls->version < 3)
658 value = strtol(token, NULL, 10);
668 double d = strtod(token, (char **) NULL);
674 if ((d) - ((int)d) >= 0.5)
675 value = ((int)d) + 1;
680 /* Ignore the rest of the line */
685 static int parse_AddSegment(stream_t *s, hls_stream_t *hls, const int duration, const char *uri)
690 /* Store segment information */
691 vlc_mutex_lock(&hls->lock);
693 char *psz_uri = relative_URI(s, uri, &hls->url);
695 segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
697 segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
700 vlc_mutex_unlock(&hls->lock);
702 return segment ? VLC_SUCCESS : VLC_ENOMEM;
705 static int parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
710 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
713 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
717 hls->duration = duration; /* seconds */
721 static int parse_StreamInformation(stream_t *s, vlc_array_t **hls_stream,
722 hls_stream_t **hls, char *p_read, const char *uri)
728 assert(*hls == NULL);
730 attr = parse_Attributes(p_read, "PROGRAM-ID");
733 msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
739 attr = parse_Attributes(p_read, "BANDWIDTH");
742 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
750 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
754 msg_Info(s, "bandwidth adaptation detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
756 char *psz_uri = relative_URI(s, uri, NULL);
758 *hls = hls_New(*hls_stream, id, bw, psz_uri ? psz_uri : uri);
762 return (*hls == NULL) ? VLC_ENOMEM : VLC_SUCCESS;
765 static int parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
770 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
773 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
777 if (hls->sequence > 0)
779 if (s->p_sys->b_live)
781 hls_stream_t *last = hls_GetLast(s->p_sys->hls_stream);
782 if ((last->sequence < sequence) && (sequence - last->sequence != 1))
783 msg_Err(s, "EXT-X-MEDIA-SEQUENCE gap in playlist (new=%d, old=%d)",
784 sequence, last->sequence);
787 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist (new=%d, old=%d)",
788 sequence, hls->sequence);
790 hls->sequence = sequence;
794 static int parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
798 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
799 int err = VLC_SUCCESS;
800 char *attr = parse_Attributes(p_read, "METHOD");
803 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
807 if (strncasecmp(attr, "NONE", 4) == 0)
809 char *uri = parse_Attributes(p_read, "URI");
812 msg_Err(s, "#EXT-X-KEY: URI not expected");
816 /* IV is only supported in version 2 and above */
817 if (hls->version >= 2)
819 char *iv = parse_Attributes(p_read, "IV");
822 msg_Err(s, "#EXT-X-KEY: IV not expected");
828 else if (strncasecmp(attr, "AES-128", 7) == 0)
830 char *value, *uri, *iv;
831 if (s->p_sys->b_aesmsg == false)
833 msg_Info(s, "playback of AES-128 encrypted HTTP Live media detected.");
834 s->p_sys->b_aesmsg = true;
836 value = uri = parse_Attributes(p_read, "URI");
839 msg_Err(s, "#EXT-X-KEY: URI not found for encrypted HTTP Live media in AES-128");
844 /* Url is put between quotes, remove them */
847 /* We need to strip the "" from the attribute value */
849 char* end = strchr(uri, '"');
853 hls->psz_current_key_path = strdup(uri);
856 value = iv = parse_Attributes(p_read, "IV");
860 * If the EXT-X-KEY tag does not have the IV attribute, implementations
861 * MUST use the sequence number of the media file as the IV when
862 * encrypting or decrypting that media file. The big-endian binary
863 * representation of the sequence number SHALL be placed in a 16-octet
864 * buffer and padded (on the left) with zeros.
866 hls->b_iv_loaded = false;
871 * If the EXT-X-KEY tag has the IV attribute, implementations MUST use
872 * the attribute value as the IV when encrypting or decrypting with that
873 * key. The value MUST be interpreted as a 128-bit hexadecimal number
874 * and MUST be prefixed with 0x or 0X.
877 if (string_to_IV(iv, hls->psz_AES_IV) == VLC_EGENERIC)
880 hls->b_iv_loaded = true;
886 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
893 static int parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
896 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
900 static int parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
904 char answer[4] = "\0";
905 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
908 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
912 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
916 static int parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
921 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
924 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
929 hls->version = version;
930 if (hls->version <= 0 || hls->version > 3)
932 msg_Err(s, "#EXT-X-VERSION should be version 1, 2 or 3 iso %d", version);
938 static int parse_EndList(stream_t *s, hls_stream_t *hls)
942 s->p_sys->b_live = false;
943 msg_Info(s, "video on demand (vod) mode");
947 static int parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
951 /* FIXME: Do we need to act on discontinuity ?? */
952 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
956 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
957 * document defines the following new tags: EXT-X-TARGETDURATION,
958 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
959 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
962 static int parse_M3U8(stream_t *s, vlc_array_t *streams, uint8_t *buffer, const ssize_t len)
964 stream_sys_t *p_sys = s->p_sys;
965 uint8_t *p_read, *p_begin, *p_end;
970 msg_Dbg(s, "parse_M3U8\n%s", buffer);
972 p_end = p_begin + len;
974 char *line = ReadLine(p_begin, &p_read, p_end - p_begin);
979 if (strncmp(line, "#EXTM3U", 7) != 0)
981 msg_Err(s, "missing #EXTM3U tag .. aborting");
989 /* What is the version ? */
991 uint8_t *p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-VERSION:");
995 char *psz_version = ReadLine(p, &tmp, p_end - p);
996 if (psz_version == NULL)
998 int ret = sscanf((const char*)psz_version, "#EXT-X-VERSION:%d", &version);
1001 msg_Warn(s, "#EXT-X-VERSION: no protocol version found, assuming version 1.");
1008 /* Is it a live stream ? */
1009 p_sys->b_live = (strstr((const char *)buffer, "#EXT-X-ENDLIST") == NULL) ? true : false;
1011 /* Is it a meta index file ? */
1012 bool b_meta = (strstr((const char *)buffer, "#EXT-X-STREAM-INF") == NULL) ? false : true;
1014 int err = VLC_SUCCESS;
1018 msg_Info(s, "Meta playlist");
1020 /* M3U8 Meta Index file */
1023 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1029 if (strncmp(line, "#EXT-X-STREAM-INF", 17) == 0)
1031 p_sys->b_meta = true;
1032 char *uri = ReadLine(p_begin, &p_read, p_end - p_begin);
1039 msg_Info(s, "Skipping invalid stream-inf: %s", uri);
1044 hls_stream_t *hls = NULL;
1045 err = parse_StreamInformation(s, &streams, &hls, line, uri);
1048 /* Download playlist file from server */
1049 uint8_t *buf = NULL;
1050 ssize_t len = read_M3U8_from_url(s, &hls->url, &buf);
1055 /* Parse HLS m3u8 content. */
1056 err = parse_M3U8(s, streams, buf, len);
1062 hls->version = version;
1064 hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
1074 if (p_begin >= p_end)
1077 } while ((err == VLC_SUCCESS) && vlc_object_alive(s));
1082 msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
1084 hls_stream_t *hls = NULL;
1086 hls = hls_GetLast(streams);
1089 /* No Meta playlist used */
1090 hls = hls_New(streams, 0, 0, NULL);
1093 /* Get TARGET-DURATION first */
1094 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1097 uint8_t *p_rest = NULL;
1098 char *psz_duration = ReadLine(p, &p_rest, p_end - p);
1099 if (psz_duration == NULL)
1100 return VLC_EGENERIC;
1101 err = parse_TargetDuration(s, hls, psz_duration);
1107 hls->version = version;
1109 else return VLC_ENOMEM;
1114 int segment_duration = -1;
1118 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1123 if (strncmp(line, "#EXTINF", 7) == 0)
1124 err = parse_SegmentInformation(hls, line, &segment_duration);
1125 else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1126 err = parse_TargetDuration(s, hls, line);
1127 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1128 err = parse_MediaSequence(s, hls, line);
1129 else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1130 err = parse_Key(s, hls, line);
1131 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1132 err = parse_ProgramDateTime(s, hls, line);
1133 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1134 err = parse_AllowCache(s, hls, line);
1135 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1136 err = parse_Discontinuity(s, hls, line);
1137 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1138 err = parse_Version(s, hls, line);
1139 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1140 err = parse_EndList(s, hls);
1141 else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1143 err = parse_AddSegment(s, hls, segment_duration, line);
1144 segment_duration = -1; /* reset duration */
1150 if (p_begin >= p_end)
1153 } while ((err == VLC_SUCCESS) && vlc_object_alive(s));
1162 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1164 uint8_t aeskey[32]; /* AES-512 can use up to 32 bytes */
1167 stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1170 msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1171 return VLC_EGENERIC;
1174 len = stream_Read(p_m3u8, aeskey, sizeof(aeskey));
1175 if (len != AES_BLOCK_SIZE)
1177 msg_Err(s, "The AES key loaded doesn't have the right size (%d)", len);
1178 stream_Delete(p_m3u8);
1179 return VLC_EGENERIC;
1182 memcpy(seg->psz_AES_key, aeskey, AES_BLOCK_SIZE);
1184 stream_Delete(p_m3u8);
1189 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1191 segment_t *seg = NULL;
1192 segment_t *prev_seg;
1193 int count = vlc_array_count(hls->segments);
1195 for (int i = 0; i < count; i++)
1198 seg = segment_GetSegment(hls, i);
1199 if (seg->psz_key_path == NULL)
1200 continue; /* No key to load ? continue */
1201 if (seg->b_key_loaded)
1202 continue; /* The key is already loaded */
1204 /* if the key has not changed, and already available from previous segment,
1205 * try to copy it, and don't load the key */
1206 if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1208 memcpy(seg->psz_AES_key, prev_seg->psz_AES_key, AES_BLOCK_SIZE);
1209 seg->b_key_loaded = true;
1212 if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1213 return VLC_EGENERIC;
1214 seg->b_key_loaded = true;
1219 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1221 /* Did the segment need to be decoded ? */
1222 if (segment->psz_key_path == NULL)
1225 /* Do we have loaded the key ? */
1226 if (!segment->b_key_loaded)
1228 /* No ? try to download it now */
1229 if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1230 return VLC_EGENERIC;
1233 /* For now, we only decode AES-128 data */
1234 gcry_error_t i_gcrypt_err;
1235 gcry_cipher_hd_t aes_ctx;
1237 i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1238 GCRY_CIPHER_MODE_CBC, 0);
1241 msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1242 gcry_cipher_close(aes_ctx);
1243 return VLC_EGENERIC;
1247 i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->psz_AES_key,
1248 sizeof(segment->psz_AES_key));
1251 msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1252 gcry_cipher_close(aes_ctx);
1253 return VLC_EGENERIC;
1256 if (hls->b_iv_loaded == false)
1258 memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1259 hls->psz_AES_IV[15] = segment->sequence & 0xff;
1260 hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1261 hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1262 hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1265 i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1266 sizeof(hls->psz_AES_IV));
1270 msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1271 gcry_cipher_close(aes_ctx);
1272 return VLC_EGENERIC;
1275 i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1276 segment->data->p_buffer, /* out */
1277 segment->data->i_buffer,
1282 msg_Err(s, "gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1283 gcry_cipher_close(aes_ctx);
1284 return VLC_EGENERIC;
1286 gcry_cipher_close(aes_ctx);
1287 /* remove the PKCS#7 padding from the buffer */
1288 int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1289 if (pad <= 0 || pad > AES_BLOCK_SIZE)
1291 msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1292 return VLC_EGENERIC;
1297 if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1299 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1300 return VLC_EGENERIC;
1304 /* not all the data is readable because of padding */
1305 segment->data->i_buffer -= pad;
1310 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1312 stream_sys_t *p_sys = s->p_sys;
1314 int err = VLC_EGENERIC;
1316 /* Duplicate HLS stream META information */
1317 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1319 hls_stream_t *src, *dst;
1320 src = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
1322 return VLC_EGENERIC;
1324 dst = hls_Copy(src, false);
1328 vlc_array_append(*streams, dst);
1331 /* Download new playlist file from server */
1332 for (int i = 0; i < vlc_array_count(*streams); i++)
1335 hls = (hls_stream_t *)vlc_array_item_at_index(*streams, i);
1337 return VLC_EGENERIC;
1339 /* Download playlist file from server */
1340 uint8_t *buf = NULL;
1341 ssize_t len = read_M3U8_from_url(s, &hls->url, &buf);
1346 /* Parse HLS m3u8 content. */
1347 err = parse_M3U8(s, *streams, buf, len);
1354 /* Reload playlist */
1355 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t **hls)
1357 int count = vlc_array_count(hls_new->segments);
1359 msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1360 hls_new->id, hls_new->bandwidth, count);
1362 for (int n = 0; n < count; n++)
1364 segment_t *p = segment_GetSegment(hls_new, n);
1365 if (p == NULL) return VLC_EGENERIC;
1367 vlc_mutex_lock(&(*hls)->lock);
1368 segment_t *segment = segment_Find(*hls, p->sequence);
1371 vlc_mutex_lock(&segment->lock);
1373 assert(p->url.psz_path);
1374 assert(segment->url.psz_path);
1376 /* they should be the same */
1377 if ((p->sequence != segment->sequence) ||
1378 (p->duration != segment->duration) ||
1379 (strcmp(p->url.psz_path, segment->url.psz_path) != 0))
1381 msg_Warn(s, "existing segment found with different content - resetting");
1382 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1383 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1384 msg_Warn(s, "- file: new=%s", p->url.psz_path);
1385 msg_Warn(s, " old=%s", segment->url.psz_path);
1387 /* Resetting content */
1388 char *psz_url = ConstructUrl(&p->url);
1389 if (psz_url == NULL)
1391 msg_Err(s, "Failed updating segment %d - skipping it", p->sequence);
1393 vlc_mutex_unlock(&segment->lock);
1396 segment->sequence = p->sequence;
1397 segment->duration = p->duration;
1398 vlc_UrlClean(&segment->url);
1399 vlc_UrlParse(&segment->url, psz_url, 0);
1400 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1403 block_Release(segment->data);
1404 segment->data = NULL;
1406 free(segment->psz_key_path);
1407 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1408 vlc_mutex_unlock(&segment->lock);
1415 int last = vlc_array_count((*hls)->segments) - 1;
1416 segment_t *l = segment_GetSegment(*hls, last);
1417 if (l == NULL) goto fail_and_unlock;
1419 if ((l->sequence + 1) != p->sequence)
1421 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1422 p->sequence, l->sequence+1);
1424 vlc_array_append((*hls)->segments, p);
1425 msg_Info(s, "- segment %d appended", p->sequence);
1427 vlc_mutex_unlock(&(*hls)->lock);
1430 /* update meta information */
1431 vlc_mutex_lock(&(*hls)->lock);
1432 (*hls)->sequence = hls_new->sequence;
1433 (*hls)->duration = (hls_new->duration == -1) ? (*hls)->duration : hls_new->duration;
1434 (*hls)->b_cache = hls_new->b_cache;
1435 vlc_mutex_unlock(&(*hls)->lock);
1440 vlc_mutex_unlock(&(*hls)->lock);
1441 return VLC_EGENERIC;
1444 static int hls_ReloadPlaylist(stream_t *s)
1446 stream_sys_t *p_sys = s->p_sys;
1448 vlc_array_t *hls_streams = vlc_array_new();
1449 if (hls_streams == NULL)
1452 msg_Info(s, "Reloading HLS live meta playlist");
1454 if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1456 /* Free hls streams */
1457 for (int i = 0; i < vlc_array_count(hls_streams); i++)
1460 hls = (hls_stream_t *)vlc_array_item_at_index(hls_streams, i);
1461 if (hls) hls_Free(hls);
1463 vlc_array_destroy(hls_streams);
1465 msg_Err(s, "reloading playlist failed");
1466 return VLC_EGENERIC;
1469 /* merge playlists */
1470 int count = vlc_array_count(hls_streams);
1471 for (int n = 0; n < count; n++)
1473 hls_stream_t *hls_new = hls_Get(hls_streams, n);
1474 if (hls_new == NULL)
1477 hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1478 if (hls_old == NULL)
1479 { /* new hls stream - append */
1480 vlc_array_append(p_sys->hls_stream, hls_new);
1481 msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1482 hls_new->id, hls_new->bandwidth);
1484 else if (hls_UpdatePlaylist(s, hls_new, &hls_old) != VLC_SUCCESS)
1485 msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1486 hls_new->id, hls_new->bandwidth);
1488 vlc_array_destroy(hls_streams);
1492 /****************************************************************************
1494 ****************************************************************************/
1495 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1497 stream_sys_t *p_sys = s->p_sys;
1499 uint64_t bw = *bandwidth;
1500 uint64_t bw_candidate = 0;
1502 int count = vlc_array_count(p_sys->hls_stream);
1503 for (int n = 0; n < count; n++)
1505 /* Select best bandwidth match */
1506 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1507 if (hls == NULL) break;
1509 /* only consider streams with the same PROGRAM-ID */
1510 if (hls->id == progid)
1512 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1514 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1515 n, bw, hls->bandwidth); /* bits / s */
1516 bw_candidate = hls->bandwidth;
1517 candidate = n; /* possible candidate */
1521 *bandwidth = bw_candidate;
1525 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1527 stream_sys_t *p_sys = s->p_sys;
1532 vlc_mutex_lock(&segment->lock);
1533 if (segment->data != NULL)
1535 /* Segment already downloaded */
1536 vlc_mutex_unlock(&segment->lock);
1540 /* sanity check - can we download this segment on time? */
1541 if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1543 uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1544 int estimated = (int)(size / p_sys->bandwidth);
1545 if (estimated > segment->duration)
1547 msg_Warn(s,"downloading of segment %d takes %ds, which is longer than its playback (%ds)",
1548 segment->sequence, estimated, segment->duration);
1552 mtime_t start = mdate();
1553 if (hls_Download(s, segment) != VLC_SUCCESS)
1555 msg_Err(s, "downloaded segment %d from stream %d failed",
1556 segment->sequence, *cur_stream);
1557 vlc_mutex_unlock(&segment->lock);
1558 return VLC_EGENERIC;
1560 mtime_t duration = mdate() - start;
1561 if (hls->bandwidth == 0)
1563 /* Try to estimate the bandwidth for this stream */
1564 hls->bandwidth = (uint64_t)((double)segment->size / ((double)duration / 1000000.0));
1567 /* If the segment is encrypted, decode it */
1568 if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1570 vlc_mutex_unlock(&segment->lock);
1571 return VLC_EGENERIC;
1574 vlc_mutex_unlock(&segment->lock);
1576 msg_Info(s, "downloaded segment %d from stream %d",
1577 segment->sequence, *cur_stream);
1579 /* check for division by zero */
1580 double ms = (double)duration / 1000.0; /* ms */
1584 uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
1585 p_sys->bandwidth = bw;
1586 if (p_sys->b_meta && (hls->bandwidth != bw))
1588 int newstream = BandwidthAdaptation(s, hls->id, &bw);
1590 /* FIXME: we need an average here */
1591 if ((newstream >= 0) && (newstream != *cur_stream))
1593 msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1594 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1595 *cur_stream = newstream;
1601 static void* hls_Thread(void *p_this)
1603 stream_t *s = (stream_t *)p_this;
1604 stream_sys_t *p_sys = s->p_sys;
1606 int canc = vlc_savecancel();
1608 while (vlc_object_alive(s))
1610 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1613 /* Sliding window (~60 seconds worth of movie) */
1614 vlc_mutex_lock(&hls->lock);
1615 int count = vlc_array_count(hls->segments);
1616 vlc_mutex_unlock(&hls->lock);
1618 /* Is there a new segment to process? */
1619 if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1620 (p_sys->download.segment >= count))
1623 vlc_mutex_lock(&p_sys->download.lock_wait);
1624 while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1625 (p_sys->download.segment >= count)) &&
1626 (p_sys->download.seek == -1))
1628 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1629 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1631 if (!vlc_object_alive(s))
1635 if (p_sys->download.seek >= 0)
1637 p_sys->download.segment = p_sys->download.seek;
1638 p_sys->download.seek = -1;
1640 vlc_mutex_unlock(&p_sys->download.lock_wait);
1643 if (!vlc_object_alive(s)) break;
1645 vlc_mutex_lock(&hls->lock);
1646 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1647 vlc_mutex_unlock(&hls->lock);
1649 if ((segment != NULL) &&
1650 (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1652 if (!vlc_object_alive(s)) break;
1656 p_sys->b_error = true;
1661 /* download succeeded */
1662 /* determine next segment to download */
1663 vlc_mutex_lock(&p_sys->download.lock_wait);
1664 if (p_sys->download.seek >= 0)
1666 p_sys->download.segment = p_sys->download.seek;
1667 p_sys->download.seek = -1;
1669 else if (p_sys->download.segment < count)
1670 p_sys->download.segment++;
1671 vlc_cond_signal(&p_sys->download.wait);
1672 vlc_mutex_unlock(&p_sys->download.lock_wait);
1675 vlc_restorecancel(canc);
1679 static void* hls_Reload(void *p_this)
1681 stream_t *s = (stream_t *)p_this;
1682 stream_sys_t *p_sys = s->p_sys;
1684 assert(p_sys->b_live);
1686 int canc = vlc_savecancel();
1689 while (vlc_object_alive(s))
1691 mtime_t now = mdate();
1692 if (now >= p_sys->playlist.wakeup)
1694 /* reload the m3u8 */
1695 if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1697 /* No change in playlist, then backoff */
1698 p_sys->playlist.tries++;
1699 if (p_sys->playlist.tries == 1) wait = 0.5;
1700 else if (p_sys->playlist.tries == 2) wait = 1;
1701 else if (p_sys->playlist.tries >= 3) wait = 2;
1703 /* Can we afford to backoff? */
1704 if (p_sys->download.segment - p_sys->playback.segment < 3)
1706 p_sys->playlist.tries = 0;
1712 p_sys->playlist.tries = 0;
1716 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1719 /* determine next time to update playlist */
1720 p_sys->playlist.last = now;
1721 p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1722 * (mtime_t)1000000);
1725 mwait(p_sys->playlist.wakeup);
1728 vlc_restorecancel(canc);
1732 static int Prefetch(stream_t *s, int *current)
1734 stream_sys_t *p_sys = s->p_sys;
1737 /* Try to pick best matching stream */;
1741 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1743 return VLC_EGENERIC;
1745 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1746 if (segment == NULL )
1747 return VLC_EGENERIC;
1749 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1750 return VLC_EGENERIC;
1752 /* Found better bandwidth match, try again */
1753 if (*current != stream)
1756 /* Download first 2 segments of this HLS stream */
1758 for (int i = 0; i < 2; i++)
1760 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1761 if (segment == NULL )
1762 return VLC_EGENERIC;
1766 p_sys->download.segment++;
1770 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1771 return VLC_EGENERIC;
1773 p_sys->download.segment++;
1775 /* adapt bandwidth? */
1776 if (*current != stream)
1778 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1780 return VLC_EGENERIC;
1789 /****************************************************************************
1791 ****************************************************************************/
1792 static int hls_Download(stream_t *s, segment_t *segment)
1797 char *psz_url = ConstructUrl(&segment->url);
1798 if (psz_url == NULL)
1801 stream_t *p_ts = stream_UrlNew(s, psz_url);
1804 return VLC_EGENERIC;
1806 segment->size = stream_Size(p_ts);
1807 assert(segment->size > 0);
1809 segment->data = block_Alloc(segment->size);
1810 if (segment->data == NULL)
1812 stream_Delete(p_ts);
1816 assert(segment->data->i_buffer == segment->size);
1818 ssize_t length = 0, curlen = 0;
1822 size = stream_Size(p_ts);
1823 if (size > segment->size)
1825 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1826 block_t *p_block = block_Realloc(segment->data, 0, size);
1827 if (p_block == NULL)
1829 stream_Delete(p_ts);
1830 block_Release(segment->data);
1831 segment->data = NULL;
1834 segment->data = p_block;
1835 segment->size = size;
1836 assert(segment->data->i_buffer == segment->size);
1839 length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1843 } while (vlc_object_alive(s));
1845 stream_Delete(p_ts);
1849 /* Read M3U8 file */
1850 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1852 int64_t total_bytes = 0;
1853 int64_t total_allocated = 0;
1861 bytes = stream_Read(s, buf, sizeof(buf));
1867 if ( (total_bytes + bytes + 1) > total_allocated )
1869 if (total_allocated)
1870 total_allocated *= 2;
1872 total_allocated = __MIN(bytes+1, sizeof(buf));
1874 p = realloc_or_free(p, total_allocated);
1879 memcpy(p+total_bytes, buf, bytes);
1880 total_bytes += bytes;
1883 if (total_allocated == 0)
1884 return VLC_EGENERIC;
1886 p[total_bytes] = '\0';
1892 static ssize_t read_M3U8_from_url(stream_t *s, vlc_url_t *url, uint8_t **buffer)
1894 assert(*buffer == NULL);
1897 char *psz_url = ConstructUrl(url);
1898 if (psz_url == NULL)
1901 stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1904 return VLC_EGENERIC;
1906 ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1907 stream_Delete(p_m3u8);
1912 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1917 uint8_t *begin = buffer;
1919 uint8_t *end = p + len;
1923 if ((*p == '\n') || (*p == '\0'))
1928 /* copy line excluding \n or \0 */
1929 line = strndup((char *)begin, p - begin);
1935 /* next pass start after \n */
1943 /****************************************************************************
1945 ****************************************************************************/
1946 static int Open(vlc_object_t *p_this)
1948 stream_t *s = (stream_t*)p_this;
1949 stream_sys_t *p_sys;
1951 if (!isHTTPLiveStreaming(s))
1952 return VLC_EGENERIC;
1954 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1956 /* Initialize crypto bit */
1960 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1964 char *psz_uri = NULL;
1965 if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1970 vlc_UrlParse(&p_sys->m3u8, psz_uri, 0);
1973 p_sys->bandwidth = 0;
1974 p_sys->b_live = true;
1975 p_sys->b_meta = false;
1976 p_sys->b_error = false;
1978 p_sys->hls_stream = vlc_array_new();
1979 if (p_sys->hls_stream == NULL)
1981 vlc_UrlClean(&p_sys->m3u8);
1989 s->pf_control = Control;
1991 /* Parse HLS m3u8 content. */
1992 uint8_t *buffer = NULL;
1993 ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1996 if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
2003 /* Choose first HLS stream to start with */
2004 int current = p_sys->playback.stream = 0;
2005 p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
2007 /* manage encryption key if needed */
2008 hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
2010 if (p_sys->b_live && (p_sys->playback.segment < 0))
2012 msg_Warn(s, "less data than 3 times 'target duration' available for live playback, playback may stall");
2015 if (Prefetch(s, ¤t) != VLC_SUCCESS)
2017 msg_Err(s, "fetching first segment failed.");
2022 p_sys->download.stream = current;
2023 p_sys->playback.stream = current;
2024 p_sys->download.seek = -1;
2026 vlc_mutex_init(&p_sys->download.lock_wait);
2027 vlc_cond_init(&p_sys->download.wait);
2029 /* Initialize HLS live stream */
2032 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
2033 p_sys->playlist.last = mdate();
2034 p_sys->playlist.wakeup = p_sys->playlist.last +
2035 ((mtime_t)hls->duration * UINT64_C(1000000));
2037 if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
2043 if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
2046 vlc_join(p_sys->reload, NULL);
2053 vlc_mutex_destroy(&p_sys->download.lock_wait);
2054 vlc_cond_destroy(&p_sys->download.wait);
2057 /* Free hls streams */
2058 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2061 hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
2062 if (hls) hls_Free(hls);
2064 vlc_array_destroy(p_sys->hls_stream);
2067 vlc_UrlClean(&p_sys->m3u8);
2069 return VLC_EGENERIC;
2072 /****************************************************************************
2074 ****************************************************************************/
2075 static void Close(vlc_object_t *p_this)
2077 stream_t *s = (stream_t*)p_this;
2078 stream_sys_t *p_sys = s->p_sys;
2080 assert(p_sys->hls_stream);
2083 vlc_mutex_lock(&p_sys->download.lock_wait);
2084 vlc_cond_signal(&p_sys->download.wait);
2085 vlc_mutex_unlock(&p_sys->download.lock_wait);
2089 vlc_join(p_sys->reload, NULL);
2090 vlc_join(p_sys->thread, NULL);
2091 vlc_mutex_destroy(&p_sys->download.lock_wait);
2092 vlc_cond_destroy(&p_sys->download.wait);
2094 /* Free hls streams */
2095 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2098 hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
2099 if (hls) hls_Free(hls);
2101 vlc_array_destroy(p_sys->hls_stream);
2104 vlc_UrlClean(&p_sys->m3u8);
2106 block_Release (p_sys->peeked);
2110 /****************************************************************************
2111 * Stream filters functions
2112 ****************************************************************************/
2113 static segment_t *GetSegment(stream_t *s)
2115 stream_sys_t *p_sys = s->p_sys;
2116 segment_t *segment = NULL;
2118 /* Is this segment of the current HLS stream ready? */
2119 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2122 vlc_mutex_lock(&hls->lock);
2123 segment = segment_GetSegment(hls, p_sys->playback.segment);
2124 if (segment != NULL)
2126 /* This segment is ready? */
2127 if (segment->data != NULL)
2129 p_sys->b_cache = hls->b_cache;
2130 vlc_mutex_unlock(&hls->lock);
2134 vlc_mutex_unlock(&hls->lock);
2137 /* Was the HLS stream changed to another bitrate? */
2140 while(vlc_object_alive(s))
2142 /* Is the next segment ready */
2143 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2147 vlc_mutex_lock(&hls->lock);
2148 segment = segment_GetSegment(hls, p_sys->playback.segment);
2149 if (segment == NULL)
2151 vlc_mutex_unlock(&hls->lock);
2155 vlc_mutex_lock(&p_sys->download.lock_wait);
2156 int i_segment = p_sys->download.segment;
2157 vlc_mutex_unlock(&p_sys->download.lock_wait);
2159 /* This segment is ready? */
2160 if ((segment->data != NULL) &&
2161 (p_sys->playback.segment < i_segment))
2163 p_sys->playback.stream = i_stream;
2164 p_sys->b_cache = hls->b_cache;
2165 vlc_mutex_unlock(&hls->lock);
2168 vlc_mutex_unlock(&hls->lock);
2173 /* Was the stream changed to another bitrate? */
2175 if (i_stream >= vlc_array_count(p_sys->hls_stream))
2183 if (segment->data->i_buffer == 0)
2185 vlc_mutex_lock(&hls->lock);
2186 int count = vlc_array_count(hls->segments);
2187 vlc_mutex_unlock(&hls->lock);
2189 if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2190 ((count != p_sys->download.segment) || p_sys->b_live))
2191 msg_Err(s, "playback will stall");
2192 else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2193 ((count != p_sys->download.segment) || p_sys->b_live))
2194 msg_Warn(s, "playback in danger of stalling");
2199 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2201 stream_sys_t *p_sys = s->p_sys;
2206 /* Determine next segment to read. If this is a meta playlist and
2207 * bandwidth conditions changed, then the stream might have switched
2208 * to another bandwidth. */
2209 segment_t *segment = GetSegment(s);
2210 if (segment == NULL)
2213 vlc_mutex_lock(&segment->lock);
2214 if (segment->data->i_buffer == 0)
2216 if (!p_sys->b_cache || p_sys->b_live)
2218 block_Release(segment->data);
2219 segment->data = NULL;
2222 { /* reset playback pointer to start of buffer */
2223 uint64_t size = segment->size - segment->data->i_buffer;
2226 segment->data->i_buffer += size;
2227 segment->data->p_buffer -= size;
2230 p_sys->playback.segment++;
2231 vlc_mutex_unlock(&segment->lock);
2233 /* signal download thread */
2234 vlc_mutex_lock(&p_sys->download.lock_wait);
2235 vlc_cond_signal(&p_sys->download.wait);
2236 vlc_mutex_unlock(&p_sys->download.lock_wait);
2240 if (segment->size == segment->data->i_buffer)
2241 msg_Info(s, "playing segment %d from stream %d",
2242 segment->sequence, p_sys->playback.stream);
2245 if (i_read <= segment->data->i_buffer)
2247 else if (i_read > segment->data->i_buffer)
2248 len = segment->data->i_buffer;
2252 memcpy(p_read + copied, segment->data->p_buffer, len);
2253 segment->data->i_buffer -= len;
2254 segment->data->p_buffer += len;
2258 vlc_mutex_unlock(&segment->lock);
2260 } while ((i_read > 0) && vlc_object_alive(s));
2265 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2267 stream_sys_t *p_sys = s->p_sys;
2270 assert(p_sys->hls_stream);
2277 /* caller skips data, get big enough buffer */
2278 msg_Warn(s, "buffer is NULL (allocate %d)", i_read);
2279 buffer = calloc(1, i_read);
2281 return 0; /* NO MEMORY left*/
2284 length = hls_Read(s, (uint8_t*) buffer, i_read);
2288 p_sys->playback.offset += length;
2292 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2294 stream_sys_t *p_sys = s->p_sys;
2296 unsigned int len = i_peek;
2298 segment = GetSegment(s);
2299 if (segment == NULL)
2301 msg_Err(s, "segment %d should have been available (stream %d)",
2302 p_sys->playback.segment, p_sys->playback.stream);
2303 return 0; /* eof? */
2306 vlc_mutex_lock(&segment->lock);
2308 size_t i_buff = segment->data->i_buffer;
2309 uint8_t *p_buff = segment->data->p_buffer;
2311 if (i_peek < i_buff)
2314 vlc_mutex_unlock(&segment->lock);
2318 else /* This will seldom be run */
2320 /* remember segment to read */
2321 int peek_segment = p_sys->playback.segment;
2323 segment_t *nsegment;
2324 p_sys->playback.segment++;
2325 block_t *peeked = p_sys->peeked;
2328 peeked = block_Alloc (i_peek);
2329 else if (peeked->i_buffer < i_peek)
2330 peeked = block_Realloc (peeked, 0, i_peek);
2334 memcpy(peeked->p_buffer, p_buff, i_buff);
2337 vlc_mutex_unlock(&segment->lock);
2339 i_buff = peeked->i_buffer;
2340 p_buff = peeked->p_buffer;
2343 while ((curlen < i_peek) && vlc_object_alive(s))
2345 nsegment = GetSegment(s);
2346 if (nsegment == NULL)
2348 msg_Err(s, "segment %d should have been available (stream %d)",
2349 p_sys->playback.segment, p_sys->playback.stream);
2350 /* restore segment to read */
2351 p_sys->playback.segment = peek_segment;
2352 return curlen; /* eof? */
2355 vlc_mutex_lock(&nsegment->lock);
2357 if (len < nsegment->data->i_buffer)
2359 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2364 size_t i_nbuff = nsegment->data->i_buffer;
2365 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2369 p_sys->playback.segment++;
2372 vlc_mutex_unlock(&nsegment->lock);
2375 /* restore segment to read */
2376 p_sys->playback.segment = peek_segment;
2381 static bool hls_MaySeek(stream_t *s)
2383 stream_sys_t *p_sys = s->p_sys;
2385 if (p_sys->hls_stream == NULL)
2388 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2389 if (hls == NULL) return false;
2393 vlc_mutex_lock(&hls->lock);
2394 int count = vlc_array_count(hls->segments);
2395 vlc_mutex_unlock(&hls->lock);
2397 vlc_mutex_lock(&p_sys->download.lock_wait);
2398 bool may_seek = (p_sys->download.segment < (count - 2));
2399 vlc_mutex_unlock(&p_sys->download.lock_wait);
2405 static uint64_t GetStreamSize(stream_t *s)
2407 stream_sys_t *p_sys = s->p_sys;
2412 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2413 if (hls == NULL) return 0;
2415 vlc_mutex_lock(&hls->lock);
2417 hls->size = hls_GetStreamSize(hls);
2418 uint64_t size = hls->size;
2419 vlc_mutex_unlock(&hls->lock);
2424 static int segment_Seek(stream_t *s, const uint64_t pos)
2426 stream_sys_t *p_sys = s->p_sys;
2428 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2430 return VLC_EGENERIC;
2432 vlc_mutex_lock(&hls->lock);
2434 bool b_found = false;
2435 uint64_t length = 0;
2436 uint64_t size = hls->size;
2437 int count = vlc_array_count(hls->segments);
2439 for (int n = 0; n < count; n++)
2441 segment_t *segment = vlc_array_item_at_index(hls->segments, n);
2442 if (segment == NULL)
2444 vlc_mutex_unlock(&hls->lock);
2445 return VLC_EGENERIC;
2448 vlc_mutex_lock(&segment->lock);
2449 length += segment->duration * (hls->bandwidth/8);
2450 vlc_mutex_unlock(&segment->lock);
2452 if (!b_found && (pos <= length))
2456 p_sys->playback.segment = n;
2460 /* Do not search in last 3 segments */
2461 vlc_mutex_unlock(&hls->lock);
2462 return VLC_EGENERIC;
2467 if (!b_found && (pos >= size))
2469 p_sys->playback.segment = count - 1;
2476 /* restore segment to start position */
2477 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2478 if (segment == NULL)
2480 vlc_mutex_unlock(&hls->lock);
2481 return VLC_EGENERIC;
2484 vlc_mutex_lock(&segment->lock);
2487 uint64_t size = segment->size -segment->data->i_buffer;
2490 segment->data->i_buffer += size;
2491 segment->data->p_buffer -= size;
2494 vlc_mutex_unlock(&segment->lock);
2496 /* start download at current playback segment */
2497 vlc_mutex_unlock(&hls->lock);
2499 /* Wake up download thread */
2500 vlc_mutex_lock(&p_sys->download.lock_wait);
2501 p_sys->download.seek = p_sys->playback.segment;
2502 vlc_cond_signal(&p_sys->download.wait);
2503 vlc_mutex_unlock(&p_sys->download.lock_wait);
2505 /* Wait for download to be finished */
2506 vlc_mutex_lock(&p_sys->download.lock_wait);
2507 msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2508 while (((p_sys->download.seek != -1) ||
2509 (p_sys->download.segment - p_sys->playback.segment < 3)) &&
2510 (p_sys->download.segment < (count - 6)))
2512 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2513 if (!vlc_object_alive(s) || s->b_error) break;
2515 vlc_mutex_unlock(&p_sys->download.lock_wait);
2519 vlc_mutex_unlock(&hls->lock);
2521 return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2524 static int Control(stream_t *s, int i_query, va_list args)
2526 stream_sys_t *p_sys = s->p_sys;
2530 case STREAM_CAN_SEEK:
2531 *(va_arg (args, bool *)) = hls_MaySeek(s);
2533 case STREAM_GET_POSITION:
2534 *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2536 case STREAM_SET_POSITION:
2539 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2540 if (segment_Seek(s, pos) == VLC_SUCCESS)
2542 p_sys->playback.offset = pos;
2546 return VLC_EGENERIC;
2547 case STREAM_GET_SIZE:
2548 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2551 return VLC_EGENERIC;