Commit 6ba5cde7 authored by Jean-Paul Saman's avatar Jean-Paul Saman

stream_filter/httplive.c: HTTP Live Streaming

Support HTTP Live Streaming as described in the IETF draft standard:
 * http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
and Apple its description:
 * http://developer.apple.com/library/ios/#documentation/networkinginternet/conceptual/streamingmediaguide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008332-CH1-DontLinkElementID_29

Not implemented (yet):
- Encrypted streams (EXT-X-KEY)
- HTTPS (maybe use access_t in stream_filter)
parent fc51cb9a
SOURCES_decomp = decomp.c SOURCES_decomp = decomp.c
SOURCES_stream_filter_record = record.c SOURCES_stream_filter_record = record.c
SOURCES_stream_filter_httplive = httplive.c
libvlc_LTLIBRARIES += \ libvlc_LTLIBRARIES += \
libstream_filter_record_plugin.la \ libstream_filter_record_plugin.la \
libstream_filter_httplive_plugin.la \
$(NULL) $(NULL)
if !HAVE_WIN32 if !HAVE_WIN32
if !HAVE_WINCE if !HAVE_WINCE
......
/*****************************************************************************
* httplive.c: HTTP Live Streaming stream filter
*****************************************************************************
* Copyright (C) 2010 M2X BV
* $Id$
*
* Author: Jean-Paul Saman <jpsaman _AT_ videolan _DOT_ org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <assert.h>
#include <vlc_threads.h>
#include <vlc_arrays.h>
#include <vlc_stream.h>
#include <vlc_input.h>
#include <vlc_fs.h>
#include <vlc_network.h>
#include <vlc_url.h>
/*****************************************************************************
* Module descriptor
*****************************************************************************/
static int Open (vlc_object_t *);
static void Close(vlc_object_t *);
vlc_module_begin()
set_category(CAT_INPUT)
set_subcategory(SUBCAT_INPUT_STREAM_FILTER)
set_description(N_("Http Live Streaming stream filter"))
set_capability("stream_filter", 20)
set_callbacks(Open, Close)
vlc_module_end()
/*****************************************************************************
*
*****************************************************************************/
typedef struct segment_s
{
int sock; /* socket */
int timeout;
int max;
uint64_t length; /* segment duration (ms) */
uint64_t size; /* segment size in bytes */
vlc_url_t url;
vlc_mutex_t lock;
block_t *data; /* data */
} segment_t;
typedef struct hls_stream_s
{
int id; /* program id */
uint64_t bandwidth; /* bandwidth usage of segments (kbps)*/
int version;
int sequence; /* media sequence number */
uint64_t duration; /* maximum duration per segment (ms) */
int segment; /* current segment downloading */
vlc_array_t *segments; /* list of segments */
vlc_url_t url; /* uri to m3u8 */
bool b_cache; /* allow caching */
} hls_stream_t;
typedef struct
{
VLC_COMMON_MEMBERS
/* */
vlc_array_t *hls_stream;/* bandwidth adaptation */
int current; /* current hls_stream */
stream_t *s;
} hls_thread_t;
struct stream_sys_t
{
hls_thread_t *thread;
vlc_array_t *hls_stream;/* bandwidth adaptation */
/* Playback */
uint64_t offset; /* current offset in media */
int current; /* current hls_stream */
int segment; /* current segment for playback */
/* state */
int i_version; /* HTTP protocol version to use */
char *psz_user_agent;
bool b_seekable; /* can seek? */
bool b_meta; /* meta playlist */
bool b_live; /* live stream? or vod? */
bool b_error; /* parsing error */
};
/****************************************************************************
* Local prototypes
****************************************************************************/
static int Read (stream_t *, void *p_read, unsigned int i_read);
static int Peek (stream_t *, const uint8_t **pp_peek, unsigned int i_peek);
static int Control(stream_t *, int i_query, va_list);
static void* hls_Thread(vlc_object_t *);
static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls);
/****************************************************************************
*
****************************************************************************/
static bool isHTTPLiveStreaming(stream_t *s)
{
const uint8_t *peek, *peek_end;
int64_t i_size = stream_Peek(s->p_source, &peek, 46);
if (i_size < 1)
return false;
if (strncasecmp((const char*)peek, "#EXTM3U", 7) != 0)
return false;
/* Parse stream and search for
* EXT-X-TARGETDURATION or EXT-X-STREAM-INF tag, see
* http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8 */
peek_end = peek + i_size;
while(peek <= peek_end)
{
if (*peek == '#')
{
if (strncasecmp((const char*)peek, "#EXT-X-TARGETDURATION", 21) == 0)
return true;
else if (strncasecmp((const char*)peek, "#EXT-X-STREAM-INF", 17) == 0)
return true;
}
peek++;
};
return false;
}
/* */
/* FIXME: Can httplive-* functions be replaced by using access_t *p_access module??? */
static int httplive_Open(stream_t *s, int *sock, const char *host, const int port)
{
assert(*sock == -1);
*sock = net_ConnectTCP(s, host, port);
if (*sock == -1)
{
msg_Err(s, "cannot connect to %s:%d", host, port);
return VLC_EGENERIC;
}
setsockopt(*sock, SOL_SOCKET, SO_KEEPALIVE, &(int){ 1 }, sizeof (int));
return VLC_SUCCESS;
}
static void httplive_Close(int *sock)
{
if (*sock > -1)
net_Close(*sock);
*sock = -1;
}
static int httplive_Request(stream_t *s, int sock, const char *psz_path, const char *host,
const int port, const int version)
{
stream_sys_t *p_sys = s->p_sys;
/* Ignore authentication, proxies and ssl for now */
if (!psz_path || !*psz_path)
{
psz_path = "/";
}
if (port != 80)
{
net_Printf(s, sock, NULL, "GET %s HTTP/1.%d\r\nHost: %s:%d\r\n",
psz_path, version, host, port);
}
else
{
net_Printf(s, sock, NULL, "GET %s HTTP/1.%d\r\nHost: %s\r\n",
psz_path, version, host);
}
/* User-Agent */
net_Printf(s, sock, NULL,
"User-Agent: %s LibVLC/"VERSION"\r\n", p_sys->psz_user_agent);
net_Printf(s, sock, NULL, "Accept: */*\r\nConnection: Keep-Alive\r\n\r\n");
return VLC_SUCCESS;
}
/* */
static inline hls_stream_t *hls_New(vlc_array_t *hls_stream, int id, uint64_t bw, char *uri)
{
hls_stream_t *hls = (hls_stream_t *)malloc(sizeof(hls_stream_t));
if (hls == NULL) return NULL;
hls->id = id;
hls->bandwidth = bw;
hls->sequence = -1; /* unknown */
hls->version = 1; /* default protocol version */
hls->segment = 0;
vlc_UrlParse(&hls->url, uri, 0);
/* assume http */
if (hls->url.i_port <= 0)
hls->url.i_port = 80;
hls->segments = vlc_array_new();
vlc_array_append(hls_stream, hls);
return hls;
}
static hls_stream_t *hls_Get(vlc_array_t *hls_stream, int wanted)
{
int count = vlc_array_count(hls_stream);
if (count <= 0)
return NULL;
if ((wanted < 0) || (wanted >= count))
return NULL;
return (hls_stream_t *) vlc_array_item_at_index(hls_stream, wanted);
}
static inline hls_stream_t *hls_GetFirst(vlc_array_t *hls_stream)
{
return (hls_stream_t*) hls_Get(hls_stream, 0);
}
static hls_stream_t *hls_GetLast(vlc_array_t *hls_stream)
{
int count = vlc_array_count(hls_stream);
if (count <= 0)
return NULL;
count--;
return (hls_stream_t *) hls_Get(hls_stream, count);
}
/* Segment */
static segment_t *segment_New(hls_stream_t* hls, uint64_t duration, char *uri)
{
segment_t *segment = (segment_t *)malloc(sizeof(segment_t));
if (segment == NULL)
return NULL;
segment->length = duration * 1000; /* ms */
vlc_UrlParse(&segment->url, uri, 0);
/* assume http */
if (segment->url.i_port <= 0)
segment->url.i_port = 80;
segment->sock = -1;
segment->data = NULL;
vlc_mutex_init(&segment->lock);
vlc_array_append(hls->segments, segment);
return segment;
}
static segment_t *segment_GetSegment(hls_stream_t *hls, int wanted)
{
assert(hls);
int count = vlc_array_count(hls->segments);
if (count <= 0)
return NULL;
if ((wanted < 0) || (wanted >= count))
return NULL;
return (segment_t *) vlc_array_item_at_index(hls->segments, wanted);
}
static segment_t *segment_GetNext(hls_stream_t *hls, int current)
{
segment_t *segment = segment_GetSegment(hls, current + 1);
if (!segment)
return NULL;
hls->segment++;
return segment;
}
static int segment_GetAnswer(stream_t *s, segment_t *segment)
{
stream_sys_t *p_sys = s->p_sys;
char *reply;
char *psz_protocol;
int i_code;
if ((reply = net_Gets(s, segment->sock, NULL)) == NULL)
{
msg_Err(s, "failed to read answer");
goto error;
}
if (!strncmp(reply, "HTTP/1.", 7))
{
psz_protocol = strdup("HTTP");
i_code = atoi(&reply[9]);
}
else
{
msg_Err(s, "invalid HTTP reply '%s'", reply);
free(reply);
goto error;
}
msg_Dbg(s, "protocol '%s' answer code %d", psz_protocol, i_code );
free(psz_protocol);
/* Check error codes */
if (i_code != 206 && i_code != 401)
{
p_sys->b_seekable = false;
}
/* Other fatal error */
else if (i_code >= 400)
{
msg_Err(s, "error: %s", reply);
free(reply);
goto error;
}
free(reply);
/* Parse the rest of the reply */
for( ;; )
{
char *reply = net_Gets(s, segment->sock, NULL);
char *p;
if (reply == NULL)
{
msg_Err(s, "failed to read answer" );
goto error;
}
if (!vlc_object_alive(s))
{
free(reply);
goto error;
}
/* msg_Dbg(p_this, "Line=%s", reply); */
if (*reply == '\0')
{
free(reply);
break;
}
if ((p = strchr(reply, ':' )) == NULL)
{
msg_Err(s, "malformed header line: %s", reply);
free(reply);
goto error;
}
*p++ = '\0';
while(*p == ' ') p++;
if (!strcasecmp(reply, "Content-Length"))
{
segment->size = (uint64_t)atoll(p);
msg_Dbg(s, "Content-Length %"PRIu64, segment->size);
}
else if (!strcasecmp(reply, "Connection"))
{
msg_Dbg(s, "Connection: %s", p);
if (strcasecmp(p, "Keep-Alive") != 0)
{
free(reply);
goto error;
}
}
else if (!strcasecmp(reply,"Accept-Ranges"))
{
msg_Dbg(s, "Accept-Ranges: %s", p);
if (strcasecmp(p, "bytes") != 0)
{
free(reply);
goto error;
}
}
else if (!strcasecmp(reply,"Keep-Alive"))
{
msg_Dbg(s, "Keep-Alive: %s", p);
sscanf(p, "timeout=%d, max=%d", &segment->timeout, &segment->max);
}
else if (!strcasecmp(reply, "Content-Type"))
{
msg_Dbg(s, "Content-Type: %s", p);
}
else if (!strcasecmp(reply, "Server" ))
{
msg_Dbg(s, "Server: %s", p);
}
free(reply);
}
/* We close the stream for zero length data.
*/
if (segment->size == 0)
{
httplive_Close(&segment->sock);
}
return VLC_SUCCESS;
error:
httplive_Close(&segment->sock);
return VLC_EGENERIC;
}
static inline int segment_Connect(stream_t *s, segment_t *segment)
{
stream_sys_t *p_sys = s->p_sys;
assert(segment);
msg_Dbg(s, "Requesting segment %s", segment->url.psz_path);
if (httplive_Open(s, &segment->sock, segment->url.psz_host,
segment->url.i_port) != VLC_SUCCESS)
{
msg_Err(s, "Error opening first segment %s",
segment->url.psz_path);
return VLC_EGENERIC;
}
if (httplive_Request(s, segment->sock, segment->url.psz_path,
segment->url.psz_host, segment->url.i_port,
p_sys->i_version) != VLC_SUCCESS)
{
msg_Err(s, "Error sending request first segment %s",
segment->url.psz_path);
return VLC_EGENERIC;
}
if (segment_GetAnswer(s, segment) != VLC_SUCCESS)
{
msg_Err(s, "Error sending request first segment %s",
segment->url.psz_path);
return VLC_EGENERIC;
}
return VLC_SUCCESS;
}
static int segment_Download(stream_t *s, segment_t *segment)
{
assert(segment);
vlc_mutex_lock(&segment->lock);
assert(segment->sock == -1);
if (segment_Connect(s, segment) != VLC_SUCCESS)
{
vlc_mutex_unlock(&segment->lock);
return VLC_EGENERIC;
}
segment->data = block_Alloc(segment->size);
if (segment->data == NULL)
{
/* ENOMEM */
httplive_Close(&segment->sock);
vlc_mutex_unlock(&segment->lock);
return VLC_EGENERIC;
}
assert(segment->data->i_buffer == segment->size);
ssize_t length = 0, curlen = 0;
do
{
length = net_Read(s, segment->sock, NULL, segment->data->p_buffer + curlen,
segment->size - curlen, true);
if ((length < 0) || ((uint64_t)length < segment->size))
break;
curlen += length;
} while(vlc_object_alive(s));
httplive_Close(&segment->sock);
vlc_mutex_unlock(&segment->lock);
return VLC_SUCCESS;
}
static inline void FreeAllSegments(hls_stream_t *hls)
{
/* Free segments */
if (hls->segments)
{
for(int n = 0; n < vlc_array_count(hls->segments); n++)
{
segment_t *segment;
segment = (segment_t *)vlc_array_item_at_index(hls->segments, n);
if (segment)
{
vlc_mutex_destroy(&segment->lock);
httplive_Close(&segment->sock);
vlc_UrlClean(&segment->url);
if (segment->data)
block_Release(segment->data);
free(segment);
segment = NULL;
}
}
vlc_array_destroy(hls->segments);
}
}
/* Parsing */
static void parse_SegmentInformation(stream_t *s, hls_stream_t *hls, char *p_read, char *uri)
{
stream_sys_t *p_sys = s->p_sys;
assert(hls);
int duration;
int ret = sscanf(p_read, "#EXTINF:%d,", &duration);
if (ret != 1)
{
msg_Err(s, "Parsing #EXTINF:<s>,");
p_sys->b_error = true;
}
else
{
segment_t *segment = segment_New(hls, duration, uri);
if (segment && segment->length > hls->duration)
{
msg_Err(s, "EXTINF:%d duration is larger then EXT-X-TARGETDURATION:%d",
duration, (int)(hls->duration/1000));
}
}
}
static void parse_TargetDuration(stream_t *s, char *p_read)
{
stream_sys_t *p_sys = s->p_sys;
int duration;
int ret = sscanf(p_read, "#EXT-X-TARGETDURATION:%d", &duration);
if (ret != 1)
{
msg_Err(s, "Parsing #EXT-X-TARGETDURATION:<s>");
p_sys->b_error = true;
}
else
{
hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
if (hls == NULL)
hls = hls_New(p_sys->hls_stream, -1, -1, NULL);
if (hls)
hls->duration = duration * 1000; /* ms */
}
}
static void parse_StreamInformation(stream_t *s, char *p_read, char *uri)
{
stream_sys_t *p_sys = s->p_sys;
/* FIXME: proper attribute parsing
* The current method only parses the most common attribute ordering, but
* does not allow other ordering. The specification does not specify the
* exact attribute ordering. */
int id, bw;
int ret = sscanf(p_read, "#EXT-X-STREAM-INF:PROGRAM-ID=%d,BANDWIDTH=%d", &id, &bw);
if (ret != 2)
{
msg_Err(s, "error parsing: #EXT-X-STREAM-INF, ignoring ...");
p_sys->b_error = true;
}
else
{
msg_Info(s, "Bandwidth adaption detected (program-id=%d, bandwidth=%d).", id, bw);
#if 1
/* FIXME: WORKAROUND FOR BUG IN ANEVIA m3u8 */
char *psz_uri = NULL;
if (asprintf(&psz_uri,"http://%s/%s","demo.anevia.com/0", uri) == -1)
{
msg_Err(s, "Failed workaround");
p_sys->b_error = true;
}
#endif
if (psz_uri != NULL)
{
msg_Info(s, "Playlist Location: %s", psz_uri);
hls_stream_t *hls = hls_New(p_sys->hls_stream, id, bw, psz_uri);
if (hls == NULL)
{
free(psz_uri);
msg_Err(s, "Could not allocate new HTTP Live Stream.");
p_sys->b_error = true;
}
}
}
}
static void parse_MediaSequence(stream_t *s, char *p_read)
{
stream_sys_t *p_sys = s->p_sys;
int sequence;
int ret = sscanf(p_read, "#EXT-X-MEDIA-SEQUENCE:%d", &sequence);
if (ret != 1)
{
msg_Err(s, "Parsing #EXT-X-MEDIA-SEQUENCE:<s>");
p_sys->b_error = true;
}
else
{
hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
if (hls == NULL)
hls = hls_New(p_sys->hls_stream, -1, -1, NULL);
if (hls)
{
if (hls->sequence >= 0)
msg_Warn(s, "EXT-X-MEDIA-SEQUENCE already present in playlist");
hls->sequence = sequence;
}
}
}
static void parse_Key(stream_t *s, char *p_read)
{
stream_sys_t *p_sys = s->p_sys;
VLC_UNUSED(p_read);
msg_Warn(s, "Playback of encrypted HTTP Live Streaming media is not supported.");
p_sys->b_error = true;
}
static void parse_ProgramDateTime(stream_t *s, char *p_read)
{
msg_Dbg(s, "#EXT-X-PROGRAM-DATE-TIME %s", p_read);
}
static void parse_AllowCache(stream_t *s, char *p_read)
{
stream_sys_t *p_sys = s->p_sys;
char answer[4] = "\0";
int ret = sscanf(p_read, "#EXT-X-ALLOW-CACHE:%3s", answer);
if (ret != 1)
{
msg_Err(s, "error parsing: #EXT-X-ALLOW-CACHE, ignoring ...");
p_sys->b_error = true;
}
else
{
hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
if (hls)
hls->b_cache = (strncmp(answer, "YES", 3) == 0);
}
}
static void parse_Version(stream_t *s, char *p_read)
{
stream_sys_t *p_sys = s->p_sys;
int version;
int ret = sscanf(p_read, "#EXT-X-VERSION:%d", &version);
if (ret != 1)
{
msg_Err(s, "error parsing: #EXT-X-VERSION, defaulting to protocol version 1.");
p_sys->b_error = true;
}
else
{
hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
if (hls)
hls->version = version;
/* FIXME: check if this version is supported else abort */
}
}
static void parse_EndList(stream_t *s)
{
stream_sys_t *p_sys = s->p_sys;
p_sys->b_live = false;
msg_Info(s, "video on demand (vod) mode");
}
static void parse_Discontinuity(stream_t *s, char *p_read)
{
/* FIXME: Do we need to act on discontinuity ?? */
msg_Dbg(s, "#EXT-X-DISCONTINUITY %s", p_read);
}
static void parse_M3U8ExtLine(stream_t *s, char *line)
{
if (*line == '#')
{
if (strncmp(line, "#EXT-X-TARGETDURATION", 21) == 0)
parse_TargetDuration(s, line);
else if (strncmp(line, "#EXT-X-MEDIA-SEQUENCE", 22) == 0)
parse_MediaSequence(s, line);
else if (strncmp(line, "#EXT-X-KEY", 11) == 0)
parse_Key(s, line);
else if (strncmp(line, "#EXT-X-PROGRAM-DATE-TIME", 25) == 0)
parse_ProgramDateTime(s, line);
else if (strncmp(line, "#EXT-X-ALLOW-CACHE", 17) == 0)
parse_AllowCache(s, line);
else if (strncmp(line, "#EXT-X-DISCONTINUITY", 20) == 0)
parse_Discontinuity(s, line);
else if (strncmp(line, "#EXT-X-VERSION", 14) == 0)
parse_Version(s, line);
else if (strncmp(line, "#EXT-X-ENDLIST", 14) == 0)
parse_EndList(s);
}
}
static int get_HTTPLivePlaylist(stream_t *s, hls_stream_t *hls)
{
stream_sys_t *p_sys = s->p_sys;
int sock = -1;
/* Download new playlist file from server */
if (httplive_Open(s, &sock, hls->url.psz_host,
hls->url.i_port) != VLC_SUCCESS)
return VLC_EGENERIC;
if (httplive_Request(s, sock, hls->url.psz_path, hls->url.psz_host,
hls->url.i_port, 0) != VLC_SUCCESS)
{
httplive_Close(&sock);
return VLC_EGENERIC;
}
/* Check return header */
char *reply;
char *psz_protocol;
int i_code;
if ((reply = net_Gets(s, sock, NULL)) == NULL)
{
msg_Err(s, "failed to read answer");
goto error;
}
if (!strncmp(reply, "HTTP/1.", 7))
{
psz_protocol = strdup("HTTP");
i_code = atoi(&reply[9]);
}
else
{
msg_Err(s, "invalid HTTP reply '%s'", reply);
free(reply);
goto error;
}
msg_Dbg(s, "protocol '%s' answer code %d", psz_protocol, i_code );
free(psz_protocol);
/* Check error codes */
if (i_code != 206 && i_code != 401)
{
p_sys->b_seekable = false;
}
/* Other fatal error */
else if (i_code >= 400)
{
msg_Err(s, "error: %s", reply);
free(reply);
goto error;
}
msg_Dbg(s, "%s", reply);
free(reply);
/* Parse the rest of the reply */
for( ;; )
{
char *reply = net_Gets(s, sock, NULL);
if (reply == NULL)
{
msg_Dbg(s, "end of data?" );
break;
}
//msg_Dbg(s, "%s", reply);
if (!vlc_object_alive(s))
{
free(reply);
goto error;
}
/* some more checks for actual data */
if (strncmp(reply, "#EXTINF", 7) == 0)
{
char *uri = net_Gets(s, sock, NULL);
if (uri == NULL)
p_sys->b_error = true;
else
{
parse_SegmentInformation(s, hls, reply, uri);
free(uri);
}
}
else parse_M3U8ExtLine(s, reply);
free(reply);
/* Error during m3u8 parsing abort */
if (p_sys->b_error)
goto error;
}
httplive_Close(&sock);
return VLC_SUCCESS;
error:
httplive_Close(&sock);
return VLC_EGENERIC;
}
/* The http://tools.ietf.org/html/draft-pantos-http-live-streaming-04#page-8
* document defines the following new tags: EXT-X-TARGETDURATION,
* EXT-X-MEDIA-SEQUENCE, EXT-X-KEY, EXT-X-PROGRAM-DATE-TIME, EXT-X-
* ALLOW-CACHE, EXT-X-STREAM-INF, EXT-X-ENDLIST, EXT-X-DISCONTINUITY,
* and EXT-X-VERSION.
*/
static int parse_HTTPLiveStreaming(stream_t *s)
{
stream_sys_t *p_sys = s->p_sys;
char *p_read, *p_begin, *p_end;
assert(p_sys->hls_stream);
p_begin = p_read = stream_ReadLine(s->p_source);
if (!p_begin)
return VLC_ENOMEM;
/* */
int i_len = strlen(p_begin);
p_end = p_read + i_len;
if (strncmp(p_read, "#EXTM3U", 7) != 0)
{
msg_Err(s, "Missing #EXTM3U tag .. aborting");
free(p_begin);
return VLC_EGENERIC;
}
do {
free(p_begin);
if (p_sys->b_error)
return VLC_EGENERIC;
/* Next line */
p_begin = stream_ReadLine(s->p_source);
if (p_begin == NULL)
break;
i_len = strlen(p_begin);
p_read = p_begin;
p_end = p_read + i_len;
if (strncmp(p_read, "#EXT-X-STREAM-INF", 17) == 0)
{
p_sys->b_meta = true;
char *uri = stream_ReadLine(s->p_source);
if (uri == NULL)
p_sys->b_error = true;
else
{
parse_StreamInformation(s, p_read, uri);
free(uri);
}
}
else if (strncmp(p_read, "#EXTINF", 7) == 0)
{
char *uri = stream_ReadLine(s->p_source);
if (uri == NULL)
p_sys->b_error = true;
else
{
hls_stream_t *hls = hls_GetLast(p_sys->hls_stream);
if (hls)
parse_SegmentInformation(s, hls, p_read, uri);
else
p_sys->b_error = true;
free(uri);
}
}
else
{
/* Parse M3U8 Ext Line */
parse_M3U8ExtLine(s, p_read);
}
} while(p_read < p_end);
free(p_begin);
/* */
if (p_sys->b_meta)
{
/* It is a meta playlist */
int count = vlc_array_count(p_sys->hls_stream);
for(int n = 0; n < count; n++)
{
hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
if (hls == NULL) break;
if (get_HTTPLivePlaylist(s, hls) != VLC_SUCCESS)
msg_Err(s, "Could not parse m3u8 meta index file." );
}
}
return VLC_SUCCESS;
}
/****************************************************************************
* hls_Thread
****************************************************************************/
static int BandwidthAdaptation(stream_t *s, int progid, uint64_t bw)
{
stream_sys_t *p_sys = s->p_sys;
int candidate = -1;
msg_Dbg(s, "bandwidth (bits/s) %"PRIu64, bw * 1000); /* bits / s */
int count = vlc_array_count(p_sys->hls_stream);
for (int n = 0; n < count; n++)
{
/* Select best bandwidth match */
hls_stream_t *hls = hls_Get(p_sys->hls_stream, n);
if (hls == NULL)
break;
/* only consider streams with the same PROGRAM-ID */
if (hls->id == progid)
{
if (bw <= hls->bandwidth)
candidate = n; /* possible candidate */
}
}
return candidate;
}
static void* hls_Thread(vlc_object_t *p_this)
{
hls_thread_t *client = (hls_thread_t *) p_this;
int canc = vlc_savecancel ();
while(vlc_object_alive(p_this))
{
hls_stream_t *hls = hls_Get(client->hls_stream, client->current);
if (hls == NULL)
break;
/* get next segment */
segment_t *segment = segment_GetNext(hls, hls->segment);
if (segment == NULL )
break;
mtime_t start = mdate();
if (segment_Download(client->s, segment) != VLC_SUCCESS)
break;
mtime_t duration = mdate() - start;
uint64_t bw = (segment->size * 8) / (duration/1000); /* bits / ms */
if (hls->bandwidth != bw)
{
int newstream = BandwidthAdaptation(client->s, hls->id, bw);
if ((newstream > 0) && (newstream != client->current))
{
msg_Info(p_this, "Switching stream to %s bandwidth stream",
hls->bandwidth > bw ? "faster" : "lower" );
client->current = newstream;
}
}
#if 0
if (p_sys->b_live)
{
/* FIXME: Reread the m3u8 index file */
}
#endif
}
vlc_restorecancel (canc);
return NULL;
}
static int Prefetch(stream_t *s)
{
stream_sys_t *p_sys = s->p_sys;
hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
if (hls == NULL)
return VLC_EGENERIC;
/* get segment */
segment_t *segment = segment_GetSegment(hls, hls->segment);
if (segment == NULL )
return VLC_EGENERIC;
if (segment_Download(s, segment) != VLC_SUCCESS)
return VLC_EGENERIC;
return VLC_SUCCESS;
}
/****************************************************************************
* Open
****************************************************************************/
static int Open(vlc_object_t *p_this)
{
stream_t *s = (stream_t*)p_this;
stream_sys_t *p_sys;
if (!isHTTPLiveStreaming(s))
return VLC_EGENERIC;
msg_Info(p_this, "HTTP Live Streaming (%s)", s->psz_path);
/* */
s->p_sys = p_sys = calloc(1, sizeof(*p_sys));
if (p_sys == NULL)
return VLC_ENOMEM;
p_sys->i_version = 1;
p_sys->b_seekable = true;
p_sys->b_live = true;
p_sys->b_meta = false;
/* Determine the HTTP user agent */
/* See RFC2616 §2.2 token definition and §3.8 user-agent header */
p_sys->psz_user_agent = var_InheritString(s, "http-user-agent");
for (char *p = p_sys->psz_user_agent; *p; p++)
{
uint8_t c = *p;
if (c < 32 || strchr( "()<>@,;:\\\"[]?={}", c ))
*p = '_'; /* remove potentially harmful characters */
}
p_sys->hls_stream = vlc_array_new();
if (p_sys->hls_stream == NULL)
{
free(p_sys);
return VLC_ENOMEM;
}
/* */
s->pf_read = Read;
s->pf_peek = Peek;
s->pf_control = Control;
/* Select first segment to play */
if (parse_HTTPLiveStreaming(s) != VLC_SUCCESS)
return VLC_EGENERIC;
/* */
p_sys->segment = 0;
p_sys->current = 0;
if (Prefetch(s) != VLC_SUCCESS)
{
msg_Err(s, "Failed fetching first segment.");
Close(p_this);
return VLC_EGENERIC;
}
p_sys->thread = vlc_object_create(s, sizeof(hls_thread_t));
if( p_sys->thread == NULL )
{
msg_Err(s, "failed to create HTTP Live Streaming client thread");
Close(p_this);
return VLC_EGENERIC;
}
p_sys->thread->hls_stream = p_sys->hls_stream;
p_sys->thread->current = p_sys->current;
p_sys->thread->s = s;
msg_Dbg(s, "Creating HTTP Live Streaming client thread");
if (vlc_thread_create(p_sys->thread, "HTTP Live Streaming client",
hls_Thread, VLC_THREAD_PRIORITY_INPUT))
{
Close(p_this);
return VLC_EGENERIC;
}
vlc_object_attach(p_sys->thread, s);
return VLC_SUCCESS;
}
/****************************************************************************
* Close
****************************************************************************/
static void Close(vlc_object_t *p_this)
{
stream_t *s = (stream_t*)p_this;
stream_sys_t *p_sys = s->p_sys;
assert(p_sys->hls_stream);
/* */
if (p_sys->thread)
{
vlc_object_kill(p_sys->thread);
vlc_thread_join(p_sys->thread);
vlc_object_release(p_sys->thread);
}
/* Free hls streams */
for (int i = 0; i < vlc_array_count(p_sys->hls_stream); i++)
{
hls_stream_t *hls;
hls = (hls_stream_t *)vlc_array_item_at_index(p_sys->hls_stream, i);
if (hls)
{
/* Free segments */
if (hls->segments)
FreeAllSegments(hls);
vlc_UrlClean(&hls->url);
free(hls);
hls = NULL;
}
}
vlc_array_destroy(p_sys->hls_stream);
/* */
free(p_sys->psz_user_agent);
free(p_sys);
}
/****************************************************************************
* Stream filters functions
****************************************************************************/
static segment_t *NextSegment(stream_t *s)
{
stream_sys_t *p_sys = s->p_sys;
segment_t *segment;
do
{
/* Is the next segment ready */
hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
if (hls == NULL)
return NULL;
segment = segment_GetSegment(hls, p_sys->segment);
if (segment == NULL)
return NULL;
/* This segment is ready? */
if (segment->data != NULL)
return segment;
/* Was the stream changed to another bitrate? */
if (!p_sys->b_meta)
return NULL;
if (p_sys->current != p_sys->thread->current)
{
/* YES it was */
p_sys->current = p_sys->thread->current;
}
else return NULL;
}
while(vlc_object_alive(s));
return segment;
}
static ssize_t hls_Read(stream_t *s, uint8_t *p_read, unsigned int i_read)
{
stream_sys_t *p_sys = s->p_sys;
ssize_t copied = 0;
do
{
/* Determine next segment to read. If this is a meta playlist and
* bandwidth conditions changed, then the stream might have switched
* to another bandwidth. */
segment_t *segment = NextSegment(s);
if (segment == NULL)
break;
vlc_mutex_lock(&segment->lock);
if (segment->data->i_buffer == 0)
{
msg_Dbg(s, "Switching to segment %d", p_sys->segment);
p_sys->segment++;
vlc_mutex_unlock(&segment->lock);
continue;
}
ssize_t len;
if (i_read <= segment->data->i_buffer)
len = i_read;
else if (i_read > segment->data->i_buffer)
len = segment->data->i_buffer;
memcpy(p_read + copied, segment->data->p_buffer, len);
segment->data->i_buffer -= len;
segment->data->p_buffer += len;
copied += len;
i_read -= len;
vlc_mutex_unlock(&segment->lock);
} while ((i_read > 0) && vlc_object_alive(s));
return copied;
}
static int Read(stream_t *s, void *buffer, unsigned int i_read)
{
stream_sys_t *p_sys = s->p_sys;
ssize_t length = 0;
assert(p_sys->hls_stream);
if (buffer == NULL)
{
/* caller skips data, get big enough buffer */
msg_Warn(s, "Buffer is NULL (allocate %d)", i_read);
buffer = calloc(1, i_read);
if (buffer == NULL)
return 0; /* NO MEMORY left*/
}
length = hls_Read(s, (uint8_t*) buffer, i_read);
if (length < 0)
return 0;
p_sys->offset += length;
return length;
}
static int Peek(stream_t *s, const uint8_t **pp_peek, unsigned int i_peek)
{
stream_sys_t *p_sys = s->p_sys;
size_t curlen = 0;
hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
if (hls == NULL)
return 0;
int peek_segment = p_sys->segment;
do
{
segment_t *segment = segment_GetSegment(hls, peek_segment);
if (segment == NULL)
return 0;
vlc_mutex_lock(&segment->lock);
assert(segment->data);
if (i_peek < segment->data->i_buffer)
{
*pp_peek = segment->data->p_buffer;
curlen += i_peek;
}
else
{
msg_Dbg(s, "PEEK: next segment=%d", peek_segment);
peek_segment++;
}
vlc_mutex_unlock(&segment->lock);
} while ((curlen < i_peek) && vlc_object_alive(s));
return curlen;
}
static bool hls_MaySeek(stream_t *s)
{
stream_sys_t *p_sys = s->p_sys;
if (p_sys->hls_stream == NULL)
return false;
hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
if (hls == NULL)
return false;
if (p_sys->b_live)
{
int count = vlc_array_count(hls->segments);
return (hls->segment < count - 2);
}
return true;
}
static int GetStreamSize(stream_t *s)
{
stream_sys_t *p_sys = s->p_sys;
if (p_sys->b_live)
return 0;
int length = 0;
hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
if (hls)
{
int count = vlc_array_count(hls->segments);
for(int n = 0; n < count; n++)
{
segment_t *segment = vlc_array_item_at_index(hls->segments, n);
if (segment)
length += segment->size;
}
}
return length;
}
static int segment_Seek(stream_t *s, uint64_t pos)
{
stream_sys_t *p_sys = s->p_sys;
/* Find the right offset */
hls_stream_t *hls = hls_Get(p_sys->hls_stream, p_sys->current);
if (hls == NULL)
return VLC_EGENERIC;
uint64_t length = 0;
bool b_found = false;
int count = vlc_array_count(hls->segments);
for (int n = 0; n < count; n++)
{
/* FIXME: Seeking in segments not dowloaded is not supported. */
if (n > hls->segment)
{
msg_Err(s, "Seeking in segment not downloaded yet.");
return VLC_EGENERIC;
}
segment_t *segment = vlc_array_item_at_index(hls->segments, n);
if (!segment)
return VLC_EGENERIC;
vlc_mutex_lock(&segment->lock);
length += segment->size;
uint64_t size = segment->size -segment->data->i_buffer;
if (size > 0)
{
segment->data->i_buffer += size;
segment->data->p_buffer -= size;
}
if (!b_found && (pos <= length))
{
uint64_t used = length - pos;
segment->data->i_buffer -= used;
segment->data->p_buffer += used;
count = p_sys->segment;
p_sys->segment = n;
b_found = true;
}
vlc_mutex_unlock(&segment->lock);
}
return VLC_SUCCESS;
}
static int Control(stream_t *s, int i_query, va_list args)
{
stream_sys_t *p_sys = s->p_sys;
switch (i_query)
{
case STREAM_CAN_SEEK:
case STREAM_CAN_FASTSEEK:
*(va_arg (args, bool *)) = hls_MaySeek(s);
break;
case STREAM_GET_POSITION:
*(va_arg (args, uint64_t *)) = p_sys->offset;
break;
case STREAM_SET_POSITION:
if (hls_MaySeek(s))
{
uint64_t pos = (uint64_t)va_arg(args, uint64_t);
if (segment_Seek(s, pos) == VLC_SUCCESS)
{
p_sys->offset = pos;
break;
}
}
return VLC_EGENERIC;
case STREAM_GET_SIZE:
*(va_arg (args, uint64_t *)) = GetStreamSize(s);
break;
default:
return VLC_EGENERIC;
}
return VLC_SUCCESS;
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment