This API is what powers the Command Line Interface but is also available to developers that wish to make use of the data Livestreamer can retrieve in their own application.
You start by creating a Livestreamer object, this object keeps track of options and loads plugins.
>>> from livestreamer import Livestreamer
>>> livestreamer = Livestreamer()
Next you should give a URL to livestreamer to see if a plugin is available for it.
If no plugin for the URL is found, a NoPluginError will be raised.
>>> plugin = livestreamer.resolve_url("http://twitch.tv/day9tv")
Now that you have a plugin, you can fetch the current streams. The returned value is a dict containing Stream objects.
If an error occurs while fetching streams, a PluginError will be raised.
>>> streams = plugin.get_streams()
>>> streams
{'720p': <livestreamer.stream.rtmpdump.RTMPStream object at 0x7fd94eb02050>, ... }
Now you can open a connection to a stream. When you call .open() on a stream, a file-like object will be returned, which you can call .read(size) and .close() on.
If an error occurs while opening a stream, a StreamError will be raised.
>>> stream = streams.get("720p")
>>> fd = stream.open()
>>> data = fd.read(1024)
>>> fd.close()
It’s also possible to inspect streams internal parameters, see the relevant stream class to see what properties are available for inspection.
For example this is a RTMPStream object which contains a params property.
>>> stream.params
{'jtv': '9571e0f58ecadd84f34010e8b87edbc19edc68fb ...',
'swfVfy': 'http://www-cdn.jtvnw.net/widgets/live_embed_player.r546689b07788ad27459b3e7add5ff4f7da1bf730.swf',
'live': True, 'rtmp': 'rtmp://199.9.255.201/app/jtv_s08_tXsNkrA91g0Q'}
A Livestreamer session is used to keep track of plugins, options and log settings.
Returns current value of specified option.
Parameters: | key – key of the option |
---|
Returns current value of plugin specific option.
Parameters: |
|
---|
Returns the loaded plugins for the session.
Attempt to load plugins from the path specified.
Parameters: | path – full path to a directory where to look for plugins |
---|
Attempts to find a plugin that can use this URL.
The default protocol (http) will be prefixed to the URL if not specified.
Raises NoPluginError on failure.
Parameters: | url – a URL to match against loaded plugins |
---|
Sets the log level used by this session.
Valid levels are: “none”, “error”, “warning”, “info” and “debug”.
Parameters: | level – level of logging to output |
---|
Sets the log output used by this session.
Parameters: | output – a file-like object with a write method |
---|
Sets general options used by plugins and streams originating from this session object.
Parameters: |
|
---|
Available options:
hds-live-edge | (float) Specify the time live HDS streams will start from the edge of stream, default: 10.0 |
hds-segment-attempts | (int) How many attempts should be done to download each HDS segment, default: 3 |
hds-segment-timeout | (float) HDS segment connect and read timeout, default: 10.0 |
hds-timeout | (float) Timeout for reading data from HDS streams, default: 60.0 |
hls-live-edge | (int) How many segments from the end to start live streams on, default: 3 |
hls-segment-attempts | (int) How many attempts should be done to download each HLS segment, default: 3 |
hls-segment-timeout | (float) HLS segment connect and read timeout, default: 10.0 |
hls-timeout | (float) Timeout for reading data from HLS streams, default: 60.0 |
http-proxy | (str) Specify a HTTP proxy to use for all HTTP requests |
https-proxy | (str) Specify a HTTPS proxy to use for all HTTPS requests |
http-cookies | (dict or str) A dict or a semi-colon (;) delimited str of cookies to add to each HTTP request, e.g. foo=bar;baz=qux |
http-headers | (dict or str) A dict or semi-colon (;) delimited str of headers to add to each HTTP request, e.g. foo=bar;baz=qux |
http-query-params | (dict or str) A dict or a ampersand (&) delimited string of query parameters to add to each HTTP request, e.g. foo=bar&baz=qux |
http-trust-env | (bool) Trust HTTP settings set in the environment, such as environment variables (HTTP_PROXY, etc) and ~/.netrc authentication |
http-ssl-verify | (bool) Verify SSL certificates, default: True |
http-ssl-cert | (str or tuple) SSL certificate to use, can be either a .pem file (str) or a .crt/.key pair (tuple) |
http-timeout | (float) General timeout used by all HTTP requests except the ones covered by other options, default: 20.0 |
http-stream-timeout | (float) Timeout for reading data from HTTP streams, default: 60.0 |
subprocess-errorlog | (bool) Log errors from subprocesses to a file located in the temp directory |
ringbuffer-size | (int) The size of the internal ring buffer used by most stream types, default: 16777216 (16MB) |
rtmp-proxy | (str) Specify a proxy (SOCKS) that RTMP streams will use |
rtmp-rtmpdump | (str) Specify the location of the rtmpdump executable used by RTMP streams, e.g. /usr/local/bin/rtmpdump |
rtmp-timeout | (float) Timeout for reading data from RTMP streams, default: 60.0 |
Sets plugin specific options used by plugins originating from this session object.
Parameters: |
|
---|
A plugin can retrieve stream information from the URL specified.
Parameters: | url – URL that the plugin will operate on |
---|
Attempts to extract available streams.
Returns a dict containing the streams, where the key is the name of the stream, most commonly the quality and the value is a Stream object.
The result can contain the synonyms best and worst which points to the streams which are likely to be of highest and lowest quality respectively.
If multiple streams with the same name are found, the order of streams specified in stream_types will determine which stream gets to keep the name while the rest will be renamed to “<name>_<stream type>”.
The synonyms can be fine tuned with the sorting_excludes parameter. This can be either of these types:
- A list of filter expressions in the format [operator]<value>. For example the filter “>480p” will exclude streams ranked higher than “480p” from the list used in the synonyms ranking. Valid operators are >, >=, < and <=. If no operator is specified then equality will be tested.
- A function that is passed to filter() with a list of stream names as input.
Parameters: |
|
---|
Changed in version 1.4.2: Added priority parameter.
Changed in version 1.5.0: Renamed priority to stream_types and changed behaviour slightly.
Changed in version 1.5.0: Added sorting_excludes parameter.
Changed in version 1.6.0: sorting_excludes can now be a list of filter expressions or a function that is passed to filter().
All streams inherit from the Stream class.
Attemps to open a connection to the stream. Returns a file-like object that can be used to read the stream data.
Raises StreamError on failure.
You are able to inspect the parameters used by each stream, different properties are available depending on stream type.
Implements the AkamaiHD Adaptive Streaming protocol
Attributes:
Implements the Adobe HTTP Dynamic Streaming protocol
Attributes:
Parses a HDS manifest and returns its substreams.
Parameters: |
|
---|
Implementation of the Apple HTTP Live Streaming protocol
Attributes:
url The URL to the HLS playlist.
to requests.request(), such as headers and cookies.
Changed in version 1.7.0: Added args attribute.
A HTTP stream using the requests library.
Attributes:
url The URL to the stream, prepared by requests.
to requests.request(), such as headers and cookies.
RTMP stream using rtmpdump.
Attributes:
Livestreamer has three types of exceptions:
Any error caused by Livestreamer will be caught with this exception.
Plugin related error.
No relevant plugin has been loaded.
This exception is raised by Livestreamer.resolve_url(), when no relevant plugin can be found.
Stream related error.
This example uses the Python bindings of GStreamer to playback a stream.
#!/usr/bin/env python2
from __future__ import print_function
from livestreamer import Livestreamer, StreamError, PluginError, NoPluginError
import gobject
gobject.threads_init()
import pygst
pygst.require("0.10")
import gst
import sys
def exit(msg):
print(msg, file=sys.stderr)
sys.exit()
class LivestreamerPlayer(object):
def __init__(self):
self.fd = None
self.mainloop = gobject.MainLoop()
# This creates a playbin pipeline and using the appsrc source
# we can feed it our stream data
self.pipeline = gst.element_factory_make("playbin2", None)
self.pipeline.set_property("uri", "appsrc://")
# When the playbin creates the appsrc source it will call
# this callback and allow us to configure it
self.pipeline.connect("source-setup", self.on_source_setup)
# Creates a bus and set callbacks to receive errors
self.bus = self.pipeline.get_bus()
self.bus.add_signal_watch()
self.bus.connect("message::eos", self.on_eos)
self.bus.connect("message::error", self.on_error)
def exit(self, msg):
self.stop()
exit(msg)
def stop(self):
# Stop playback and exit mainloop
self.pipeline.set_state(gst.STATE_NULL)
self.mainloop.quit()
# Close the stream
if self.fd:
self.fd.close()
def play(self, stream):
# Attempt to open the stream
try:
self.fd = stream.open()
except StreamError as err:
self.exit("Failed to open stream: {0}".format(err))
# Start playback
self.pipeline.set_state(gst.STATE_PLAYING)
self.mainloop.run()
def on_source_setup(self, element, source):
# When this callback is called the appsrc expects
# us to feed it more data
source.connect("need-data", self.on_source_need_data)
def on_source_need_data(self, source, length):
# Attempt to read data from the stream
try:
data = self.fd.read(length)
except IOError as err:
self.exit("Failed to read data from stream: {0}".format(err))
# If data is empty it's the end of stream
if not data:
source.emit("end-of-stream")
return
# Convert the Python bytes into a GStreamer Buffer
# and then push it to the appsrc
buf = gst.Buffer(data)
source.emit("push-buffer", buf)
def on_eos(self, bus, msg):
# Stop playback on end of stream
self.stop()
def on_error(self, bus, msg):
# Print error message and exit on error
error = msg.parse_error()[1]
self.exit(error)
def main():
if len(sys.argv) < 3:
exit("Usage: {0} <url> <quality>".format(sys.argv[0]))
# Collect arguments
url = sys.argv[1]
quality = sys.argv[2]
# Create the Livestreamer session
livestreamer = Livestreamer()
# Enable logging
livestreamer.set_loglevel("info")
livestreamer.set_logoutput(sys.stdout)
# Attempt to find a plugin for this URL
try:
plugin = livestreamer.resolve_url(url)
except NoPluginError:
exit("Livestreamer is unable to handle the URL '{0}'".format(url))
# Attempt to fetch streams
try:
streams = plugin.get_streams()
except PluginError as err:
exit("Plugin error: {0}".format(err))
if len(streams) == 0:
exit("No streams found on URL '{0}'".format(url))
# Look for specified stream
if quality not in streams:
exit("Unable to find '{0}' stream on URL '{1}'".format(quality, url))
# We found the stream
stream = streams[quality]
# Create the player and start playback
player = LivestreamerPlayer()
# Blocks until playback is done
player.play(stream)
if __name__ == "__main__":
main()