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 = 7; i >= 0 ; --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)
546 assert(psz_url != NULL && psz_path != NULL);
549 //If the path is actually an absolute URL, don't do anything.
550 if (strncmp(psz_path, "http", 4) == 0)
553 size_t len = strlen(psz_path);
555 char *new_url = strdup(psz_url);
556 if (unlikely(!new_url))
559 if( psz_path[0] == '/' ) //Relative URL with absolute path
561 //Try to find separator for name and path, try to skip
562 //access and first ://
563 char *slash = strchr(&new_url[8], '/');
564 if (unlikely(slash == NULL))
569 while(len >= 3 && !strncmp(psz_path, "../", 3)) {
575 char *slash = strrchr(new_url, '/');
576 if (unlikely(slash == NULL))
582 if (asprintf(&ret, "%s/%s", new_url, psz_path) < 0)
590 static int parse_SegmentInformation(hls_stream_t *hls, char *p_read, int *duration)
595 /* strip of #EXTINF: */
597 char *token = strtok_r(p_read, ":", &p_next);
602 token = strtok_r(NULL, ",", &p_next);
608 if (hls->version < 3)
611 value = strtol(token, &endptr, 10);
612 if (token == endptr || errno == ERANGE)
622 double d = strtof(token, &endptr);
623 if (token == endptr || errno == ERANGE)
628 if ((d) - ((int)d) >= 0.5)
629 value = ((int)d) + 1;
635 /* Ignore the rest of the line */
639 static int parse_AddSegment(hls_stream_t *hls, const int duration, const char *uri)
644 /* Store segment information */
645 vlc_mutex_lock(&hls->lock);
647 char *psz_uri = relative_URI(hls->url, uri);
649 segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
651 segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
654 vlc_mutex_unlock(&hls->lock);
656 return segment ? VLC_SUCCESS : VLC_ENOMEM;
659 static int parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
664 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
667 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
671 hls->duration = duration; /* seconds */
675 static int parse_StreamInformation(stream_t *s, vlc_array_t **hls_stream,
676 hls_stream_t **hls, char *p_read, const char *uri)
682 assert(*hls == NULL);
684 attr = parse_Attributes(p_read, "PROGRAM-ID");
693 attr = parse_Attributes(p_read, "BANDWIDTH");
696 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
704 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
708 msg_Info(s, "bandwidth adaptation detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
710 char *psz_uri = relative_URI(s->p_sys->m3u8, uri);
712 *hls = hls_New(*hls_stream, id, bw, psz_uri ? psz_uri : uri);
716 return (*hls == NULL) ? VLC_ENOMEM : VLC_SUCCESS;
719 static int parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
724 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
727 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
731 if (hls->sequence > 0)
733 if (s->p_sys->b_live)
735 hls_stream_t *last = hls_GetLast(s->p_sys->hls_stream);
736 if ((last->sequence < sequence) && (sequence - last->sequence != 1))
737 msg_Err(s, "EXT-X-MEDIA-SEQUENCE gap in playlist (new=%d, old=%d)",
738 sequence, last->sequence);
741 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist (new=%d, old=%d)",
742 sequence, hls->sequence);
744 hls->sequence = sequence;
748 static int parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
752 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
753 int err = VLC_SUCCESS;
754 char *attr = parse_Attributes(p_read, "METHOD");
757 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
761 if (strncasecmp(attr, "NONE", 4) == 0)
763 char *uri = parse_Attributes(p_read, "URI");
766 msg_Err(s, "#EXT-X-KEY: URI not expected");
770 /* IV is only supported in version 2 and above */
771 if (hls->version >= 2)
773 char *iv = parse_Attributes(p_read, "IV");
776 msg_Err(s, "#EXT-X-KEY: IV not expected");
782 else if (strncasecmp(attr, "AES-128", 7) == 0)
784 char *value, *uri, *iv;
785 if (s->p_sys->b_aesmsg == false)
787 msg_Info(s, "playback of AES-128 encrypted HTTP Live media detected.");
788 s->p_sys->b_aesmsg = true;
790 value = uri = parse_Attributes(p_read, "URI");
793 msg_Err(s, "#EXT-X-KEY: URI not found for encrypted HTTP Live media in AES-128");
798 /* Url is put between quotes, remove them */
801 /* We need to strip the "" from the attribute value */
803 char* end = strchr(uri, '"');
807 /* For absolute URI, just duplicate it
808 * don't limit to HTTP, maybe some sanity checking
809 * should be done more in here? */
810 if( strstr( uri , "://" ) )
811 hls->psz_current_key_path = strdup( uri );
813 hls->psz_current_key_path = relative_URI(hls->url, uri);
816 value = iv = parse_Attributes(p_read, "IV");
820 * If the EXT-X-KEY tag does not have the IV attribute, implementations
821 * MUST use the sequence number of the media file as the IV when
822 * encrypting or decrypting that media file. The big-endian binary
823 * representation of the sequence number SHALL be placed in a 16-octet
824 * buffer and padded (on the left) with zeros.
826 hls->b_iv_loaded = false;
831 * If the EXT-X-KEY tag has the IV attribute, implementations MUST use
832 * the attribute value as the IV when encrypting or decrypting with that
833 * key. The value MUST be interpreted as a 128-bit hexadecimal number
834 * and MUST be prefixed with 0x or 0X.
837 if (string_to_IV(iv, hls->psz_AES_IV) == VLC_EGENERIC)
839 msg_Err(s, "IV invalid");
843 hls->b_iv_loaded = true;
849 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
856 static int parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
859 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
863 static int parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
867 char answer[4] = "\0";
868 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
871 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
875 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
879 static int parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
884 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
887 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
892 hls->version = version;
893 if (hls->version <= 0 || hls->version > 3)
895 msg_Err(s, "#EXT-X-VERSION should be version 1, 2 or 3 iso %d", version);
901 static int parse_EndList(stream_t *s, hls_stream_t *hls)
905 s->p_sys->b_live = false;
906 msg_Info(s, "video on demand (vod) mode");
910 static int parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
914 /* FIXME: Do we need to act on discontinuity ?? */
915 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
919 static int hls_CompareStreams( const void* a, const void* b )
921 hls_stream_t* stream_a = *(hls_stream_t**)a;
922 hls_stream_t* stream_b = *(hls_stream_t**)b;
923 return stream_a->bandwidth > stream_b->bandwidth;
926 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
927 * document defines the following new tags: EXT-X-TARGETDURATION,
928 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
929 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
932 static int parse_M3U8(stream_t *s, vlc_array_t *streams, uint8_t *buffer, const ssize_t len)
934 stream_sys_t *p_sys = s->p_sys;
935 uint8_t *p_read, *p_begin, *p_end;
940 msg_Dbg(s, "parse_M3U8\n%s", buffer);
942 p_end = p_begin + len;
944 char *line = ReadLine(p_begin, &p_read, p_end - p_begin);
949 if (strncmp(line, "#EXTM3U", 7) != 0)
951 msg_Err(s, "missing #EXTM3U tag .. aborting");
959 /* What is the version ? */
961 uint8_t *p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-VERSION:");
965 char *psz_version = ReadLine(p, &tmp, p_end - p);
966 if (psz_version == NULL)
968 int ret = sscanf((const char*)psz_version, "#EXT-X-VERSION:%d", &version);
971 msg_Warn(s, "#EXT-X-VERSION: no protocol version found, assuming version 1.");
978 /* Is it a live stream ? */
979 p_sys->b_live = (strstr((const char *)buffer, "#EXT-X-ENDLIST") == NULL) ? true : false;
981 /* Is it a meta index file ? */
982 bool b_meta = (strstr((const char *)buffer, "#EXT-X-STREAM-INF") == NULL) ? false : true;
984 int err = VLC_SUCCESS;
988 msg_Info(s, "Meta playlist");
990 /* M3U8 Meta Index file */
992 bool failed_to_download_stream_m3u8 = false;
995 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1001 if (strncmp(line, "#EXT-X-STREAM-INF", 17) == 0)
1003 p_sys->b_meta = true;
1004 char *uri = ReadLine(p_begin, &p_read, p_end - p_begin);
1011 msg_Info(s, "Skipping invalid stream-inf: %s", uri);
1016 bool new_stream_added = false;
1017 hls_stream_t *hls = NULL;
1018 err = parse_StreamInformation(s, &streams, &hls, line, uri);
1019 if (err == VLC_SUCCESS)
1020 new_stream_added = true;
1026 /* Download playlist file from server */
1027 uint8_t *buf = NULL;
1028 ssize_t len = read_M3U8_from_url(s, hls->url, &buf);
1031 msg_Warn(s, "failed to read %s, continue for other streams", hls->url);
1032 failed_to_download_stream_m3u8 = true;
1034 /* remove stream just added */
1035 if (new_stream_added)
1036 vlc_array_remove(streams, vlc_array_count(streams) - 1);
1038 /* ignore download error, so we have chance to try other streams */
1043 /* Parse HLS m3u8 content. */
1044 err = parse_M3U8(s, streams, buf, len);
1048 hls->version = version;
1050 hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
1060 if (p_begin >= p_end)
1063 } while (err == VLC_SUCCESS);
1065 size_t stream_count = vlc_array_count(streams);
1066 msg_Dbg(s, "%d streams loaded in Meta playlist", (int)stream_count);
1067 if (stream_count == 0)
1069 msg_Err(s, "No playable streams found in Meta playlist");
1075 msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
1077 hls_stream_t *hls = NULL;
1079 hls = hls_GetLast(streams);
1082 /* No Meta playlist used */
1083 hls = hls_New(streams, 0, 0, p_sys->m3u8);
1086 /* Get TARGET-DURATION first */
1087 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1090 uint8_t *p_rest = NULL;
1091 char *psz_duration = ReadLine(p, &p_rest, p_end - p);
1092 if (psz_duration == NULL)
1093 return VLC_EGENERIC;
1094 err = parse_TargetDuration(s, hls, psz_duration);
1100 hls->version = version;
1102 else return VLC_ENOMEM;
1107 bool media_sequence_loaded = false;
1108 int segment_duration = -1;
1112 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1117 if (strncmp(line, "#EXTINF", 7) == 0)
1118 err = parse_SegmentInformation(hls, line, &segment_duration);
1119 else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1120 err = parse_TargetDuration(s, hls, line);
1121 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1123 /* A Playlist file MUST NOT contain more than one EXT-X-MEDIA-SEQUENCE tag. */
1124 /* We only care about first one */
1125 if (!media_sequence_loaded)
1127 err = parse_MediaSequence(s, hls, line);
1128 media_sequence_loaded = true;
1131 else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1132 err = parse_Key(s, hls, line);
1133 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1134 err = parse_ProgramDateTime(s, hls, line);
1135 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1136 err = parse_AllowCache(s, hls, line);
1137 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1138 err = parse_Discontinuity(s, hls, line);
1139 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1140 err = parse_Version(s, hls, line);
1141 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1142 err = parse_EndList(s, hls);
1143 else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1145 err = parse_AddSegment(hls, segment_duration, line);
1146 segment_duration = -1; /* reset duration */
1152 if (p_begin >= p_end)
1155 } while (err == VLC_SUCCESS);
1164 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1166 stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1169 msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1170 return VLC_EGENERIC;
1173 int len = stream_Read(p_m3u8, seg->aes_key, sizeof(seg->aes_key));
1174 stream_Delete(p_m3u8);
1175 if (len != AES_BLOCK_SIZE)
1177 msg_Err(s, "The AES key loaded doesn't have the right size (%d)", len);
1178 return VLC_EGENERIC;
1184 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1186 segment_t *seg = NULL;
1187 segment_t *prev_seg;
1188 int count = vlc_array_count(hls->segments);
1190 for (int i = 0; i < count; i++)
1193 seg = segment_GetSegment(hls, i);
1196 if (seg->psz_key_path == NULL)
1197 continue; /* No key to load ? continue */
1198 if (seg->b_key_loaded)
1199 continue; /* The key is already loaded */
1201 /* if the key has not changed, and already available from previous segment,
1202 * try to copy it, and don't load the key */
1203 if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1205 memcpy(seg->aes_key, prev_seg->aes_key, AES_BLOCK_SIZE);
1206 seg->b_key_loaded = true;
1209 if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1210 return VLC_EGENERIC;
1211 seg->b_key_loaded = true;
1216 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1218 /* Did the segment need to be decoded ? */
1219 if (segment->psz_key_path == NULL)
1222 /* Do we have loaded the key ? */
1223 if (!segment->b_key_loaded)
1225 /* No ? try to download it now */
1226 if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1227 return VLC_EGENERIC;
1230 /* For now, we only decode AES-128 data */
1231 gcry_error_t i_gcrypt_err;
1232 gcry_cipher_hd_t aes_ctx;
1234 i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1235 GCRY_CIPHER_MODE_CBC, 0);
1238 msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1239 gcry_cipher_close(aes_ctx);
1240 return VLC_EGENERIC;
1244 i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->aes_key,
1245 sizeof(segment->aes_key));
1248 msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1249 gcry_cipher_close(aes_ctx);
1250 return VLC_EGENERIC;
1253 if (hls->b_iv_loaded == false)
1255 memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1256 hls->psz_AES_IV[15] = segment->sequence & 0xff;
1257 hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1258 hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1259 hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1262 i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1263 sizeof(hls->psz_AES_IV));
1267 msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1268 gcry_cipher_close(aes_ctx);
1269 return VLC_EGENERIC;
1272 i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1273 segment->data->p_buffer, /* out */
1274 segment->data->i_buffer,
1279 msg_Err(s, "gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1280 gcry_cipher_close(aes_ctx);
1281 return VLC_EGENERIC;
1283 gcry_cipher_close(aes_ctx);
1284 /* remove the PKCS#7 padding from the buffer */
1285 int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1286 if (pad <= 0 || pad > AES_BLOCK_SIZE)
1288 msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1289 return VLC_EGENERIC;
1294 if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1296 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1297 return VLC_EGENERIC;
1301 /* not all the data is readable because of padding */
1302 segment->data->i_buffer -= pad;
1307 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1309 stream_sys_t *p_sys = s->p_sys;
1311 int err = VLC_EGENERIC;
1313 /* Duplicate HLS stream META information */
1314 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1316 hls_stream_t *src, *dst;
1317 src = hls_Get(p_sys->hls_stream, i);
1319 return VLC_EGENERIC;
1321 dst = hls_Copy(src, false);
1324 vlc_array_append(*streams, dst);
1326 /* Download playlist file from server */
1327 uint8_t *buf = NULL;
1328 ssize_t len = read_M3U8_from_url(s, dst->url, &buf);
1333 /* Parse HLS m3u8 content. */
1334 err = parse_M3U8(s, *streams, buf, len);
1341 /* Update hls_old (an existing member of p_sys->hls_stream) to match hls_new
1342 (which represents a downloaded, perhaps newer version of the same playlist) */
1343 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t *hls_old)
1345 int count = vlc_array_count(hls_new->segments);
1347 msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1348 hls_new->id, hls_new->bandwidth, count);
1350 vlc_mutex_lock(&hls_old->lock);
1351 for (int n = 0; n < count; n++)
1353 segment_t *p = segment_GetSegment(hls_new, n);
1356 vlc_mutex_unlock(&hls_old->lock);
1357 return VLC_EGENERIC;
1360 segment_t *segment = segment_Find(hls_old, p->sequence);
1363 vlc_mutex_lock(&segment->lock);
1366 assert(segment->url);
1368 /* they should be the same */
1369 if ((p->sequence != segment->sequence) ||
1370 (p->duration != segment->duration) ||
1371 (strcmp(p->url, segment->url) != 0))
1373 msg_Warn(s, "existing segment found with different content - resetting");
1374 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1375 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1376 msg_Warn(s, "- file: new=%s", p->url);
1377 msg_Warn(s, " old=%s", segment->url);
1379 /* Resetting content */
1380 segment->sequence = p->sequence;
1381 segment->duration = p->duration;
1383 segment->url = strdup(p->url);
1384 if ( segment->url == NULL )
1386 msg_Err(s, "Failed updating segment %d - skipping it", p->sequence);
1388 vlc_mutex_unlock(&segment->lock);
1391 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1392 if ((p->psz_key_path || p->b_key_loaded) &&
1395 block_Release(segment->data);
1396 segment->data = NULL;
1398 free(segment->psz_key_path);
1399 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1402 vlc_mutex_unlock(&segment->lock);
1406 int last = vlc_array_count(hls_old->segments) - 1;
1407 segment_t *l = segment_GetSegment(hls_old, last);
1409 vlc_mutex_unlock(&hls_old->lock);
1410 return VLC_EGENERIC;
1413 if ((l->sequence + 1) != p->sequence)
1415 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1416 p->sequence, l->sequence+1);
1418 vlc_array_append(hls_old->segments, p);
1419 msg_Info(s, "- segment %d appended", p->sequence);
1423 /* update meta information */
1424 hls_old->sequence = hls_new->sequence;
1425 hls_old->duration = (hls_new->duration == -1) ? hls_old->duration : hls_new->duration;
1426 hls_old->b_cache = hls_new->b_cache;
1427 vlc_mutex_unlock(&hls_old->lock);
1432 static int hls_ReloadPlaylist(stream_t *s)
1434 stream_sys_t *p_sys = s->p_sys;
1436 vlc_array_t *hls_streams = vlc_array_new();
1437 if (hls_streams == NULL)
1440 msg_Info(s, "Reloading HLS live meta playlist");
1442 if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1444 /* Free hls streams */
1445 for (int i = 0; i < vlc_array_count(hls_streams); i++)
1448 hls = hls_Get(hls_streams, i);
1449 if (hls) hls_Free(hls);
1451 vlc_array_destroy(hls_streams);
1453 msg_Err(s, "reloading playlist failed");
1454 return VLC_EGENERIC;
1457 /* merge playlists */
1458 int count = vlc_array_count(hls_streams);
1459 for (int n = 0; n < count; n++)
1461 hls_stream_t *hls_new = hls_Get(hls_streams, n);
1462 if (hls_new == NULL)
1465 hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1466 if (hls_old == NULL)
1467 { /* new hls stream - append */
1468 vlc_array_append(p_sys->hls_stream, hls_new);
1469 msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1470 hls_new->id, hls_new->bandwidth);
1472 else if (hls_UpdatePlaylist(s, hls_new, hls_old) != VLC_SUCCESS)
1473 msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1474 hls_new->id, hls_new->bandwidth);
1476 vlc_array_destroy(hls_streams);
1480 /****************************************************************************
1482 ****************************************************************************/
1483 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1485 stream_sys_t *p_sys = s->p_sys;
1487 uint64_t bw = *bandwidth;
1488 uint64_t bw_candidate = 0;
1490 int count = vlc_array_count(p_sys->hls_stream);
1491 for (int n = 0; n < count; n++)
1493 /* Select best bandwidth match */
1494 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1495 if (hls == NULL) break;
1497 /* only consider streams with the same PROGRAM-ID */
1498 if (hls->id == progid)
1500 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1502 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1503 n, bw, hls->bandwidth); /* bits / s */
1504 bw_candidate = hls->bandwidth;
1505 candidate = n; /* possible candidate */
1509 *bandwidth = bw_candidate;
1513 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1515 stream_sys_t *p_sys = s->p_sys;
1520 vlc_mutex_lock(&segment->lock);
1521 if (segment->data != NULL)
1523 /* Segment already downloaded */
1524 vlc_mutex_unlock(&segment->lock);
1528 /* sanity check - can we download this segment on time? */
1529 if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1531 uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1532 int estimated = (int)(size / p_sys->bandwidth);
1533 if (estimated > segment->duration)
1535 msg_Warn(s,"downloading segment %d predicted to take %ds, which exceeds its length (%ds)",
1536 segment->sequence, estimated, segment->duration);
1540 mtime_t start = mdate();
1541 if (hls_Download(s, segment) != VLC_SUCCESS)
1543 msg_Err(s, "downloading segment %d from stream %d failed",
1544 segment->sequence, *cur_stream);
1545 vlc_mutex_unlock(&segment->lock);
1546 return VLC_EGENERIC;
1548 mtime_t duration = mdate() - start;
1549 if (hls->bandwidth == 0 && segment->duration > 0)
1551 /* Try to estimate the bandwidth for this stream */
1552 hls->bandwidth = (uint64_t)(((double)segment->size * 8) / ((double)segment->duration));
1555 /* If the segment is encrypted, decode it */
1556 if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1558 vlc_mutex_unlock(&segment->lock);
1559 return VLC_EGENERIC;
1562 vlc_mutex_unlock(&segment->lock);
1564 msg_Info(s, "downloaded segment %d from stream %d",
1565 segment->sequence, *cur_stream);
1567 uint64_t bw = segment->size * 8 * 1000000 / __MAX(1, duration); /* bits / s */
1568 p_sys->bandwidth = bw;
1569 if (p_sys->b_meta && (hls->bandwidth != bw))
1571 int newstream = BandwidthAdaptation(s, hls->id, &bw);
1573 /* FIXME: we need an average here */
1574 if ((newstream >= 0) && (newstream != *cur_stream))
1576 msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1577 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1578 *cur_stream = newstream;
1584 static void* hls_Thread(void *p_this)
1586 stream_t *s = (stream_t *)p_this;
1587 stream_sys_t *p_sys = s->p_sys;
1589 int canc = vlc_savecancel();
1591 while (vlc_object_alive(s))
1593 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1596 /* Sliding window (~60 seconds worth of movie) */
1597 vlc_mutex_lock(&hls->lock);
1598 int count = vlc_array_count(hls->segments);
1599 vlc_mutex_unlock(&hls->lock);
1601 /* Is there a new segment to process? */
1602 if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1603 (p_sys->download.segment >= count))
1606 vlc_mutex_lock(&p_sys->download.lock_wait);
1607 while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1608 (p_sys->download.segment >= count)) &&
1609 (p_sys->download.seek == -1))
1611 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1612 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1614 if (!vlc_object_alive(s))
1618 if (p_sys->download.seek >= 0)
1620 p_sys->download.segment = p_sys->download.seek;
1621 p_sys->download.seek = -1;
1623 vlc_mutex_unlock(&p_sys->download.lock_wait);
1626 if (!vlc_object_alive(s)) break;
1628 vlc_mutex_lock(&hls->lock);
1629 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1630 vlc_mutex_unlock(&hls->lock);
1632 if ((segment != NULL) &&
1633 (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1635 if (!vlc_object_alive(s)) break;
1639 p_sys->b_error = true;
1644 /* download succeeded */
1645 /* determine next segment to download */
1646 vlc_mutex_lock(&p_sys->download.lock_wait);
1647 if (p_sys->download.seek >= 0)
1649 p_sys->download.segment = p_sys->download.seek;
1650 p_sys->download.seek = -1;
1652 else if (p_sys->download.segment < count)
1653 p_sys->download.segment++;
1654 vlc_cond_signal(&p_sys->download.wait);
1655 vlc_mutex_unlock(&p_sys->download.lock_wait);
1658 vlc_restorecancel(canc);
1662 static void* hls_Reload(void *p_this)
1664 stream_t *s = (stream_t *)p_this;
1665 stream_sys_t *p_sys = s->p_sys;
1667 assert(p_sys->b_live);
1669 int canc = vlc_savecancel();
1672 while (vlc_object_alive(s))
1674 mtime_t now = mdate();
1675 if (now >= p_sys->playlist.wakeup)
1677 /* reload the m3u8 */
1678 if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1680 /* No change in playlist, then backoff */
1681 p_sys->playlist.tries++;
1682 if (p_sys->playlist.tries == 1) wait = 0.5;
1683 else if (p_sys->playlist.tries == 2) wait = 1;
1684 else if (p_sys->playlist.tries >= 3) wait = 2;
1686 /* Can we afford to backoff? */
1687 if (p_sys->download.segment - p_sys->playback.segment < 3)
1689 p_sys->playlist.tries = 0;
1695 p_sys->playlist.tries = 0;
1699 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1702 /* determine next time to update playlist */
1703 p_sys->playlist.last = now;
1704 p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1705 * (mtime_t)1000000);
1708 mwait(p_sys->playlist.wakeup);
1711 vlc_restorecancel(canc);
1715 static int Prefetch(stream_t *s, int *current)
1717 stream_sys_t *p_sys = s->p_sys;
1718 int stream = *current;
1720 hls_stream_t *hls = hls_Get(p_sys->hls_stream, stream);
1722 return VLC_EGENERIC;
1724 if (vlc_array_count(hls->segments) == 0)
1725 return VLC_EGENERIC;
1726 else if (vlc_array_count(hls->segments) == 1 && p_sys->b_live)
1727 msg_Warn(s, "Only 1 segment available to prefetch in live stream; may stall");
1729 /* Download first 2 segments of this HLS stream if they exist */
1730 for (int i = 0; i < __MIN(vlc_array_count(hls->segments), 2); i++)
1732 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1733 if (segment == NULL )
1734 return VLC_EGENERIC;
1736 /* It is useless to lock the segment here, as Prefetch is called before
1737 download and playlit thread are started. */
1740 p_sys->download.segment++;
1744 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1745 return VLC_EGENERIC;
1747 p_sys->download.segment++;
1749 /* adapt bandwidth? */
1750 if (*current != stream)
1752 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1754 return VLC_EGENERIC;
1763 /****************************************************************************
1765 ****************************************************************************/
1766 static int hls_Download(stream_t *s, segment_t *segment)
1770 stream_t *p_ts = stream_UrlNew(s, segment->url);
1772 return VLC_EGENERIC;
1774 segment->size = stream_Size(p_ts);
1775 assert(segment->size > 0);
1777 segment->data = block_Alloc(segment->size);
1778 if (segment->data == NULL)
1780 stream_Delete(p_ts);
1784 assert(segment->data->i_buffer == segment->size);
1786 ssize_t length = 0, curlen = 0;
1790 /* NOTE: Beware the size reported for a segment by the HLS server may not
1791 * be correct, when downloading the segment data. Therefore check the size
1792 * and enlarge the segment data block if necessary.
1794 size = stream_Size(p_ts);
1795 if (size > segment->size)
1797 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1798 block_t *p_block = block_Realloc(segment->data, 0, size);
1799 if (p_block == NULL)
1801 stream_Delete(p_ts);
1802 block_Release(segment->data);
1803 segment->data = NULL;
1806 segment->data = p_block;
1807 segment->size = size;
1808 assert(segment->data->i_buffer == segment->size);
1811 length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1815 } while (vlc_object_alive(s));
1817 stream_Delete(p_ts);
1821 /* Read M3U8 file */
1822 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1824 int64_t total_bytes = 0;
1825 int64_t total_allocated = 0;
1833 bytes = stream_Read(s, buf, sizeof(buf));
1842 if ( (total_bytes + bytes + 1) > total_allocated )
1844 if (total_allocated)
1845 total_allocated *= 2;
1847 total_allocated = __MIN((uint64_t)bytes+1, sizeof(buf));
1849 p = realloc_or_free(p, total_allocated);
1854 memcpy(p+total_bytes, buf, bytes);
1855 total_bytes += bytes;
1858 if (total_allocated == 0)
1859 return VLC_EGENERIC;
1861 p[total_bytes] = '\0';
1867 static ssize_t read_M3U8_from_url(stream_t *s, const char* psz_url, uint8_t **buffer)
1869 assert(*buffer == NULL);
1872 stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1874 return VLC_EGENERIC;
1876 ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1877 stream_Delete(p_m3u8);
1882 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1887 uint8_t *begin = buffer;
1889 uint8_t *end = p + len;
1893 if ((*p == '\r') || (*p == '\n') || (*p == '\0'))
1898 /* copy line excluding \r \n or \0 */
1899 line = strndup((char *)begin, p - begin);
1901 while ((*p == '\r') || (*p == '\n') || (*p == '\0'))
1910 /* next pass start after \r and \n */
1919 /****************************************************************************
1921 ****************************************************************************/
1922 static int Open(vlc_object_t *p_this)
1924 stream_t *s = (stream_t*)p_this;
1925 stream_sys_t *p_sys;
1927 if (!isHTTPLiveStreaming(s))
1928 return VLC_EGENERIC;
1930 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1932 /* Initialize crypto bit */
1936 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1940 char *psz_uri = NULL;
1941 if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1946 p_sys->m3u8 = psz_uri;
1949 if (asprintf(&new_path, "%s.ts", s->psz_path) < 0)
1956 s->psz_path = new_path;
1958 p_sys->bandwidth = 0;
1959 p_sys->b_live = true;
1960 p_sys->b_meta = false;
1961 p_sys->b_error = false;
1963 p_sys->hls_stream = vlc_array_new();
1964 if (p_sys->hls_stream == NULL)
1974 s->pf_control = Control;
1976 /* Parse HLS m3u8 content. */
1977 uint8_t *buffer = NULL;
1978 ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1981 if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
1987 /* HLS standard doesn't provide any guaranty about streams
1988 being sorted by bandwidth, so we sort them */
1989 qsort( p_sys->hls_stream->pp_elems, p_sys->hls_stream->i_count,
1990 sizeof( hls_stream_t* ), &hls_CompareStreams );
1992 /* Choose first HLS stream to start with */
1993 int current = p_sys->playback.stream = 0;
1994 p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
1996 /* manage encryption key if needed */
1997 hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
1999 if (Prefetch(s, ¤t) != VLC_SUCCESS)
2001 msg_Err(s, "fetching first segment failed.");
2005 p_sys->download.stream = current;
2006 p_sys->playback.stream = current;
2007 p_sys->download.seek = -1;
2009 vlc_mutex_init(&p_sys->download.lock_wait);
2010 vlc_cond_init(&p_sys->download.wait);
2012 /* Initialize HLS live stream */
2015 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
2016 p_sys->playlist.last = mdate();
2017 p_sys->playlist.wakeup = p_sys->playlist.last +
2018 ((mtime_t)hls->duration * UINT64_C(1000000));
2020 if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
2026 if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
2029 vlc_join(p_sys->reload, NULL);
2036 vlc_mutex_destroy(&p_sys->download.lock_wait);
2037 vlc_cond_destroy(&p_sys->download.wait);
2040 /* Free hls streams */
2041 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2043 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
2044 if (hls) hls_Free(hls);
2046 vlc_array_destroy(p_sys->hls_stream);
2051 return VLC_EGENERIC;
2054 /****************************************************************************
2056 ****************************************************************************/
2057 static void Close(vlc_object_t *p_this)
2059 stream_t *s = (stream_t*)p_this;
2060 stream_sys_t *p_sys = s->p_sys;
2062 assert(p_sys->hls_stream);
2065 vlc_mutex_lock(&p_sys->download.lock_wait);
2066 /* negate the condition variable's predicate */
2067 p_sys->download.segment = p_sys->playback.segment = 0;
2068 p_sys->download.seek = 0; /* better safe than sorry */
2069 vlc_cond_signal(&p_sys->download.wait);
2070 vlc_mutex_unlock(&p_sys->download.lock_wait);
2074 vlc_join(p_sys->reload, NULL);
2075 vlc_join(p_sys->thread, NULL);
2076 vlc_mutex_destroy(&p_sys->download.lock_wait);
2077 vlc_cond_destroy(&p_sys->download.wait);
2079 /* Free hls streams */
2080 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2082 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
2083 if (hls) hls_Free(hls);
2085 vlc_array_destroy(p_sys->hls_stream);
2090 block_Release (p_sys->peeked);
2094 /****************************************************************************
2095 * Stream filters functions
2096 ****************************************************************************/
2097 static segment_t *GetSegment(stream_t *s)
2099 stream_sys_t *p_sys = s->p_sys;
2100 segment_t *segment = NULL;
2102 /* Is this segment of the current HLS stream ready? */
2103 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2106 vlc_mutex_lock(&hls->lock);
2107 segment = segment_GetSegment(hls, p_sys->playback.segment);
2108 if (segment != NULL)
2110 vlc_mutex_lock(&segment->lock);
2111 /* This segment is ready? */
2112 if (segment->data != NULL)
2114 vlc_mutex_unlock(&segment->lock);
2115 p_sys->b_cache = hls->b_cache;
2116 vlc_mutex_unlock(&hls->lock);
2119 vlc_mutex_unlock(&segment->lock);
2121 vlc_mutex_unlock(&hls->lock);
2124 /* Was the HLS stream changed to another bitrate? */
2126 for (int i_stream = 0; i_stream < vlc_array_count(p_sys->hls_stream); i_stream++)
2128 /* Is the next segment ready */
2129 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2133 vlc_mutex_lock(&hls->lock);
2134 segment = segment_GetSegment(hls, p_sys->playback.segment);
2135 if (segment == NULL)
2137 vlc_mutex_unlock(&hls->lock);
2141 vlc_mutex_lock(&p_sys->download.lock_wait);
2142 int i_segment = p_sys->download.segment;
2143 vlc_mutex_unlock(&p_sys->download.lock_wait);
2145 vlc_mutex_lock(&segment->lock);
2146 /* This segment is ready? */
2147 if ((segment->data != NULL) &&
2148 (p_sys->playback.segment < i_segment))
2150 p_sys->playback.stream = i_stream;
2151 p_sys->b_cache = hls->b_cache;
2152 vlc_mutex_unlock(&segment->lock);
2153 vlc_mutex_unlock(&hls->lock);
2156 vlc_mutex_unlock(&segment->lock);
2157 vlc_mutex_unlock(&hls->lock);
2167 assert(segment->data);
2168 if (segment->data->i_buffer == 0)
2170 vlc_mutex_lock(&hls->lock);
2171 int count = vlc_array_count(hls->segments);
2172 vlc_mutex_unlock(&hls->lock);
2174 if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2175 ((count != p_sys->download.segment) || p_sys->b_live))
2176 msg_Err(s, "playback will stall");
2177 else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2178 ((count != p_sys->download.segment) || p_sys->b_live))
2179 msg_Warn(s, "playback in danger of stalling");
2184 static int segment_RestorePos(segment_t *segment)
2188 uint64_t size = segment->size - segment->data->i_buffer;
2191 segment->data->i_buffer += size;
2192 segment->data->p_buffer -= size;
2198 /* p_read might be NULL if caller wants to skip data */
2199 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2201 stream_sys_t *p_sys = s->p_sys;
2206 /* Determine next segment to read. If this is a meta playlist and
2207 * bandwidth conditions changed, then the stream might have switched
2208 * to another bandwidth. */
2209 segment_t *segment = GetSegment(s);
2210 if (segment == NULL)
2213 vlc_mutex_lock(&segment->lock);
2214 if (segment->data->i_buffer == 0)
2216 if (!p_sys->b_cache || p_sys->b_live)
2218 block_Release(segment->data);
2219 segment->data = NULL;
2222 segment_RestorePos(segment);
2224 vlc_mutex_unlock(&segment->lock);
2226 /* signal download thread */
2227 vlc_mutex_lock(&p_sys->download.lock_wait);
2228 p_sys->playback.segment++;
2229 vlc_cond_signal(&p_sys->download.wait);
2230 vlc_mutex_unlock(&p_sys->download.lock_wait);
2234 if (segment->size == segment->data->i_buffer)
2235 msg_Info(s, "playing segment %d from stream %d",
2236 segment->sequence, p_sys->playback.stream);
2239 if (i_read <= segment->data->i_buffer)
2241 else if (i_read > segment->data->i_buffer)
2242 len = segment->data->i_buffer;
2246 if (p_read) /* if NULL, then caller skips data */
2247 memcpy(p_read + used, segment->data->p_buffer, len);
2248 segment->data->i_buffer -= len;
2249 segment->data->p_buffer += len;
2253 vlc_mutex_unlock(&segment->lock);
2255 } while (i_read > 0);
2260 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2262 stream_sys_t *p_sys = s->p_sys;
2265 assert(p_sys->hls_stream);
2270 /* NOTE: buffer might be NULL if caller wants to skip data */
2271 length = hls_Read(s, (uint8_t*) buffer, i_read);
2275 p_sys->playback.offset += length;
2279 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2281 stream_sys_t *p_sys = s->p_sys;
2283 unsigned int len = i_peek;
2285 segment = GetSegment(s);
2286 if (segment == NULL)
2288 msg_Err(s, "segment %d should have been available (stream %d)",
2289 p_sys->playback.segment, p_sys->playback.stream);
2290 return 0; /* eof? */
2293 vlc_mutex_lock(&segment->lock);
2295 size_t i_buff = segment->data->i_buffer;
2296 uint8_t *p_buff = segment->data->p_buffer;
2298 if (i_peek < i_buff)
2301 vlc_mutex_unlock(&segment->lock);
2305 else /* This will seldom be run */
2307 /* remember segment to read */
2308 int peek_segment = p_sys->playback.segment;
2310 segment_t *nsegment;
2311 p_sys->playback.segment++;
2312 block_t *peeked = p_sys->peeked;
2315 peeked = block_Alloc (i_peek);
2316 else if (peeked->i_buffer < i_peek)
2317 peeked = block_Realloc (peeked, 0, i_peek);
2320 vlc_mutex_unlock(&segment->lock);
2323 p_sys->peeked = peeked;
2325 memcpy(peeked->p_buffer, p_buff, i_buff);
2328 vlc_mutex_unlock(&segment->lock);
2330 i_buff = peeked->i_buffer;
2331 p_buff = peeked->p_buffer;
2334 while (curlen < i_peek)
2336 nsegment = GetSegment(s);
2337 if (nsegment == NULL)
2339 msg_Err(s, "segment %d should have been available (stream %d)",
2340 p_sys->playback.segment, p_sys->playback.stream);
2341 /* restore segment to read */
2342 p_sys->playback.segment = peek_segment;
2343 return curlen; /* eof? */
2346 vlc_mutex_lock(&nsegment->lock);
2348 if (len < nsegment->data->i_buffer)
2350 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2355 size_t i_nbuff = nsegment->data->i_buffer;
2356 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2360 p_sys->playback.segment++;
2363 vlc_mutex_unlock(&nsegment->lock);
2366 /* restore segment to read */
2367 p_sys->playback.segment = peek_segment;
2372 static bool hls_MaySeek(stream_t *s)
2374 stream_sys_t *p_sys = s->p_sys;
2376 if (p_sys->hls_stream == NULL)
2379 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2380 if (hls == NULL) return false;
2384 vlc_mutex_lock(&hls->lock);
2385 int count = vlc_array_count(hls->segments);
2386 vlc_mutex_unlock(&hls->lock);
2388 vlc_mutex_lock(&p_sys->download.lock_wait);
2389 bool may_seek = (p_sys->download.segment < (count - 2));
2390 vlc_mutex_unlock(&p_sys->download.lock_wait);
2396 static uint64_t GetStreamSize(stream_t *s)
2398 stream_sys_t *p_sys = s->p_sys;
2403 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2404 if (hls == NULL) return 0;
2406 vlc_mutex_lock(&hls->lock);
2408 hls->size = hls_GetStreamSize(hls);
2409 uint64_t size = hls->size;
2410 vlc_mutex_unlock(&hls->lock);
2415 static int segment_Seek(stream_t *s, const uint64_t pos)
2417 stream_sys_t *p_sys = s->p_sys;
2419 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2421 return VLC_EGENERIC;
2423 vlc_mutex_lock(&hls->lock);
2425 bool b_found = false;
2426 uint64_t length = 0;
2427 uint64_t size = hls->size;
2428 int count = vlc_array_count(hls->segments);
2430 segment_t *currentSegment = segment_GetSegment(hls, p_sys->playback.segment);
2431 if (currentSegment == NULL)
2433 vlc_mutex_unlock(&hls->lock);
2434 return VLC_EGENERIC;
2437 for (int n = 0; n < count; n++)
2439 segment_t *segment = segment_GetSegment(hls, n);
2440 if (segment == NULL)
2442 vlc_mutex_unlock(&hls->lock);
2443 return VLC_EGENERIC;
2446 vlc_mutex_lock(&segment->lock);
2447 length += segment->duration * (hls->bandwidth/8);
2448 vlc_mutex_unlock(&segment->lock);
2454 p_sys->playback.segment = n;
2458 /* Do not search in last 3 segments */
2459 vlc_mutex_unlock(&hls->lock);
2460 return VLC_EGENERIC;
2465 if (!b_found && (pos >= size))
2467 p_sys->playback.segment = count - 1;
2475 /* restore current segment to start position */
2476 vlc_mutex_lock(¤tSegment->lock);
2477 segment_RestorePos(currentSegment);
2478 vlc_mutex_unlock(¤tSegment->lock);
2480 /* restore seeked segment to start position */
2481 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2482 if (segment == NULL)
2484 vlc_mutex_unlock(&hls->lock);
2485 return VLC_EGENERIC;
2488 vlc_mutex_lock(&segment->lock);
2489 segment_RestorePos(segment);
2490 vlc_mutex_unlock(&segment->lock);
2492 /* start download at current playback segment */
2493 vlc_mutex_unlock(&hls->lock);
2495 /* Wake up download thread */
2496 vlc_mutex_lock(&p_sys->download.lock_wait);
2497 p_sys->download.seek = p_sys->playback.segment;
2498 vlc_cond_signal(&p_sys->download.wait);
2500 /* Wait for download to be finished */
2501 msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2502 while ((p_sys->download.seek != -1) ||
2503 ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2504 (p_sys->download.segment < count)))
2506 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2507 if (!vlc_object_alive(s) || s->b_error) break;
2509 vlc_mutex_unlock(&p_sys->download.lock_wait);
2513 vlc_mutex_unlock(&hls->lock);
2515 return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2518 static int Control(stream_t *s, int i_query, va_list args)
2520 stream_sys_t *p_sys = s->p_sys;
2524 case STREAM_CAN_SEEK:
2525 *(va_arg (args, bool *)) = hls_MaySeek(s);
2527 case STREAM_CAN_CONTROL_PACE:
2528 *(va_arg (args, bool *)) = true;
2530 case STREAM_CAN_FASTSEEK:
2531 case STREAM_CAN_PAUSE: /* TODO */
2532 *(va_arg (args, bool *)) = false;
2534 case STREAM_GET_POSITION:
2535 *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2537 case STREAM_SET_POSITION:
2540 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2541 if (segment_Seek(s, pos) == VLC_SUCCESS)
2543 p_sys->playback.offset = pos;
2547 return VLC_EGENERIC;
2548 case STREAM_GET_SIZE:
2549 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2552 return VLC_EGENERIC;