python-librtmp¶
python-librtmp is a RTMP client library. It uses the implementation provided by librtmp via cffi.
- Free software: BSD license
- Documentation: http://pythonhosted.org/python-librtmp
Installation¶
The latest stable version is available to install using pip
sudo pip install python-librtmp
But you can also get the development version using Git:
git clone git://github.com/chrippa/python-librtmp.git
cd python-librtmp
sudo python setup.py install
Note
cffi 1.0 was released recently which contains significant changes. If you have an old version already installed you will have to manually upgrade it or you will get an error when attempting to install python-librtmp.
Dependencies¶
- Python, at least version 2.6 or 3.3.
- a C compiler capapable of building Python extensions, e.g. gcc
- librtmp: The library including its headers (librtmp-dev or equivalent)
- cffi: cffi depends on libffi and its headers (libffi-dev or equivalent)
- On Python <3.4 the backport of singledispatch is also required.
Features¶
Streaming¶
The most common use case of RTMP is to read a video stream from a server.
import librtmp
# Create a connection
conn = librtmp.RTMP("rtmp://your.server.net/app/playpath", live=True)
# Attempt to connect
conn.connect()
# Get a file-like object to access to the stream
stream = conn.create_stream()
# Read 1024 bytes of data
data = stream.read(1024)
Remote function calls¶
Here is a example of creating a Python function that can be used to call remote functions:
my_remote_method = conn.remote_method("MyRemoteMethod", block=True)
result = my_remote_method("some argument")
Waiting for the server to call our function:
# This will automatically name the function after it's Python name
@conn.invoke_handler
def my_add(a, b):
return a + b
# Start waiting for calls
conn.process_packets()
You can also use custom function name instead:
@conn.invoke_handler("MyMath.MyAdd")
Instead of blocking forever when waiting for a call you can specify to wait only for a specific invoke and then stop blocking:
conn.process_packets(invoked_method="MyMath.MyAdd", timeout=30)
API¶
librtmp¶
Client connection¶
-
class
librtmp.
RTMP
(url, playpath=None, tcurl=None, app=None, pageurl=None, auth=None, swfhash=None, swfsize=None, swfurl=None, swfvfy=None, flashver=None, subscribe=None, token=None, live=None, jtv=None, connect_data=None, socks=None, start=None, stop=None, buffer=None, timeout=None)¶ A RTMP client session.
Parameters: - url – str, A RTMP URL in the format rtmp[t][e|s]://hostname[:port][/app[/playpath]].
- playpath – str, Overrides the playpath parsed from the RTMP URL.
- tcurl – str, URL of the target stream. Defaults to rtmp[t][e|s]://host[:port]/app.
- app – str, Name of application to connect to on the RTMP server.
- pageurl – str, URL of the web page in which the media was embedded.
- auth – str, Authentication string to be appended to the connect string.
- connect_data – This value will be encoded to AMF and added to the connect packet.
- swfhash – str, SHA256 hash of the decompressed SWF file (hexdigest).
- swfsize – int, Size of the decompressed SWF file.
- swfurl – str, URL of the SWF player for the media.
- swfvfy – bool, Calculate the correct swfhash and swfsize parameter from the swfurl specified.
- flashver – str, Version of the Flash plugin used to run the SWF player.
- subscribe – str, Name of live stream to subscribe to. Defaults to playpath.
- token – str, Key for SecureToken response, used if the server requires SecureToken authentication.
- live – bool, Specify that the media is a live stream.
- jtv – str, JSON token used by Twitch/Justin.tv servers.
- socks – str, Use the specified SOCKS4 proxy.
- start – int, Start at num seconds into the stream. Not valid for live streams.
- stop – int, Stop at num seconds into the stream.
- buffer – int, Set buffer time to num milliseconds. This is used to control rate of data sent by FMS servers, not buffering of data. The default is 30000.
- timeout – int, Timeout the session after num seconds without receiving any data from the server. The default is 30.
-
call
(method, *args, **params)¶ Calls a method on the server.
-
close
()¶ Closes the connection to the server.
-
connect
(packet=None)¶ Connect to the server.
Parameters: packet – RTMPPacket, this packet will be sent instead of the regular “connect” packet. Raises
RTMPError
if the connect attempt fails.
-
connected
¶ Returns True if connected to the server.
Usage:
>>> conn.connected True
-
create_stream
(seek=None, writeable=False, update_buffer=True)¶ - Prepares the session for streaming of audio/video
- and returns a
RTMPStream
object.
Parameters: - seek – int, Attempt to seek to this position.
- writeable – bool, Make the stream writeable instead of readable.
- update_buffer – bool, When enabled will attempt to speed up download by telling the server our buffer can fit the whole stream.
Raises
RTMPError
if a stream could not be created.Usage:
>>> stream = conn.create_stream() >>> data = stream.read(1024)
-
handle_packet
(packet)¶ Lets librtmp look at a packet and send a response if needed.
-
process_packets
(transaction_id=None, invoked_method=None, timeout=None)¶ Wait for packets and process them as needed.
Parameters: - transaction_id – int, Wait until the result of this transaction ID is recieved.
- invoked_method – int, Wait until this method is invoked by the server.
- timeout – int, The time to wait for a result from the server. Note: This is the timeout used by this method only, the connection timeout is still used when reading packets.
Raises
RTMPError
on error. RaisesRTMPTimeoutError
on timeout.Usage:
>>> @conn.invoke_handler ... def add(x, y): ... return x + y >>> @conn.process_packets()
-
read_packet
()¶ Reads a RTMP packet from the server.
Returns a
RTMPPacket
.Raises
RTMPError
on error. RaisesRTMPTimeoutError
on timeout.Usage:
>>> packet = conn.read_packet() >>> packet.body b'packet body ...'
-
remote_method
(method, block=False, **params)¶ - Creates a Python function that will attempt to
- call a remote method when used.
Parameters: - method – str, Method name on the server to call
- block – bool, Wheter to wait for result or not
Usage:
>>> send_usher_token = conn.remote_method("NetStream.Authenticate.UsherToken", block=True) >>> send_usher_token("some token") 'Token Accepted'
-
send_packet
(packet, queue=True)¶ Sends a RTMP packet to the server.
Parameters: - packet – RTMPPacket, the packet to send to the server.
- queue – bool, If True, queue up the packet in a internal queue rather than sending it right away.
-
set_option
(key, value)¶ Sets a option for this session.
For a detailed list of available options see the librtmp(3) man page.
Parameters: - key – str, A valid option key.
- value – A value, anything that can be converted to str is valid.
Raises
ValueError
if a invalid option is specified.
-
setup_url
(url)¶ Attempt to parse a RTMP URL.
Additional options may be specified by appending space-separated key=value pairs to the URL. Special characters in values may need to be escaped to prevent misinterpretation by the option parser. The escape encoding uses a backslash followed by two hexadecimal digits representing the ASCII value of the character. E.g., spaces must be escaped as \20 and backslashes must be escaped as \5c.
Parameters: url – str, A RTMP URL in the format rtmp[t][e|s]://hostname[:port][/app[/playpath]] Raises
RTMPError
if URL parsing fails.
Streaming¶
-
class
librtmp.
RTMPStream
(client, update_buffer=True)¶ A file-like interface to a stream within a RTMP session.
-
close
()¶ Closes the connection.
-
duration
¶ The duration of the stream.
-
pause
()¶ Pauses the stream.
-
read
(size)¶ Attempts to read data from the stream.
Parameters: size – int, The maximum amount of bytes to read. Raises
IOError
on error.
-
seek
(time)¶ Attempts to seek in the stream.
Parameters: time – int, Time to seek to in seconds
-
unpause
()¶ Unpauses the stream.
-
update_buffer
(ms)¶ Tells the server how big our buffer is (in milliseconds).
-
write
(data)¶ Writes data to the stream.
Parameters: data – bytes, FLV data to write to the stream The data passed can contain multiple FLV tags, but it MUST always contain complete tags or undefined behaviour might occur.
Raises
IOError
on error.
-
Remote call result¶
-
class
librtmp.
RTMPCall
(conn, transaction_id)¶ A RTMP call.
Contains the result of a
RTMP.call()
.-
result
(timeout=None)¶ Retrieves the result of the call.
Parameters: timeout – The time to wait for a result from the server. Raises
RTMPTimeoutError
on timeout.
-
Packets¶
-
class
librtmp.
RTMPPacket
(type, format, channel, timestamp=0, absolute_timestamp=False, body=None)¶ -
absolute_timestamp
¶ True if the timestamp is absolute.
-
body
¶ The body of the packet.
-
channel
¶ Channel of the packet.
-
dump
()¶ Dumps packet to logger.
-
format
¶ Format of the packet.
-
timestamp
¶ Timestamp of the packet.
-
type
¶ Type of the packet.
-