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 */
140 vlc_mutex_t lock_wait; /* used by read condition variable */
141 vlc_cond_t wait; /* some condition to wait on during read */
145 bool b_cache; /* can cache files */
146 bool b_meta; /* meta playlist */
147 bool b_live; /* live stream? or vod? */
148 bool b_error; /* parsing error */
149 bool b_aesmsg; /* only print one time that the media is encrypted */
157 /****************************************************************************
159 ****************************************************************************/
160 static int Read (stream_t *, void *p_read, unsigned int i_read);
161 static int Peek (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
162 static int Control(stream_t *, int i_query, va_list);
164 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer);
165 static ssize_t read_M3U8_from_url(stream_t *s, const char *psz_url, uint8_t **buffer);
166 static char *ReadLine(uint8_t *buffer, uint8_t **pos, size_t len);
168 static int hls_Download(stream_t *s, segment_t *segment);
170 static void* hls_Thread(void *);
171 static void* hls_Reload(void *);
173 static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted);
174 static void segment_Free(segment_t *segment);
176 /****************************************************************************
178 ****************************************************************************/
179 static bool isHTTPLiveStreaming(stream_t *s)
183 int size = stream_Peek(s->p_source, &peek, 46);
187 if (memcmp(peek, "#EXTM3U", 7) != 0)
193 /* Parse stream and search for
194 * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
195 * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
198 static const char *const ext[] = {
215 if (memcmp(peek, "EXT-X-", 6))
221 for (size_t i = 0; i < ARRAY_SIZE(ext); i++)
223 size_t len = strlen(ext[i]);
224 if (size < 0 || (size_t)size < len)
226 if (!memcmp(peek, ext[i], len))
234 /* HTTP Live Streaming */
235 static hls_stream_t *hls_New(vlc_array_t *hls_stream, const int id, const uint64_t bw, const char *uri)
237 hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
238 if (hls == NULL) return NULL;
242 hls->duration = -1;/* unknown */
244 hls->sequence = 0; /* default is 0 */
245 hls->version = 1; /* default protocol version */
247 hls->url = strdup(uri);
248 if (hls->url == NULL)
253 hls->psz_current_key_path = NULL;
254 hls->segments = vlc_array_new();
255 vlc_array_append(hls_stream, hls);
256 vlc_mutex_init(&hls->lock);
260 static void hls_Free(hls_stream_t *hls)
262 vlc_mutex_destroy(&hls->lock);
266 for (int n = 0; n < vlc_array_count(hls->segments); n++)
268 segment_t *segment = segment_GetSegment(hls, n);
269 if (segment) segment_Free(segment);
271 vlc_array_destroy(hls->segments);
274 free(hls->psz_current_key_path);
278 static hls_stream_t *hls_Copy(hls_stream_t *src, const bool b_cp_segments)
281 assert(!b_cp_segments); /* FIXME: copying segments is not implemented */
283 hls_stream_t *dst = (hls_stream_t *)malloc(sizeof(hls_stream_t));
284 if (dst == NULL) return NULL;
287 dst->bandwidth = src->bandwidth;
288 dst->duration = src->duration;
289 dst->size = src->size;
290 dst->sequence = src->sequence;
291 dst->version = src->version;
292 dst->b_cache = src->b_cache;
293 dst->psz_current_key_path = src->psz_current_key_path ?
294 strdup( src->psz_current_key_path ) : NULL;
295 dst->url = strdup(src->url);
296 if (dst->url == NULL)
302 dst->segments = vlc_array_new();
303 vlc_mutex_init(&dst->lock);
307 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, const int wanted)
309 int count = vlc_array_count(hls_stream);
312 if ((wanted < 0) || (wanted >= count))
314 return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
317 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
319 return hls_Get(hls_stream, 0);
322 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
324 int count = vlc_array_count(hls_stream);
328 return hls_Get(hls_stream, count);
331 static hls_stream_t *hls_Find(vlc_array_t *hls_stream, hls_stream_t *hls_new)
333 int count = vlc_array_count(hls_stream);
334 for (int n = 0; n < count; n++)
336 hls_stream_t *hls = hls_Get(hls_stream, n);
340 if ((hls->id == hls_new->id) &&
341 ((hls->bandwidth == hls_new->bandwidth)||(hls_new->bandwidth==0)))
348 static uint64_t hls_GetStreamSize(hls_stream_t *hls)
350 /* NOTE: Stream size is calculated based on segment duration and
351 * HLS stream bandwidth from the .m3u8 file. If these are not correct
352 * then the deviation from exact byte size will be big and the seek/
353 * progressbar will not behave entirely as one expects. */
356 /* If there is no valid bandwidth yet, then there is no point in
357 * computing stream size. */
358 if (hls->bandwidth == 0)
361 int count = vlc_array_count(hls->segments);
362 for (int n = 0; n < count; n++)
364 segment_t *segment = segment_GetSegment(hls, n);
367 size += (segment->duration * (hls->bandwidth / 8));
374 static segment_t *segment_New(hls_stream_t* hls, const int duration, const char *uri)
376 segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
380 segment->duration = duration; /* seconds */
381 segment->size = 0; /* bytes */
382 segment->sequence = 0;
383 segment->bandwidth = 0;
384 segment->url = strdup(uri);
385 if (segment->url == NULL)
390 segment->data = NULL;
391 vlc_array_append(hls->segments, segment);
392 vlc_mutex_init(&segment->lock);
393 segment->b_key_loaded = false;
394 segment->psz_key_path = NULL;
395 if (hls->psz_current_key_path)
396 segment->psz_key_path = strdup(hls->psz_current_key_path);
400 static void segment_Free(segment_t *segment)
402 vlc_mutex_destroy(&segment->lock);
405 free(segment->psz_key_path);
407 block_Release(segment->data);
411 static segment_t *segment_GetSegment(hls_stream_t *hls, const int wanted)
415 int count = vlc_array_count(hls->segments);
418 if ((wanted < 0) || (wanted >= count))
420 return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
423 static segment_t *segment_Find(hls_stream_t *hls, const int sequence)
427 int count = vlc_array_count(hls->segments);
428 if (count <= 0) return NULL;
429 for (int n = 0; n < count; n++)
431 segment_t *segment = segment_GetSegment(hls, n);
432 if (segment == NULL) break;
433 if (segment->sequence == sequence)
439 static int ChooseSegment(stream_t *s, const int current)
441 stream_sys_t *p_sys = (stream_sys_t *)s->p_sys;
442 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
443 if (hls == NULL) return 0;
445 /* Choose a segment to start which is no closer than
446 * 3 times the target duration from the end of the playlist.
451 int count = vlc_array_count(hls->segments);
452 int i = p_sys->b_live ? count - 1 : -1;
454 /* We do while loop only with live case, otherwise return 0*/
455 while((i >= 0) && (i < count))
457 segment_t *segment = segment_GetSegment(hls, i);
460 if (segment->duration > hls->duration)
462 msg_Err(s, "EXTINF:%d duration is larger than EXT-X-TARGETDURATION:%d",
463 segment->duration, hls->duration);
466 duration += segment->duration;
467 if (duration >= 3 * hls->duration)
469 /* Start point found */
471 sequence = segment->sequence;
478 msg_Dbg(s, "Choose segment %d/%d (sequence=%d)", wanted, count, sequence);
483 static char *parse_Attributes(const char *line, const char *attr)
486 char *begin = (char *) line;
487 char *end = begin + strlen(line);
489 /* Find start of attributes */
490 if ((p = strchr(begin, ':' )) == NULL)
496 if (strncasecmp(begin, attr, strlen(attr)) == 0
497 && begin[strlen(attr)] == '=')
499 /* <attr>=<value>[,]* */
500 p = strchr(begin, ',');
501 begin += strlen(attr) + 1;
504 if (p == NULL) /* last attribute */
505 return strndup(begin, end - begin);
507 return strndup(begin, p - begin);
510 } while(begin < end);
515 static int string_to_IV(char *string_hexa, uint8_t iv[AES_BLOCK_SIZE])
517 unsigned long long iv_hi, iv_lo;
519 if (*string_hexa++ != '0')
521 if (*string_hexa != 'x' && *string_hexa != 'X')
526 size_t len = strlen(string_hexa);
529 iv_lo = strtoull(string_hexa, &end, 16);
533 iv_lo = strtoull(&string_hexa[len-16], NULL, 16);
536 string_hexa[len-16] = '\0';
537 iv_hi = strtoull(string_hexa, NULL, 16);
542 for (int i = 7; i >= 0 ; --i) {
543 iv[ i] = iv_hi & 0xff;
544 iv[8+i] = iv_lo & 0xff;
552 static char *relative_URI(const char *psz_url, const char *psz_path)
555 assert(psz_url != NULL && psz_path != NULL);
558 //If the path is actually an absolute URL, don't do anything.
559 if (strncmp(psz_path, "http", 4) == 0)
562 size_t len = strlen(psz_path);
564 char *new_url = strdup(psz_url);
565 if (unlikely(!new_url))
568 if( psz_path[0] == '/' ) //Relative URL with absolute path
570 //Try to find separator for name and path, try to skip
571 //access and first ://
572 char *slash = strchr(&new_url[8], '/');
573 if (unlikely(slash == NULL))
578 while(len >= 3 && !strncmp(psz_path, "../", 3)) {
584 char *slash = strrchr(new_url, '/');
585 if (unlikely(slash == NULL))
591 if (asprintf(&ret, "%s/%s", new_url, psz_path) < 0)
599 static int parse_SegmentInformation(hls_stream_t *hls, char *p_read, int *duration)
604 /* strip of #EXTINF: */
606 char *token = strtok_r(p_read, ":", &p_next);
611 token = strtok_r(NULL, ",", &p_next);
617 if (hls->version < 3)
620 value = strtol(token, &endptr, 10);
621 if (token == endptr || errno == ERANGE)
631 double d = strtof(token, &endptr);
632 if (token == endptr || errno == ERANGE)
637 if ((d) - ((int)d) >= 0.5)
638 value = ((int)d) + 1;
644 /* Ignore the rest of the line */
648 static int parse_AddSegment(hls_stream_t *hls, const int duration, const char *uri)
653 /* Store segment information */
654 vlc_mutex_lock(&hls->lock);
656 char *psz_uri = relative_URI(hls->url, uri);
658 segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
660 segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
663 vlc_mutex_unlock(&hls->lock);
665 return segment ? VLC_SUCCESS : VLC_ENOMEM;
668 static int parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
673 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
676 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
680 hls->duration = duration; /* seconds */
684 static int parse_StreamInformation(stream_t *s, vlc_array_t **hls_stream,
685 hls_stream_t **hls, char *p_read, const char *uri)
691 assert(*hls == NULL);
693 attr = parse_Attributes(p_read, "PROGRAM-ID");
702 attr = parse_Attributes(p_read, "BANDWIDTH");
705 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
713 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
717 msg_Dbg(s, "bandwidth adaptation detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
719 char *psz_uri = relative_URI(s->p_sys->m3u8, uri);
721 *hls = hls_New(*hls_stream, id, bw, psz_uri ? psz_uri : uri);
725 return (*hls == NULL) ? VLC_ENOMEM : VLC_SUCCESS;
728 static int parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
733 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
736 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
740 if (hls->sequence > 0)
742 if (s->p_sys->b_live)
744 hls_stream_t *last = hls_GetLast(s->p_sys->hls_stream);
745 segment_t *last_segment = segment_GetSegment( last, vlc_array_count( last->segments ) - 1 );
746 if ( ( last_segment->sequence < sequence) &&
747 ( sequence - last_segment->sequence >= 1 ))
748 msg_Err(s, "EXT-X-MEDIA-SEQUENCE gap in playlist (new=%d, old=%d)",
749 sequence, last_segment->sequence);
752 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist (new=%d, old=%d)",
753 sequence, hls->sequence);
755 hls->sequence = sequence;
759 static int parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
763 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
764 int err = VLC_SUCCESS;
765 char *attr = parse_Attributes(p_read, "METHOD");
768 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
772 if (strncasecmp(attr, "NONE", 4) == 0)
774 char *uri = parse_Attributes(p_read, "URI");
777 msg_Err(s, "#EXT-X-KEY: URI not expected");
781 /* IV is only supported in version 2 and above */
782 if (hls->version >= 2)
784 char *iv = parse_Attributes(p_read, "IV");
787 msg_Err(s, "#EXT-X-KEY: IV not expected");
793 else if (strncasecmp(attr, "AES-128", 7) == 0)
795 char *value, *uri, *iv;
796 if (s->p_sys->b_aesmsg == false)
798 msg_Dbg(s, "playback of AES-128 encrypted HTTP Live media detected.");
799 s->p_sys->b_aesmsg = true;
801 value = uri = parse_Attributes(p_read, "URI");
804 msg_Err(s, "#EXT-X-KEY: URI not found for encrypted HTTP Live media in AES-128");
809 /* Url is put between quotes, remove them */
812 /* We need to strip the "" from the attribute value */
814 char* end = strchr(uri, '"');
818 /* For absolute URI, just duplicate it
819 * don't limit to HTTP, maybe some sanity checking
820 * should be done more in here? */
821 if( strstr( uri , "://" ) )
822 hls->psz_current_key_path = strdup( uri );
824 hls->psz_current_key_path = relative_URI(hls->url, uri);
827 value = iv = parse_Attributes(p_read, "IV");
831 * If the EXT-X-KEY tag does not have the IV attribute, implementations
832 * MUST use the sequence number of the media file as the IV when
833 * encrypting or decrypting that media file. The big-endian binary
834 * representation of the sequence number SHALL be placed in a 16-octet
835 * buffer and padded (on the left) with zeros.
837 hls->b_iv_loaded = false;
842 * If the EXT-X-KEY tag has the IV attribute, implementations MUST use
843 * the attribute value as the IV when encrypting or decrypting with that
844 * key. The value MUST be interpreted as a 128-bit hexadecimal number
845 * and MUST be prefixed with 0x or 0X.
848 if (string_to_IV(iv, hls->psz_AES_IV) == VLC_EGENERIC)
850 msg_Err(s, "IV invalid");
854 hls->b_iv_loaded = true;
860 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
867 static int parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
870 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
874 static int parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
878 char answer[4] = "\0";
879 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
882 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
886 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
890 static int parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
895 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
898 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
903 hls->version = version;
904 if (hls->version <= 0 || hls->version > 3)
906 msg_Err(s, "#EXT-X-VERSION should be version 1, 2 or 3 iso %d", version);
912 static int parse_EndList(stream_t *s, hls_stream_t *hls)
916 s->p_sys->b_live = false;
917 msg_Dbg(s, "video on demand (vod) mode");
921 static int parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
925 /* FIXME: Do we need to act on discontinuity ?? */
926 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
930 static int hls_CompareStreams( const void* a, const void* b )
932 hls_stream_t* stream_a = *(hls_stream_t**)a;
933 hls_stream_t* stream_b = *(hls_stream_t**)b;
935 return stream_a->bandwidth - stream_b->bandwidth;
938 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
939 * document defines the following new tags: EXT-X-TARGETDURATION,
940 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
941 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
944 static int parse_M3U8(stream_t *s, vlc_array_t *streams, uint8_t *buffer, const ssize_t len)
946 stream_sys_t *p_sys = s->p_sys;
947 uint8_t *p_read, *p_begin, *p_end;
952 msg_Dbg(s, "parse_M3U8\n%s", buffer);
954 p_end = p_begin + len;
956 char *line = ReadLine(p_begin, &p_read, p_end - p_begin);
961 if (strncmp(line, "#EXTM3U", 7) != 0)
963 msg_Err(s, "missing #EXTM3U tag .. aborting");
971 /* What is the version ? */
973 uint8_t *p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-VERSION:");
977 char *psz_version = ReadLine(p, &tmp, p_end - p);
978 if (psz_version == NULL)
980 int ret = sscanf((const char*)psz_version, "#EXT-X-VERSION:%d", &version);
983 msg_Warn(s, "#EXT-X-VERSION: no protocol version found, assuming version 1.");
990 /* Is it a live stream ? */
991 p_sys->b_live = (strstr((const char *)buffer, "#EXT-X-ENDLIST") == NULL) ? true : false;
993 /* Is it a meta index file ? */
994 bool b_meta = (strstr((const char *)buffer, "#EXT-X-STREAM-INF") == NULL) ? false : true;
996 int err = VLC_SUCCESS;
1000 msg_Dbg(s, "Meta playlist");
1002 /* M3U8 Meta Index file */
1005 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1011 if (strncmp(line, "#EXT-X-STREAM-INF", 17) == 0)
1013 p_sys->b_meta = true;
1014 char *uri = ReadLine(p_begin, &p_read, p_end - p_begin);
1021 msg_Warn(s, "Skipping invalid stream-inf: %s", uri);
1026 bool new_stream_added = false;
1027 hls_stream_t *hls = NULL;
1028 err = parse_StreamInformation(s, &streams, &hls, line, uri);
1029 if (err == VLC_SUCCESS)
1030 new_stream_added = true;
1036 /* Download playlist file from server */
1037 uint8_t *buf = NULL;
1038 ssize_t len = read_M3U8_from_url(s, hls->url, &buf);
1041 msg_Warn(s, "failed to read %s, continue for other streams", hls->url);
1043 /* remove stream just added */
1044 if (new_stream_added)
1045 vlc_array_remove(streams, vlc_array_count(streams) - 1);
1047 /* ignore download error, so we have chance to try other streams */
1052 /* Parse HLS m3u8 content. */
1053 err = parse_M3U8(s, streams, buf, len);
1057 hls->version = version;
1059 hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
1069 if (p_begin >= p_end)
1072 } while (err == VLC_SUCCESS);
1074 size_t stream_count = vlc_array_count(streams);
1075 msg_Dbg(s, "%d streams loaded in Meta playlist", (int)stream_count);
1076 if (stream_count == 0)
1078 msg_Err(s, "No playable streams found in Meta playlist");
1084 msg_Dbg(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
1086 hls_stream_t *hls = NULL;
1088 hls = hls_GetLast(streams);
1091 /* No Meta playlist used */
1092 hls = hls_New(streams, 0, 0, p_sys->m3u8);
1095 /* Get TARGET-DURATION first */
1096 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1099 uint8_t *p_rest = NULL;
1100 char *psz_duration = ReadLine(p, &p_rest, p_end - p);
1101 if (psz_duration == NULL)
1102 return VLC_EGENERIC;
1103 err = parse_TargetDuration(s, hls, psz_duration);
1109 hls->version = version;
1111 else return VLC_ENOMEM;
1116 bool media_sequence_loaded = false;
1117 int segment_duration = -1;
1121 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1126 if (strncmp(line, "#EXTINF", 7) == 0)
1127 err = parse_SegmentInformation(hls, line, &segment_duration);
1128 else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1129 err = parse_TargetDuration(s, hls, line);
1130 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1132 /* A Playlist file MUST NOT contain more than one EXT-X-MEDIA-SEQUENCE tag. */
1133 /* We only care about first one */
1134 if (!media_sequence_loaded)
1136 err = parse_MediaSequence(s, hls, line);
1137 media_sequence_loaded = true;
1140 else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1141 err = parse_Key(s, hls, line);
1142 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1143 err = parse_ProgramDateTime(s, hls, line);
1144 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1145 err = parse_AllowCache(s, hls, line);
1146 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1147 err = parse_Discontinuity(s, hls, line);
1148 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1149 err = parse_Version(s, hls, line);
1150 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1151 err = parse_EndList(s, hls);
1152 else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1154 err = parse_AddSegment(hls, segment_duration, line);
1155 segment_duration = -1; /* reset duration */
1161 if (p_begin >= p_end)
1164 } while (err == VLC_SUCCESS);
1173 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1175 stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1178 msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1179 return VLC_EGENERIC;
1182 int len = stream_Read(p_m3u8, seg->aes_key, sizeof(seg->aes_key));
1183 stream_Delete(p_m3u8);
1184 if (len != AES_BLOCK_SIZE)
1186 msg_Err(s, "The AES key loaded doesn't have the right size (%d)", len);
1187 return VLC_EGENERIC;
1193 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1195 segment_t *seg = NULL;
1196 segment_t *prev_seg;
1197 int count = vlc_array_count(hls->segments);
1199 for (int i = 0; i < count; i++)
1202 seg = segment_GetSegment(hls, i);
1205 if (seg->psz_key_path == NULL)
1206 continue; /* No key to load ? continue */
1207 if (seg->b_key_loaded)
1208 continue; /* The key is already loaded */
1210 /* if the key has not changed, and already available from previous segment,
1211 * try to copy it, and don't load the key */
1212 if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1214 memcpy(seg->aes_key, prev_seg->aes_key, AES_BLOCK_SIZE);
1215 seg->b_key_loaded = true;
1218 if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1219 return VLC_EGENERIC;
1220 seg->b_key_loaded = true;
1225 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1227 /* Did the segment need to be decoded ? */
1228 if (segment->psz_key_path == NULL)
1231 /* Do we have loaded the key ? */
1232 if (!segment->b_key_loaded)
1234 /* No ? try to download it now */
1235 if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1236 return VLC_EGENERIC;
1239 /* For now, we only decode AES-128 data */
1240 gcry_error_t i_gcrypt_err;
1241 gcry_cipher_hd_t aes_ctx;
1243 i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1244 GCRY_CIPHER_MODE_CBC, 0);
1247 msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1248 gcry_cipher_close(aes_ctx);
1249 return VLC_EGENERIC;
1253 i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->aes_key,
1254 sizeof(segment->aes_key));
1257 msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1258 gcry_cipher_close(aes_ctx);
1259 return VLC_EGENERIC;
1262 if (hls->b_iv_loaded == false)
1264 memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1265 hls->psz_AES_IV[15] = segment->sequence & 0xff;
1266 hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1267 hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1268 hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1271 i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1272 sizeof(hls->psz_AES_IV));
1276 msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1277 gcry_cipher_close(aes_ctx);
1278 return VLC_EGENERIC;
1281 i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1282 segment->data->p_buffer, /* out */
1283 segment->data->i_buffer,
1288 msg_Err(s, "gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1289 gcry_cipher_close(aes_ctx);
1290 return VLC_EGENERIC;
1292 gcry_cipher_close(aes_ctx);
1293 /* remove the PKCS#7 padding from the buffer */
1294 int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1295 if (pad <= 0 || pad > AES_BLOCK_SIZE)
1297 msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1298 return VLC_EGENERIC;
1303 if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1305 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1306 return VLC_EGENERIC;
1310 /* not all the data is readable because of padding */
1311 segment->data->i_buffer -= pad;
1316 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1318 stream_sys_t *p_sys = s->p_sys;
1320 int err = VLC_EGENERIC;
1322 /* Duplicate HLS stream META information */
1323 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1325 hls_stream_t *src, *dst;
1326 src = hls_Get(p_sys->hls_stream, i);
1328 return VLC_EGENERIC;
1330 dst = hls_Copy(src, false);
1333 vlc_array_append(*streams, dst);
1335 /* Download playlist file from server */
1336 uint8_t *buf = NULL;
1337 ssize_t len = read_M3U8_from_url(s, dst->url, &buf);
1342 /* Parse HLS m3u8 content. */
1343 err = parse_M3U8(s, *streams, buf, len);
1350 /* Update hls_old (an existing member of p_sys->hls_stream) to match hls_new
1351 (which represents a downloaded, perhaps newer version of the same playlist) */
1352 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t *hls_old, bool *stream_appended)
1354 int count = vlc_array_count(hls_new->segments);
1356 msg_Dbg(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1357 hls_new->id, hls_new->bandwidth, count);
1359 vlc_mutex_lock(&hls_old->lock);
1360 for (int n = 0; n < count; n++)
1362 segment_t *p = segment_GetSegment(hls_new, n);
1365 vlc_mutex_unlock(&hls_old->lock);
1366 return VLC_EGENERIC;
1369 segment_t *segment = segment_Find(hls_old, p->sequence);
1372 vlc_mutex_lock(&segment->lock);
1375 assert(segment->url);
1377 /* they should be the same */
1378 if ((p->sequence != segment->sequence) ||
1379 (p->duration != segment->duration) ||
1380 (strcmp(p->url, segment->url) != 0))
1382 msg_Warn(s, "existing segment found with different content - resetting");
1383 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1384 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1385 msg_Warn(s, "- file: new=%s", p->url);
1386 msg_Warn(s, " old=%s", segment->url);
1388 /* Resetting content */
1389 segment->sequence = p->sequence;
1390 segment->duration = p->duration;
1392 segment->url = strdup(p->url);
1393 if ( segment->url == NULL )
1395 msg_Err(s, "Failed updating segment %d - skipping it", p->sequence);
1397 vlc_mutex_unlock(&segment->lock);
1400 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1401 if ((p->psz_key_path || p->b_key_loaded) &&
1404 block_Release(segment->data);
1405 segment->data = NULL;
1407 free(segment->psz_key_path);
1408 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1411 vlc_mutex_unlock(&segment->lock);
1415 int last = vlc_array_count(hls_old->segments) - 1;
1416 segment_t *l = segment_GetSegment(hls_old, last);
1418 vlc_mutex_unlock(&hls_old->lock);
1419 return VLC_EGENERIC;
1422 if ((l->sequence + 1) != p->sequence)
1424 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1425 p->sequence, l->sequence+1);
1427 vlc_array_append(hls_old->segments, p);
1428 msg_Dbg(s, "- segment %d appended", p->sequence);
1430 // Signal download thread otherwise the segment will not get downloaded
1431 *stream_appended = true;
1435 /* update meta information */
1436 hls_old->sequence = hls_new->sequence;
1437 hls_old->duration = (hls_new->duration == -1) ? hls_old->duration : hls_new->duration;
1438 hls_old->b_cache = hls_new->b_cache;
1439 vlc_mutex_unlock(&hls_old->lock);
1444 static int hls_ReloadPlaylist(stream_t *s)
1446 stream_sys_t *p_sys = s->p_sys;
1448 // Flag to indicate if we should signal download thread
1449 bool stream_appended = false;
1451 vlc_array_t *hls_streams = vlc_array_new();
1452 if (hls_streams == NULL)
1455 msg_Dbg(s, "Reloading HLS live meta playlist");
1457 if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1459 /* Free hls streams */
1460 for (int i = 0; i < vlc_array_count(hls_streams); i++)
1463 hls = hls_Get(hls_streams, i);
1464 if (hls) hls_Free(hls);
1466 vlc_array_destroy(hls_streams);
1468 msg_Err(s, "reloading playlist failed");
1469 return VLC_EGENERIC;
1472 /* merge playlists */
1473 int count = vlc_array_count(hls_streams);
1474 for (int n = 0; n < count; n++)
1476 hls_stream_t *hls_new = hls_Get(hls_streams, n);
1477 if (hls_new == NULL)
1480 hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1481 if (hls_old == NULL)
1482 { /* new hls stream - append */
1483 vlc_array_append(p_sys->hls_stream, hls_new);
1484 msg_Dbg(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1485 hls_new->id, hls_new->bandwidth);
1487 // New segment available - signal download thread
1488 stream_appended = true;
1490 else if (hls_UpdatePlaylist(s, hls_new, hls_old, &stream_appended) != VLC_SUCCESS)
1491 msg_Warn(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1492 hls_new->id, hls_new->bandwidth);
1494 vlc_array_destroy(hls_streams);
1496 // Must signal the download thread otherwise new segments will not be downloaded at all!
1497 if (stream_appended == true)
1499 vlc_mutex_lock(&p_sys->download.lock_wait);
1500 vlc_cond_signal(&p_sys->download.wait);
1501 vlc_mutex_unlock(&p_sys->download.lock_wait);
1507 /****************************************************************************
1509 ****************************************************************************/
1510 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1512 stream_sys_t *p_sys = s->p_sys;
1514 uint64_t bw = *bandwidth;
1515 uint64_t bw_candidate = 0;
1517 int count = vlc_array_count(p_sys->hls_stream);
1518 for (int n = 0; n < count; n++)
1520 /* Select best bandwidth match */
1521 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1522 if (hls == NULL) break;
1524 /* only consider streams with the same PROGRAM-ID */
1525 if (hls->id == progid)
1527 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1529 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1530 n, bw, hls->bandwidth); /* bits / s */
1531 bw_candidate = hls->bandwidth;
1532 candidate = n; /* possible candidate */
1536 *bandwidth = bw_candidate;
1540 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1542 stream_sys_t *p_sys = s->p_sys;
1547 vlc_mutex_lock(&segment->lock);
1548 if (segment->data != NULL)
1550 /* Segment already downloaded */
1551 vlc_mutex_unlock(&segment->lock);
1555 /* sanity check - can we download this segment on time? */
1556 if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1558 uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1559 int estimated = (int)(size / p_sys->bandwidth);
1560 if (estimated > segment->duration)
1562 msg_Warn(s,"downloading segment %d predicted to take %ds, which exceeds its length (%ds)",
1563 segment->sequence, estimated, segment->duration);
1567 mtime_t start = mdate();
1568 if (hls_Download(s, segment) != VLC_SUCCESS)
1570 msg_Err(s, "downloading segment %d from stream %d failed",
1571 segment->sequence, *cur_stream);
1572 vlc_mutex_unlock(&segment->lock);
1573 return VLC_EGENERIC;
1575 mtime_t duration = mdate() - start;
1576 if (hls->bandwidth == 0 && segment->duration > 0)
1578 /* Try to estimate the bandwidth for this stream */
1579 hls->bandwidth = (uint64_t)(((double)segment->size * 8) / ((double)segment->duration));
1582 /* If the segment is encrypted, decode it */
1583 if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1585 vlc_mutex_unlock(&segment->lock);
1586 return VLC_EGENERIC;
1589 vlc_mutex_unlock(&segment->lock);
1591 msg_Dbg(s, "downloaded segment %d from stream %d",
1592 segment->sequence, *cur_stream);
1594 uint64_t bw = segment->size * 8 * 1000000 / __MAX(1, duration); /* bits / s */
1595 p_sys->bandwidth = bw;
1596 if (p_sys->b_meta && (hls->bandwidth != bw))
1598 int newstream = BandwidthAdaptation(s, hls->id, &bw);
1600 /* FIXME: we need an average here */
1601 if ((newstream >= 0) && (newstream != *cur_stream))
1603 msg_Dbg(s, "detected %s bandwidth (%"PRIu64") stream",
1604 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1605 *cur_stream = newstream;
1611 static void* hls_Thread(void *p_this)
1613 stream_t *s = (stream_t *)p_this;
1614 stream_sys_t *p_sys = s->p_sys;
1616 int canc = vlc_savecancel();
1618 while (vlc_object_alive(s))
1620 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1623 /* Sliding window (~60 seconds worth of movie) */
1624 vlc_mutex_lock(&hls->lock);
1625 int count = vlc_array_count(hls->segments);
1626 vlc_mutex_unlock(&hls->lock);
1628 /* Is there a new segment to process? */
1629 if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1630 (p_sys->download.segment >= count))
1633 vlc_mutex_lock(&p_sys->download.lock_wait);
1634 while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1635 (p_sys->download.segment >= count)) &&
1636 (p_sys->download.seek == -1))
1638 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1639 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1641 if (!vlc_object_alive(s))
1645 if (p_sys->download.seek >= 0)
1647 p_sys->download.segment = p_sys->download.seek;
1648 p_sys->download.seek = -1;
1650 vlc_mutex_unlock(&p_sys->download.lock_wait);
1653 if (!vlc_object_alive(s)) break;
1655 vlc_mutex_lock(&hls->lock);
1656 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1657 vlc_mutex_unlock(&hls->lock);
1659 if ((segment != NULL) &&
1660 (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1662 if (!vlc_object_alive(s)) break;
1666 p_sys->b_error = true;
1671 /* download succeeded */
1672 /* determine next segment to download */
1673 vlc_mutex_lock(&p_sys->download.lock_wait);
1674 if (p_sys->download.seek >= 0)
1676 p_sys->download.segment = p_sys->download.seek;
1677 p_sys->download.seek = -1;
1679 else if (p_sys->download.segment < count)
1680 p_sys->download.segment++;
1681 vlc_cond_signal(&p_sys->download.wait);
1682 vlc_mutex_unlock(&p_sys->download.lock_wait);
1684 // In case of a successful download signal the read thread that data is available
1685 vlc_mutex_lock(&p_sys->read.lock_wait);
1686 vlc_cond_signal(&p_sys->read.wait);
1687 vlc_mutex_unlock(&p_sys->read.lock_wait);
1690 vlc_restorecancel(canc);
1694 static void* hls_Reload(void *p_this)
1696 stream_t *s = (stream_t *)p_this;
1697 stream_sys_t *p_sys = s->p_sys;
1699 assert(p_sys->b_live);
1701 int canc = vlc_savecancel();
1704 while (vlc_object_alive(s))
1706 mtime_t now = mdate();
1707 if (now >= p_sys->playlist.wakeup)
1709 /* reload the m3u8 if there are less than 2 segments what aren't downloaded */
1710 if ( ( p_sys->download.segment - p_sys->playback.segment < 2 ) &&
1711 ( hls_ReloadPlaylist(s) != VLC_SUCCESS) )
1713 /* No change in playlist, then backoff */
1714 p_sys->playlist.tries++;
1715 if (p_sys->playlist.tries == 1) wait = 0.5;
1716 else if (p_sys->playlist.tries == 2) wait = 1;
1717 else if (p_sys->playlist.tries >= 3) wait = 1.5;
1719 /* Can we afford to backoff? */
1720 if (p_sys->download.segment - p_sys->playback.segment < 3)
1722 p_sys->playlist.tries = 0;
1728 p_sys->playlist.tries = 0;
1732 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1735 /* determine next time to update playlist */
1736 p_sys->playlist.last = now;
1737 p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1738 * (mtime_t)1000000);
1741 mwait(p_sys->playlist.wakeup);
1744 vlc_restorecancel(canc);
1748 static int Prefetch(stream_t *s, int *current)
1750 stream_sys_t *p_sys = s->p_sys;
1751 int stream = *current;
1753 hls_stream_t *hls = hls_Get(p_sys->hls_stream, stream);
1755 return VLC_EGENERIC;
1757 if (vlc_array_count(hls->segments) == 0)
1758 return VLC_EGENERIC;
1759 else if (vlc_array_count(hls->segments) == 1 && p_sys->b_live)
1760 msg_Warn(s, "Only 1 segment available to prefetch in live stream; may stall");
1762 /* Download ~10s worth of segments of this HLS stream if they exist */
1763 unsigned segment_amount = (0.5f + 10/hls->duration);
1764 for (int i = 0; i < __MIN(vlc_array_count(hls->segments), segment_amount); i++)
1766 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1767 if (segment == NULL )
1768 return VLC_EGENERIC;
1770 /* It is useless to lock the segment here, as Prefetch is called before
1771 download and playlit thread are started. */
1774 p_sys->download.segment++;
1778 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1779 return VLC_EGENERIC;
1781 p_sys->download.segment++;
1783 /* adapt bandwidth? */
1784 if (*current != stream)
1786 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1788 return VLC_EGENERIC;
1797 /****************************************************************************
1799 ****************************************************************************/
1800 static int hls_Download(stream_t *s, segment_t *segment)
1802 stream_sys_t *p_sys = s->p_sys;
1805 vlc_mutex_lock(&p_sys->lock);
1806 while (p_sys->paused)
1807 vlc_cond_wait(&p_sys->wait, &p_sys->lock);
1808 vlc_mutex_unlock(&p_sys->lock);
1810 stream_t *p_ts = stream_UrlNew(s, segment->url);
1812 return VLC_EGENERIC;
1814 segment->size = stream_Size(p_ts);
1815 assert(segment->size > 0);
1817 segment->data = block_Alloc(segment->size);
1818 if (segment->data == NULL)
1820 stream_Delete(p_ts);
1824 assert(segment->data->i_buffer == segment->size);
1826 ssize_t length = 0, curlen = 0;
1830 /* NOTE: Beware the size reported for a segment by the HLS server may not
1831 * be correct, when downloading the segment data. Therefore check the size
1832 * and enlarge the segment data block if necessary.
1834 size = stream_Size(p_ts);
1835 if (size > segment->size)
1837 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1838 block_t *p_block = block_Realloc(segment->data, 0, size);
1839 if (p_block == NULL)
1841 stream_Delete(p_ts);
1842 block_Release(segment->data);
1843 segment->data = NULL;
1846 segment->data = p_block;
1847 segment->size = size;
1848 assert(segment->data->i_buffer == segment->size);
1851 length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1855 } while (vlc_object_alive(s));
1857 stream_Delete(p_ts);
1861 /* Read M3U8 file */
1862 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1864 int64_t total_bytes = 0;
1865 int64_t total_allocated = 0;
1873 bytes = stream_Read(s, buf, sizeof(buf));
1882 if ( (total_bytes + bytes + 1) > total_allocated )
1884 if (total_allocated)
1885 total_allocated *= 2;
1887 total_allocated = __MIN((uint64_t)bytes+1, sizeof(buf));
1889 p = realloc_or_free(p, total_allocated);
1894 memcpy(p+total_bytes, buf, bytes);
1895 total_bytes += bytes;
1898 if (total_allocated == 0)
1899 return VLC_EGENERIC;
1901 p[total_bytes] = '\0';
1907 static ssize_t read_M3U8_from_url(stream_t *s, const char* psz_url, uint8_t **buffer)
1909 assert(*buffer == NULL);
1912 stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1914 return VLC_EGENERIC;
1916 ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1917 stream_Delete(p_m3u8);
1922 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1927 uint8_t *begin = buffer;
1929 uint8_t *end = p + len;
1933 if ((*p == '\r') || (*p == '\n') || (*p == '\0'))
1938 /* copy line excluding \r \n or \0 */
1939 line = strndup((char *)begin, p - begin);
1941 while ((*p == '\r') || (*p == '\n') || (*p == '\0'))
1950 /* next pass start after \r and \n */
1959 /****************************************************************************
1961 ****************************************************************************/
1962 static int Open(vlc_object_t *p_this)
1964 stream_t *s = (stream_t*)p_this;
1965 stream_sys_t *p_sys;
1967 if (!isHTTPLiveStreaming(s))
1968 return VLC_EGENERIC;
1970 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1972 /* Initialize crypto bit */
1976 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1980 char *psz_uri = NULL;
1981 if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1986 p_sys->m3u8 = psz_uri;
1989 if (asprintf(&new_path, "%s.ts", s->psz_path) < 0)
1996 s->psz_path = new_path;
1998 p_sys->bandwidth = 0;
1999 p_sys->b_live = true;
2000 p_sys->b_meta = false;
2001 p_sys->b_error = false;
2003 p_sys->hls_stream = vlc_array_new();
2004 if (p_sys->hls_stream == NULL)
2014 s->pf_control = Control;
2016 p_sys->paused = false;
2018 vlc_cond_init(&p_sys->wait);
2019 vlc_mutex_init(&p_sys->lock);
2021 /* Parse HLS m3u8 content. */
2022 uint8_t *buffer = NULL;
2023 ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
2026 if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
2032 /* HLS standard doesn't provide any guaranty about streams
2033 being sorted by bandwidth, so we sort them */
2034 qsort( p_sys->hls_stream->pp_elems, p_sys->hls_stream->i_count,
2035 sizeof( hls_stream_t* ), &hls_CompareStreams );
2037 /* Choose first HLS stream to start with */
2038 int current = p_sys->playback.stream = p_sys->hls_stream->i_count-1;
2039 p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
2041 /* manage encryption key if needed */
2042 hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
2044 if (Prefetch(s, ¤t) != VLC_SUCCESS)
2046 msg_Err(s, "fetching first segment failed.");
2050 p_sys->download.stream = current;
2051 p_sys->playback.stream = current;
2052 p_sys->download.seek = -1;
2054 vlc_mutex_init(&p_sys->download.lock_wait);
2055 vlc_cond_init(&p_sys->download.wait);
2057 vlc_mutex_init(&p_sys->read.lock_wait);
2058 vlc_cond_init(&p_sys->read.wait);
2060 /* Initialize HLS live stream */
2063 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
2064 p_sys->playlist.last = mdate();
2065 p_sys->playlist.wakeup = p_sys->playlist.last +
2066 ((mtime_t)hls->duration * UINT64_C(1000000));
2068 if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
2074 if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
2077 vlc_join(p_sys->reload, NULL);
2084 vlc_mutex_destroy(&p_sys->download.lock_wait);
2085 vlc_cond_destroy(&p_sys->download.wait);
2087 vlc_mutex_destroy(&p_sys->read.lock_wait);
2088 vlc_cond_destroy(&p_sys->read.wait);
2091 /* Free hls streams */
2092 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2094 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
2095 if (hls) hls_Free(hls);
2097 vlc_array_destroy(p_sys->hls_stream);
2099 vlc_mutex_destroy(&p_sys->lock);
2100 vlc_cond_destroy(&p_sys->wait);
2105 return VLC_EGENERIC;
2108 /****************************************************************************
2110 ****************************************************************************/
2111 static void Close(vlc_object_t *p_this)
2113 stream_t *s = (stream_t*)p_this;
2114 stream_sys_t *p_sys = s->p_sys;
2116 assert(p_sys->hls_stream);
2118 vlc_mutex_lock(&p_sys->lock);
2119 p_sys->paused = false;
2120 vlc_cond_signal(&p_sys->wait);
2121 vlc_mutex_unlock(&p_sys->lock);
2124 vlc_mutex_lock(&p_sys->download.lock_wait);
2125 /* negate the condition variable's predicate */
2126 p_sys->download.segment = p_sys->playback.segment = 0;
2127 p_sys->download.seek = 0; /* better safe than sorry */
2128 vlc_cond_signal(&p_sys->download.wait);
2129 vlc_mutex_unlock(&p_sys->download.lock_wait);
2133 vlc_join(p_sys->reload, NULL);
2134 vlc_join(p_sys->thread, NULL);
2135 vlc_mutex_destroy(&p_sys->download.lock_wait);
2136 vlc_cond_destroy(&p_sys->download.wait);
2138 vlc_mutex_destroy(&p_sys->read.lock_wait);
2139 vlc_cond_destroy(&p_sys->read.wait);
2141 /* Free hls streams */
2142 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
2144 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
2145 if (hls) hls_Free(hls);
2147 vlc_array_destroy(p_sys->hls_stream);
2151 vlc_mutex_destroy(&p_sys->lock);
2152 vlc_cond_destroy(&p_sys->wait);
2156 block_Release (p_sys->peeked);
2160 /****************************************************************************
2161 * Stream filters functions
2162 ****************************************************************************/
2163 static segment_t *GetSegment(stream_t *s)
2165 stream_sys_t *p_sys = s->p_sys;
2166 segment_t *segment = NULL;
2168 /* Is this segment of the current HLS stream ready? */
2169 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2172 vlc_mutex_lock(&hls->lock);
2173 segment = segment_GetSegment(hls, p_sys->playback.segment);
2174 if (segment != NULL)
2176 vlc_mutex_lock(&segment->lock);
2177 /* This segment is ready? */
2178 if (segment->data != NULL)
2180 vlc_mutex_unlock(&segment->lock);
2181 p_sys->b_cache = hls->b_cache;
2182 vlc_mutex_unlock(&hls->lock);
2185 vlc_mutex_unlock(&segment->lock);
2187 vlc_mutex_unlock(&hls->lock);
2190 /* Was the HLS stream changed to another bitrate? */
2192 for (int i_stream = 0; i_stream < vlc_array_count(p_sys->hls_stream); i_stream++)
2194 /* Is the next segment ready */
2195 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2199 vlc_mutex_lock(&hls->lock);
2200 segment = segment_GetSegment(hls, p_sys->playback.segment);
2201 if (segment == NULL)
2203 vlc_mutex_unlock(&hls->lock);
2207 vlc_mutex_lock(&p_sys->download.lock_wait);
2208 int i_segment = p_sys->download.segment;
2209 vlc_mutex_unlock(&p_sys->download.lock_wait);
2211 vlc_mutex_lock(&segment->lock);
2212 /* This segment is ready? */
2213 if ((segment->data != NULL) &&
2214 (p_sys->playback.segment < i_segment))
2216 p_sys->playback.stream = i_stream;
2217 p_sys->b_cache = hls->b_cache;
2218 vlc_mutex_unlock(&segment->lock);
2219 vlc_mutex_unlock(&hls->lock);
2222 vlc_mutex_unlock(&segment->lock);
2223 vlc_mutex_unlock(&hls->lock);
2233 assert(segment->data);
2234 if (segment->data->i_buffer == 0)
2236 vlc_mutex_lock(&hls->lock);
2237 int count = vlc_array_count(hls->segments);
2238 vlc_mutex_unlock(&hls->lock);
2240 if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2241 ((count != p_sys->download.segment) || p_sys->b_live))
2242 msg_Err(s, "playback will stall");
2243 else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2244 ((count != p_sys->download.segment) || p_sys->b_live))
2245 msg_Warn(s, "playback in danger of stalling");
2250 static int segment_RestorePos(segment_t *segment)
2254 uint64_t size = segment->size - segment->data->i_buffer;
2257 segment->data->i_buffer += size;
2258 segment->data->p_buffer -= size;
2264 /* p_read might be NULL if caller wants to skip data */
2265 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2267 stream_sys_t *p_sys = s->p_sys;
2272 /* Determine next segment to read. If this is a meta playlist and
2273 * bandwidth conditions changed, then the stream might have switched
2274 * to another bandwidth. */
2275 segment_t *segment = GetSegment(s);
2276 if (segment == NULL)
2279 vlc_mutex_lock(&segment->lock);
2280 if (segment->data->i_buffer == 0)
2282 if (!p_sys->b_cache || p_sys->b_live)
2284 block_Release(segment->data);
2285 segment->data = NULL;
2288 segment_RestorePos(segment);
2290 vlc_mutex_unlock(&segment->lock);
2292 /* signal download thread */
2293 vlc_mutex_lock(&p_sys->download.lock_wait);
2294 p_sys->playback.segment++;
2295 vlc_cond_signal(&p_sys->download.wait);
2296 vlc_mutex_unlock(&p_sys->download.lock_wait);
2300 if (segment->size == segment->data->i_buffer)
2301 msg_Dbg(s, "playing segment %d from stream %d",
2302 segment->sequence, p_sys->playback.stream);
2305 if (i_read <= segment->data->i_buffer)
2307 else if (i_read > segment->data->i_buffer)
2308 len = segment->data->i_buffer;
2312 if (p_read) /* if NULL, then caller skips data */
2313 memcpy(p_read + used, segment->data->p_buffer, len);
2314 segment->data->i_buffer -= len;
2315 segment->data->p_buffer += len;
2319 vlc_mutex_unlock(&segment->lock);
2321 } while (i_read > 0);
2326 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2328 stream_sys_t *p_sys = s->p_sys;
2331 assert(p_sys->hls_stream);
2335 // In case an error occurred or the stream was closed return 0
2336 if (p_sys->b_error || !vlc_object_alive(s))
2339 // Lock the mutex before trying to read to avoid a race condition with the download thread
2340 vlc_mutex_lock(&p_sys->read.lock_wait);
2342 /* NOTE: buffer might be NULL if caller wants to skip data */
2343 length = hls_Read(s, (uint8_t*) buffer, i_read);
2345 // An error has occurred in hls_Read
2348 vlc_mutex_unlock(&p_sys->read.lock_wait);
2353 // There is no data available yet for the demuxer so we need to wait until reload and
2354 // download operation are over.
2355 // Download thread will signal once download is finished.
2356 // A timed wait is used to avoid deadlock in case data never arrives since the thread
2357 // running this read operation is also responsible for closing the stream
2360 mtime_t start = mdate();
2362 // Wait for 10 seconds
2363 mtime_t timeout_limit = start + (10 * UINT64_C(1000000));
2365 int res = vlc_cond_timedwait(&p_sys->read.wait, &p_sys->read.lock_wait, timeout_limit);
2367 // Error - reached a timeout of 10 seconds without data arriving - kill the stream
2368 if (res == ETIMEDOUT)
2370 msg_Warn(s, "timeout limit reached!");
2372 vlc_mutex_unlock(&p_sys->read.lock_wait);
2376 else if (res == EINVAL)
2377 return 0; // Error - lock is not locked so we can just return
2380 vlc_mutex_unlock(&p_sys->read.lock_wait);
2383 p_sys->playback.offset += length;
2387 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2389 stream_sys_t *p_sys = s->p_sys;
2391 unsigned int len = i_peek;
2393 segment = GetSegment(s);
2394 if (segment == NULL)
2396 msg_Err(s, "segment %d should have been available (stream %d)",
2397 p_sys->playback.segment, p_sys->playback.stream);
2398 return 0; /* eof? */
2401 vlc_mutex_lock(&segment->lock);
2403 size_t i_buff = segment->data->i_buffer;
2404 uint8_t *p_buff = segment->data->p_buffer;
2406 if ( likely(i_peek < i_buff))
2409 vlc_mutex_unlock(&segment->lock);
2413 else /* This will seldom be run */
2415 /* remember segment to read */
2416 int peek_segment = p_sys->playback.segment;
2418 segment_t *nsegment;
2419 p_sys->playback.segment++;
2420 block_t *peeked = p_sys->peeked;
2423 peeked = block_Alloc (i_peek);
2424 else if (peeked->i_buffer < i_peek)
2425 peeked = block_Realloc (peeked, 0, i_peek);
2428 vlc_mutex_unlock(&segment->lock);
2431 p_sys->peeked = peeked;
2433 memcpy(peeked->p_buffer, p_buff, i_buff);
2436 vlc_mutex_unlock(&segment->lock);
2438 i_buff = peeked->i_buffer;
2439 p_buff = peeked->p_buffer;
2442 while (curlen < i_peek)
2444 nsegment = GetSegment(s);
2445 if (nsegment == NULL)
2447 msg_Err(s, "segment %d should have been available (stream %d)",
2448 p_sys->playback.segment, p_sys->playback.stream);
2449 /* restore segment to read */
2450 p_sys->playback.segment = peek_segment;
2451 return curlen; /* eof? */
2454 vlc_mutex_lock(&nsegment->lock);
2456 if (len < nsegment->data->i_buffer)
2458 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2463 size_t i_nbuff = nsegment->data->i_buffer;
2464 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2468 p_sys->playback.segment++;
2471 vlc_mutex_unlock(&nsegment->lock);
2474 /* restore segment to read */
2475 p_sys->playback.segment = peek_segment;
2480 static bool hls_MaySeek(stream_t *s)
2482 stream_sys_t *p_sys = s->p_sys;
2484 if (p_sys->hls_stream == NULL)
2487 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2488 if (hls == NULL) return false;
2492 vlc_mutex_lock(&hls->lock);
2493 int count = vlc_array_count(hls->segments);
2494 vlc_mutex_unlock(&hls->lock);
2496 vlc_mutex_lock(&p_sys->download.lock_wait);
2497 bool may_seek = (p_sys->download.segment < (count - 2));
2498 vlc_mutex_unlock(&p_sys->download.lock_wait);
2504 static uint64_t GetStreamSize(stream_t *s)
2506 stream_sys_t *p_sys = s->p_sys;
2511 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2512 if (hls == NULL) return 0;
2514 vlc_mutex_lock(&hls->lock);
2516 hls->size = hls_GetStreamSize(hls);
2517 uint64_t size = hls->size;
2518 vlc_mutex_unlock(&hls->lock);
2523 static int segment_Seek(stream_t *s, const uint64_t pos)
2525 stream_sys_t *p_sys = s->p_sys;
2527 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2529 return VLC_EGENERIC;
2531 vlc_mutex_lock(&hls->lock);
2533 bool b_found = false;
2534 uint64_t length = 0;
2535 uint64_t size = hls->size;
2536 int count = vlc_array_count(hls->segments);
2538 segment_t *currentSegment = segment_GetSegment(hls, p_sys->playback.segment);
2539 if (currentSegment == NULL)
2541 vlc_mutex_unlock(&hls->lock);
2542 return VLC_EGENERIC;
2545 for (int n = 0; n < count; n++)
2547 segment_t *segment = segment_GetSegment(hls, n);
2548 if (segment == NULL)
2550 vlc_mutex_unlock(&hls->lock);
2551 return VLC_EGENERIC;
2554 vlc_mutex_lock(&segment->lock);
2555 length += segment->duration * (hls->bandwidth/8);
2556 vlc_mutex_unlock(&segment->lock);
2562 p_sys->playback.segment = n;
2566 /* Do not search in last 3 segments */
2567 vlc_mutex_unlock(&hls->lock);
2568 return VLC_EGENERIC;
2573 if (!b_found && (pos >= size))
2575 p_sys->playback.segment = count - 1;
2583 /* restore current segment to start position */
2584 vlc_mutex_lock(¤tSegment->lock);
2585 segment_RestorePos(currentSegment);
2586 vlc_mutex_unlock(¤tSegment->lock);
2588 /* restore seeked segment to start position */
2589 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2590 if (segment == NULL)
2592 vlc_mutex_unlock(&hls->lock);
2593 return VLC_EGENERIC;
2596 vlc_mutex_lock(&segment->lock);
2597 segment_RestorePos(segment);
2598 vlc_mutex_unlock(&segment->lock);
2600 /* start download at current playback segment */
2601 vlc_mutex_unlock(&hls->lock);
2603 /* Wake up download thread */
2604 vlc_mutex_lock(&p_sys->download.lock_wait);
2605 p_sys->download.seek = p_sys->playback.segment;
2606 vlc_cond_signal(&p_sys->download.wait);
2608 /* Wait for download to be finished */
2609 msg_Dbg(s, "seek to segment %d", p_sys->playback.segment);
2610 while ((p_sys->download.seek != -1) ||
2611 ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2612 (p_sys->download.segment < count)))
2614 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2615 if (!vlc_object_alive(s) || s->b_error) break;
2617 vlc_mutex_unlock(&p_sys->download.lock_wait);
2621 vlc_mutex_unlock(&hls->lock);
2623 return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2626 static int Control(stream_t *s, int i_query, va_list args)
2628 stream_sys_t *p_sys = s->p_sys;
2632 case STREAM_CAN_SEEK:
2633 *(va_arg (args, bool *)) = hls_MaySeek(s);
2635 case STREAM_CAN_CONTROL_PACE:
2636 case STREAM_CAN_PAUSE:
2637 *(va_arg (args, bool *)) = true;
2639 case STREAM_CAN_FASTSEEK:
2640 *(va_arg (args, bool *)) = false;
2642 case STREAM_GET_POSITION:
2643 *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2645 case STREAM_SET_PAUSE_STATE:
2647 bool paused = va_arg (args, unsigned);
2649 vlc_mutex_lock(&p_sys->lock);
2650 p_sys->paused = paused;
2651 vlc_cond_signal(&p_sys->wait);
2652 vlc_mutex_unlock(&p_sys->lock);
2655 case STREAM_SET_POSITION:
2658 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2659 if (segment_Seek(s, pos) == VLC_SUCCESS)
2661 p_sys->playback.offset = pos;
2665 return VLC_EGENERIC;
2666 case STREAM_GET_SIZE:
2667 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2669 case STREAM_GET_PTS_DELAY:
2670 *va_arg (args, int64_t *) =
2671 var_InheritInteger(s, "network-caching");
2674 return VLC_EGENERIC;