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);
1037 hls_stream_t *hls = NULL;
1038 err = parse_StreamInformation(s, &streams, &hls, line, uri);
1041 /* Download playlist file from server */
1042 uint8_t *buf = NULL;
1043 ssize_t len = read_M3U8_from_url(s, &hls->url, &buf);
1048 /* Parse HLS m3u8 content. */
1049 err = parse_M3U8(s, streams, buf, len);
1055 hls->version = version;
1057 hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
1066 if (p_begin >= p_end)
1069 } while ((err == VLC_SUCCESS) && vlc_object_alive(s));
1074 msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
1076 hls_stream_t *hls = NULL;
1078 hls = hls_GetLast(streams);
1081 /* No Meta playlist used */
1082 hls = hls_New(streams, 0, 0, NULL);
1085 /* Get TARGET-DURATION first */
1086 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1089 uint8_t *p_rest = NULL;
1090 char *psz_duration = ReadLine(p, &p_rest, p_end - p);
1091 if (psz_duration == NULL)
1092 return VLC_EGENERIC;
1093 err = parse_TargetDuration(s, hls, psz_duration);
1099 hls->version = version;
1101 else return VLC_ENOMEM;
1106 int segment_duration = -1;
1110 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1115 if (strncmp(line, "#EXTINF", 7) == 0)
1116 err = parse_SegmentInformation(hls, line, &segment_duration);
1117 else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1118 err = parse_TargetDuration(s, hls, line);
1119 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1120 err = parse_MediaSequence(s, hls, line);
1121 else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1122 err = parse_Key(s, hls, line);
1123 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1124 err = parse_ProgramDateTime(s, hls, line);
1125 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1126 err = parse_AllowCache(s, hls, line);
1127 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1128 err = parse_Discontinuity(s, hls, line);
1129 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1130 err = parse_Version(s, hls, line);
1131 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1132 err = parse_EndList(s, hls);
1133 else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1135 err = parse_AddSegment(s, hls, segment_duration, line);
1136 segment_duration = -1; /* reset duration */
1142 if (p_begin >= p_end)
1145 } while ((err == VLC_SUCCESS) && vlc_object_alive(s));
1154 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1156 uint8_t aeskey[32]; /* AES-512 can use up to 32 bytes */
1159 stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1162 msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1163 return VLC_EGENERIC;
1166 len = stream_Read(p_m3u8, aeskey, sizeof(aeskey));
1167 if (len != AES_BLOCK_SIZE)
1169 msg_Err(s, "The AES key loaded doesn't have the right size (%d)", len);
1170 stream_Delete(p_m3u8);
1171 return VLC_EGENERIC;
1174 memcpy(seg->psz_AES_key, aeskey, AES_BLOCK_SIZE);
1176 stream_Delete(p_m3u8);
1181 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1183 segment_t *seg = NULL;
1184 segment_t *prev_seg;
1185 int count = vlc_array_count(hls->segments);
1187 for (int i = 0; i < count; i++)
1190 seg = segment_GetSegment(hls, i);
1191 if (seg->psz_key_path == NULL)
1192 continue; /* No key to load ? continue */
1193 if (seg->b_key_loaded)
1194 continue; /* The key is already loaded */
1196 /* if the key has not changed, and already available from previous segment,
1197 * try to copy it, and don't load the key */
1198 if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1200 memcpy(seg->psz_AES_key, prev_seg->psz_AES_key, AES_BLOCK_SIZE);
1201 seg->b_key_loaded = true;
1204 if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1205 return VLC_EGENERIC;
1206 seg->b_key_loaded = true;
1211 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1213 /* Did the segment need to be decoded ? */
1214 if (segment->psz_key_path == NULL)
1217 /* Do we have loaded the key ? */
1218 if (!segment->b_key_loaded)
1220 /* No ? try to download it now */
1221 if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1222 return VLC_EGENERIC;
1225 /* For now, we only decode AES-128 data */
1226 gcry_error_t i_gcrypt_err;
1227 gcry_cipher_hd_t aes_ctx;
1229 i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1230 GCRY_CIPHER_MODE_CBC, 0);
1233 msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1234 gcry_cipher_close(aes_ctx);
1235 return VLC_EGENERIC;
1239 i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->psz_AES_key,
1240 sizeof(segment->psz_AES_key));
1243 msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1244 gcry_cipher_close(aes_ctx);
1245 return VLC_EGENERIC;
1248 if (hls->b_iv_loaded == false)
1250 memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1251 hls->psz_AES_IV[15] = segment->sequence & 0xff;
1252 hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1253 hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1254 hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1257 i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1258 sizeof(hls->psz_AES_IV));
1262 msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1263 gcry_cipher_close(aes_ctx);
1264 return VLC_EGENERIC;
1267 i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1268 segment->data->p_buffer, /* out */
1269 segment->data->i_buffer,
1274 msg_Err(s, "gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1275 gcry_cipher_close(aes_ctx);
1276 return VLC_EGENERIC;
1278 gcry_cipher_close(aes_ctx);
1279 /* remove the PKCS#7 padding from the buffer */
1280 int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1281 if (pad <= 0 || pad > AES_BLOCK_SIZE)
1283 msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1284 return VLC_EGENERIC;
1289 if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1291 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1292 return VLC_EGENERIC;
1296 /* not all the data is readable because of padding */
1297 segment->data->i_buffer -= pad;
1302 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1304 stream_sys_t *p_sys = s->p_sys;
1306 int err = VLC_EGENERIC;
1308 /* Duplicate HLS stream META information */
1309 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1311 hls_stream_t *src, *dst;
1312 src = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
1314 return VLC_EGENERIC;
1316 dst = hls_Copy(src, false);
1320 vlc_array_append(*streams, dst);
1323 /* Download new playlist file from server */
1324 for (int i = 0; i < vlc_array_count(*streams); i++)
1327 hls = (hls_stream_t *)vlc_array_item_at_index(*streams, i);
1329 return VLC_EGENERIC;
1331 /* Download playlist file from server */
1332 uint8_t *buf = NULL;
1333 ssize_t len = read_M3U8_from_url(s, &hls->url, &buf);
1338 /* Parse HLS m3u8 content. */
1339 err = parse_M3U8(s, *streams, buf, len);
1346 /* Reload playlist */
1347 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t **hls)
1349 int count = vlc_array_count(hls_new->segments);
1351 msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1352 hls_new->id, hls_new->bandwidth, count);
1354 for (int n = 0; n < count; n++)
1356 segment_t *p = segment_GetSegment(hls_new, n);
1357 if (p == NULL) return VLC_EGENERIC;
1359 vlc_mutex_lock(&(*hls)->lock);
1360 segment_t *segment = segment_Find(*hls, p->sequence);
1363 vlc_mutex_lock(&segment->lock);
1365 assert(p->url.psz_path);
1366 assert(segment->url.psz_path);
1368 /* they should be the same */
1369 if ((p->sequence != segment->sequence) ||
1370 (p->duration != segment->duration) ||
1371 (strcmp(p->url.psz_path, segment->url.psz_path) != 0))
1373 msg_Warn(s, "existing segment found with different content - resetting");
1374 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1375 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1376 msg_Warn(s, "- file: new=%s", p->url.psz_path);
1377 msg_Warn(s, " old=%s", segment->url.psz_path);
1379 /* Resetting content */
1380 char *psz_url = ConstructUrl(&p->url);
1381 if (psz_url == NULL)
1383 msg_Err(s, "Failed updating segment %d - skipping it", p->sequence);
1385 vlc_mutex_unlock(&segment->lock);
1388 segment->sequence = p->sequence;
1389 segment->duration = p->duration;
1390 vlc_UrlClean(&segment->url);
1391 vlc_UrlParse(&segment->url, psz_url, 0);
1392 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1395 block_Release(segment->data);
1396 segment->data = NULL;
1398 free(segment->psz_key_path);
1399 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1400 vlc_mutex_unlock(&segment->lock);
1407 int last = vlc_array_count((*hls)->segments) - 1;
1408 segment_t *l = segment_GetSegment(*hls, last);
1409 if (l == NULL) goto fail_and_unlock;
1411 if ((l->sequence + 1) != p->sequence)
1413 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1414 p->sequence, l->sequence+1);
1416 vlc_array_append((*hls)->segments, p);
1417 msg_Info(s, "- segment %d appended", p->sequence);
1419 vlc_mutex_unlock(&(*hls)->lock);
1422 /* update meta information */
1423 vlc_mutex_lock(&(*hls)->lock);
1424 (*hls)->sequence = hls_new->sequence;
1425 (*hls)->duration = (hls_new->duration == -1) ? (*hls)->duration : hls_new->duration;
1426 (*hls)->b_cache = hls_new->b_cache;
1427 vlc_mutex_unlock(&(*hls)->lock);
1432 vlc_mutex_unlock(&(*hls)->lock);
1433 return VLC_EGENERIC;
1436 static int hls_ReloadPlaylist(stream_t *s)
1438 stream_sys_t *p_sys = s->p_sys;
1440 vlc_array_t *hls_streams = vlc_array_new();
1441 if (hls_streams == NULL)
1444 msg_Info(s, "Reloading HLS live meta playlist");
1446 if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1448 /* Free hls streams */
1449 for (int i = 0; i < vlc_array_count(hls_streams); i++)
1452 hls = (hls_stream_t *)vlc_array_item_at_index(hls_streams, i);
1453 if (hls) hls_Free(hls);
1455 vlc_array_destroy(hls_streams);
1457 msg_Err(s, "reloading playlist failed");
1458 return VLC_EGENERIC;
1461 /* merge playlists */
1462 int count = vlc_array_count(hls_streams);
1463 for (int n = 0; n < count; n++)
1465 hls_stream_t *hls_new = hls_Get(hls_streams, n);
1466 if (hls_new == NULL)
1469 hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1470 if (hls_old == NULL)
1471 { /* new hls stream - append */
1472 vlc_array_append(p_sys->hls_stream, hls_new);
1473 msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1474 hls_new->id, hls_new->bandwidth);
1476 else if (hls_UpdatePlaylist(s, hls_new, &hls_old) != VLC_SUCCESS)
1477 msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1478 hls_new->id, hls_new->bandwidth);
1480 vlc_array_destroy(hls_streams);
1484 /****************************************************************************
1486 ****************************************************************************/
1487 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1489 stream_sys_t *p_sys = s->p_sys;
1491 uint64_t bw = *bandwidth;
1492 uint64_t bw_candidate = 0;
1494 int count = vlc_array_count(p_sys->hls_stream);
1495 for (int n = 0; n < count; n++)
1497 /* Select best bandwidth match */
1498 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1499 if (hls == NULL) break;
1501 /* only consider streams with the same PROGRAM-ID */
1502 if (hls->id == progid)
1504 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1506 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1507 n, bw, hls->bandwidth); /* bits / s */
1508 bw_candidate = hls->bandwidth;
1509 candidate = n; /* possible candidate */
1513 *bandwidth = bw_candidate;
1517 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1519 stream_sys_t *p_sys = s->p_sys;
1524 vlc_mutex_lock(&segment->lock);
1525 if (segment->data != NULL)
1527 /* Segment already downloaded */
1528 vlc_mutex_unlock(&segment->lock);
1532 /* sanity check - can we download this segment on time? */
1533 if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1535 uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1536 int estimated = (int)(size / p_sys->bandwidth);
1537 if (estimated > segment->duration)
1539 msg_Warn(s,"downloading of segment %d takes %ds, which is longer than its playback (%ds)",
1540 segment->sequence, estimated, segment->duration);
1544 mtime_t start = mdate();
1545 if (hls_Download(s, segment) != VLC_SUCCESS)
1547 msg_Err(s, "downloaded segment %d from stream %d failed",
1548 segment->sequence, *cur_stream);
1549 vlc_mutex_unlock(&segment->lock);
1550 return VLC_EGENERIC;
1552 mtime_t duration = mdate() - start;
1554 /* If the segment is encrypted, decode it */
1555 if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1557 vlc_mutex_unlock(&segment->lock);
1558 return VLC_EGENERIC;
1561 vlc_mutex_unlock(&segment->lock);
1563 msg_Info(s, "downloaded segment %d from stream %d",
1564 segment->sequence, *cur_stream);
1566 /* check for division by zero */
1567 double ms = (double)duration / 1000.0; /* ms */
1571 uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
1572 p_sys->bandwidth = bw;
1573 if (p_sys->b_meta && (hls->bandwidth != bw))
1575 int newstream = BandwidthAdaptation(s, hls->id, &bw);
1577 /* FIXME: we need an average here */
1578 if ((newstream >= 0) && (newstream != *cur_stream))
1580 msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1581 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1582 *cur_stream = newstream;
1588 static void* hls_Thread(void *p_this)
1590 stream_t *s = (stream_t *)p_this;
1591 stream_sys_t *p_sys = s->p_sys;
1593 int canc = vlc_savecancel();
1595 while (vlc_object_alive(s))
1597 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1600 /* Sliding window (~60 seconds worth of movie) */
1601 vlc_mutex_lock(&hls->lock);
1602 int count = vlc_array_count(hls->segments);
1603 vlc_mutex_unlock(&hls->lock);
1605 /* Is there a new segment to process? */
1606 if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1607 (p_sys->download.segment >= count))
1610 vlc_mutex_lock(&p_sys->download.lock_wait);
1611 while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1612 (p_sys->download.segment >= count)) &&
1613 (p_sys->download.seek == -1))
1615 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1616 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1618 if (!vlc_object_alive(s))
1622 if (p_sys->download.seek >= 0)
1624 p_sys->download.segment = p_sys->download.seek;
1625 p_sys->download.seek = -1;
1627 vlc_mutex_unlock(&p_sys->download.lock_wait);
1630 if (!vlc_object_alive(s)) break;
1632 vlc_mutex_lock(&hls->lock);
1633 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1634 vlc_mutex_unlock(&hls->lock);
1636 if ((segment != NULL) &&
1637 (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1639 if (!vlc_object_alive(s)) break;
1643 p_sys->b_error = true;
1648 /* download succeeded */
1649 /* determine next segment to download */
1650 vlc_mutex_lock(&p_sys->download.lock_wait);
1651 if (p_sys->download.seek >= 0)
1653 p_sys->download.segment = p_sys->download.seek;
1654 p_sys->download.seek = -1;
1656 else if (p_sys->download.segment < count)
1657 p_sys->download.segment++;
1658 vlc_cond_signal(&p_sys->download.wait);
1659 vlc_mutex_unlock(&p_sys->download.lock_wait);
1662 vlc_restorecancel(canc);
1666 static void* hls_Reload(void *p_this)
1668 stream_t *s = (stream_t *)p_this;
1669 stream_sys_t *p_sys = s->p_sys;
1671 assert(p_sys->b_live);
1673 int canc = vlc_savecancel();
1676 while (vlc_object_alive(s))
1678 mtime_t now = mdate();
1679 if (now >= p_sys->playlist.wakeup)
1681 /* reload the m3u8 */
1682 if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1684 /* No change in playlist, then backoff */
1685 p_sys->playlist.tries++;
1686 if (p_sys->playlist.tries == 1) wait = 0.5;
1687 else if (p_sys->playlist.tries == 2) wait = 1;
1688 else if (p_sys->playlist.tries >= 3) wait = 2;
1690 /* Can we afford to backoff? */
1691 if (p_sys->download.segment - p_sys->playback.segment < 3)
1693 p_sys->playlist.tries = 0;
1699 p_sys->playlist.tries = 0;
1703 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1706 /* determine next time to update playlist */
1707 p_sys->playlist.last = now;
1708 p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1709 * (mtime_t)1000000);
1712 mwait(p_sys->playlist.wakeup);
1715 vlc_restorecancel(canc);
1719 static int Prefetch(stream_t *s, int *current)
1721 stream_sys_t *p_sys = s->p_sys;
1724 /* Try to pick best matching stream */;
1728 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1730 return VLC_EGENERIC;
1732 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1733 if (segment == NULL )
1734 return VLC_EGENERIC;
1736 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1737 return VLC_EGENERIC;
1739 /* Found better bandwidth match, try again */
1740 if (*current != stream)
1743 /* Download first 2 segments of this HLS stream */
1745 for (int i = 0; i < 2; i++)
1747 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1748 if (segment == NULL )
1749 return VLC_EGENERIC;
1753 p_sys->download.segment++;
1757 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1758 return VLC_EGENERIC;
1760 p_sys->download.segment++;
1762 /* adapt bandwidth? */
1763 if (*current != stream)
1765 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1767 return VLC_EGENERIC;
1776 /****************************************************************************
1778 ****************************************************************************/
1779 static int hls_Download(stream_t *s, segment_t *segment)
1784 char *psz_url = ConstructUrl(&segment->url);
1785 if (psz_url == NULL)
1788 stream_t *p_ts = stream_UrlNew(s, psz_url);
1791 return VLC_EGENERIC;
1793 segment->size = stream_Size(p_ts);
1794 assert(segment->size > 0);
1796 segment->data = block_Alloc(segment->size);
1797 if (segment->data == NULL)
1799 stream_Delete(p_ts);
1803 assert(segment->data->i_buffer == segment->size);
1805 ssize_t length = 0, curlen = 0;
1809 size = stream_Size(p_ts);
1810 if (size > segment->size)
1812 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1813 block_t *p_block = block_Realloc(segment->data, 0, size);
1814 if (p_block == NULL)
1816 stream_Delete(p_ts);
1817 block_Release(segment->data);
1818 segment->data = NULL;
1821 segment->data = p_block;
1822 segment->size = size;
1823 assert(segment->data->i_buffer == segment->size);
1826 length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1830 } while (vlc_object_alive(s));
1832 stream_Delete(p_ts);
1836 /* Read M3U8 file */
1837 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1839 int64_t total_bytes = 0;
1840 int64_t total_allocated = 0;
1848 bytes = stream_Read(s, buf, sizeof(buf));
1854 if ( (total_bytes + bytes + 1) > total_allocated )
1856 if (total_allocated)
1857 total_allocated *= 2;
1859 total_allocated = __MIN(bytes+1, sizeof(buf));
1861 p = realloc_or_free(p, total_allocated);
1866 memcpy(p+total_bytes, buf, bytes);
1867 total_bytes += bytes;
1870 if (total_allocated == 0)
1871 return VLC_EGENERIC;
1873 p[total_bytes] = '\0';
1879 static ssize_t read_M3U8_from_url(stream_t *s, vlc_url_t *url, uint8_t **buffer)
1881 assert(*buffer == NULL);
1884 char *psz_url = ConstructUrl(url);
1885 if (psz_url == NULL)
1888 stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1891 return VLC_EGENERIC;
1893 ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1894 stream_Delete(p_m3u8);
1899 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1904 uint8_t *begin = buffer;
1906 uint8_t *end = p + len;
1910 if ((*p == '\n') || (*p == '\0'))
1915 /* copy line excluding \n or \0 */
1916 line = strndup((char *)begin, p - begin);
1922 /* next pass start after \n */
1930 /****************************************************************************
1932 ****************************************************************************/
1933 static int Open(vlc_object_t *p_this)
1935 stream_t *s = (stream_t*)p_this;
1936 stream_sys_t *p_sys;
1938 if (!isHTTPLiveStreaming(s))
1939 return VLC_EGENERIC;
1941 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1943 /* Initialize crypto bit */
1947 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1951 char *psz_uri = NULL;
1952 if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1957 vlc_UrlParse(&p_sys->m3u8, psz_uri, 0);
1960 p_sys->bandwidth = 0;
1961 p_sys->b_live = true;
1962 p_sys->b_meta = false;
1963 p_sys->b_error = false;
1965 p_sys->hls_stream = vlc_array_new();
1966 if (p_sys->hls_stream == NULL)
1968 vlc_UrlClean(&p_sys->m3u8);
1976 s->pf_control = Control;
1978 /* Parse HLS m3u8 content. */
1979 uint8_t *buffer = NULL;
1980 ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1983 if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
1990 /* Choose first HLS stream to start with */
1991 int current = p_sys->playback.stream = 0;
1992 p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
1994 /* manage encryption key if needed */
1995 hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
1997 if (p_sys->b_live && (p_sys->playback.segment < 0))
1999 msg_Warn(s, "less data than 3 times 'target duration' available for live playback, playback may stall");
2002 if (Prefetch(s, ¤t) != VLC_SUCCESS)
2004 msg_Err(s, "fetching first segment failed.");
2009 p_sys->download.stream = current;
2010 p_sys->playback.stream = current;
2011 p_sys->download.seek = -1;
2013 vlc_mutex_init(&p_sys->download.lock_wait);
2014 vlc_cond_init(&p_sys->download.wait);
2016 /* Initialize HLS live stream */
2019 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
2020 p_sys->playlist.last = mdate();
2021 p_sys->playlist.wakeup = p_sys->playlist.last +
2022 ((mtime_t)hls->duration * UINT64_C(1000000));
2024 if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
2030 if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
2033 vlc_join(p_sys->reload, NULL);
2040 vlc_mutex_destroy(&p_sys->download.lock_wait);
2041 vlc_cond_destroy(&p_sys->download.wait);
2044 /* Free hls streams */
2045 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2048 hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
2049 if (hls) hls_Free(hls);
2051 vlc_array_destroy(p_sys->hls_stream);
2054 vlc_UrlClean(&p_sys->m3u8);
2056 return VLC_EGENERIC;
2059 /****************************************************************************
2061 ****************************************************************************/
2062 static void Close(vlc_object_t *p_this)
2064 stream_t *s = (stream_t*)p_this;
2065 stream_sys_t *p_sys = s->p_sys;
2067 assert(p_sys->hls_stream);
2070 vlc_mutex_lock(&p_sys->download.lock_wait);
2071 vlc_cond_signal(&p_sys->download.wait);
2072 vlc_mutex_unlock(&p_sys->download.lock_wait);
2076 vlc_join(p_sys->reload, NULL);
2077 vlc_join(p_sys->thread, NULL);
2078 vlc_mutex_destroy(&p_sys->download.lock_wait);
2079 vlc_cond_destroy(&p_sys->download.wait);
2081 /* Free hls streams */
2082 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2085 hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
2086 if (hls) hls_Free(hls);
2088 vlc_array_destroy(p_sys->hls_stream);
2091 vlc_UrlClean(&p_sys->m3u8);
2093 block_Release (p_sys->peeked);
2097 /****************************************************************************
2098 * Stream filters functions
2099 ****************************************************************************/
2100 static segment_t *GetSegment(stream_t *s)
2102 stream_sys_t *p_sys = s->p_sys;
2103 segment_t *segment = NULL;
2105 /* Is this segment of the current HLS stream ready? */
2106 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2109 vlc_mutex_lock(&hls->lock);
2110 segment = segment_GetSegment(hls, p_sys->playback.segment);
2111 if (segment != NULL)
2113 /* This segment is ready? */
2114 if (segment->data != NULL)
2116 p_sys->b_cache = hls->b_cache;
2117 vlc_mutex_unlock(&hls->lock);
2121 vlc_mutex_unlock(&hls->lock);
2124 /* Was the HLS stream changed to another bitrate? */
2127 while(vlc_object_alive(s))
2129 /* Is the next segment ready */
2130 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2134 vlc_mutex_lock(&hls->lock);
2135 segment = segment_GetSegment(hls, p_sys->playback.segment);
2136 if (segment == NULL)
2138 vlc_mutex_unlock(&hls->lock);
2142 vlc_mutex_lock(&p_sys->download.lock_wait);
2143 int i_segment = p_sys->download.segment;
2144 vlc_mutex_unlock(&p_sys->download.lock_wait);
2146 /* This segment is ready? */
2147 if ((segment->data != NULL) &&
2148 (p_sys->playback.segment < i_segment))
2150 p_sys->playback.stream = i_stream;
2151 p_sys->b_cache = hls->b_cache;
2152 vlc_mutex_unlock(&hls->lock);
2155 vlc_mutex_unlock(&hls->lock);
2160 /* Was the stream changed to another bitrate? */
2162 if (i_stream >= vlc_array_count(p_sys->hls_stream))
2170 if (segment->data->i_buffer == 0)
2172 vlc_mutex_lock(&hls->lock);
2173 int count = vlc_array_count(hls->segments);
2174 vlc_mutex_unlock(&hls->lock);
2176 if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2177 ((count != p_sys->download.segment) || p_sys->b_live))
2178 msg_Err(s, "playback will stall");
2179 else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2180 ((count != p_sys->download.segment) || p_sys->b_live))
2181 msg_Warn(s, "playback in danger of stalling");
2186 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2188 stream_sys_t *p_sys = s->p_sys;
2193 /* Determine next segment to read. If this is a meta playlist and
2194 * bandwidth conditions changed, then the stream might have switched
2195 * to another bandwidth. */
2196 segment_t *segment = GetSegment(s);
2197 if (segment == NULL)
2200 vlc_mutex_lock(&segment->lock);
2201 if (segment->data->i_buffer == 0)
2203 if (!p_sys->b_cache || p_sys->b_live)
2205 block_Release(segment->data);
2206 segment->data = NULL;
2209 { /* reset playback pointer to start of buffer */
2210 uint64_t size = segment->size - segment->data->i_buffer;
2213 segment->data->i_buffer += size;
2214 segment->data->p_buffer -= size;
2217 p_sys->playback.segment++;
2218 vlc_mutex_unlock(&segment->lock);
2220 /* signal download thread */
2221 vlc_mutex_lock(&p_sys->download.lock_wait);
2222 vlc_cond_signal(&p_sys->download.wait);
2223 vlc_mutex_unlock(&p_sys->download.lock_wait);
2227 if (segment->size == segment->data->i_buffer)
2228 msg_Info(s, "playing segment %d from stream %d",
2229 segment->sequence, p_sys->playback.stream);
2232 if (i_read <= segment->data->i_buffer)
2234 else if (i_read > segment->data->i_buffer)
2235 len = segment->data->i_buffer;
2239 memcpy(p_read + copied, segment->data->p_buffer, len);
2240 segment->data->i_buffer -= len;
2241 segment->data->p_buffer += len;
2245 vlc_mutex_unlock(&segment->lock);
2247 } while ((i_read > 0) && vlc_object_alive(s));
2252 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2254 stream_sys_t *p_sys = s->p_sys;
2257 assert(p_sys->hls_stream);
2264 /* caller skips data, get big enough buffer */
2265 msg_Warn(s, "buffer is NULL (allocate %d)", i_read);
2266 buffer = calloc(1, i_read);
2268 return 0; /* NO MEMORY left*/
2271 length = hls_Read(s, (uint8_t*) buffer, i_read);
2275 p_sys->playback.offset += length;
2279 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2281 stream_sys_t *p_sys = s->p_sys;
2283 unsigned int len = i_peek;
2285 segment = GetSegment(s);
2286 if (segment == NULL)
2288 msg_Err(s, "segment %d should have been available (stream %d)",
2289 p_sys->playback.segment, p_sys->playback.stream);
2290 return 0; /* eof? */
2293 vlc_mutex_lock(&segment->lock);
2295 size_t i_buff = segment->data->i_buffer;
2296 uint8_t *p_buff = segment->data->p_buffer;
2298 if (i_peek < i_buff)
2301 vlc_mutex_unlock(&segment->lock);
2305 else /* This will seldom be run */
2307 /* remember segment to read */
2308 int peek_segment = p_sys->playback.segment;
2310 segment_t *nsegment;
2311 p_sys->playback.segment++;
2312 block_t *peeked = p_sys->peeked;
2315 peeked = block_Alloc (i_peek);
2316 else if (peeked->i_buffer < i_peek)
2317 peeked = block_Realloc (peeked, 0, i_peek);
2321 memcpy(peeked->p_buffer, p_buff, i_buff);
2324 vlc_mutex_unlock(&segment->lock);
2326 i_buff = peeked->i_buffer;
2327 p_buff = peeked->p_buffer;
2330 while ((curlen < i_peek) && vlc_object_alive(s))
2332 nsegment = GetSegment(s);
2333 if (nsegment == NULL)
2335 msg_Err(s, "segment %d should have been available (stream %d)",
2336 p_sys->playback.segment, p_sys->playback.stream);
2337 /* restore segment to read */
2338 p_sys->playback.segment = peek_segment;
2339 return curlen; /* eof? */
2342 vlc_mutex_lock(&nsegment->lock);
2344 if (len < nsegment->data->i_buffer)
2346 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2351 size_t i_nbuff = nsegment->data->i_buffer;
2352 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2356 p_sys->playback.segment++;
2359 vlc_mutex_unlock(&nsegment->lock);
2362 /* restore segment to read */
2363 p_sys->playback.segment = peek_segment;
2368 static bool hls_MaySeek(stream_t *s)
2370 stream_sys_t *p_sys = s->p_sys;
2372 if (p_sys->hls_stream == NULL)
2375 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2376 if (hls == NULL) return false;
2380 vlc_mutex_lock(&hls->lock);
2381 int count = vlc_array_count(hls->segments);
2382 vlc_mutex_unlock(&hls->lock);
2384 vlc_mutex_lock(&p_sys->download.lock_wait);
2385 bool may_seek = (p_sys->download.segment < (count - 2));
2386 vlc_mutex_unlock(&p_sys->download.lock_wait);
2392 static uint64_t GetStreamSize(stream_t *s)
2394 stream_sys_t *p_sys = s->p_sys;
2399 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2400 if (hls == NULL) return 0;
2402 vlc_mutex_lock(&hls->lock);
2404 hls->size = hls_GetStreamSize(hls);
2405 uint64_t size = hls->size;
2406 vlc_mutex_unlock(&hls->lock);
2411 static int segment_Seek(stream_t *s, const uint64_t pos)
2413 stream_sys_t *p_sys = s->p_sys;
2415 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2417 return VLC_EGENERIC;
2419 vlc_mutex_lock(&hls->lock);
2421 bool b_found = false;
2422 uint64_t length = 0;
2423 uint64_t size = hls->size;
2424 int count = vlc_array_count(hls->segments);
2426 for (int n = 0; n < count; n++)
2428 segment_t *segment = vlc_array_item_at_index(hls->segments, n);
2429 if (segment == NULL)
2431 vlc_mutex_unlock(&hls->lock);
2432 return VLC_EGENERIC;
2435 vlc_mutex_lock(&segment->lock);
2436 length += segment->duration * (hls->bandwidth/8);
2437 vlc_mutex_unlock(&segment->lock);
2439 if (!b_found && (pos <= length))
2443 p_sys->playback.segment = n;
2447 /* Do not search in last 3 segments */
2448 vlc_mutex_unlock(&hls->lock);
2449 return VLC_EGENERIC;
2454 if (!b_found && (pos >= size))
2456 p_sys->playback.segment = count - 1;
2463 /* restore segment to start position */
2464 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2465 if (segment == NULL)
2467 vlc_mutex_unlock(&hls->lock);
2468 return VLC_EGENERIC;
2471 vlc_mutex_lock(&segment->lock);
2474 uint64_t size = segment->size -segment->data->i_buffer;
2477 segment->data->i_buffer += size;
2478 segment->data->p_buffer -= size;
2481 vlc_mutex_unlock(&segment->lock);
2483 /* start download at current playback segment */
2484 vlc_mutex_unlock(&hls->lock);
2486 /* Wake up download thread */
2487 vlc_mutex_lock(&p_sys->download.lock_wait);
2488 p_sys->download.seek = p_sys->playback.segment;
2489 vlc_cond_signal(&p_sys->download.wait);
2490 vlc_mutex_unlock(&p_sys->download.lock_wait);
2492 /* Wait for download to be finished */
2493 vlc_mutex_lock(&p_sys->download.lock_wait);
2494 msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2495 while (((p_sys->download.seek != -1) ||
2496 (p_sys->download.segment - p_sys->playback.segment < 3)) &&
2497 (p_sys->download.segment < (count - 6)))
2499 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2500 if (!vlc_object_alive(s) || s->b_error) break;
2502 vlc_mutex_unlock(&p_sys->download.lock_wait);
2506 vlc_mutex_unlock(&hls->lock);
2508 return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2511 static int Control(stream_t *s, int i_query, va_list args)
2513 stream_sys_t *p_sys = s->p_sys;
2517 case STREAM_CAN_SEEK:
2518 *(va_arg (args, bool *)) = hls_MaySeek(s);
2520 case STREAM_GET_POSITION:
2521 *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2523 case STREAM_SET_POSITION:
2526 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2527 if (segment_Seek(s, pos) == VLC_SUCCESS)
2529 p_sys->playback.offset = pos;
2533 return VLC_EGENERIC;
2534 case STREAM_GET_SIZE:
2535 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2538 return VLC_EGENERIC;