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 it
10 * under the terms of the GNU Lesser General Public License as published by
11 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this program; if not, write to the Free Software Foundation,
21 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
40 #include <vlc_threads.h>
41 #include <vlc_arrays.h>
42 #include <vlc_stream.h>
43 #include <vlc_memory.h>
44 #include <vlc_gcrypt.h>
46 /*****************************************************************************
48 *****************************************************************************/
49 static int Open (vlc_object_t *);
50 static void Close(vlc_object_t *);
53 set_category(CAT_INPUT)
54 set_subcategory(SUBCAT_INPUT_STREAM_FILTER)
55 set_description(N_("Http Live Streaming stream filter"))
56 set_capability("stream_filter", 20)
57 set_callbacks(Open, Close)
60 /*****************************************************************************
62 *****************************************************************************/
63 #define AES_BLOCK_SIZE 16 /* Only support AES-128 */
64 typedef struct segment_s
66 int sequence; /* unique sequence number */
67 int duration; /* segment duration (seconds) */
68 uint64_t size; /* segment size in bytes */
69 uint64_t bandwidth; /* bandwidth usage of segments (bits per second)*/
72 char *psz_key_path; /* url key path */
73 uint8_t aes_key[16]; /* AES-128 */
77 block_t *data; /* data */
80 typedef struct hls_stream_s
82 int id; /* program id */
83 int version; /* protocol version should be 1 */
84 int sequence; /* media sequence number */
85 int duration; /* maximum duration per segment (s) */
86 uint64_t bandwidth; /* bandwidth usage of segments (bits per second)*/
87 uint64_t size; /* stream length is calculated by taking the sum
88 foreach segment of (segment->duration * hls->bandwidth/8) */
90 vlc_array_t *segments; /* list of segments */
91 char *url; /* uri to m3u8 */
93 bool b_cache; /* allow caching */
95 char *psz_current_key_path; /* URL path of the encrypted key */
96 uint8_t psz_AES_IV[AES_BLOCK_SIZE]; /* IV used when decypher the block */
102 char *m3u8; /* M3U8 url */
103 vlc_thread_t reload; /* HLS m3u8 reload thread */
104 vlc_thread_t thread; /* HLS segment download thread */
109 vlc_array_t *hls_stream; /* bandwidth adaptation */
110 uint64_t bandwidth; /* measured bandwidth (bits per second) */
113 struct hls_download_s
115 int stream; /* current hls_stream */
116 int segment; /* current segment for downloading */
117 int seek; /* segment requested by seek (default -1) */
118 vlc_mutex_t lock_wait; /* protect segment download counter */
119 vlc_cond_t wait; /* some condition to wait on */
123 struct hls_playback_s
125 uint64_t offset; /* current offset in media */
126 int stream; /* current hls_stream */
127 int segment; /* current segment for playback */
131 struct hls_playlist_s
133 mtime_t last; /* playlist last loaded */
134 mtime_t wakeup; /* next reload time */
135 int tries; /* times it was not changed */
139 bool b_cache; /* can cache files */
140 bool b_meta; /* meta playlist */
141 bool b_live; /* live stream? or vod? */
142 bool b_error; /* parsing error */
143 bool b_aesmsg; /* only print one time that the media is encrypted */
146 /****************************************************************************
148 ****************************************************************************/
149 static int Read (stream_t *, void *p_read, unsigned int i_read);
150 static int Peek (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
151 static int Control(stream_t *, int i_query, va_list);
153 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer);
154 static ssize_t read_M3U8_from_url(stream_t *s, const char *psz_url, uint8_t **buffer);
155 static char *ReadLine(uint8_t *buffer, uint8_t **pos, size_t len);
157 static int hls_Download(stream_t *s, segment_t *segment);
159 static void* hls_Thread(void *);
160 static void* hls_Reload(void *);
162 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted);
163 static void segment_Free(segment_t *segment);
165 /****************************************************************************
167 ****************************************************************************/
168 static bool isHTTPLiveStreaming(stream_t *s)
172 int size = stream_Peek(s->p_source, &peek, 46);
176 if (memcmp(peek, "#EXTM3U", 7) != 0)
182 /* Parse stream and search for
183 * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
184 * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
187 static const char *const ext[] = {
204 if (memcmp(peek, "EXT-X-", 6))
210 for (size_t i = 0; i < ARRAY_SIZE(ext); i++)
212 size_t len = strlen(ext[i]);
213 if (size < 0 || (size_t)size < len)
215 if (!memcmp(peek, ext[i], len))
223 /* HTTP Live Streaming */
224 static hls_stream_t *hls_New(vlc_array_t *hls_stream, const int id, const uint64_t bw, const char *uri)
226 hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
227 if (hls == NULL) return NULL;
231 hls->duration = -1;/* unknown */
233 hls->sequence = 0; /* default is 0 */
234 hls->version = 1; /* default protocol version */
236 hls->url = strdup(uri);
237 if (hls->url == NULL)
242 hls->psz_current_key_path = NULL;
243 hls->segments = vlc_array_new();
244 vlc_array_append(hls_stream, hls);
245 vlc_mutex_init(&hls->lock);
249 static void hls_Free(hls_stream_t *hls)
251 vlc_mutex_destroy(&hls->lock);
255 for (int n = 0; n < vlc_array_count(hls->segments); n++)
257 segment_t *segment = segment_GetSegment(hls, n);
258 if (segment) segment_Free(segment);
260 vlc_array_destroy(hls->segments);
263 free(hls->psz_current_key_path);
267 static hls_stream_t *hls_Copy(hls_stream_t *src, const bool b_cp_segments)
270 assert(!b_cp_segments); /* FIXME: copying segments is not implemented */
272 hls_stream_t *dst = (hls_stream_t *)malloc(sizeof(hls_stream_t));
273 if (dst == NULL) return NULL;
276 dst->bandwidth = src->bandwidth;
277 dst->duration = src->duration;
278 dst->size = src->size;
279 dst->sequence = src->sequence;
280 dst->version = src->version;
281 dst->b_cache = src->b_cache;
282 dst->psz_current_key_path = src->psz_current_key_path ?
283 strdup( src->psz_current_key_path ) : NULL;
284 dst->url = strdup(src->url);
285 if (dst->url == NULL)
291 dst->segments = vlc_array_new();
292 vlc_mutex_init(&dst->lock);
296 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, const int wanted)
298 int count = vlc_array_count(hls_stream);
301 if ((wanted < 0) || (wanted >= count))
303 return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
306 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
308 return hls_Get(hls_stream, 0);
311 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
313 int count = vlc_array_count(hls_stream);
317 return hls_Get(hls_stream, count);
320 static hls_stream_t *hls_Find(vlc_array_t *hls_stream, hls_stream_t *hls_new)
322 int count = vlc_array_count(hls_stream);
323 for (int n = 0; n < count; n++)
325 hls_stream_t *hls = hls_Get(hls_stream, n);
329 if ((hls->id == hls_new->id) &&
330 ((hls->bandwidth == hls_new->bandwidth)||(hls_new->bandwidth==0)))
337 static uint64_t hls_GetStreamSize(hls_stream_t *hls)
339 /* NOTE: Stream size is calculated based on segment duration and
340 * HLS stream bandwidth from the .m3u8 file. If these are not correct
341 * then the deviation from exact byte size will be big and the seek/
342 * progressbar will not behave entirely as one expects. */
345 /* If there is no valid bandwidth yet, then there is no point in
346 * computing stream size. */
347 if (hls->bandwidth == 0)
350 int count = vlc_array_count(hls->segments);
351 for (int n = 0; n < count; n++)
353 segment_t *segment = segment_GetSegment(hls, n);
356 size += (segment->duration * (hls->bandwidth / 8));
363 static segment_t *segment_New(hls_stream_t* hls, const int duration, const char *uri)
365 segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
369 segment->duration = duration; /* seconds */
370 segment->size = 0; /* bytes */
371 segment->sequence = 0;
372 segment->bandwidth = 0;
373 segment->url = strdup(uri);
374 if (segment->url == NULL)
379 segment->data = NULL;
380 vlc_array_append(hls->segments, segment);
381 vlc_mutex_init(&segment->lock);
382 segment->b_key_loaded = false;
383 segment->psz_key_path = NULL;
384 if (hls->psz_current_key_path)
385 segment->psz_key_path = strdup(hls->psz_current_key_path);
389 static void segment_Free(segment_t *segment)
391 vlc_mutex_destroy(&segment->lock);
394 free(segment->psz_key_path);
396 block_Release(segment->data);
400 static segment_t *segment_GetSegment(hls_stream_t *hls, const int wanted)
404 int count = vlc_array_count(hls->segments);
407 if ((wanted < 0) || (wanted >= count))
409 return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
412 static segment_t *segment_Find(hls_stream_t *hls, const int sequence)
416 int count = vlc_array_count(hls->segments);
417 if (count <= 0) return NULL;
418 for (int n = 0; n < count; n++)
420 segment_t *segment = segment_GetSegment(hls, n);
421 if (segment == NULL) break;
422 if (segment->sequence == sequence)
428 static int ChooseSegment(stream_t *s, const int current)
430 stream_sys_t *p_sys = (stream_sys_t *)s->p_sys;
431 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
432 if (hls == NULL) return 0;
434 /* Choose a segment to start which is no closer than
435 * 3 times the target duration from the end of the playlist.
440 int count = vlc_array_count(hls->segments);
441 int i = p_sys->b_live ? count - 1 : 0;
443 while((i >= 0) && (i < count))
445 segment_t *segment = segment_GetSegment(hls, i);
448 if (segment->duration > hls->duration)
450 msg_Err(s, "EXTINF:%d duration is larger than EXT-X-TARGETDURATION:%d",
451 segment->duration, hls->duration);
454 duration += segment->duration;
455 if (duration >= 3 * hls->duration)
457 /* Start point found */
458 wanted = p_sys->b_live ? i : 0;
459 sequence = segment->sequence;
469 msg_Info(s, "Choose segment %d/%d (sequence=%d)", wanted, count, sequence);
474 static char *parse_Attributes(const char *line, const char *attr)
477 char *begin = (char *) line;
478 char *end = begin + strlen(line);
480 /* Find start of attributes */
481 if ((p = strchr(begin, ':' )) == NULL)
487 if (strncasecmp(begin, attr, strlen(attr)) == 0
488 && begin[strlen(attr)] == '=')
490 /* <attr>=<value>[,]* */
491 p = strchr(begin, ',');
492 begin += strlen(attr) + 1;
495 if (p == NULL) /* last attribute */
496 return strndup(begin, end - begin);
498 return strndup(begin, p - begin);
501 } while(begin < end);
506 static int string_to_IV(char *string_hexa, uint8_t iv[AES_BLOCK_SIZE])
508 unsigned long long iv_hi, iv_lo;
510 if (*string_hexa++ != '0')
512 if (*string_hexa != 'x' && *string_hexa != 'X')
517 size_t len = strlen(string_hexa);
520 iv_lo = strtoull(string_hexa, &end, 16);
524 iv_lo = strtoull(&string_hexa[len-16], NULL, 16);
527 string_hexa[len-16] = '\0';
528 iv_hi = strtoull(string_hexa, NULL, 16);
533 for (int i = 8; i ; --i) {
534 iv[ i] = iv_hi & 0xff;
535 iv[8+i] = iv_lo & 0xff;
543 static char *relative_URI(const char *psz_url, const char *psz_path)
545 assert(psz_url != NULL && psz_path != NULL);
546 //If the path is actually an absolute URL, don't do anything.
547 if (strncmp(psz_path, "http", 4) == 0)
550 char *path_end = strrchr(psz_url, '/');
551 if (path_end == NULL)
553 unsigned int url_length = path_end - psz_url + 1;
554 char *psz_res = malloc(url_length + strlen(psz_path) + 1);
555 strncpy(psz_res, psz_url, url_length);
556 psz_res[url_length] = 0;
557 strcat(psz_res, psz_path);
561 static int parse_SegmentInformation(hls_stream_t *hls, char *p_read, int *duration)
566 /* strip of #EXTINF: */
568 char *token = strtok_r(p_read, ":", &p_next);
573 token = strtok_r(NULL, ",", &p_next);
579 if (hls->version < 3)
582 value = strtol(token, &endptr, 10);
583 if (token == endptr || errno == ERANGE)
593 double d = strtof(token, &endptr);
594 if (token == endptr || errno == ERANGE)
599 if ((d) - ((int)d) >= 0.5)
600 value = ((int)d) + 1;
606 /* Ignore the rest of the line */
610 static int parse_AddSegment(hls_stream_t *hls, const int duration, const char *uri)
615 /* Store segment information */
616 vlc_mutex_lock(&hls->lock);
618 char *psz_uri = relative_URI(hls->url, uri);
620 segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
622 segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
625 vlc_mutex_unlock(&hls->lock);
627 return segment ? VLC_SUCCESS : VLC_ENOMEM;
630 static int parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
635 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
638 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
642 hls->duration = duration; /* seconds */
646 static int parse_StreamInformation(stream_t *s, vlc_array_t **hls_stream,
647 hls_stream_t **hls, char *p_read, const char *uri)
653 assert(*hls == NULL);
655 attr = parse_Attributes(p_read, "PROGRAM-ID");
658 msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
664 attr = parse_Attributes(p_read, "BANDWIDTH");
667 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
675 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
679 msg_Info(s, "bandwidth adaptation detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
681 char *psz_uri = relative_URI(s->p_sys->m3u8, uri);
683 *hls = hls_New(*hls_stream, id, bw, psz_uri ? psz_uri : uri);
687 return (*hls == NULL) ? VLC_ENOMEM : VLC_SUCCESS;
690 static int parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
695 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
698 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
702 if (hls->sequence > 0)
704 if (s->p_sys->b_live)
706 hls_stream_t *last = hls_GetLast(s->p_sys->hls_stream);
707 if ((last->sequence < sequence) && (sequence - last->sequence != 1))
708 msg_Err(s, "EXT-X-MEDIA-SEQUENCE gap in playlist (new=%d, old=%d)",
709 sequence, last->sequence);
712 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist (new=%d, old=%d)",
713 sequence, hls->sequence);
715 hls->sequence = sequence;
719 static int parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
723 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
724 int err = VLC_SUCCESS;
725 char *attr = parse_Attributes(p_read, "METHOD");
728 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
732 if (strncasecmp(attr, "NONE", 4) == 0)
734 char *uri = parse_Attributes(p_read, "URI");
737 msg_Err(s, "#EXT-X-KEY: URI not expected");
741 /* IV is only supported in version 2 and above */
742 if (hls->version >= 2)
744 char *iv = parse_Attributes(p_read, "IV");
747 msg_Err(s, "#EXT-X-KEY: IV not expected");
753 else if (strncasecmp(attr, "AES-128", 7) == 0)
755 char *value, *uri, *iv;
756 if (s->p_sys->b_aesmsg == false)
758 msg_Info(s, "playback of AES-128 encrypted HTTP Live media detected.");
759 s->p_sys->b_aesmsg = true;
761 value = uri = parse_Attributes(p_read, "URI");
764 msg_Err(s, "#EXT-X-KEY: URI not found for encrypted HTTP Live media in AES-128");
769 /* Url is put between quotes, remove them */
772 /* We need to strip the "" from the attribute value */
774 char* end = strchr(uri, '"');
778 hls->psz_current_key_path = strdup(uri);
781 value = iv = parse_Attributes(p_read, "IV");
785 * If the EXT-X-KEY tag does not have the IV attribute, implementations
786 * MUST use the sequence number of the media file as the IV when
787 * encrypting or decrypting that media file. The big-endian binary
788 * representation of the sequence number SHALL be placed in a 16-octet
789 * buffer and padded (on the left) with zeros.
791 hls->b_iv_loaded = false;
796 * If the EXT-X-KEY tag has the IV attribute, implementations MUST use
797 * the attribute value as the IV when encrypting or decrypting with that
798 * key. The value MUST be interpreted as a 128-bit hexadecimal number
799 * and MUST be prefixed with 0x or 0X.
802 if (string_to_IV(iv, hls->psz_AES_IV) == VLC_EGENERIC)
804 msg_Err(s, "IV invalid");
808 hls->b_iv_loaded = true;
814 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
821 static int parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
824 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
828 static int parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
832 char answer[4] = "\0";
833 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
836 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
840 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
844 static int parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
849 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
852 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
857 hls->version = version;
858 if (hls->version <= 0 || hls->version > 3)
860 msg_Err(s, "#EXT-X-VERSION should be version 1, 2 or 3 iso %d", version);
866 static int parse_EndList(stream_t *s, hls_stream_t *hls)
870 s->p_sys->b_live = false;
871 msg_Info(s, "video on demand (vod) mode");
875 static int parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
879 /* FIXME: Do we need to act on discontinuity ?? */
880 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
884 static int hls_CompareStreams( const void* a, const void* b )
886 hls_stream_t* stream_a = *(hls_stream_t**)a;
887 hls_stream_t* stream_b = *(hls_stream_t**)b;
888 return stream_a->bandwidth > stream_b->bandwidth;
891 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
892 * document defines the following new tags: EXT-X-TARGETDURATION,
893 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
894 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
897 static int parse_M3U8(stream_t *s, vlc_array_t *streams, uint8_t *buffer, const ssize_t len)
899 stream_sys_t *p_sys = s->p_sys;
900 uint8_t *p_read, *p_begin, *p_end;
905 msg_Dbg(s, "parse_M3U8\n%s", buffer);
907 p_end = p_begin + len;
909 char *line = ReadLine(p_begin, &p_read, p_end - p_begin);
914 if (strncmp(line, "#EXTM3U", 7) != 0)
916 msg_Err(s, "missing #EXTM3U tag .. aborting");
924 /* What is the version ? */
926 uint8_t *p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-VERSION:");
930 char *psz_version = ReadLine(p, &tmp, p_end - p);
931 if (psz_version == NULL)
933 int ret = sscanf((const char*)psz_version, "#EXT-X-VERSION:%d", &version);
936 msg_Warn(s, "#EXT-X-VERSION: no protocol version found, assuming version 1.");
943 /* Is it a live stream ? */
944 p_sys->b_live = (strstr((const char *)buffer, "#EXT-X-ENDLIST") == NULL) ? true : false;
946 /* Is it a meta index file ? */
947 bool b_meta = (strstr((const char *)buffer, "#EXT-X-STREAM-INF") == NULL) ? false : true;
949 int err = VLC_SUCCESS;
953 msg_Info(s, "Meta playlist");
955 /* M3U8 Meta Index file */
958 line = ReadLine(p_begin, &p_read, p_end - p_begin);
964 if (strncmp(line, "#EXT-X-STREAM-INF", 17) == 0)
966 p_sys->b_meta = true;
967 char *uri = ReadLine(p_begin, &p_read, p_end - p_begin);
974 msg_Info(s, "Skipping invalid stream-inf: %s", uri);
979 hls_stream_t *hls = NULL;
980 err = parse_StreamInformation(s, &streams, &hls, line, uri);
983 /* Download playlist file from server */
985 ssize_t len = read_M3U8_from_url(s, hls->url, &buf);
990 /* Parse HLS m3u8 content. */
991 err = parse_M3U8(s, streams, buf, len);
997 hls->version = version;
999 hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
1009 if (p_begin >= p_end)
1012 } while (err == VLC_SUCCESS);
1017 msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
1019 hls_stream_t *hls = NULL;
1021 hls = hls_GetLast(streams);
1024 /* No Meta playlist used */
1025 hls = hls_New(streams, 0, 0, p_sys->m3u8);
1028 /* Get TARGET-DURATION first */
1029 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1032 uint8_t *p_rest = NULL;
1033 char *psz_duration = ReadLine(p, &p_rest, p_end - p);
1034 if (psz_duration == NULL)
1035 return VLC_EGENERIC;
1036 err = parse_TargetDuration(s, hls, psz_duration);
1042 hls->version = version;
1044 else return VLC_ENOMEM;
1049 int segment_duration = -1;
1053 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1058 if (strncmp(line, "#EXTINF", 7) == 0)
1059 err = parse_SegmentInformation(hls, line, &segment_duration);
1060 else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1061 err = parse_TargetDuration(s, hls, line);
1062 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1063 err = parse_MediaSequence(s, hls, line);
1064 else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1065 err = parse_Key(s, hls, line);
1066 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1067 err = parse_ProgramDateTime(s, hls, line);
1068 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1069 err = parse_AllowCache(s, hls, line);
1070 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1071 err = parse_Discontinuity(s, hls, line);
1072 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1073 err = parse_Version(s, hls, line);
1074 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1075 err = parse_EndList(s, hls);
1076 else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1078 err = parse_AddSegment(hls, segment_duration, line);
1079 segment_duration = -1; /* reset duration */
1085 if (p_begin >= p_end)
1088 } while (err == VLC_SUCCESS);
1097 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1099 stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1102 msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1103 return VLC_EGENERIC;
1106 int len = stream_Read(p_m3u8, seg->aes_key, sizeof(seg->aes_key));
1107 stream_Delete(p_m3u8);
1108 if (len != AES_BLOCK_SIZE)
1110 msg_Err(s, "The AES key loaded doesn't have the right size (%d)", len);
1111 return VLC_EGENERIC;
1117 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1119 segment_t *seg = NULL;
1120 segment_t *prev_seg;
1121 int count = vlc_array_count(hls->segments);
1123 for (int i = 0; i < count; i++)
1126 seg = segment_GetSegment(hls, i);
1129 if (seg->psz_key_path == NULL)
1130 continue; /* No key to load ? continue */
1131 if (seg->b_key_loaded)
1132 continue; /* The key is already loaded */
1134 /* if the key has not changed, and already available from previous segment,
1135 * try to copy it, and don't load the key */
1136 if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1138 memcpy(seg->aes_key, prev_seg->aes_key, AES_BLOCK_SIZE);
1139 seg->b_key_loaded = true;
1142 if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1143 return VLC_EGENERIC;
1144 seg->b_key_loaded = true;
1149 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1151 /* Did the segment need to be decoded ? */
1152 if (segment->psz_key_path == NULL)
1155 /* Do we have loaded the key ? */
1156 if (!segment->b_key_loaded)
1158 /* No ? try to download it now */
1159 if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1160 return VLC_EGENERIC;
1163 /* For now, we only decode AES-128 data */
1164 gcry_error_t i_gcrypt_err;
1165 gcry_cipher_hd_t aes_ctx;
1167 i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1168 GCRY_CIPHER_MODE_CBC, 0);
1171 msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1172 gcry_cipher_close(aes_ctx);
1173 return VLC_EGENERIC;
1177 i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->aes_key,
1178 sizeof(segment->aes_key));
1181 msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1182 gcry_cipher_close(aes_ctx);
1183 return VLC_EGENERIC;
1186 if (hls->b_iv_loaded == false)
1188 memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1189 hls->psz_AES_IV[15] = segment->sequence & 0xff;
1190 hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1191 hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1192 hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1195 i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1196 sizeof(hls->psz_AES_IV));
1200 msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1201 gcry_cipher_close(aes_ctx);
1202 return VLC_EGENERIC;
1205 i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1206 segment->data->p_buffer, /* out */
1207 segment->data->i_buffer,
1212 msg_Err(s, "gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1213 gcry_cipher_close(aes_ctx);
1214 return VLC_EGENERIC;
1216 gcry_cipher_close(aes_ctx);
1217 /* remove the PKCS#7 padding from the buffer */
1218 int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1219 if (pad <= 0 || pad > AES_BLOCK_SIZE)
1221 msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1222 return VLC_EGENERIC;
1227 if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1229 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1230 return VLC_EGENERIC;
1234 /* not all the data is readable because of padding */
1235 segment->data->i_buffer -= pad;
1240 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1242 stream_sys_t *p_sys = s->p_sys;
1244 int err = VLC_EGENERIC;
1246 /* Duplicate HLS stream META information */
1247 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1249 hls_stream_t *src, *dst;
1250 src = hls_Get(p_sys->hls_stream, i);
1252 return VLC_EGENERIC;
1254 dst = hls_Copy(src, false);
1257 vlc_array_append(*streams, dst);
1259 /* Download playlist file from server */
1260 uint8_t *buf = NULL;
1261 ssize_t len = read_M3U8_from_url(s, dst->url, &buf);
1266 /* Parse HLS m3u8 content. */
1267 err = parse_M3U8(s, *streams, buf, len);
1274 /* Reload playlist */
1275 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t **hls)
1277 int count = vlc_array_count(hls_new->segments);
1279 msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1280 hls_new->id, hls_new->bandwidth, count);
1282 for (int n = 0; n < count; n++)
1284 segment_t *p = segment_GetSegment(hls_new, n);
1285 if (p == NULL) return VLC_EGENERIC;
1287 vlc_mutex_lock(&(*hls)->lock);
1288 segment_t *segment = segment_Find(*hls, p->sequence);
1291 vlc_mutex_lock(&segment->lock);
1294 assert(segment->url);
1296 /* they should be the same */
1297 if ((p->sequence != segment->sequence) ||
1298 (p->duration != segment->duration) ||
1299 (strcmp(p->url, segment->url) != 0))
1301 msg_Warn(s, "existing segment found with different content - resetting");
1302 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1303 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1304 msg_Warn(s, "- file: new=%s", p->url);
1305 msg_Warn(s, " old=%s", segment->url);
1307 /* Resetting content */
1308 segment->sequence = p->sequence;
1309 segment->duration = p->duration;
1311 segment->url = strdup(p->url);
1312 if ( segment->url == NULL )
1314 msg_Err(s, "Failed updating segment %d - skipping it", p->sequence);
1316 vlc_mutex_unlock(&segment->lock);
1319 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1320 if ((p->psz_key_path || p->b_key_loaded) &&
1323 block_Release(segment->data);
1324 segment->data = NULL;
1326 free(segment->psz_key_path);
1327 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1330 vlc_mutex_unlock(&segment->lock);
1334 int last = vlc_array_count((*hls)->segments) - 1;
1335 segment_t *l = segment_GetSegment(*hls, last);
1336 if (l == NULL) goto fail_and_unlock;
1338 if ((l->sequence + 1) != p->sequence)
1340 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1341 p->sequence, l->sequence+1);
1343 vlc_array_append((*hls)->segments, p);
1344 msg_Info(s, "- segment %d appended", p->sequence);
1346 vlc_mutex_unlock(&(*hls)->lock);
1349 /* update meta information */
1350 vlc_mutex_lock(&(*hls)->lock);
1351 (*hls)->sequence = hls_new->sequence;
1352 (*hls)->duration = (hls_new->duration == -1) ? (*hls)->duration : hls_new->duration;
1353 (*hls)->b_cache = hls_new->b_cache;
1354 vlc_mutex_unlock(&(*hls)->lock);
1359 vlc_mutex_unlock(&(*hls)->lock);
1360 return VLC_EGENERIC;
1363 static int hls_ReloadPlaylist(stream_t *s)
1365 stream_sys_t *p_sys = s->p_sys;
1367 vlc_array_t *hls_streams = vlc_array_new();
1368 if (hls_streams == NULL)
1371 msg_Info(s, "Reloading HLS live meta playlist");
1373 if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1375 /* Free hls streams */
1376 for (int i = 0; i < vlc_array_count(hls_streams); i++)
1379 hls = hls_Get(hls_streams, i);
1380 if (hls) hls_Free(hls);
1382 vlc_array_destroy(hls_streams);
1384 msg_Err(s, "reloading playlist failed");
1385 return VLC_EGENERIC;
1388 /* merge playlists */
1389 int count = vlc_array_count(hls_streams);
1390 for (int n = 0; n < count; n++)
1392 hls_stream_t *hls_new = hls_Get(hls_streams, n);
1393 if (hls_new == NULL)
1396 hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1397 if (hls_old == NULL)
1398 { /* new hls stream - append */
1399 vlc_array_append(p_sys->hls_stream, hls_new);
1400 msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1401 hls_new->id, hls_new->bandwidth);
1403 else if (hls_UpdatePlaylist(s, hls_new, &hls_old) != VLC_SUCCESS)
1404 msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1405 hls_new->id, hls_new->bandwidth);
1407 vlc_array_destroy(hls_streams);
1411 /****************************************************************************
1413 ****************************************************************************/
1414 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1416 stream_sys_t *p_sys = s->p_sys;
1418 uint64_t bw = *bandwidth;
1419 uint64_t bw_candidate = 0;
1421 int count = vlc_array_count(p_sys->hls_stream);
1422 for (int n = 0; n < count; n++)
1424 /* Select best bandwidth match */
1425 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1426 if (hls == NULL) break;
1428 /* only consider streams with the same PROGRAM-ID */
1429 if (hls->id == progid)
1431 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1433 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1434 n, bw, hls->bandwidth); /* bits / s */
1435 bw_candidate = hls->bandwidth;
1436 candidate = n; /* possible candidate */
1440 *bandwidth = bw_candidate;
1444 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1446 stream_sys_t *p_sys = s->p_sys;
1451 vlc_mutex_lock(&segment->lock);
1452 if (segment->data != NULL)
1454 /* Segment already downloaded */
1455 vlc_mutex_unlock(&segment->lock);
1459 /* sanity check - can we download this segment on time? */
1460 if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1462 uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1463 int estimated = (int)(size / p_sys->bandwidth);
1464 if (estimated > segment->duration)
1466 msg_Warn(s,"downloading of segment %d takes %ds, which is longer than its playback (%ds)",
1467 segment->sequence, estimated, segment->duration);
1471 mtime_t start = mdate();
1472 if (hls_Download(s, segment) != VLC_SUCCESS)
1474 msg_Err(s, "downloaded segment %d from stream %d failed",
1475 segment->sequence, *cur_stream);
1476 vlc_mutex_unlock(&segment->lock);
1477 return VLC_EGENERIC;
1479 mtime_t duration = mdate() - start;
1480 if (hls->bandwidth == 0 && segment->duration > 0)
1482 /* Try to estimate the bandwidth for this stream */
1483 hls->bandwidth = (uint64_t)(((double)segment->size * 8) / ((double)segment->duration));
1486 /* If the segment is encrypted, decode it */
1487 if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1489 vlc_mutex_unlock(&segment->lock);
1490 return VLC_EGENERIC;
1493 vlc_mutex_unlock(&segment->lock);
1495 msg_Info(s, "downloaded segment %d from stream %d",
1496 segment->sequence, *cur_stream);
1498 uint64_t bw = segment->size * 8 * 1000000 / __MAX(1, duration); /* bits / s */
1499 p_sys->bandwidth = bw;
1500 if (p_sys->b_meta && (hls->bandwidth != bw))
1502 int newstream = BandwidthAdaptation(s, hls->id, &bw);
1504 /* FIXME: we need an average here */
1505 if ((newstream >= 0) && (newstream != *cur_stream))
1507 msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1508 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1509 *cur_stream = newstream;
1515 static void* hls_Thread(void *p_this)
1517 stream_t *s = (stream_t *)p_this;
1518 stream_sys_t *p_sys = s->p_sys;
1520 int canc = vlc_savecancel();
1522 while (vlc_object_alive(s))
1524 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1527 /* Sliding window (~60 seconds worth of movie) */
1528 vlc_mutex_lock(&hls->lock);
1529 int count = vlc_array_count(hls->segments);
1530 vlc_mutex_unlock(&hls->lock);
1532 /* Is there a new segment to process? */
1533 if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1534 (p_sys->download.segment >= count))
1537 vlc_mutex_lock(&p_sys->download.lock_wait);
1538 while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1539 (p_sys->download.segment >= count)) &&
1540 (p_sys->download.seek == -1))
1542 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1543 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1545 if (!vlc_object_alive(s))
1549 if (p_sys->download.seek >= 0)
1551 p_sys->download.segment = p_sys->download.seek;
1552 p_sys->download.seek = -1;
1554 vlc_mutex_unlock(&p_sys->download.lock_wait);
1557 if (!vlc_object_alive(s)) break;
1559 vlc_mutex_lock(&hls->lock);
1560 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1561 vlc_mutex_unlock(&hls->lock);
1563 if ((segment != NULL) &&
1564 (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1566 if (!vlc_object_alive(s)) break;
1570 p_sys->b_error = true;
1575 /* download succeeded */
1576 /* determine next segment to download */
1577 vlc_mutex_lock(&p_sys->download.lock_wait);
1578 if (p_sys->download.seek >= 0)
1580 p_sys->download.segment = p_sys->download.seek;
1581 p_sys->download.seek = -1;
1583 else if (p_sys->download.segment < count)
1584 p_sys->download.segment++;
1585 vlc_cond_signal(&p_sys->download.wait);
1586 vlc_mutex_unlock(&p_sys->download.lock_wait);
1589 vlc_restorecancel(canc);
1593 static void* hls_Reload(void *p_this)
1595 stream_t *s = (stream_t *)p_this;
1596 stream_sys_t *p_sys = s->p_sys;
1598 assert(p_sys->b_live);
1600 int canc = vlc_savecancel();
1603 while (vlc_object_alive(s))
1605 mtime_t now = mdate();
1606 if (now >= p_sys->playlist.wakeup)
1608 /* reload the m3u8 */
1609 if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1611 /* No change in playlist, then backoff */
1612 p_sys->playlist.tries++;
1613 if (p_sys->playlist.tries == 1) wait = 0.5;
1614 else if (p_sys->playlist.tries == 2) wait = 1;
1615 else if (p_sys->playlist.tries >= 3) wait = 2;
1617 /* Can we afford to backoff? */
1618 if (p_sys->download.segment - p_sys->playback.segment < 3)
1620 p_sys->playlist.tries = 0;
1626 p_sys->playlist.tries = 0;
1630 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1633 /* determine next time to update playlist */
1634 p_sys->playlist.last = now;
1635 p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1636 * (mtime_t)1000000);
1639 mwait(p_sys->playlist.wakeup);
1642 vlc_restorecancel(canc);
1646 static int Prefetch(stream_t *s, int *current)
1648 stream_sys_t *p_sys = s->p_sys;
1649 int stream = *current;
1651 hls_stream_t *hls = hls_Get(p_sys->hls_stream, stream);
1653 return VLC_EGENERIC;
1655 if (vlc_array_count(hls->segments) == 0)
1656 return VLC_EGENERIC;
1657 else if (vlc_array_count(hls->segments) == 1 && p_sys->b_live)
1658 msg_Warn(s, "Only 1 segment available to prefetch in live stream; may stall");
1660 /* Download first 2 segments of this HLS stream if they exist */
1661 for (int i = 0; i < __MIN(vlc_array_count(hls->segments), 2); i++)
1663 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1664 if (segment == NULL )
1665 return VLC_EGENERIC;
1667 /* It is useless to lock the segment here, as Prefetch is called before
1668 download and playlit thread are started. */
1671 p_sys->download.segment++;
1675 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1676 return VLC_EGENERIC;
1678 p_sys->download.segment++;
1680 /* adapt bandwidth? */
1681 if (*current != stream)
1683 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1685 return VLC_EGENERIC;
1694 /****************************************************************************
1696 ****************************************************************************/
1697 static int hls_Download(stream_t *s, segment_t *segment)
1701 stream_t *p_ts = stream_UrlNew(s, segment->url);
1703 return VLC_EGENERIC;
1705 segment->size = stream_Size(p_ts);
1706 assert(segment->size > 0);
1708 segment->data = block_Alloc(segment->size);
1709 if (segment->data == NULL)
1711 stream_Delete(p_ts);
1715 assert(segment->data->i_buffer == segment->size);
1717 ssize_t length = 0, curlen = 0;
1721 /* NOTE: Beware the size reported for a segment by the HLS server may not
1722 * be correct, when downloading the segment data. Therefore check the size
1723 * and enlarge the segment data block if necessary.
1725 size = stream_Size(p_ts);
1726 if (size > segment->size)
1728 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1729 block_t *p_block = block_Realloc(segment->data, 0, size);
1730 if (p_block == NULL)
1732 stream_Delete(p_ts);
1733 block_Release(segment->data);
1734 segment->data = NULL;
1737 segment->data = p_block;
1738 segment->size = size;
1739 assert(segment->data->i_buffer == segment->size);
1742 length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1746 } while (vlc_object_alive(s));
1748 stream_Delete(p_ts);
1752 /* Read M3U8 file */
1753 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1755 int64_t total_bytes = 0;
1756 int64_t total_allocated = 0;
1764 bytes = stream_Read(s, buf, sizeof(buf));
1770 if ( (total_bytes + bytes + 1) > total_allocated )
1772 if (total_allocated)
1773 total_allocated *= 2;
1775 total_allocated = __MIN((uint64_t)bytes+1, sizeof(buf));
1777 p = realloc_or_free(p, total_allocated);
1782 memcpy(p+total_bytes, buf, bytes);
1783 total_bytes += bytes;
1786 if (total_allocated == 0)
1787 return VLC_EGENERIC;
1789 p[total_bytes] = '\0';
1795 static ssize_t read_M3U8_from_url(stream_t *s, const char* psz_url, uint8_t **buffer)
1797 assert(*buffer == NULL);
1800 stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1802 return VLC_EGENERIC;
1804 ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1805 stream_Delete(p_m3u8);
1810 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1815 uint8_t *begin = buffer;
1817 uint8_t *end = p + len;
1821 if ((*p == '\r') || (*p == '\n') || (*p == '\0'))
1826 /* copy line excluding \r \n or \0 */
1827 line = strndup((char *)begin, p - begin);
1829 while ((*p == '\r') || (*p == '\n') || (*p == '\0'))
1838 /* next pass start after \r and \n */
1847 /****************************************************************************
1849 ****************************************************************************/
1850 static int Open(vlc_object_t *p_this)
1852 stream_t *s = (stream_t*)p_this;
1853 stream_sys_t *p_sys;
1855 if (!isHTTPLiveStreaming(s))
1856 return VLC_EGENERIC;
1858 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1860 /* Initialize crypto bit */
1864 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1868 char *psz_uri = NULL;
1869 if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1874 p_sys->m3u8 = psz_uri;
1877 if (asprintf(&new_path, "%s.ts", s->psz_path) < 0)
1884 s->psz_path = new_path;
1886 p_sys->bandwidth = 0;
1887 p_sys->b_live = true;
1888 p_sys->b_meta = false;
1889 p_sys->b_error = false;
1891 p_sys->hls_stream = vlc_array_new();
1892 if (p_sys->hls_stream == NULL)
1902 s->pf_control = Control;
1904 /* Parse HLS m3u8 content. */
1905 uint8_t *buffer = NULL;
1906 ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1909 if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
1915 /* HLS standard doesn't provide any guaranty about streams
1916 being sorted by bandwidth, so we sort them */
1917 qsort( p_sys->hls_stream->pp_elems, p_sys->hls_stream->i_count,
1918 sizeof( hls_stream_t* ), &hls_CompareStreams );
1920 /* Choose first HLS stream to start with */
1921 int current = p_sys->playback.stream = 0;
1922 p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
1924 /* manage encryption key if needed */
1925 hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
1927 if (p_sys->b_live && (p_sys->playback.segment < 0))
1929 msg_Warn(s, "less data than 3 times 'target duration' available for live playback, playback may stall");
1932 if (Prefetch(s, ¤t) != VLC_SUCCESS)
1934 msg_Err(s, "fetching first segment failed.");
1938 p_sys->download.stream = current;
1939 p_sys->playback.stream = current;
1940 p_sys->download.seek = -1;
1942 vlc_mutex_init(&p_sys->download.lock_wait);
1943 vlc_cond_init(&p_sys->download.wait);
1945 /* Initialize HLS live stream */
1948 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
1949 p_sys->playlist.last = mdate();
1950 p_sys->playlist.wakeup = p_sys->playlist.last +
1951 ((mtime_t)hls->duration * UINT64_C(1000000));
1953 if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
1959 if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
1962 vlc_join(p_sys->reload, NULL);
1969 vlc_mutex_destroy(&p_sys->download.lock_wait);
1970 vlc_cond_destroy(&p_sys->download.wait);
1973 /* Free hls streams */
1974 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1976 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
1977 if (hls) hls_Free(hls);
1979 vlc_array_destroy(p_sys->hls_stream);
1984 return VLC_EGENERIC;
1987 /****************************************************************************
1989 ****************************************************************************/
1990 static void Close(vlc_object_t *p_this)
1992 stream_t *s = (stream_t*)p_this;
1993 stream_sys_t *p_sys = s->p_sys;
1995 assert(p_sys->hls_stream);
1998 vlc_mutex_lock(&p_sys->download.lock_wait);
1999 vlc_cond_signal(&p_sys->download.wait);
2000 vlc_mutex_unlock(&p_sys->download.lock_wait);
2004 vlc_join(p_sys->reload, NULL);
2005 vlc_join(p_sys->thread, NULL);
2006 vlc_mutex_destroy(&p_sys->download.lock_wait);
2007 vlc_cond_destroy(&p_sys->download.wait);
2009 /* Free hls streams */
2010 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2012 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
2013 if (hls) hls_Free(hls);
2015 vlc_array_destroy(p_sys->hls_stream);
2020 block_Release (p_sys->peeked);
2024 /****************************************************************************
2025 * Stream filters functions
2026 ****************************************************************************/
2027 static segment_t *GetSegment(stream_t *s)
2029 stream_sys_t *p_sys = s->p_sys;
2030 segment_t *segment = NULL;
2032 /* Is this segment of the current HLS stream ready? */
2033 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2036 vlc_mutex_lock(&hls->lock);
2037 segment = segment_GetSegment(hls, p_sys->playback.segment);
2038 if (segment != NULL)
2040 vlc_mutex_lock(&segment->lock);
2041 /* This segment is ready? */
2042 if (segment->data != NULL)
2044 vlc_mutex_unlock(&segment->lock);
2045 p_sys->b_cache = hls->b_cache;
2046 vlc_mutex_unlock(&hls->lock);
2049 vlc_mutex_unlock(&segment->lock);
2051 vlc_mutex_unlock(&hls->lock);
2054 /* Was the HLS stream changed to another bitrate? */
2056 for (int i_stream = 0; i_stream < vlc_array_count(p_sys->hls_stream); i_stream++)
2058 /* Is the next segment ready */
2059 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2063 vlc_mutex_lock(&hls->lock);
2064 segment = segment_GetSegment(hls, p_sys->playback.segment);
2065 if (segment == NULL)
2067 vlc_mutex_unlock(&hls->lock);
2071 vlc_mutex_lock(&p_sys->download.lock_wait);
2072 int i_segment = p_sys->download.segment;
2073 vlc_mutex_unlock(&p_sys->download.lock_wait);
2075 vlc_mutex_lock(&segment->lock);
2076 /* This segment is ready? */
2077 if ((segment->data != NULL) &&
2078 (p_sys->playback.segment < i_segment))
2080 p_sys->playback.stream = i_stream;
2081 p_sys->b_cache = hls->b_cache;
2082 vlc_mutex_unlock(&segment->lock);
2083 vlc_mutex_unlock(&hls->lock);
2086 vlc_mutex_unlock(&segment->lock);
2087 vlc_mutex_unlock(&hls->lock);
2097 assert(segment->data);
2098 if (segment->data->i_buffer == 0)
2100 vlc_mutex_lock(&hls->lock);
2101 int count = vlc_array_count(hls->segments);
2102 vlc_mutex_unlock(&hls->lock);
2104 if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2105 ((count != p_sys->download.segment) || p_sys->b_live))
2106 msg_Err(s, "playback will stall");
2107 else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2108 ((count != p_sys->download.segment) || p_sys->b_live))
2109 msg_Warn(s, "playback in danger of stalling");
2114 static int segment_RestorePos(segment_t *segment)
2118 uint64_t size = segment->size - segment->data->i_buffer;
2121 segment->data->i_buffer += size;
2122 segment->data->p_buffer -= size;
2128 /* p_read might be NULL if caller wants to skip data */
2129 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2131 stream_sys_t *p_sys = s->p_sys;
2136 /* Determine next segment to read. If this is a meta playlist and
2137 * bandwidth conditions changed, then the stream might have switched
2138 * to another bandwidth. */
2139 segment_t *segment = GetSegment(s);
2140 if (segment == NULL)
2143 vlc_mutex_lock(&segment->lock);
2144 if (segment->data->i_buffer == 0)
2146 if (!p_sys->b_cache || p_sys->b_live)
2148 block_Release(segment->data);
2149 segment->data = NULL;
2152 segment_RestorePos(segment);
2154 p_sys->playback.segment++;
2155 vlc_mutex_unlock(&segment->lock);
2157 /* signal download thread */
2158 vlc_mutex_lock(&p_sys->download.lock_wait);
2159 vlc_cond_signal(&p_sys->download.wait);
2160 vlc_mutex_unlock(&p_sys->download.lock_wait);
2164 if (segment->size == segment->data->i_buffer)
2165 msg_Info(s, "playing segment %d from stream %d",
2166 segment->sequence, p_sys->playback.stream);
2169 if (i_read <= segment->data->i_buffer)
2171 else if (i_read > segment->data->i_buffer)
2172 len = segment->data->i_buffer;
2176 if (p_read) /* if NULL, then caller skips data */
2177 memcpy(p_read + used, segment->data->p_buffer, len);
2178 segment->data->i_buffer -= len;
2179 segment->data->p_buffer += len;
2183 vlc_mutex_unlock(&segment->lock);
2185 } while (i_read > 0);
2190 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2192 stream_sys_t *p_sys = s->p_sys;
2195 assert(p_sys->hls_stream);
2200 /* NOTE: buffer might be NULL if caller wants to skip data */
2201 length = hls_Read(s, (uint8_t*) buffer, i_read);
2205 p_sys->playback.offset += length;
2209 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2211 stream_sys_t *p_sys = s->p_sys;
2213 unsigned int len = i_peek;
2215 segment = GetSegment(s);
2216 if (segment == NULL)
2218 msg_Err(s, "segment %d should have been available (stream %d)",
2219 p_sys->playback.segment, p_sys->playback.stream);
2220 return 0; /* eof? */
2223 vlc_mutex_lock(&segment->lock);
2225 size_t i_buff = segment->data->i_buffer;
2226 uint8_t *p_buff = segment->data->p_buffer;
2228 if (i_peek < i_buff)
2231 vlc_mutex_unlock(&segment->lock);
2235 else /* This will seldom be run */
2237 /* remember segment to read */
2238 int peek_segment = p_sys->playback.segment;
2240 segment_t *nsegment;
2241 p_sys->playback.segment++;
2242 block_t *peeked = p_sys->peeked;
2245 peeked = block_Alloc (i_peek);
2246 else if (peeked->i_buffer < i_peek)
2247 peeked = block_Realloc (peeked, 0, i_peek);
2250 p_sys->peeked = peeked;
2252 memcpy(peeked->p_buffer, p_buff, i_buff);
2255 vlc_mutex_unlock(&segment->lock);
2257 i_buff = peeked->i_buffer;
2258 p_buff = peeked->p_buffer;
2261 while (curlen < i_peek)
2263 nsegment = GetSegment(s);
2264 if (nsegment == NULL)
2266 msg_Err(s, "segment %d should have been available (stream %d)",
2267 p_sys->playback.segment, p_sys->playback.stream);
2268 /* restore segment to read */
2269 p_sys->playback.segment = peek_segment;
2270 return curlen; /* eof? */
2273 vlc_mutex_lock(&nsegment->lock);
2275 if (len < nsegment->data->i_buffer)
2277 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2282 size_t i_nbuff = nsegment->data->i_buffer;
2283 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2287 p_sys->playback.segment++;
2290 vlc_mutex_unlock(&nsegment->lock);
2293 /* restore segment to read */
2294 p_sys->playback.segment = peek_segment;
2299 static bool hls_MaySeek(stream_t *s)
2301 stream_sys_t *p_sys = s->p_sys;
2303 if (p_sys->hls_stream == NULL)
2306 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2307 if (hls == NULL) return false;
2311 vlc_mutex_lock(&hls->lock);
2312 int count = vlc_array_count(hls->segments);
2313 vlc_mutex_unlock(&hls->lock);
2315 vlc_mutex_lock(&p_sys->download.lock_wait);
2316 bool may_seek = (p_sys->download.segment < (count - 2));
2317 vlc_mutex_unlock(&p_sys->download.lock_wait);
2323 static uint64_t GetStreamSize(stream_t *s)
2325 stream_sys_t *p_sys = s->p_sys;
2330 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2331 if (hls == NULL) return 0;
2333 vlc_mutex_lock(&hls->lock);
2335 hls->size = hls_GetStreamSize(hls);
2336 uint64_t size = hls->size;
2337 vlc_mutex_unlock(&hls->lock);
2342 static int segment_Seek(stream_t *s, const uint64_t pos)
2344 stream_sys_t *p_sys = s->p_sys;
2346 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2348 return VLC_EGENERIC;
2350 vlc_mutex_lock(&hls->lock);
2352 bool b_found = false;
2353 uint64_t length = 0;
2354 uint64_t size = hls->size;
2355 int count = vlc_array_count(hls->segments);
2357 segment_t *currentSegment = segment_GetSegment(hls, p_sys->playback.segment);
2358 if (currentSegment == NULL)
2360 vlc_mutex_unlock(&hls->lock);
2361 return VLC_EGENERIC;
2364 for (int n = 0; n < count; n++)
2366 segment_t *segment = segment_GetSegment(hls, n);
2367 if (segment == NULL)
2369 vlc_mutex_unlock(&hls->lock);
2370 return VLC_EGENERIC;
2373 vlc_mutex_lock(&segment->lock);
2374 length += segment->duration * (hls->bandwidth/8);
2375 vlc_mutex_unlock(&segment->lock);
2381 p_sys->playback.segment = n;
2385 /* Do not search in last 3 segments */
2386 vlc_mutex_unlock(&hls->lock);
2387 return VLC_EGENERIC;
2392 if (!b_found && (pos >= size))
2394 p_sys->playback.segment = count - 1;
2402 /* restore current segment to start position */
2403 vlc_mutex_lock(¤tSegment->lock);
2404 segment_RestorePos(currentSegment);
2405 vlc_mutex_unlock(¤tSegment->lock);
2407 /* restore seeked segment to start position */
2408 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2409 if (segment == NULL)
2411 vlc_mutex_unlock(&hls->lock);
2412 return VLC_EGENERIC;
2415 vlc_mutex_lock(&segment->lock);
2416 segment_RestorePos(segment);
2417 vlc_mutex_unlock(&segment->lock);
2419 /* start download at current playback segment */
2420 vlc_mutex_unlock(&hls->lock);
2422 /* Wake up download thread */
2423 vlc_mutex_lock(&p_sys->download.lock_wait);
2424 p_sys->download.seek = p_sys->playback.segment;
2425 vlc_cond_signal(&p_sys->download.wait);
2427 /* Wait for download to be finished */
2428 msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2429 while ((p_sys->download.seek != -1) ||
2430 ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2431 (p_sys->download.segment < count)))
2433 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2434 if (!vlc_object_alive(s) || s->b_error) break;
2436 vlc_mutex_unlock(&p_sys->download.lock_wait);
2440 vlc_mutex_unlock(&hls->lock);
2442 return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2445 static int Control(stream_t *s, int i_query, va_list args)
2447 stream_sys_t *p_sys = s->p_sys;
2451 case STREAM_CAN_SEEK:
2452 *(va_arg (args, bool *)) = hls_MaySeek(s);
2454 case STREAM_GET_POSITION:
2455 *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2457 case STREAM_SET_POSITION:
2460 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2461 if (segment_Seek(s, pos) == VLC_SUCCESS)
2463 p_sys->playback.offset = pos;
2467 return VLC_EGENERIC;
2468 case STREAM_GET_SIZE:
2469 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2472 return VLC_EGENERIC;