1 /*****************************************************************************
2 * httplive.c: HTTP Live Streaming stream filter
3 *****************************************************************************
4 * Copyright (C) 2010-2012 M2X BV
7 * Author: Jean-Paul Saman <jpsaman _AT_ videolan _DOT_ org>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
40 #include <vlc_threads.h>
41 #include <vlc_arrays.h>
42 #include <vlc_stream.h>
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 psz_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 const char *const ext[] = {
169 "#EXT-X-TARGETDURATION",
170 "#EXT-X-MEDIA-SEQUENCE",
172 "#EXT-X-ALLOW-CACHE",
175 "#EXT-X-DISCONTINUITY",
179 static bool isHTTPLiveStreaming(stream_t *s)
181 const uint8_t *peek, *peek_end;
183 int64_t i_size = stream_Peek(s->p_source, &peek, 46);
187 if (strncasecmp((const char*)peek, "#EXTM3U", 7) != 0)
190 /* Parse stream and search for
191 * EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
192 * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
193 peek_end = peek + i_size;
194 while(peek <= peek_end)
198 for (unsigned int i = 0; i < ARRAY_SIZE(ext); i++)
200 char *p = strstr((const char*)peek, ext[i]);
211 /* HTTP Live Streaming */
212 static hls_stream_t *hls_New(vlc_array_t *hls_stream, const int id, const uint64_t bw, const char *uri)
214 hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
215 if (hls == NULL) return NULL;
219 hls->duration = -1;/* unknown */
221 hls->sequence = 0; /* default is 0 */
222 hls->version = 1; /* default protocol version */
224 hls->url = strdup(uri);
225 if (hls->url == NULL)
230 hls->psz_current_key_path = NULL;
231 hls->segments = vlc_array_new();
232 vlc_array_append(hls_stream, hls);
233 vlc_mutex_init(&hls->lock);
237 static void hls_Free(hls_stream_t *hls)
239 vlc_mutex_destroy(&hls->lock);
243 for (int n = 0; n < vlc_array_count(hls->segments); n++)
245 segment_t *segment = segment_GetSegment(hls, n);
246 if (segment) segment_Free(segment);
248 vlc_array_destroy(hls->segments);
251 free(hls->psz_current_key_path);
255 static hls_stream_t *hls_Copy(hls_stream_t *src, const bool b_cp_segments)
258 assert(!b_cp_segments); /* FIXME: copying segments is not implemented */
260 hls_stream_t *dst = (hls_stream_t *)malloc(sizeof(hls_stream_t));
261 if (dst == NULL) return NULL;
264 dst->bandwidth = src->bandwidth;
265 dst->duration = src->duration;
266 dst->size = src->size;
267 dst->sequence = src->sequence;
268 dst->version = src->version;
269 dst->b_cache = src->b_cache;
270 dst->psz_current_key_path = src->psz_current_key_path ?
271 strdup( src->psz_current_key_path ) : NULL;
272 dst->url = strdup(src->url);
273 if (dst->url == NULL)
279 dst->segments = vlc_array_new();
280 vlc_mutex_init(&dst->lock);
284 static hls_stream_t *hls_Get(vlc_array_t *hls_stream, const int wanted)
286 int count = vlc_array_count(hls_stream);
289 if ((wanted < 0) || (wanted >= count))
291 return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
294 static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
296 return hls_Get(hls_stream, 0);
299 static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
301 int count = vlc_array_count(hls_stream);
305 return hls_Get(hls_stream, count);
308 static hls_stream_t *hls_Find(vlc_array_t *hls_stream, hls_stream_t *hls_new)
310 int count = vlc_array_count(hls_stream);
311 for (int n = 0; n < count; n++)
313 hls_stream_t *hls = hls_Get(hls_stream, n);
317 if ((hls->id == hls_new->id) &&
318 ((hls->bandwidth == hls_new->bandwidth)||(hls_new->bandwidth==0)))
325 static uint64_t hls_GetStreamSize(hls_stream_t *hls)
327 /* NOTE: Stream size is calculated based on segment duration and
328 * HLS stream bandwidth from the .m3u8 file. If these are not correct
329 * then the deviation from exact byte size will be big and the seek/
330 * progressbar will not behave entirely as one expects. */
333 /* If there is no valid bandwidth yet, then there is no point in
334 * computing stream size. */
335 if (hls->bandwidth == 0)
338 int count = vlc_array_count(hls->segments);
339 for (int n = 0; n < count; n++)
341 segment_t *segment = segment_GetSegment(hls, n);
344 size += (segment->duration * (hls->bandwidth / 8));
351 static segment_t *segment_New(hls_stream_t* hls, const int duration, const char *uri)
353 segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
357 segment->duration = duration; /* seconds */
358 segment->size = 0; /* bytes */
359 segment->sequence = 0;
360 segment->bandwidth = 0;
361 segment->url = strdup(uri);
362 if (segment->url == NULL)
367 segment->data = NULL;
368 vlc_array_append(hls->segments, segment);
369 vlc_mutex_init(&segment->lock);
370 segment->b_key_loaded = false;
371 segment->psz_key_path = NULL;
372 if (hls->psz_current_key_path)
373 segment->psz_key_path = strdup(hls->psz_current_key_path);
377 static void segment_Free(segment_t *segment)
379 vlc_mutex_destroy(&segment->lock);
382 free(segment->psz_key_path);
384 block_Release(segment->data);
388 static segment_t *segment_GetSegment(hls_stream_t *hls, const int wanted)
392 int count = vlc_array_count(hls->segments);
395 if ((wanted < 0) || (wanted >= count))
397 return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
400 static segment_t *segment_Find(hls_stream_t *hls, const int sequence)
404 int count = vlc_array_count(hls->segments);
405 if (count <= 0) return NULL;
406 for (int n = 0; n < count; n++)
408 segment_t *segment = segment_GetSegment(hls, n);
409 if (segment == NULL) break;
410 if (segment->sequence == sequence)
416 static int ChooseSegment(stream_t *s, const int current)
418 stream_sys_t *p_sys = (stream_sys_t *)s->p_sys;
419 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
420 if (hls == NULL) return 0;
422 /* Choose a segment to start which is no closer than
423 * 3 times the target duration from the end of the playlist.
428 int count = vlc_array_count(hls->segments);
429 int i = p_sys->b_live ? count - 1 : 0;
431 while((i >= 0) && (i < count))
433 segment_t *segment = segment_GetSegment(hls, i);
436 if (segment->duration > hls->duration)
438 msg_Err(s, "EXTINF:%d duration is larger than EXT-X-TARGETDURATION:%d",
439 segment->duration, hls->duration);
442 duration += segment->duration;
443 if (duration >= 3 * hls->duration)
445 /* Start point found */
446 wanted = p_sys->b_live ? i : 0;
447 sequence = segment->sequence;
457 msg_Info(s, "Choose segment %d/%d (sequence=%d)", wanted, count, sequence);
462 static char *parse_Attributes(const char *line, const char *attr)
465 char *begin = (char *) line;
466 char *end = begin + strlen(line);
468 /* Find start of attributes */
469 if ((p = strchr(begin, ':' )) == NULL)
475 if (strncasecmp(begin, attr, strlen(attr)) == 0)
477 /* <attr>=<value>[,]* */
478 p = strchr(begin, ',');
479 begin += strlen(attr) + 1;
482 if (p == NULL) /* last attribute */
483 return strndup(begin, end - begin);
485 return strndup(begin, p - begin);
488 } while(begin < end);
493 static int hex2int(char c)
495 if (c >= '0' && c <= '9')
497 if (c >= 'A' && c <= 'F')
499 if (c >= 'a' && c <= 'f')
504 static int string_to_IV(const char *string_hexa, uint8_t iv[AES_BLOCK_SIZE])
506 const char *p = string_hexa;
517 c = hex2int(*p++) << 4;
525 static char *relative_URI(const char *psz_url, const char *psz_path)
527 assert(psz_url != NULL && psz_path != NULL);
528 //If the path is actually an absolute URL, don't do anything.
529 if (strncmp(psz_path, "http", 4) == 0)
532 char *path_end = strrchr(psz_url, '/');
533 if (path_end == NULL)
535 unsigned int url_length = path_end - psz_url + 1;
536 char *psz_res = malloc(url_length + strlen(psz_path) + 1);
537 strncpy(psz_res, psz_url, url_length);
538 psz_res[url_length] = 0;
539 strcat(psz_res, psz_path);
543 static int parse_SegmentInformation(hls_stream_t *hls, char *p_read, int *duration)
548 /* strip of #EXTINF: */
550 char *token = strtok_r(p_read, ":", &p_next);
555 token = strtok_r(NULL, ",", &p_next);
560 if (hls->version < 3)
562 value = strtol(token, NULL, 10);
572 double d = strtod(token, (char **) NULL);
578 if ((d) - ((int)d) >= 0.5)
579 value = ((int)d) + 1;
584 /* Ignore the rest of the line */
588 static int parse_AddSegment(hls_stream_t *hls, const int duration, const char *uri)
593 /* Store segment information */
594 vlc_mutex_lock(&hls->lock);
596 char *psz_uri = relative_URI(hls->url, uri);
598 segment_t *segment = segment_New(hls, duration, psz_uri ? psz_uri : uri);
600 segment->sequence = hls->sequence + vlc_array_count(hls->segments) - 1;
603 vlc_mutex_unlock(&hls->lock);
605 return segment ? VLC_SUCCESS : VLC_ENOMEM;
608 static int parse_TargetDuration(stream_t *s, hls_stream_t *hls, char *p_read)
613 int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
616 msg_Err(s, "expected #EXT-X-TARGETDURATION:<s>");
620 hls->duration = duration; /* seconds */
624 static int parse_StreamInformation(stream_t *s, vlc_array_t **hls_stream,
625 hls_stream_t **hls, char *p_read, const char *uri)
631 assert(*hls == NULL);
633 attr = parse_Attributes(p_read, "PROGRAM-ID");
636 msg_Err(s, "#EXT-X-STREAM-INF: expected PROGRAM-ID=<value>");
642 attr = parse_Attributes(p_read, "BANDWIDTH");
645 msg_Err(s, "#EXT-X-STREAM-INF: expected BANDWIDTH=<value>");
653 msg_Err(s, "#EXT-X-STREAM-INF: bandwidth cannot be 0");
657 msg_Info(s, "bandwidth adaptation detected (program-id=%d, bandwidth=%"PRIu64").", id, bw);
659 char *psz_uri = relative_URI(s->p_sys->m3u8, uri);
661 *hls = hls_New(*hls_stream, id, bw, psz_uri ? psz_uri : uri);
665 return (*hls == NULL) ? VLC_ENOMEM : VLC_SUCCESS;
668 static int parse_MediaSequence(stream_t *s, hls_stream_t *hls, char *p_read)
673 int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
676 msg_Err(s, "expected #EXT-X-MEDIA-SEQUENCE:<s>");
680 if (hls->sequence > 0)
682 if (s->p_sys->b_live)
684 hls_stream_t *last = hls_GetLast(s->p_sys->hls_stream);
685 if ((last->sequence < sequence) && (sequence - last->sequence != 1))
686 msg_Err(s, "EXT-X-MEDIA-SEQUENCE gap in playlist (new=%d, old=%d)",
687 sequence, last->sequence);
690 msg_Err(s, "EXT-X-MEDIA-SEQUENCE already present in playlist (new=%d, old=%d)",
691 sequence, hls->sequence);
693 hls->sequence = sequence;
697 static int parse_Key(stream_t *s, hls_stream_t *hls, char *p_read)
701 /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"][,IV=<IV>] */
702 int err = VLC_SUCCESS;
703 char *attr = parse_Attributes(p_read, "METHOD");
706 msg_Err(s, "#EXT-X-KEY: expected METHOD=<value>");
710 if (strncasecmp(attr, "NONE", 4) == 0)
712 char *uri = parse_Attributes(p_read, "URI");
715 msg_Err(s, "#EXT-X-KEY: URI not expected");
719 /* IV is only supported in version 2 and above */
720 if (hls->version >= 2)
722 char *iv = parse_Attributes(p_read, "IV");
725 msg_Err(s, "#EXT-X-KEY: IV not expected");
731 else if (strncasecmp(attr, "AES-128", 7) == 0)
733 char *value, *uri, *iv;
734 if (s->p_sys->b_aesmsg == false)
736 msg_Info(s, "playback of AES-128 encrypted HTTP Live media detected.");
737 s->p_sys->b_aesmsg = true;
739 value = uri = parse_Attributes(p_read, "URI");
742 msg_Err(s, "#EXT-X-KEY: URI not found for encrypted HTTP Live media in AES-128");
747 /* Url is put between quotes, remove them */
750 /* We need to strip the "" from the attribute value */
752 char* end = strchr(uri, '"');
756 hls->psz_current_key_path = strdup(uri);
759 value = iv = parse_Attributes(p_read, "IV");
763 * If the EXT-X-KEY tag does not have the IV attribute, implementations
764 * MUST use the sequence number of the media file as the IV when
765 * encrypting or decrypting that media file. The big-endian binary
766 * representation of the sequence number SHALL be placed in a 16-octet
767 * buffer and padded (on the left) with zeros.
769 hls->b_iv_loaded = false;
774 * If the EXT-X-KEY tag has the IV attribute, implementations MUST use
775 * the attribute value as the IV when encrypting or decrypting with that
776 * key. The value MUST be interpreted as a 128-bit hexadecimal number
777 * and MUST be prefixed with 0x or 0X.
780 if (string_to_IV(iv, hls->psz_AES_IV) == VLC_EGENERIC)
783 hls->b_iv_loaded = true;
789 msg_Warn(s, "playback of encrypted HTTP Live media is not supported.");
796 static int parse_ProgramDateTime(stream_t *s, hls_stream_t *hls, char *p_read)
799 msg_Dbg(s, "tag not supported: #EXT-X-PROGRAM-DATE-TIME %s", p_read);
803 static int parse_AllowCache(stream_t *s, hls_stream_t *hls, char *p_read)
807 char answer[4] = "\0";
808 int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
811 msg_Err(s, "#EXT-X-ALLOW-CACHE, ignoring ...");
815 hls->b_cache = (strncmp(answer, "NO", 2) != 0);
819 static int parse_Version(stream_t *s, hls_stream_t *hls, char *p_read)
824 int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
827 msg_Err(s, "#EXT-X-VERSION: no protocol version found, should be version 1.");
832 hls->version = version;
833 if (hls->version <= 0 || hls->version > 3)
835 msg_Err(s, "#EXT-X-VERSION should be version 1, 2 or 3 iso %d", version);
841 static int parse_EndList(stream_t *s, hls_stream_t *hls)
845 s->p_sys->b_live = false;
846 msg_Info(s, "video on demand (vod) mode");
850 static int parse_Discontinuity(stream_t *s, hls_stream_t *hls, char *p_read)
854 /* FIXME: Do we need to act on discontinuity ?? */
855 msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
859 static int hls_CompareStreams( const void* a, const void* b )
861 hls_stream_t* stream_a = *(hls_stream_t**)a;
862 hls_stream_t* stream_b = *(hls_stream_t**)b;
863 return stream_a->bandwidth > stream_b->bandwidth;
866 /* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
867 * document defines the following new tags: EXT-X-TARGETDURATION,
868 * EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
869 * ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
872 static int parse_M3U8(stream_t *s, vlc_array_t *streams, uint8_t *buffer, const ssize_t len)
874 stream_sys_t *p_sys = s->p_sys;
875 uint8_t *p_read, *p_begin, *p_end;
880 msg_Dbg(s, "parse_M3U8\n%s", buffer);
882 p_end = p_begin + len;
884 char *line = ReadLine(p_begin, &p_read, p_end - p_begin);
889 if (strncmp(line, "#EXTM3U", 7) != 0)
891 msg_Err(s, "missing #EXTM3U tag .. aborting");
899 /* What is the version ? */
901 uint8_t *p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-VERSION:");
905 char *psz_version = ReadLine(p, &tmp, p_end - p);
906 if (psz_version == NULL)
908 int ret = sscanf((const char*)psz_version, "#EXT-X-VERSION:%d", &version);
911 msg_Warn(s, "#EXT-X-VERSION: no protocol version found, assuming version 1.");
918 /* Is it a live stream ? */
919 p_sys->b_live = (strstr((const char *)buffer, "#EXT-X-ENDLIST") == NULL) ? true : false;
921 /* Is it a meta index file ? */
922 bool b_meta = (strstr((const char *)buffer, "#EXT-X-STREAM-INF") == NULL) ? false : true;
924 int err = VLC_SUCCESS;
928 msg_Info(s, "Meta playlist");
930 /* M3U8 Meta Index file */
933 line = ReadLine(p_begin, &p_read, p_end - p_begin);
939 if (strncmp(line, "#EXT-X-STREAM-INF", 17) == 0)
941 p_sys->b_meta = true;
942 char *uri = ReadLine(p_begin, &p_read, p_end - p_begin);
949 msg_Info(s, "Skipping invalid stream-inf: %s", uri);
954 hls_stream_t *hls = NULL;
955 err = parse_StreamInformation(s, &streams, &hls, line, uri);
958 /* Download playlist file from server */
960 ssize_t len = read_M3U8_from_url(s, hls->url, &buf);
965 /* Parse HLS m3u8 content. */
966 err = parse_M3U8(s, streams, buf, len);
972 hls->version = version;
974 hls->size = hls_GetStreamSize(hls); /* Stream size (approximate) */
984 if (p_begin >= p_end)
987 } while (err == VLC_SUCCESS);
992 msg_Info(s, "%s Playlist HLS protocol version: %d", p_sys->b_live ? "Live": "VOD", version);
994 hls_stream_t *hls = NULL;
996 hls = hls_GetLast(streams);
999 /* No Meta playlist used */
1000 hls = hls_New(streams, 0, 0, p_sys->m3u8);
1003 /* Get TARGET-DURATION first */
1004 p = (uint8_t *)strstr((const char *)buffer, "#EXT-X-TARGETDURATION:");
1007 uint8_t *p_rest = NULL;
1008 char *psz_duration = ReadLine(p, &p_rest, p_end - p);
1009 if (psz_duration == NULL)
1010 return VLC_EGENERIC;
1011 err = parse_TargetDuration(s, hls, psz_duration);
1017 hls->version = version;
1019 else return VLC_ENOMEM;
1024 int segment_duration = -1;
1028 line = ReadLine(p_begin, &p_read, p_end - p_begin);
1033 if (strncmp(line, "#EXTINF", 7) == 0)
1034 err = parse_SegmentInformation(hls, line, &segment_duration);
1035 else if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
1036 err = parse_TargetDuration(s, hls, line);
1037 else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 21) == 0)
1038 err = parse_MediaSequence(s, hls, line);
1039 else if (strncmp(line, "#EXT-X-KEY", 10) == 0)
1040 err = parse_Key(s, hls, line);
1041 else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 24) == 0)
1042 err = parse_ProgramDateTime(s, hls, line);
1043 else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 18) == 0)
1044 err = parse_AllowCache(s, hls, line);
1045 else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
1046 err = parse_Discontinuity(s, hls, line);
1047 else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
1048 err = parse_Version(s, hls, line);
1049 else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
1050 err = parse_EndList(s, hls);
1051 else if ((strncmp(line, "#", 1) != 0) && (*line != '\0') )
1053 err = parse_AddSegment(hls, segment_duration, line);
1054 segment_duration = -1; /* reset duration */
1060 if (p_begin >= p_end)
1063 } while (err == VLC_SUCCESS);
1072 static int hls_DownloadSegmentKey(stream_t *s, segment_t *seg)
1074 uint8_t aeskey[32]; /* AES-512 can use up to 32 bytes */
1077 stream_t *p_m3u8 = stream_UrlNew(s, seg->psz_key_path);
1080 msg_Err(s, "Failed to load the AES key for segment sequence %d", seg->sequence);
1081 return VLC_EGENERIC;
1084 len = stream_Read(p_m3u8, aeskey, sizeof(aeskey));
1085 if (len != AES_BLOCK_SIZE)
1087 msg_Err(s, "The AES key loaded doesn't have the right size (%zd)", len);
1088 stream_Delete(p_m3u8);
1089 return VLC_EGENERIC;
1092 memcpy(seg->psz_AES_key, aeskey, AES_BLOCK_SIZE);
1094 stream_Delete(p_m3u8);
1099 static int hls_ManageSegmentKeys(stream_t *s, hls_stream_t *hls)
1101 segment_t *seg = NULL;
1102 segment_t *prev_seg;
1103 int count = vlc_array_count(hls->segments);
1105 for (int i = 0; i < count; i++)
1108 seg = segment_GetSegment(hls, i);
1111 if (seg->psz_key_path == NULL)
1112 continue; /* No key to load ? continue */
1113 if (seg->b_key_loaded)
1114 continue; /* The key is already loaded */
1116 /* if the key has not changed, and already available from previous segment,
1117 * try to copy it, and don't load the key */
1118 if (prev_seg && prev_seg->b_key_loaded && strcmp(seg->psz_key_path, prev_seg->psz_key_path) == 0)
1120 memcpy(seg->psz_AES_key, prev_seg->psz_AES_key, AES_BLOCK_SIZE);
1121 seg->b_key_loaded = true;
1124 if (hls_DownloadSegmentKey(s, seg) != VLC_SUCCESS)
1125 return VLC_EGENERIC;
1126 seg->b_key_loaded = true;
1131 static int hls_DecodeSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment)
1133 /* Did the segment need to be decoded ? */
1134 if (segment->psz_key_path == NULL)
1137 /* Do we have loaded the key ? */
1138 if (!segment->b_key_loaded)
1140 /* No ? try to download it now */
1141 if (hls_ManageSegmentKeys(s, hls) != VLC_SUCCESS)
1142 return VLC_EGENERIC;
1145 /* For now, we only decode AES-128 data */
1146 gcry_error_t i_gcrypt_err;
1147 gcry_cipher_hd_t aes_ctx;
1149 i_gcrypt_err = gcry_cipher_open(&aes_ctx, GCRY_CIPHER_AES,
1150 GCRY_CIPHER_MODE_CBC, 0);
1153 msg_Err(s, "gcry_cipher_open failed: %s", gpg_strerror(i_gcrypt_err));
1154 gcry_cipher_close(aes_ctx);
1155 return VLC_EGENERIC;
1159 i_gcrypt_err = gcry_cipher_setkey(aes_ctx, segment->psz_AES_key,
1160 sizeof(segment->psz_AES_key));
1163 msg_Err(s, "gcry_cipher_setkey failed: %s", gpg_strerror(i_gcrypt_err));
1164 gcry_cipher_close(aes_ctx);
1165 return VLC_EGENERIC;
1168 if (hls->b_iv_loaded == false)
1170 memset(hls->psz_AES_IV, 0, AES_BLOCK_SIZE);
1171 hls->psz_AES_IV[15] = segment->sequence & 0xff;
1172 hls->psz_AES_IV[14] = (segment->sequence >> 8)& 0xff;
1173 hls->psz_AES_IV[13] = (segment->sequence >> 16)& 0xff;
1174 hls->psz_AES_IV[12] = (segment->sequence >> 24)& 0xff;
1177 i_gcrypt_err = gcry_cipher_setiv(aes_ctx, hls->psz_AES_IV,
1178 sizeof(hls->psz_AES_IV));
1182 msg_Err(s, "gcry_cipher_setiv failed: %s", gpg_strerror(i_gcrypt_err));
1183 gcry_cipher_close(aes_ctx);
1184 return VLC_EGENERIC;
1187 i_gcrypt_err = gcry_cipher_decrypt(aes_ctx,
1188 segment->data->p_buffer, /* out */
1189 segment->data->i_buffer,
1194 msg_Err(s, "gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(i_gcrypt_err), gcry_strerror(i_gcrypt_err));
1195 gcry_cipher_close(aes_ctx);
1196 return VLC_EGENERIC;
1198 gcry_cipher_close(aes_ctx);
1199 /* remove the PKCS#7 padding from the buffer */
1200 int pad = segment->data->p_buffer[segment->data->i_buffer-1];
1201 if (pad <= 0 || pad > AES_BLOCK_SIZE)
1203 msg_Err(s, "Bad padding character (0x%x), perhaps we failed to decrypt the segment with the correct key", pad);
1204 return VLC_EGENERIC;
1209 if (segment->data->p_buffer[segment->data->i_buffer-1-count] != pad)
1211 msg_Err(s, "Bad ending buffer, perhaps we failed to decrypt the segment with the correct key");
1212 return VLC_EGENERIC;
1216 /* not all the data is readable because of padding */
1217 segment->data->i_buffer -= pad;
1222 static int get_HTTPLiveMetaPlaylist(stream_t *s, vlc_array_t **streams)
1224 stream_sys_t *p_sys = s->p_sys;
1226 int err = VLC_EGENERIC;
1228 /* Duplicate HLS stream META information */
1229 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1231 hls_stream_t *src, *dst;
1232 src = hls_Get(p_sys->hls_stream, i);
1234 return VLC_EGENERIC;
1236 dst = hls_Copy(src, false);
1239 vlc_array_append(*streams, dst);
1241 /* Download playlist file from server */
1242 uint8_t *buf = NULL;
1243 ssize_t len = read_M3U8_from_url(s, dst->url, &buf);
1248 /* Parse HLS m3u8 content. */
1249 err = parse_M3U8(s, *streams, buf, len);
1256 /* Reload playlist */
1257 static int hls_UpdatePlaylist(stream_t *s, hls_stream_t *hls_new, hls_stream_t **hls)
1259 int count = vlc_array_count(hls_new->segments);
1261 msg_Info(s, "updating hls stream (program-id=%d, bandwidth=%"PRIu64") has %d segments",
1262 hls_new->id, hls_new->bandwidth, count);
1264 for (int n = 0; n < count; n++)
1266 segment_t *p = segment_GetSegment(hls_new, n);
1267 if (p == NULL) return VLC_EGENERIC;
1269 vlc_mutex_lock(&(*hls)->lock);
1270 segment_t *segment = segment_Find(*hls, p->sequence);
1273 vlc_mutex_lock(&segment->lock);
1276 assert(segment->url);
1278 /* they should be the same */
1279 if ((p->sequence != segment->sequence) ||
1280 (p->duration != segment->duration) ||
1281 (strcmp(p->url, segment->url) != 0))
1283 msg_Warn(s, "existing segment found with different content - resetting");
1284 msg_Warn(s, "- sequence: new=%d, old=%d", p->sequence, segment->sequence);
1285 msg_Warn(s, "- duration: new=%d, old=%d", p->duration, segment->duration);
1286 msg_Warn(s, "- file: new=%s", p->url);
1287 msg_Warn(s, " old=%s", segment->url);
1289 /* Resetting content */
1290 segment->sequence = p->sequence;
1291 segment->duration = p->duration;
1293 segment->url = strdup(p->url);
1294 if ( segment->url == NULL )
1296 msg_Err(s, "Failed updating segment %d - skipping it", p->sequence);
1298 vlc_mutex_unlock(&segment->lock);
1301 /* We must free the content, because if the key was not downloaded, content can't be decrypted */
1304 block_Release(segment->data);
1305 segment->data = NULL;
1307 free(segment->psz_key_path);
1308 segment->psz_key_path = p->psz_key_path ? strdup(p->psz_key_path) : NULL;
1311 vlc_mutex_unlock(&segment->lock);
1315 int last = vlc_array_count((*hls)->segments) - 1;
1316 segment_t *l = segment_GetSegment(*hls, last);
1317 if (l == NULL) goto fail_and_unlock;
1319 if ((l->sequence + 1) != p->sequence)
1321 msg_Err(s, "gap in sequence numbers found: new=%d expected %d",
1322 p->sequence, l->sequence+1);
1324 vlc_array_append((*hls)->segments, p);
1325 msg_Info(s, "- segment %d appended", p->sequence);
1327 vlc_mutex_unlock(&(*hls)->lock);
1330 /* update meta information */
1331 vlc_mutex_lock(&(*hls)->lock);
1332 (*hls)->sequence = hls_new->sequence;
1333 (*hls)->duration = (hls_new->duration == -1) ? (*hls)->duration : hls_new->duration;
1334 (*hls)->b_cache = hls_new->b_cache;
1335 vlc_mutex_unlock(&(*hls)->lock);
1340 vlc_mutex_unlock(&(*hls)->lock);
1341 return VLC_EGENERIC;
1344 static int hls_ReloadPlaylist(stream_t *s)
1346 stream_sys_t *p_sys = s->p_sys;
1348 vlc_array_t *hls_streams = vlc_array_new();
1349 if (hls_streams == NULL)
1352 msg_Info(s, "Reloading HLS live meta playlist");
1354 if (get_HTTPLiveMetaPlaylist(s, &hls_streams) != VLC_SUCCESS)
1356 /* Free hls streams */
1357 for (int i = 0; i < vlc_array_count(hls_streams); i++)
1360 hls = hls_Get(hls_streams, i);
1361 if (hls) hls_Free(hls);
1363 vlc_array_destroy(hls_streams);
1365 msg_Err(s, "reloading playlist failed");
1366 return VLC_EGENERIC;
1369 /* merge playlists */
1370 int count = vlc_array_count(hls_streams);
1371 for (int n = 0; n < count; n++)
1373 hls_stream_t *hls_new = hls_Get(hls_streams, n);
1374 if (hls_new == NULL)
1377 hls_stream_t *hls_old = hls_Find(p_sys->hls_stream, hls_new);
1378 if (hls_old == NULL)
1379 { /* new hls stream - append */
1380 vlc_array_append(p_sys->hls_stream, hls_new);
1381 msg_Info(s, "new HLS stream appended (id=%d, bandwidth=%"PRIu64")",
1382 hls_new->id, hls_new->bandwidth);
1384 else if (hls_UpdatePlaylist(s, hls_new, &hls_old) != VLC_SUCCESS)
1385 msg_Info(s, "failed updating HLS stream (id=%d, bandwidth=%"PRIu64")",
1386 hls_new->id, hls_new->bandwidth);
1388 vlc_array_destroy(hls_streams);
1392 /****************************************************************************
1394 ****************************************************************************/
1395 static int BandwidthAdaptation(stream_t *s, int progid, uint64_t *bandwidth)
1397 stream_sys_t *p_sys = s->p_sys;
1399 uint64_t bw = *bandwidth;
1400 uint64_t bw_candidate = 0;
1402 int count = vlc_array_count(p_sys->hls_stream);
1403 for (int n = 0; n < count; n++)
1405 /* Select best bandwidth match */
1406 hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
1407 if (hls == NULL) break;
1409 /* only consider streams with the same PROGRAM-ID */
1410 if (hls->id == progid)
1412 if ((bw >= hls->bandwidth) && (bw_candidate < hls->bandwidth))
1414 msg_Dbg(s, "candidate %d bandwidth (bits/s) %"PRIu64" >= %"PRIu64,
1415 n, bw, hls->bandwidth); /* bits / s */
1416 bw_candidate = hls->bandwidth;
1417 candidate = n; /* possible candidate */
1421 *bandwidth = bw_candidate;
1425 static int hls_DownloadSegmentData(stream_t *s, hls_stream_t *hls, segment_t *segment, int *cur_stream)
1427 stream_sys_t *p_sys = s->p_sys;
1432 vlc_mutex_lock(&segment->lock);
1433 if (segment->data != NULL)
1435 /* Segment already downloaded */
1436 vlc_mutex_unlock(&segment->lock);
1440 /* sanity check - can we download this segment on time? */
1441 if ((p_sys->bandwidth > 0) && (hls->bandwidth > 0))
1443 uint64_t size = (segment->duration * hls->bandwidth); /* bits */
1444 int estimated = (int)(size / p_sys->bandwidth);
1445 if (estimated > segment->duration)
1447 msg_Warn(s,"downloading of segment %d takes %ds, which is longer than its playback (%ds)",
1448 segment->sequence, estimated, segment->duration);
1452 mtime_t start = mdate();
1453 if (hls_Download(s, segment) != VLC_SUCCESS)
1455 msg_Err(s, "downloaded segment %d from stream %d failed",
1456 segment->sequence, *cur_stream);
1457 vlc_mutex_unlock(&segment->lock);
1458 return VLC_EGENERIC;
1460 mtime_t duration = mdate() - start;
1461 if (hls->bandwidth == 0)
1463 /* Try to estimate the bandwidth for this stream */
1464 hls->bandwidth = (uint64_t)((double)segment->size / ((double)duration / 1000000.0));
1467 /* If the segment is encrypted, decode it */
1468 if (hls_DecodeSegmentData(s, hls, segment) != VLC_SUCCESS)
1470 vlc_mutex_unlock(&segment->lock);
1471 return VLC_EGENERIC;
1474 vlc_mutex_unlock(&segment->lock);
1476 msg_Info(s, "downloaded segment %d from stream %d",
1477 segment->sequence, *cur_stream);
1479 /* check for division by zero */
1480 double ms = (double)duration / 1000.0; /* ms */
1484 uint64_t bw = ((double)(segment->size * 8) / ms) * 1000; /* bits / s */
1485 p_sys->bandwidth = bw;
1486 if (p_sys->b_meta && (hls->bandwidth != bw))
1488 int newstream = BandwidthAdaptation(s, hls->id, &bw);
1490 /* FIXME: we need an average here */
1491 if ((newstream >= 0) && (newstream != *cur_stream))
1493 msg_Info(s, "detected %s bandwidth (%"PRIu64") stream",
1494 (bw >= hls->bandwidth) ? "faster" : "lower", bw);
1495 *cur_stream = newstream;
1501 static void* hls_Thread(void *p_this)
1503 stream_t *s = (stream_t *)p_this;
1504 stream_sys_t *p_sys = s->p_sys;
1506 int canc = vlc_savecancel();
1508 while (vlc_object_alive(s))
1510 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1513 /* Sliding window (~60 seconds worth of movie) */
1514 vlc_mutex_lock(&hls->lock);
1515 int count = vlc_array_count(hls->segments);
1516 vlc_mutex_unlock(&hls->lock);
1518 /* Is there a new segment to process? */
1519 if ((!p_sys->b_live && (p_sys->playback.segment < (count - 6))) ||
1520 (p_sys->download.segment >= count))
1523 vlc_mutex_lock(&p_sys->download.lock_wait);
1524 while (((p_sys->download.segment - p_sys->playback.segment > 6) ||
1525 (p_sys->download.segment >= count)) &&
1526 (p_sys->download.seek == -1))
1528 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
1529 if (p_sys->b_live /*&& (mdate() >= p_sys->playlist.wakeup)*/)
1531 if (!vlc_object_alive(s))
1535 if (p_sys->download.seek >= 0)
1537 p_sys->download.segment = p_sys->download.seek;
1538 p_sys->download.seek = -1;
1540 vlc_mutex_unlock(&p_sys->download.lock_wait);
1543 if (!vlc_object_alive(s)) break;
1545 vlc_mutex_lock(&hls->lock);
1546 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1547 vlc_mutex_unlock(&hls->lock);
1549 if ((segment != NULL) &&
1550 (hls_DownloadSegmentData(s, hls, segment, &p_sys->download.stream) != VLC_SUCCESS))
1552 if (!vlc_object_alive(s)) break;
1556 p_sys->b_error = true;
1561 /* download succeeded */
1562 /* determine next segment to download */
1563 vlc_mutex_lock(&p_sys->download.lock_wait);
1564 if (p_sys->download.seek >= 0)
1566 p_sys->download.segment = p_sys->download.seek;
1567 p_sys->download.seek = -1;
1569 else if (p_sys->download.segment < count)
1570 p_sys->download.segment++;
1571 vlc_cond_signal(&p_sys->download.wait);
1572 vlc_mutex_unlock(&p_sys->download.lock_wait);
1575 vlc_restorecancel(canc);
1579 static void* hls_Reload(void *p_this)
1581 stream_t *s = (stream_t *)p_this;
1582 stream_sys_t *p_sys = s->p_sys;
1584 assert(p_sys->b_live);
1586 int canc = vlc_savecancel();
1589 while (vlc_object_alive(s))
1591 mtime_t now = mdate();
1592 if (now >= p_sys->playlist.wakeup)
1594 /* reload the m3u8 */
1595 if (hls_ReloadPlaylist(s) != VLC_SUCCESS)
1597 /* No change in playlist, then backoff */
1598 p_sys->playlist.tries++;
1599 if (p_sys->playlist.tries == 1) wait = 0.5;
1600 else if (p_sys->playlist.tries == 2) wait = 1;
1601 else if (p_sys->playlist.tries >= 3) wait = 2;
1603 /* Can we afford to backoff? */
1604 if (p_sys->download.segment - p_sys->playback.segment < 3)
1606 p_sys->playlist.tries = 0;
1612 p_sys->playlist.tries = 0;
1616 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->download.stream);
1619 /* determine next time to update playlist */
1620 p_sys->playlist.last = now;
1621 p_sys->playlist.wakeup = now + ((mtime_t)(hls->duration * wait)
1622 * (mtime_t)1000000);
1625 mwait(p_sys->playlist.wakeup);
1628 vlc_restorecancel(canc);
1632 static int Prefetch(stream_t *s, int *current)
1634 stream_sys_t *p_sys = s->p_sys;
1635 int stream = *current;
1637 hls_stream_t *hls = hls_Get(p_sys->hls_stream, stream);
1639 return VLC_EGENERIC;
1641 /* Download first 2 segments of this HLS stream */
1642 for (int i = 0; i < 2; i++)
1644 segment_t *segment = segment_GetSegment(hls, p_sys->download.segment);
1645 if (segment == NULL )
1646 return VLC_EGENERIC;
1648 /* It is useless to lock the segment here, as Prefetch is called before
1649 download and playlit thread are started. */
1652 p_sys->download.segment++;
1656 if (hls_DownloadSegmentData(s, hls, segment, current) != VLC_SUCCESS)
1657 return VLC_EGENERIC;
1659 p_sys->download.segment++;
1661 /* adapt bandwidth? */
1662 if (*current != stream)
1664 hls_stream_t *hls = hls_Get(p_sys->hls_stream, *current);
1666 return VLC_EGENERIC;
1675 /****************************************************************************
1677 ****************************************************************************/
1678 static int hls_Download(stream_t *s, segment_t *segment)
1682 stream_t *p_ts = stream_UrlNew(s, segment->url);
1684 return VLC_EGENERIC;
1686 segment->size = stream_Size(p_ts);
1687 assert(segment->size > 0);
1689 segment->data = block_Alloc(segment->size);
1690 if (segment->data == NULL)
1692 stream_Delete(p_ts);
1696 assert(segment->data->i_buffer == segment->size);
1698 ssize_t length = 0, curlen = 0;
1702 size = stream_Size(p_ts);
1703 if (size > segment->size)
1705 msg_Dbg(s, "size changed %"PRIu64, segment->size);
1706 block_t *p_block = block_Realloc(segment->data, 0, size);
1707 if (p_block == NULL)
1709 stream_Delete(p_ts);
1710 block_Release(segment->data);
1711 segment->data = NULL;
1714 segment->data = p_block;
1715 segment->size = size;
1716 assert(segment->data->i_buffer == segment->size);
1719 length = stream_Read(p_ts, segment->data->p_buffer + curlen, segment->size - curlen);
1723 } while (vlc_object_alive(s));
1725 stream_Delete(p_ts);
1729 /* Read M3U8 file */
1730 static ssize_t read_M3U8_from_stream(stream_t *s, uint8_t **buffer)
1732 int64_t total_bytes = 0;
1733 int64_t total_allocated = 0;
1741 bytes = stream_Read(s, buf, sizeof(buf));
1747 if ( (total_bytes + bytes + 1) > total_allocated )
1749 if (total_allocated)
1750 total_allocated *= 2;
1752 total_allocated = __MIN((uint64_t)bytes+1, sizeof(buf));
1754 p = realloc_or_free(p, total_allocated);
1759 memcpy(p+total_bytes, buf, bytes);
1760 total_bytes += bytes;
1763 if (total_allocated == 0)
1764 return VLC_EGENERIC;
1766 p[total_bytes] = '\0';
1772 static ssize_t read_M3U8_from_url(stream_t *s, const char* psz_url, uint8_t **buffer)
1774 assert(*buffer == NULL);
1777 stream_t *p_m3u8 = stream_UrlNew(s, psz_url);
1779 return VLC_EGENERIC;
1781 ssize_t size = read_M3U8_from_stream(p_m3u8, buffer);
1782 stream_Delete(p_m3u8);
1787 static char *ReadLine(uint8_t *buffer, uint8_t **pos, const size_t len)
1792 uint8_t *begin = buffer;
1794 uint8_t *end = p + len;
1798 if ((*p == '\n') || (*p == '\0'))
1803 /* copy line excluding \n or \0 */
1804 line = strndup((char *)begin, p - begin);
1810 /* next pass start after \n */
1818 /****************************************************************************
1820 ****************************************************************************/
1821 static int Open(vlc_object_t *p_this)
1823 stream_t *s = (stream_t*)p_this;
1824 stream_sys_t *p_sys;
1826 if (!isHTTPLiveStreaming(s))
1827 return VLC_EGENERIC;
1829 msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
1831 /* Initialize crypto bit */
1835 s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
1839 char *psz_uri = NULL;
1840 if (asprintf(&psz_uri,"%s://%s", s->psz_access, s->psz_path) < 0)
1845 p_sys->m3u8 = psz_uri;
1848 if (asprintf(&new_path, "%s.ts", s->psz_path) < 0)
1855 s->psz_path = new_path;
1857 p_sys->bandwidth = 0;
1858 p_sys->b_live = true;
1859 p_sys->b_meta = false;
1860 p_sys->b_error = false;
1862 p_sys->hls_stream = vlc_array_new();
1863 if (p_sys->hls_stream == NULL)
1873 s->pf_control = Control;
1875 /* Parse HLS m3u8 content. */
1876 uint8_t *buffer = NULL;
1877 ssize_t len = read_M3U8_from_stream(s->p_source, &buffer);
1880 if (parse_M3U8(s, p_sys->hls_stream, buffer, len) != VLC_SUCCESS)
1886 /* HLS standard doesn't provide any guaranty about streams
1887 being sorted by bandwidth, so we sort them */
1888 qsort( p_sys->hls_stream->pp_elems, p_sys->hls_stream->i_count,
1889 sizeof( hls_stream_t* ), &hls_CompareStreams );
1891 /* Choose first HLS stream to start with */
1892 int current = p_sys->playback.stream = 0;
1893 p_sys->playback.segment = p_sys->download.segment = ChooseSegment(s, current);
1895 /* manage encryption key if needed */
1896 hls_ManageSegmentKeys(s, hls_Get(p_sys->hls_stream, current));
1898 if (p_sys->b_live && (p_sys->playback.segment < 0))
1900 msg_Warn(s, "less data than 3 times 'target duration' available for live playback, playback may stall");
1903 if (Prefetch(s, ¤t) != VLC_SUCCESS)
1905 msg_Err(s, "fetching first segment failed.");
1909 p_sys->download.stream = current;
1910 p_sys->playback.stream = current;
1911 p_sys->download.seek = -1;
1913 vlc_mutex_init(&p_sys->download.lock_wait);
1914 vlc_cond_init(&p_sys->download.wait);
1916 /* Initialize HLS live stream */
1919 hls_stream_t *hls = hls_Get(p_sys->hls_stream, current);
1920 p_sys->playlist.last = mdate();
1921 p_sys->playlist.wakeup = p_sys->playlist.last +
1922 ((mtime_t)hls->duration * UINT64_C(1000000));
1924 if (vlc_clone(&p_sys->reload, hls_Reload, s, VLC_THREAD_PRIORITY_LOW))
1930 if (vlc_clone(&p_sys->thread, hls_Thread, s, VLC_THREAD_PRIORITY_INPUT))
1933 vlc_join(p_sys->reload, NULL);
1940 vlc_mutex_destroy(&p_sys->download.lock_wait);
1941 vlc_cond_destroy(&p_sys->download.wait);
1944 /* Free hls streams */
1945 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1947 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
1948 if (hls) hls_Free(hls);
1950 vlc_array_destroy(p_sys->hls_stream);
1955 return VLC_EGENERIC;
1958 /****************************************************************************
1960 ****************************************************************************/
1961 static void Close(vlc_object_t *p_this)
1963 stream_t *s = (stream_t*)p_this;
1964 stream_sys_t *p_sys = s->p_sys;
1966 assert(p_sys->hls_stream);
1969 vlc_mutex_lock(&p_sys->download.lock_wait);
1970 vlc_cond_signal(&p_sys->download.wait);
1971 vlc_mutex_unlock(&p_sys->download.lock_wait);
1975 vlc_join(p_sys->reload, NULL);
1976 vlc_join(p_sys->thread, NULL);
1977 vlc_mutex_destroy(&p_sys->download.lock_wait);
1978 vlc_cond_destroy(&p_sys->download.wait);
1980 /* Free hls streams */
1981 for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
1983 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i);
1984 if (hls) hls_Free(hls);
1986 vlc_array_destroy(p_sys->hls_stream);
1991 block_Release (p_sys->peeked);
1995 /****************************************************************************
1996 * Stream filters functions
1997 ****************************************************************************/
1998 static segment_t *GetSegment(stream_t *s)
2000 stream_sys_t *p_sys = s->p_sys;
2001 segment_t *segment = NULL;
2003 /* Is this segment of the current HLS stream ready? */
2004 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2007 vlc_mutex_lock(&hls->lock);
2008 segment = segment_GetSegment(hls, p_sys->playback.segment);
2009 if (segment != NULL)
2011 vlc_mutex_lock(&segment->lock);
2012 /* This segment is ready? */
2013 if (segment->data != NULL)
2015 vlc_mutex_unlock(&segment->lock);
2016 p_sys->b_cache = hls->b_cache;
2017 vlc_mutex_unlock(&hls->lock);
2020 vlc_mutex_unlock(&segment->lock);
2022 vlc_mutex_unlock(&hls->lock);
2025 /* Was the HLS stream changed to another bitrate? */
2027 for (int i_stream = 0; i_stream < vlc_array_count(p_sys->hls_stream); i_stream++)
2029 /* Is the next segment ready */
2030 hls_stream_t *hls = hls_Get(p_sys->hls_stream, i_stream);
2034 vlc_mutex_lock(&hls->lock);
2035 segment = segment_GetSegment(hls, p_sys->playback.segment);
2036 if (segment == NULL)
2038 vlc_mutex_unlock(&hls->lock);
2042 vlc_mutex_lock(&p_sys->download.lock_wait);
2043 int i_segment = p_sys->download.segment;
2044 vlc_mutex_unlock(&p_sys->download.lock_wait);
2046 vlc_mutex_lock(&segment->lock);
2047 /* This segment is ready? */
2048 if ((segment->data != NULL) &&
2049 (p_sys->playback.segment < i_segment))
2051 p_sys->playback.stream = i_stream;
2052 p_sys->b_cache = hls->b_cache;
2053 vlc_mutex_unlock(&segment->lock);
2054 vlc_mutex_unlock(&hls->lock);
2057 vlc_mutex_unlock(&segment->lock);
2058 vlc_mutex_unlock(&hls->lock);
2068 assert(segment->data);
2069 if (segment->data->i_buffer == 0)
2071 vlc_mutex_lock(&hls->lock);
2072 int count = vlc_array_count(hls->segments);
2073 vlc_mutex_unlock(&hls->lock);
2075 if ((p_sys->download.segment - p_sys->playback.segment == 0) &&
2076 ((count != p_sys->download.segment) || p_sys->b_live))
2077 msg_Err(s, "playback will stall");
2078 else if ((p_sys->download.segment - p_sys->playback.segment < 3) &&
2079 ((count != p_sys->download.segment) || p_sys->b_live))
2080 msg_Warn(s, "playback in danger of stalling");
2085 static int segment_RestorePos(segment_t *segment)
2089 uint64_t size = segment->size - segment->data->i_buffer;
2092 segment->data->i_buffer += size;
2093 segment->data->p_buffer -= size;
2099 /* p_read might be NULL if caller wants to skip data */
2100 static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
2102 stream_sys_t *p_sys = s->p_sys;
2107 /* Determine next segment to read. If this is a meta playlist and
2108 * bandwidth conditions changed, then the stream might have switched
2109 * to another bandwidth. */
2110 segment_t *segment = GetSegment(s);
2111 if (segment == NULL)
2114 vlc_mutex_lock(&segment->lock);
2115 if (segment->data->i_buffer == 0)
2117 if (!p_sys->b_cache || p_sys->b_live)
2119 block_Release(segment->data);
2120 segment->data = NULL;
2123 segment_RestorePos(segment);
2125 p_sys->playback.segment++;
2126 vlc_mutex_unlock(&segment->lock);
2128 /* signal download thread */
2129 vlc_mutex_lock(&p_sys->download.lock_wait);
2130 vlc_cond_signal(&p_sys->download.wait);
2131 vlc_mutex_unlock(&p_sys->download.lock_wait);
2135 if (segment->size == segment->data->i_buffer)
2136 msg_Info(s, "playing segment %d from stream %d",
2137 segment->sequence, p_sys->playback.stream);
2140 if (i_read <= segment->data->i_buffer)
2142 else if (i_read > segment->data->i_buffer)
2143 len = segment->data->i_buffer;
2147 if (p_read) /* if NULL, then caller skips data */
2148 memcpy(p_read + used, segment->data->p_buffer, len);
2149 segment->data->i_buffer -= len;
2150 segment->data->p_buffer += len;
2154 vlc_mutex_unlock(&segment->lock);
2156 } while (i_read > 0);
2161 static int Read(stream_t *s, void *buffer, unsigned int i_read)
2163 stream_sys_t *p_sys = s->p_sys;
2166 assert(p_sys->hls_stream);
2171 /* NOTE: buffer might be NULL if caller wants to skip data */
2172 length = hls_Read(s, (uint8_t*) buffer, i_read);
2176 p_sys->playback.offset += length;
2180 static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
2182 stream_sys_t *p_sys = s->p_sys;
2184 unsigned int len = i_peek;
2186 segment = GetSegment(s);
2187 if (segment == NULL)
2189 msg_Err(s, "segment %d should have been available (stream %d)",
2190 p_sys->playback.segment, p_sys->playback.stream);
2191 return 0; /* eof? */
2194 vlc_mutex_lock(&segment->lock);
2196 size_t i_buff = segment->data->i_buffer;
2197 uint8_t *p_buff = segment->data->p_buffer;
2199 if (i_peek < i_buff)
2202 vlc_mutex_unlock(&segment->lock);
2206 else /* This will seldom be run */
2208 /* remember segment to read */
2209 int peek_segment = p_sys->playback.segment;
2211 segment_t *nsegment;
2212 p_sys->playback.segment++;
2213 block_t *peeked = p_sys->peeked;
2216 peeked = block_Alloc (i_peek);
2217 else if (peeked->i_buffer < i_peek)
2218 peeked = block_Realloc (peeked, 0, i_peek);
2221 p_sys->peeked = peeked;
2223 memcpy(peeked->p_buffer, p_buff, i_buff);
2226 vlc_mutex_unlock(&segment->lock);
2228 i_buff = peeked->i_buffer;
2229 p_buff = peeked->p_buffer;
2232 while (curlen < i_peek)
2234 nsegment = GetSegment(s);
2235 if (nsegment == NULL)
2237 msg_Err(s, "segment %d should have been available (stream %d)",
2238 p_sys->playback.segment, p_sys->playback.stream);
2239 /* restore segment to read */
2240 p_sys->playback.segment = peek_segment;
2241 return curlen; /* eof? */
2244 vlc_mutex_lock(&nsegment->lock);
2246 if (len < nsegment->data->i_buffer)
2248 memcpy(p_buff + curlen, nsegment->data->p_buffer, len);
2253 size_t i_nbuff = nsegment->data->i_buffer;
2254 memcpy(p_buff + curlen, nsegment->data->p_buffer, i_nbuff);
2258 p_sys->playback.segment++;
2261 vlc_mutex_unlock(&nsegment->lock);
2264 /* restore segment to read */
2265 p_sys->playback.segment = peek_segment;
2270 static bool hls_MaySeek(stream_t *s)
2272 stream_sys_t *p_sys = s->p_sys;
2274 if (p_sys->hls_stream == NULL)
2277 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2278 if (hls == NULL) return false;
2282 vlc_mutex_lock(&hls->lock);
2283 int count = vlc_array_count(hls->segments);
2284 vlc_mutex_unlock(&hls->lock);
2286 vlc_mutex_lock(&p_sys->download.lock_wait);
2287 bool may_seek = (p_sys->download.segment < (count - 2));
2288 vlc_mutex_unlock(&p_sys->download.lock_wait);
2294 static uint64_t GetStreamSize(stream_t *s)
2296 stream_sys_t *p_sys = s->p_sys;
2301 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2302 if (hls == NULL) return 0;
2304 vlc_mutex_lock(&hls->lock);
2306 hls->size = hls_GetStreamSize(hls);
2307 uint64_t size = hls->size;
2308 vlc_mutex_unlock(&hls->lock);
2313 static int segment_Seek(stream_t *s, const uint64_t pos)
2315 stream_sys_t *p_sys = s->p_sys;
2317 hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->playback.stream);
2319 return VLC_EGENERIC;
2321 vlc_mutex_lock(&hls->lock);
2323 bool b_found = false;
2324 uint64_t length = 0;
2325 uint64_t size = hls->size;
2326 int count = vlc_array_count(hls->segments);
2328 /* restore current segment to start position */
2329 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2330 if (segment == NULL)
2332 vlc_mutex_unlock(&hls->lock);
2333 return VLC_EGENERIC;
2335 vlc_mutex_lock(&segment->lock);
2336 segment_RestorePos(segment);
2337 vlc_mutex_unlock(&segment->lock);
2339 for (int n = 0; n < count; n++)
2341 segment_t *segment = segment_GetSegment(hls, n);
2342 if (segment == NULL)
2344 vlc_mutex_unlock(&hls->lock);
2345 return VLC_EGENERIC;
2348 vlc_mutex_lock(&segment->lock);
2349 length += segment->duration * (hls->bandwidth/8);
2350 vlc_mutex_unlock(&segment->lock);
2356 p_sys->playback.segment = n;
2360 /* Do not search in last 3 segments */
2361 vlc_mutex_unlock(&hls->lock);
2362 return VLC_EGENERIC;
2367 if (!b_found && (pos >= size))
2369 p_sys->playback.segment = count - 1;
2376 /* restore segment to start position */
2377 segment_t *segment = segment_GetSegment(hls, p_sys->playback.segment);
2378 if (segment == NULL)
2380 vlc_mutex_unlock(&hls->lock);
2381 return VLC_EGENERIC;
2384 vlc_mutex_lock(&segment->lock);
2385 segment_RestorePos(segment);
2386 vlc_mutex_unlock(&segment->lock);
2388 /* start download at current playback segment */
2389 vlc_mutex_unlock(&hls->lock);
2391 /* Wake up download thread */
2392 vlc_mutex_lock(&p_sys->download.lock_wait);
2393 p_sys->download.seek = p_sys->playback.segment;
2394 vlc_cond_signal(&p_sys->download.wait);
2395 vlc_mutex_unlock(&p_sys->download.lock_wait);
2397 /* Wait for download to be finished */
2398 vlc_mutex_lock(&p_sys->download.lock_wait);
2399 msg_Info(s, "seek to segment %d", p_sys->playback.segment);
2400 while (((p_sys->download.seek != -1) ||
2401 (p_sys->download.segment - p_sys->playback.segment < 3)) &&
2402 (p_sys->download.segment < (count - 6)))
2404 vlc_cond_wait(&p_sys->download.wait, &p_sys->download.lock_wait);
2405 if (!vlc_object_alive(s) || s->b_error) break;
2407 vlc_mutex_unlock(&p_sys->download.lock_wait);
2411 vlc_mutex_unlock(&hls->lock);
2413 return b_found ? VLC_SUCCESS : VLC_EGENERIC;
2416 static int Control(stream_t *s, int i_query, va_list args)
2418 stream_sys_t *p_sys = s->p_sys;
2422 case STREAM_CAN_SEEK:
2423 *(va_arg (args, bool *)) = hls_MaySeek(s);
2425 case STREAM_GET_POSITION:
2426 *(va_arg (args, uint64_t *)) = p_sys->playback.offset;
2428 case STREAM_SET_POSITION:
2431 uint64_t pos = (uint64_t)va_arg(args, uint64_t);
2432 if (segment_Seek(s, pos) == VLC_SUCCESS)
2434 p_sys->playback.offset = pos;
2438 return VLC_EGENERIC;
2439 case STREAM_GET_SIZE:
2440 *(va_arg (args, uint64_t *)) = GetStreamSize(s);
2443 return VLC_EGENERIC;