1 /*****************************************************************************
2 * httplive.c: HTTP Live Streaming stream filter
3 *****************************************************************************
4 * Copyright (C) 2010-2012 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_GetSegment(hls, 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);
253 static hls_stream_t *hls_Copy(hls_stream_t *src, const bool b_cp_segments)
256 assert(!b_cp_segments); /* FIXME: copying segments is not implemented */
258 hls_stream_t *dst = (hls_stream_t *)malloc(sizeof(hls_stream_t));
259 if (dst == NULL) return NULL;
262 dst->bandwidth = src->bandwidth;
263 dst->duration = src->duration;
264 dst->size = src->size;
265 dst->sequence = src->sequence;
266 dst->version = src->version;
267 dst->b_cache = src->b_cache;
268 dst->psz_current_key_path = src->psz_current_key_path ?
269 strdup( src->psz_current_key_path ) : NULL;
270 char *uri = ConstructUrl(&src->url);
276 vlc_UrlParse(&dst->url, uri, 0);
278 dst->segments = vlc_array_new();
279 vlc_mutex_init(&dst->lock);
283 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, const int wanted)
285 int count = vlc_array_count(hls_stream);
288 if ((wanted < 0) || (wanted >= count))
290 return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
293 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
295 return hls_Get(hls_stream, 0);
298 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
300 int count = vlc_array_count(hls_stream);
304 return hls_Get(hls_stream, count);
307 static hls_stream_t *hls_Find(vlc_array_t *hls_stream, hls_stream_t *hls_new)
309 int count = vlc_array_count(hls_stream);
310 for (int n = 0; n < count; n++)
312 hls_stream_t *hls = hls_Get(hls_stream, n);
316 if ((hls->id == hls_new->id) &&
317 (hls->bandwidth == hls_new->bandwidth))
324 static uint64_t hls_GetStreamSize(hls_stream_t *hls)
326 /* NOTE: Stream size is calculated based on segment duration and
327 * HLS stream bandwidth from the .m3u8 file. If these are not correct
328 * then the deviation from exact byte size will be big and the seek/
329 * progressbar will not behave entirely as one expects. */
332 /* If there is no valid bandwidth yet, then there is no point in
333 * computing stream size. */
334 if (hls->bandwidth == 0)
337 int count = vlc_array_count(hls->segments);
338 for (int n = 0; n < count; n++)
340 segment_t *segment = segment_GetSegment(hls, n);
343 size += (segment->duration * (hls->bandwidth / 8));
350 static segment_t *segment_New(hls_stream_t* hls, const int duration, const char *uri)
352 segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
356 segment->duration = duration; /* seconds */
357 segment->size = 0; /* bytes */
358 segment->sequence = 0;
359 segment->bandwidth = 0;
360 vlc_UrlParse(&segment->url, uri, 0);
361 segment->data = NULL;
362 vlc_array_append(hls->segments, segment);
363 vlc_mutex_init(&segment->lock);
364 segment->b_key_loaded = false;
365 segment->psz_key_path = NULL;
366 if (hls->psz_current_key_path)
367 segment->psz_key_path = strdup(hls->psz_current_key_path);
371 static void segment_Free(segment_t *segment)
373 vlc_mutex_destroy(&segment->lock);
375 vlc_UrlClean(&segment->url);
376 free(segment->psz_key_path);
378 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 = segment_GetSegment(hls, 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))
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 */
684 static int parse_AddSegment(stream_t *s, hls_stream_t *hls, const int duration, const char *uri)
689 /* Store segment information */
690 vlc_mutex_lock(&hls->lock);
692 char *psz_uri = relative_URI(s, uri, &hls->url);
694 segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
696 segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
699 vlc_mutex_unlock(&hls->lock);
701 return segment ? VLC_SUCCESS : VLC_ENOMEM;
704 static int parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
709 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
712 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
716 hls->duration = duration; /* seconds */
720 static int parse_StreamInformation(stream_t *s, vlc_array_t **hls_stream,
721 hls_stream_t **hls, char *p_read, const char *uri)
727 assert(*hls == NULL);
729 attr = parse_Attributes(p_read, "PROGRAM-ID");
732 msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
738 attr = parse_Attributes(p_read, "BANDWIDTH");
741 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
749 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
753 msg_Info(s, "bandwidth adaptation detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
755 char *psz_uri = relative_URI(s, uri, NULL);
757 *hls = hls_New(*hls_stream, id, bw, psz_uri ? psz_uri : uri);
761 return (*hls == NULL) ? VLC_ENOMEM : VLC_SUCCESS;
764 static int parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
769 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
772 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
776 if (hls->sequence > 0)
778 if (s->p_sys->b_live)
780 hls_stream_t *last = hls_GetLast(s->p_sys->hls_stream);
781 if ((last->sequence < sequence) && (sequence - last->sequence != 1))
782 msg_Err(s, "EXT-X-MEDIA-SEQUENCE gap in playlist (new=%d, old=%d)",
783 sequence, last->sequence);
786 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist (new=%d, old=%d)",
787 sequence, hls->sequence);
789 hls->sequence = sequence;
793 static int parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
797 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
798 int err = VLC_SUCCESS;
799 char *attr = parse_Attributes(p_read, "METHOD");
802 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
806 if (strncasecmp(attr, "NONE", 4) == 0)
808 char *uri = parse_Attributes(p_read, "URI");
811 msg_Err(s, "#EXT-X-KEY: URI not expected");
815 /* IV is only supported in version 2 and above */
816 if (hls->version >= 2)
818 char *iv = parse_Attributes(p_read, "IV");
821 msg_Err(s, "#EXT-X-KEY: IV not expected");
827 else if (strncasecmp(attr, "AES-128", 7) == 0)
829 char *value, *uri, *iv;
830 if (s->p_sys->b_aesmsg == false)
832 msg_Info(s, "playback of AES-128 encrypted HTTP Live media detected.");
833 s->p_sys->b_aesmsg = true;
835 value = uri = parse_Attributes(p_read, "URI");
838 msg_Err(s, "#EXT-X-KEY: URI not found for encrypted HTTP Live media in AES-128");
843 /* Url is put between quotes, remove them */
846 /* We need to strip the "" from the attribute value */
848 char* end = strchr(uri, '"');
852 hls->psz_current_key_path = strdup(uri);
855 value = iv = parse_Attributes(p_read, "IV");
859 * If the EXT-X-KEY tag does not have the IV attribute, implementations
860 * MUST use the sequence number of the media file as the IV when
861 * encrypting or decrypting that media file. The big-endian binary
862 * representation of the sequence number SHALL be placed in a 16-octet
863 * buffer and padded (on the left) with zeros.
865 hls->b_iv_loaded = false;
870 * If the EXT-X-KEY tag has the IV attribute, implementations MUST use
871 * the attribute value as the IV when encrypting or decrypting with that
872 * key. The value MUST be interpreted as a 128-bit hexadecimal number
873 * and MUST be prefixed with 0x or 0X.
876 if (string_to_IV(iv, hls->psz_AES_IV) == VLC_EGENERIC)
879 hls->b_iv_loaded = true;
885 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
892 static int parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
895 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
899 static int parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
903 char answer[4] = "\0";
904 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
907 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
911 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
915 static int parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
920 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
923 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
928 hls->version = version;
929 if (hls->version <= 0 || hls->version > 3)
931 msg_Err(s, "#EXT-X-VERSION should be version 1, 2 or 3 iso %d", version);
937 static int parse_EndList(stream_t *s, hls_stream_t *hls)
941 s->p_sys->b_live = false;
942 msg_Info(s, "video on demand (vod) mode");
946 static int parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
950 /* FIXME: Do we need to act on discontinuity ?? */
951 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
955 static int hls_CompareStreams( const void* a, const void* b )
957 hls_stream_t* stream_a = *(hls_stream_t**)a;
958 hls_stream_t* stream_b = *(hls_stream_t**)b;
959 return stream_a->bandwidth > stream_b->bandwidth;
962 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
963 * document defines the following new tags: EXT-X-TARGETDURATION,
964 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
965 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
968 static int parse_M3U8(stream_t *s, vlc_array_t *streams, uint8_t *buffer, const ssize_t len)
970 stream_sys_t *p_sys = s->p_sys;
971 uint8_t *p_read, *p_begin, *p_end;
976 msg_Dbg(s, "parse_M3U8\n%s", buffer);
978 p_end = p_begin + len;
980 char *line = ReadLine(p_begin, &p_read, p_end - p_begin);
985 if (strncmp(line, "#EXTM3U", 7) != 0)
987 msg_Err(s, "missing #EXTM3U tag .. aborting");
995 /* What is the version ? */
997 uint8_t *p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-VERSION:");
1000 uint8_t *tmp = NULL;
1001 char *psz_version = ReadLine(p, &tmp, p_end - p);
1002 if (psz_version == NULL)
1004 int ret = sscanf((const char*)psz_version, "#EXT-X-VERSION:%d", &version);
1007 msg_Warn(s, "#EXT-X-VERSION: no protocol version found, assuming version 1.");
1014 /* Is it a live stream ? */
1015 p_sys->b_live = (strstr((const char *)buffer, "#EXT-X-ENDLIST") == NULL) ? true : false;
1017 /* Is it a meta index file ? */
1018 bool b_meta = (strstr((const char *)buffer, "#EXT-X-STREAM-INF") == NULL) ? false : true;
1020 int err = VLC_SUCCESS;
1024 msg_Info(s, "Meta playlist");
1026 /* M3U8 Meta Index file */
1029 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1035 if (strncmp(line, "#EXT-X-STREAM-INF", 17) == 0)
1037 p_sys->b_meta = true;
1038 char *uri = ReadLine(p_begin, &p_read, p_end - p_begin);
1045 msg_Info(s, "Skipping invalid stream-inf: %s", uri);
1050 hls_stream_t *hls = NULL;
1051 err = parse_StreamInformation(s, &streams, &hls, line, uri);
1054 /* Download playlist file from server */
1055 uint8_t *buf = NULL;
1056 ssize_t len = read_M3U8_from_url(s, &hls->url, &buf);
1061 /* Parse HLS m3u8 content. */
1062 err = parse_M3U8(s, streams, buf, len);
1068 hls->version = version;
1070 hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
1080 if (p_begin >= p_end)
1083 } while (err == VLC_SUCCESS);
1088 msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
1090 hls_stream_t *hls = NULL;
1092 hls = hls_GetLast(streams);
1095 /* No Meta playlist used */
1096 char* uri = ConstructUrl( &s->p_sys->m3u8 );
1098 return VLC_EGENERIC;
1099 hls = hls_New(streams, 0, 0, uri);
1103 /* Get TARGET-DURATION first */
1104 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1107 uint8_t *p_rest = NULL;
1108 char *psz_duration = ReadLine(p, &p_rest, p_end - p);
1109 if (psz_duration == NULL)
1110 return VLC_EGENERIC;
1111 err = parse_TargetDuration(s, hls, psz_duration);
1117 hls->version = version;
1119 else return VLC_ENOMEM;
1124 int segment_duration = -1;
1128 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1133 if (strncmp(line, "#EXTINF", 7) == 0)
1134 err = parse_SegmentInformation(hls, line, &segment_duration);
1135 else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1136 err = parse_TargetDuration(s, hls, line);
1137 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1138 err = parse_MediaSequence(s, hls, line);
1139 else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1140 err = parse_Key(s, hls, line);
1141 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1142 err = parse_ProgramDateTime(s, hls, line);
1143 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1144 err = parse_AllowCache(s, hls, line);
1145 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1146 err = parse_Discontinuity(s, hls, line);
1147 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1148 err = parse_Version(s, hls, line);
1149 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1150 err = parse_EndList(s, hls);
1151 else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1153 err = parse_AddSegment(s, hls, segment_duration, line);
1154 segment_duration = -1; /* reset duration */
1160 if (p_begin >= p_end)
1163 } while (err == VLC_SUCCESS);
1172 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1174 uint8_t aeskey[32]; /* AES-512 can use up to 32 bytes */
1177 stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1180 msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1181 return VLC_EGENERIC;
1184 len = stream_Read(p_m3u8, aeskey, sizeof(aeskey));
1185 if (len != AES_BLOCK_SIZE)
1187 msg_Err(s, "The AES key loaded doesn't have the right size (%zd)", len);
1188 stream_Delete(p_m3u8);
1189 return VLC_EGENERIC;
1192 memcpy(seg->psz_AES_key, aeskey, AES_BLOCK_SIZE);
1194 stream_Delete(p_m3u8);
1199 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1201 segment_t *seg = NULL;
1202 segment_t *prev_seg;
1203 int count = vlc_array_count(hls->segments);
1205 for (int i = 0; i < count; i++)
1208 seg = segment_GetSegment(hls, i);
1211 if (seg->psz_key_path == NULL)
1212 continue; /* No key to load ? continue */
1213 if (seg->b_key_loaded)
1214 continue; /* The key is already loaded */
1216 /* if the key has not changed, and already available from previous segment,
1217 * try to copy it, and don't load the key */
1218 if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1220 memcpy(seg->psz_AES_key, prev_seg->psz_AES_key, AES_BLOCK_SIZE);
1221 seg->b_key_loaded = true;
1224 if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1225 return VLC_EGENERIC;
1226 seg->b_key_loaded = true;
1231 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1233 /* Did the segment need to be decoded ? */
1234 if (segment->psz_key_path == NULL)
1237 /* Do we have loaded the key ? */
1238 if (!segment->b_key_loaded)
1240 /* No ? try to download it now */
1241 if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1242 return VLC_EGENERIC;
1245 /* For now, we only decode AES-128 data */
1246 gcry_error_t i_gcrypt_err;
1247 gcry_cipher_hd_t aes_ctx;
1249 i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1250 GCRY_CIPHER_MODE_CBC, 0);
1253 msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1254 gcry_cipher_close(aes_ctx);
1255 return VLC_EGENERIC;
1259 i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->psz_AES_key,
1260 sizeof(segment->psz_AES_key));
1263 msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1264 gcry_cipher_close(aes_ctx);
1265 return VLC_EGENERIC;
1268 if (hls->b_iv_loaded == false)
1270 memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1271 hls->psz_AES_IV[15] = segment->sequence & 0xff;
1272 hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1273 hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1274 hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1277 i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1278 sizeof(hls->psz_AES_IV));
1282 msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1283 gcry_cipher_close(aes_ctx);
1284 return VLC_EGENERIC;
1287 i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1288 segment->data->p_buffer, /* out */
1289 segment->data->i_buffer,
1294 msg_Err(s, "gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1295 gcry_cipher_close(aes_ctx);
1296 return VLC_EGENERIC;
1298 gcry_cipher_close(aes_ctx);
1299 /* remove the PKCS#7 padding from the buffer */
1300 int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1301 if (pad <= 0 || pad > AES_BLOCK_SIZE)
1303 msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1304 return VLC_EGENERIC;
1309 if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1311 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1312 return VLC_EGENERIC;
1316 /* not all the data is readable because of padding */
1317 segment->data->i_buffer -= pad;
1322 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1324 stream_sys_t *p_sys = s->p_sys;
1326 int err = VLC_EGENERIC;
1328 /* Duplicate HLS stream META information */
1329 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1331 hls_stream_t *src, *dst;
1332 src = hls_Get(p_sys->hls_stream, i);
1334 return VLC_EGENERIC;
1336 dst = hls_Copy(src, false);
1339 vlc_array_append(*streams, dst);
1341 /* Download playlist file from server */
1342 uint8_t *buf = NULL;
1343 ssize_t len = read_M3U8_from_url(s, &dst->url, &buf);
1348 /* Parse HLS m3u8 content. */
1349 err = parse_M3U8(s, *streams, buf, len);
1356 /* Reload playlist */
1357 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t **hls)
1359 int count = vlc_array_count(hls_new->segments);
1361 msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1362 hls_new->id, hls_new->bandwidth, count);
1364 for (int n = 0; n < count; n++)
1366 segment_t *p = segment_GetSegment(hls_new, n);
1367 if (p == NULL) return VLC_EGENERIC;
1369 vlc_mutex_lock(&(*hls)->lock);
1370 segment_t *segment = segment_Find(*hls, p->sequence);
1373 vlc_mutex_lock(&segment->lock);
1375 assert(p->url.psz_path);
1376 assert(segment->url.psz_path);
1378 /* they should be the same */
1379 if ((p->sequence != segment->sequence) ||
1380 (p->duration != segment->duration) ||
1381 (strcmp(p->url.psz_path, segment->url.psz_path) != 0))
1383 msg_Warn(s, "existing segment found with different content - resetting");
1384 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1385 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1386 msg_Warn(s, "- file: new=%s", p->url.psz_path);
1387 msg_Warn(s, " old=%s", segment->url.psz_path);
1389 /* Resetting content */
1390 char *psz_url = ConstructUrl(&p->url);
1391 if (psz_url == NULL)
1393 msg_Err(s, "Failed updating segment %d - skipping it", p->sequence);
1395 vlc_mutex_unlock(&segment->lock);
1398 segment->sequence = p->sequence;
1399 segment->duration = p->duration;
1400 vlc_UrlClean(&segment->url);
1401 vlc_UrlParse(&segment->url, psz_url, 0);
1402 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1405 block_Release(segment->data);
1406 segment->data = NULL;
1408 free(segment->psz_key_path);
1409 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1413 vlc_mutex_unlock(&segment->lock);
1417 int last = vlc_array_count((*hls)->segments) - 1;
1418 segment_t *l = segment_GetSegment(*hls, last);
1419 if (l == NULL) goto fail_and_unlock;
1421 if ((l->sequence + 1) != p->sequence)
1423 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1424 p->sequence, l->sequence+1);
1426 vlc_array_append((*hls)->segments, p);
1427 msg_Info(s, "- segment %d appended", p->sequence);
1429 vlc_mutex_unlock(&(*hls)->lock);
1432 /* update meta information */
1433 vlc_mutex_lock(&(*hls)->lock);
1434 (*hls)->sequence = hls_new->sequence;
1435 (*hls)->duration = (hls_new->duration == -1) ? (*hls)->duration : hls_new->duration;
1436 (*hls)->b_cache = hls_new->b_cache;
1437 vlc_mutex_unlock(&(*hls)->lock);
1442 vlc_mutex_unlock(&(*hls)->lock);
1443 return VLC_EGENERIC;
1446 static int hls_ReloadPlaylist(stream_t *s)
1448 stream_sys_t *p_sys = s->p_sys;
1450 vlc_array_t *hls_streams = vlc_array_new();
1451 if (hls_streams == NULL)
1454 msg_Info(s, "Reloading HLS live meta playlist");
1456 if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1458 /* Free hls streams */
1459 for (int i = 0; i < vlc_array_count(hls_streams); i++)
1462 hls = hls_Get(hls_streams, i);
1463 if (hls) hls_Free(hls);
1465 vlc_array_destroy(hls_streams);
1467 msg_Err(s, "reloading playlist failed");
1468 return VLC_EGENERIC;
1471 /* merge playlists */
1472 int count = vlc_array_count(hls_streams);
1473 for (int n = 0; n < count; n++)
1475 hls_stream_t *hls_new = hls_Get(hls_streams, n);
1476 if (hls_new == NULL)
1479 hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1480 if (hls_old == NULL)
1481 { /* new hls stream - append */
1482 vlc_array_append(p_sys->hls_stream, hls_new);
1483 msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1484 hls_new->id, hls_new->bandwidth);
1486 else if (hls_UpdatePlaylist(s, hls_new, &hls_old) != VLC_SUCCESS)
1487 msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1488 hls_new->id, hls_new->bandwidth);
1490 vlc_array_destroy(hls_streams);
1494 /****************************************************************************
1496 ****************************************************************************/
1497 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1499 stream_sys_t *p_sys = s->p_sys;
1501 uint64_t bw = *bandwidth;
1502 uint64_t bw_candidate = 0;
1504 int count = vlc_array_count(p_sys->hls_stream);
1505 for (int n = 0; n < count; n++)
1507 /* Select best bandwidth match */
1508 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1509 if (hls == NULL) break;
1511 /* only consider streams with the same PROGRAM-ID */
1512 if (hls->id == progid)
1514 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1516 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1517 n, bw, hls->bandwidth); /* bits / s */
1518 bw_candidate = hls->bandwidth;
1519 candidate = n; /* possible candidate */
1523 *bandwidth = bw_candidate;
1527 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1529 stream_sys_t *p_sys = s->p_sys;
1534 vlc_mutex_lock(&segment->lock);
1535 if (segment->data != NULL)
1537 /* Segment already downloaded */
1538 vlc_mutex_unlock(&segment->lock);
1542 /* sanity check - can we download this segment on time? */
1543 if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1545 uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1546 int estimated = (int)(size / p_sys->bandwidth);
1547 if (estimated > segment->duration)
1549 msg_Warn(s,"downloading of segment %d takes %ds, which is longer than its playback (%ds)",
1550 segment->sequence, estimated, segment->duration);
1554 mtime_t start = mdate();
1555 if (hls_Download(s, segment) != VLC_SUCCESS)
1557 msg_Err(s, "downloaded segment %d from stream %d failed",
1558 segment->sequence, *cur_stream);
1559 vlc_mutex_unlock(&segment->lock);
1560 return VLC_EGENERIC;
1562 mtime_t duration = mdate() - start;
1563 if (hls->bandwidth == 0)
1565 /* Try to estimate the bandwidth for this stream */
1566 hls->bandwidth = (uint64_t)((double)segment->size / ((double)duration / 1000000.0));
1569 /* If the segment is encrypted, decode it */
1570 if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1572 vlc_mutex_unlock(&segment->lock);
1573 return VLC_EGENERIC;
1576 vlc_mutex_unlock(&segment->lock);
1578 msg_Info(s, "downloaded segment %d from stream %d",
1579 segment->sequence, *cur_stream);
1581 /* check for division by zero */
1582 double ms = (double)duration / 1000.0; /* ms */
1586 uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
1587 p_sys->bandwidth = bw;
1588 if (p_sys->b_meta && (hls->bandwidth != bw))
1590 int newstream = BandwidthAdaptation(s, hls->id, &bw);
1592 /* FIXME: we need an average here */
1593 if ((newstream >= 0) && (newstream != *cur_stream))
1595 msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1596 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1597 *cur_stream = newstream;
1603 static void* hls_Thread(void *p_this)
1605 stream_t *s = (stream_t *)p_this;
1606 stream_sys_t *p_sys = s->p_sys;
1608 int canc = vlc_savecancel();
1610 while (vlc_object_alive(s))
1612 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1615 /* Sliding window (~60 seconds worth of movie) */
1616 vlc_mutex_lock(&hls->lock);
1617 int count = vlc_array_count(hls->segments);
1618 vlc_mutex_unlock(&hls->lock);
1620 /* Is there a new segment to process? */
1621 if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1622 (p_sys->download.segment >= count))
1625 vlc_mutex_lock(&p_sys->download.lock_wait);
1626 while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1627 (p_sys->download.segment >= count)) &&
1628 (p_sys->download.seek == -1))
1630 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1631 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1633 if (!vlc_object_alive(s))
1637 if (p_sys->download.seek >= 0)
1639 p_sys->download.segment = p_sys->download.seek;
1640 p_sys->download.seek = -1;
1642 vlc_mutex_unlock(&p_sys->download.lock_wait);
1645 if (!vlc_object_alive(s)) break;
1647 vlc_mutex_lock(&hls->lock);
1648 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1649 vlc_mutex_unlock(&hls->lock);
1651 if ((segment != NULL) &&
1652 (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1654 if (!vlc_object_alive(s)) break;
1658 p_sys->b_error = true;
1663 /* download succeeded */
1664 /* determine next segment to download */
1665 vlc_mutex_lock(&p_sys->download.lock_wait);
1666 if (p_sys->download.seek >= 0)
1668 p_sys->download.segment = p_sys->download.seek;
1669 p_sys->download.seek = -1;
1671 else if (p_sys->download.segment < count)
1672 p_sys->download.segment++;
1673 vlc_cond_signal(&p_sys->download.wait);
1674 vlc_mutex_unlock(&p_sys->download.lock_wait);
1677 vlc_restorecancel(canc);
1681 static void* hls_Reload(void *p_this)
1683 stream_t *s = (stream_t *)p_this;
1684 stream_sys_t *p_sys = s->p_sys;
1686 assert(p_sys->b_live);
1688 int canc = vlc_savecancel();
1691 while (vlc_object_alive(s))
1693 mtime_t now = mdate();
1694 if (now >= p_sys->playlist.wakeup)
1696 /* reload the m3u8 */
1697 if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1699 /* No change in playlist, then backoff */
1700 p_sys->playlist.tries++;
1701 if (p_sys->playlist.tries == 1) wait = 0.5;
1702 else if (p_sys->playlist.tries == 2) wait = 1;
1703 else if (p_sys->playlist.tries >= 3) wait = 2;
1705 /* Can we afford to backoff? */
1706 if (p_sys->download.segment - p_sys->playback.segment < 3)
1708 p_sys->playlist.tries = 0;
1714 p_sys->playlist.tries = 0;
1718 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1721 /* determine next time to update playlist */
1722 p_sys->playlist.last = now;
1723 p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1724 * (mtime_t)1000000);
1727 mwait(p_sys->playlist.wakeup);
1730 vlc_restorecancel(canc);
1734 static int Prefetch(stream_t *s, int *current)
1736 stream_sys_t *p_sys = s->p_sys;
1737 int stream = *current;
1739 hls_stream_t *hls = hls_Get(p_sys->hls_stream, stream);
1741 return VLC_EGENERIC;
1743 /* Download first 2 segments of this HLS stream */
1744 for (int i = 0; i < 2; i++)
1746 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1747 if (segment == NULL )
1748 return VLC_EGENERIC;
1750 /* It is useless to lock the segment here, as Prefetch is called before
1751 download and playlit thread are started. */
1754 p_sys->download.segment++;
1758 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1759 return VLC_EGENERIC;
1761 p_sys->download.segment++;
1763 /* adapt bandwidth? */
1764 if (*current != stream)
1766 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1768 return VLC_EGENERIC;
1777 /****************************************************************************
1779 ****************************************************************************/
1780 static int hls_Download(stream_t *s, segment_t *segment)
1785 char *psz_url = ConstructUrl(&segment->url);
1786 if (psz_url == NULL)
1789 stream_t *p_ts = stream_UrlNew(s, psz_url);
1792 return VLC_EGENERIC;
1794 segment->size = stream_Size(p_ts);
1795 assert(segment->size > 0);
1797 segment->data = block_Alloc(segment->size);
1798 if (segment->data == NULL)
1800 stream_Delete(p_ts);
1804 assert(segment->data->i_buffer == segment->size);
1806 ssize_t length = 0, curlen = 0;
1810 size = stream_Size(p_ts);
1811 if (size > segment->size)
1813 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1814 block_t *p_block = block_Realloc(segment->data, 0, size);
1815 if (p_block == NULL)
1817 stream_Delete(p_ts);
1818 block_Release(segment->data);
1819 segment->data = NULL;
1822 segment->data = p_block;
1823 segment->size = size;
1824 assert(segment->data->i_buffer == segment->size);
1827 length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1831 } while (vlc_object_alive(s));
1833 stream_Delete(p_ts);
1837 /* Read M3U8 file */
1838 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1840 int64_t total_bytes = 0;
1841 int64_t total_allocated = 0;
1849 bytes = stream_Read(s, buf, sizeof(buf));
1855 if ( (total_bytes + bytes + 1) > total_allocated )
1857 if (total_allocated)
1858 total_allocated *= 2;
1860 total_allocated = __MIN((uint64_t)bytes+1, sizeof(buf));
1862 p = realloc_or_free(p, total_allocated);
1867 memcpy(p+total_bytes, buf, bytes);
1868 total_bytes += bytes;
1871 if (total_allocated == 0)
1872 return VLC_EGENERIC;
1874 p[total_bytes] = '\0';
1880 static ssize_t read_M3U8_from_url(stream_t *s, vlc_url_t *url, uint8_t **buffer)
1882 assert(*buffer == NULL);
1885 char *psz_url = ConstructUrl(url);
1886 if (psz_url == NULL)
1889 stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1892 return VLC_EGENERIC;
1894 ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1895 stream_Delete(p_m3u8);
1900 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1905 uint8_t *begin = buffer;
1907 uint8_t *end = p + len;
1911 if ((*p == '\n') || (*p == '\0'))
1916 /* copy line excluding \n or \0 */
1917 line = strndup((char *)begin, p - begin);
1923 /* next pass start after \n */
1931 /****************************************************************************
1933 ****************************************************************************/
1934 static int Open(vlc_object_t *p_this)
1936 stream_t *s = (stream_t*)p_this;
1937 stream_sys_t *p_sys;
1939 if (!isHTTPLiveStreaming(s))
1940 return VLC_EGENERIC;
1942 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1944 /* Initialize crypto bit */
1948 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1952 char *psz_uri = NULL;
1953 if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1958 vlc_UrlParse(&p_sys->m3u8, psz_uri, 0);
1961 p_sys->bandwidth = 0;
1962 p_sys->b_live = true;
1963 p_sys->b_meta = false;
1964 p_sys->b_error = false;
1966 p_sys->hls_stream = vlc_array_new();
1967 if (p_sys->hls_stream == NULL)
1969 vlc_UrlClean(&p_sys->m3u8);
1977 s->pf_control = Control;
1979 /* Parse HLS m3u8 content. */
1980 uint8_t *buffer = NULL;
1981 ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1984 if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
1990 /* HLS standard doesn't provide any guaranty about streams
1991 being sorted by bandwidth, so we sort them */
1992 qsort( p_sys->hls_stream->pp_elems, p_sys->hls_stream->i_count,
1993 sizeof( hls_stream_t* ), &hls_CompareStreams );
1995 /* Choose first HLS stream to start with */
1996 int current = p_sys->playback.stream = 0;
1997 p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
1999 /* manage encryption key if needed */
2000 hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
2002 if (p_sys->b_live && (p_sys->playback.segment < 0))
2004 msg_Warn(s, "less data than 3 times 'target duration' available for live playback, playback may stall");
2007 if (Prefetch(s, ¤t) != VLC_SUCCESS)
2009 msg_Err(s, "fetching first segment failed.");
2013 p_sys->download.stream = current;
2014 p_sys->playback.stream = current;
2015 p_sys->download.seek = -1;
2017 vlc_mutex_init(&p_sys->download.lock_wait);
2018 vlc_cond_init(&p_sys->download.wait);
2020 /* Initialize HLS live stream */
2023 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
2024 p_sys->playlist.last = mdate();
2025 p_sys->playlist.wakeup = p_sys->playlist.last +
2026 ((mtime_t)hls->duration * UINT64_C(1000000));
2028 if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
2034 if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
2037 vlc_join(p_sys->reload, NULL);
2044 vlc_mutex_destroy(&p_sys->download.lock_wait);
2045 vlc_cond_destroy(&p_sys->download.wait);
2048 /* Free hls streams */
2049 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2051 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
2052 if (hls) hls_Free(hls);
2054 vlc_array_destroy(p_sys->hls_stream);
2057 vlc_UrlClean(&p_sys->m3u8);
2059 return VLC_EGENERIC;
2062 /****************************************************************************
2064 ****************************************************************************/
2065 static void Close(vlc_object_t *p_this)
2067 stream_t *s = (stream_t*)p_this;
2068 stream_sys_t *p_sys = s->p_sys;
2070 assert(p_sys->hls_stream);
2073 vlc_mutex_lock(&p_sys->download.lock_wait);
2074 vlc_cond_signal(&p_sys->download.wait);
2075 vlc_mutex_unlock(&p_sys->download.lock_wait);
2079 vlc_join(p_sys->reload, NULL);
2080 vlc_join(p_sys->thread, NULL);
2081 vlc_mutex_destroy(&p_sys->download.lock_wait);
2082 vlc_cond_destroy(&p_sys->download.wait);
2084 /* Free hls streams */
2085 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2087 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
2088 if (hls) hls_Free(hls);
2090 vlc_array_destroy(p_sys->hls_stream);
2093 vlc_UrlClean(&p_sys->m3u8);
2095 block_Release (p_sys->peeked);
2099 /****************************************************************************
2100 * Stream filters functions
2101 ****************************************************************************/
2102 static segment_t *GetSegment(stream_t *s)
2104 stream_sys_t *p_sys = s->p_sys;
2105 segment_t *segment = NULL;
2107 /* Is this segment of the current HLS stream ready? */
2108 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2111 vlc_mutex_lock(&hls->lock);
2112 segment = segment_GetSegment(hls, p_sys->playback.segment);
2113 if (segment != NULL)
2115 /* This segment is ready? */
2116 if (segment->data != NULL)
2118 p_sys->b_cache = hls->b_cache;
2119 vlc_mutex_unlock(&hls->lock);
2123 vlc_mutex_unlock(&hls->lock);
2126 /* Was the HLS stream changed to another bitrate? */
2128 for (int i_stream = 0; i_stream < vlc_array_count(p_sys->hls_stream); i_stream++)
2130 /* Is the next segment ready */
2131 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2135 vlc_mutex_lock(&hls->lock);
2136 segment = segment_GetSegment(hls, p_sys->playback.segment);
2137 if (segment == NULL)
2139 vlc_mutex_unlock(&hls->lock);
2143 vlc_mutex_lock(&p_sys->download.lock_wait);
2144 int i_segment = p_sys->download.segment;
2145 vlc_mutex_unlock(&p_sys->download.lock_wait);
2147 /* This segment is ready? */
2148 if ((segment->data != NULL) &&
2149 (p_sys->playback.segment < i_segment))
2151 p_sys->playback.stream = i_stream;
2152 p_sys->b_cache = hls->b_cache;
2153 vlc_mutex_unlock(&hls->lock);
2156 vlc_mutex_unlock(&hls->lock);
2166 assert(segment->data);
2167 if (segment->data->i_buffer == 0)
2169 vlc_mutex_lock(&hls->lock);
2170 int count = vlc_array_count(hls->segments);
2171 vlc_mutex_unlock(&hls->lock);
2173 if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2174 ((count != p_sys->download.segment) || p_sys->b_live))
2175 msg_Err(s, "playback will stall");
2176 else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2177 ((count != p_sys->download.segment) || p_sys->b_live))
2178 msg_Warn(s, "playback in danger of stalling");
2183 static int segment_RestorePos(segment_t *segment)
2187 uint64_t size = segment->size - segment->data->i_buffer;
2190 segment->data->i_buffer += size;
2191 segment->data->p_buffer -= size;
2197 /* p_read might be NULL if caller wants to skip data */
2198 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2200 stream_sys_t *p_sys = s->p_sys;
2205 /* Determine next segment to read. If this is a meta playlist and
2206 * bandwidth conditions changed, then the stream might have switched
2207 * to another bandwidth. */
2208 segment_t *segment = GetSegment(s);
2209 if (segment == NULL)
2212 vlc_mutex_lock(&segment->lock);
2213 if (segment->data->i_buffer == 0)
2215 if (!p_sys->b_cache || p_sys->b_live)
2217 block_Release(segment->data);
2218 segment->data = NULL;
2221 segment_RestorePos(segment);
2223 p_sys->playback.segment++;
2224 vlc_mutex_unlock(&segment->lock);
2226 /* signal download thread */
2227 vlc_mutex_lock(&p_sys->download.lock_wait);
2228 vlc_cond_signal(&p_sys->download.wait);
2229 vlc_mutex_unlock(&p_sys->download.lock_wait);
2233 if (segment->size == segment->data->i_buffer)
2234 msg_Info(s, "playing segment %d from stream %d",
2235 segment->sequence, p_sys->playback.stream);
2238 if (i_read <= segment->data->i_buffer)
2240 else if (i_read > segment->data->i_buffer)
2241 len = segment->data->i_buffer;
2245 if (p_read) /* if NULL, then caller skips data */
2246 memcpy(p_read + used, segment->data->p_buffer, len);
2247 segment->data->i_buffer -= len;
2248 segment->data->p_buffer += len;
2252 vlc_mutex_unlock(&segment->lock);
2254 } while (i_read > 0);
2259 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2261 stream_sys_t *p_sys = s->p_sys;
2264 assert(p_sys->hls_stream);
2269 /* NOTE: buffer might be NULL if caller wants to skip data */
2270 length = hls_Read(s, (uint8_t*) buffer, i_read);
2274 p_sys->playback.offset += length;
2278 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2280 stream_sys_t *p_sys = s->p_sys;
2282 unsigned int len = i_peek;
2284 segment = GetSegment(s);
2285 if (segment == NULL)
2287 msg_Err(s, "segment %d should have been available (stream %d)",
2288 p_sys->playback.segment, p_sys->playback.stream);
2289 return 0; /* eof? */
2292 vlc_mutex_lock(&segment->lock);
2294 size_t i_buff = segment->data->i_buffer;
2295 uint8_t *p_buff = segment->data->p_buffer;
2297 if (i_peek < i_buff)
2300 vlc_mutex_unlock(&segment->lock);
2304 else /* This will seldom be run */
2306 /* remember segment to read */
2307 int peek_segment = p_sys->playback.segment;
2309 segment_t *nsegment;
2310 p_sys->playback.segment++;
2311 block_t *peeked = p_sys->peeked;
2314 peeked = block_Alloc (i_peek);
2315 else if (peeked->i_buffer < i_peek)
2316 peeked = block_Realloc (peeked, 0, i_peek);
2320 memcpy(peeked->p_buffer, p_buff, i_buff);
2323 vlc_mutex_unlock(&segment->lock);
2325 i_buff = peeked->i_buffer;
2326 p_buff = peeked->p_buffer;
2329 while (curlen < i_peek)
2331 nsegment = GetSegment(s);
2332 if (nsegment == NULL)
2334 msg_Err(s, "segment %d should have been available (stream %d)",
2335 p_sys->playback.segment, p_sys->playback.stream);
2336 /* restore segment to read */
2337 p_sys->playback.segment = peek_segment;
2338 return curlen; /* eof? */
2341 vlc_mutex_lock(&nsegment->lock);
2343 if (len < nsegment->data->i_buffer)
2345 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2350 size_t i_nbuff = nsegment->data->i_buffer;
2351 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2355 p_sys->playback.segment++;
2358 vlc_mutex_unlock(&nsegment->lock);
2361 /* restore segment to read */
2362 p_sys->playback.segment = peek_segment;
2367 static bool hls_MaySeek(stream_t *s)
2369 stream_sys_t *p_sys = s->p_sys;
2371 if (p_sys->hls_stream == NULL)
2374 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2375 if (hls == NULL) return false;
2379 vlc_mutex_lock(&hls->lock);
2380 int count = vlc_array_count(hls->segments);
2381 vlc_mutex_unlock(&hls->lock);
2383 vlc_mutex_lock(&p_sys->download.lock_wait);
2384 bool may_seek = (p_sys->download.segment < (count - 2));
2385 vlc_mutex_unlock(&p_sys->download.lock_wait);
2391 static uint64_t GetStreamSize(stream_t *s)
2393 stream_sys_t *p_sys = s->p_sys;
2398 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2399 if (hls == NULL) return 0;
2401 vlc_mutex_lock(&hls->lock);
2403 hls->size = hls_GetStreamSize(hls);
2404 uint64_t size = hls->size;
2405 vlc_mutex_unlock(&hls->lock);
2410 static int segment_Seek(stream_t *s, const uint64_t pos)
2412 stream_sys_t *p_sys = s->p_sys;
2414 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2416 return VLC_EGENERIC;
2418 vlc_mutex_lock(&hls->lock);
2420 bool b_found = false;
2421 uint64_t length = 0;
2422 uint64_t size = hls->size;
2423 int count = vlc_array_count(hls->segments);
2425 /* restore current segment to start position */
2426 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2427 if (segment == NULL)
2429 vlc_mutex_unlock(&hls->lock);
2430 return VLC_EGENERIC;
2432 vlc_mutex_lock(&segment->lock);
2433 segment_RestorePos(segment);
2434 vlc_mutex_unlock(&segment->lock);
2436 for (int n = 0; n < count; n++)
2438 segment_t *segment = segment_GetSegment(hls, n);
2439 if (segment == NULL)
2441 vlc_mutex_unlock(&hls->lock);
2442 return VLC_EGENERIC;
2445 vlc_mutex_lock(&segment->lock);
2446 length += segment->duration * (hls->bandwidth/8);
2447 vlc_mutex_unlock(&segment->lock);
2449 if (!b_found && (pos <= length))
2453 p_sys->playback.segment = n;
2457 /* Do not search in last 3 segments */
2458 vlc_mutex_unlock(&hls->lock);
2459 return VLC_EGENERIC;
2464 if (!b_found && (pos >= size))
2466 p_sys->playback.segment = count - 1;
2473 /* restore segment to start position */
2474 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2475 if (segment == NULL)
2477 vlc_mutex_unlock(&hls->lock);
2478 return VLC_EGENERIC;
2481 vlc_mutex_lock(&segment->lock);
2482 segment_RestorePos(segment);
2483 vlc_mutex_unlock(&segment->lock);
2485 /* start download at current playback segment */
2486 vlc_mutex_unlock(&hls->lock);
2488 /* Wake up download thread */
2489 vlc_mutex_lock(&p_sys->download.lock_wait);
2490 p_sys->download.seek = p_sys->playback.segment;
2491 vlc_cond_signal(&p_sys->download.wait);
2492 vlc_mutex_unlock(&p_sys->download.lock_wait);
2494 /* Wait for download to be finished */
2495 vlc_mutex_lock(&p_sys->download.lock_wait);
2496 msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2497 while (((p_sys->download.seek != -1) ||
2498 (p_sys->download.segment - p_sys->playback.segment < 3)) &&
2499 (p_sys->download.segment < (count - 6)))
2501 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2502 if (!vlc_object_alive(s) || s->b_error) break;
2504 vlc_mutex_unlock(&p_sys->download.lock_wait);
2508 vlc_mutex_unlock(&hls->lock);
2510 return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2513 static int Control(stream_t *s, int i_query, va_list args)
2515 stream_sys_t *p_sys = s->p_sys;
2519 case STREAM_CAN_SEEK:
2520 *(va_arg (args, bool *)) = hls_MaySeek(s);
2522 case STREAM_GET_POSITION:
2523 *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2525 case STREAM_SET_POSITION:
2528 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2529 if (segment_Seek(s, pos) == VLC_SUCCESS)
2531 p_sys->playback.offset = pos;
2535 return VLC_EGENERIC;
2536 case STREAM_GET_SIZE:
2537 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2540 return VLC_EGENERIC;