Project

General

Profile

Actions

SIP Core API

Introduction

This chapter describes the internal architecture and API of the SIP core of the sipsimple library.
sipsimple is a Python package, the core of which wraps the PJSIP C library, which handles SIP signaling and audio media for the SIP SIMPLE client.

SIP stands for 'Sessions Initiation Protocol', an IETF standard described by RFC 3261. SIP is an application-layer control protocol that can establish,
modify and terminate multimedia sessions such as Internet telephony calls
(VoIP). Media can be added to (and removed from) an existing session.

SIP transparently supports name mapping and redirection services, which
supports personal mobility, users can maintain a single externally visible
address identifier, which can be in the form of a standard email address or
E.164 telephone number regardless of their physical network location.

SIP allows the endpoints to negotiate and combine any type of session they
mutually understand like video, instant messaging (IM), file transfer,
desktop sharing and provides a generic event notification system with
real-time publications and subscriptions about state changes that can be
used for asynchronous services like presence, message waiting indicator and
busy line appearance.

For a comprehensive overview of SIP related protocols and use cases visit http://www.tech-invite.com

PJSIP library

sipsimple builds on PJSIP http://www.pjsip.org, a set of static libraries, written in C, which provide SIP signaling and media capabilities.
PJSIP is considered to be the most mature and advanced open source SIP stack available.
The following diagram, taken from the PJSIP documentation, illustrates the library stack of PJSIP:

The diagram shows that there is a common base library, and two more or less independent stacks of libraries, one for SIP signaling and one for SIP media.
The latter also includes an abstraction layer for the sound-card.
Both of these stracks are integrated in the high level library, called PJSUA.

PJSIP itself provides a high-level Python wrapper for PJSUA.
Despite this, the choice was made to bypass PJSUA and write the SIP core of the sipsimple package as a Python wrapper, which directly uses the PJSIP and PJMEDIA libraries.
The main reasons for this are the following:
  • PJSUA assumes a session with exactly one audio stream, whilst for the SIP SIMPLE client more advanced (i.e. low-level) manipulation of the SDP is needed.
  • What is advertised as SIMPLE functionality, it is minimal and incomplete subset of it. Only page mode messaging using SIP MESSAGE method and basic device status presence are possible, while session mode IM and rich presence are desired.
  • PJSUA integrates the decoding and encoding of payloads (e.g. presence related XML documents), while in the SIP SIMPLE client this should be done at a high level, not by the SIP stack.

PJSIP itself is by nature asynchronous.
In the case of PJSIP it means that in general there will be one thread which handles reception and transmission of SIP signaling messages by means of a polling function which is continually called by the application.
Whenever the application performs some action through a function, this function will return immediately.
If PJSIP has a result for this action, it will notify the application by means of a callback function in the context of the polling function thread.

NOTE: Currently the core starts the media handling as a separate C thread to avoid lag caused by the GIL.
The sound-card also has its own C thread.

Architecture

The sipsimple core wrapper itself is mostly written using Cython (formerly Pyrex).
It allows a Python-like file with some added C manipulation statements to be compiled to C.
This in turn compiles to a Python C extension module, which links with the PJSIP static libraries.

The SIP core part of the sipsimple Python library resides in the sipsimple.core package. This package aggregates three modules, sipsimple.core._core, sipsimple.core._engine and sipsimple.core._primitives. The former is a Python C extension module which makes wrappers around PJSIP objects available in Python, while the latter two contain SIP core objects written in Python. All core objects should be accessed from the enclosing sipsimple.core module. The following list enumerates the various SIP core objects available:
  • The Engine class which is a Python wrapper around the low-level PJSIPUA class. The latter represents the SIP endpoint and manages the initialization and destruction of all the PJSIP libraries. It is also the central management point to the SIP core. The application should not use the PJSIPUA class directly, but rather through the wrapping Engine, which is a singleton class.
  • Utility classes used throughout the core:
    • frozenlist and frozendict: classes which relate respectively to list and dict similarly to how the standard frozenset relates to set.
  • Helper classes which represent a structured collection of data which is used throughout the core:
    • BaseSIPURI, SIPURI and FrozenSIPURI
    • BaseCredentials, Credentials and FrozenCredentials
  • SDP manipulation classes, which directly wrap the PJSIP structures representing either the parsed or to be generated SDP:
    • BaseSDPSession, SDPSession and FrozenSDPSession
    • BaseSDPMediaStream, SDPMediaStream and FrozenSDPMediaStream
    • BaseSDPConnection, SDPConnection and FrozenSDPConnection
    • SDPAttributeList and FrozenSDPAttributeList
    • BaseSDPAttribute, SDPAttribute and FrozenSDPAttribute
  • Audio handling classes:
    • AudioMixer
    • MixerPort
    • WaveFile
    • RecordingWaveFile
    • ToneGenerator
  • Media transport handling classes, using the functionality built into PJMEDIA:
    • RTPTransport
    • AudioTransport
  • SIP signalling related classes:
    • Request and IncomingRequest: low-level transaction support
    • Invitation: INVITE-dialog support
    • Subscription and IncomingSubscription: SUBSCRIBE-dialog support (including NOTIFY handling within the SUBSCRIBE dialog)
    • Referral and IncomingReferral: REFER-dialog support (including NOTIFY handling within the dialog)
    • Registration: Python object based on Request for REGISTER support
    • Message: Python object based on Request for MESSAGE support
    • Publication: Python object based on Request for PUBLISH support
  • Exceptions:
    • SIPCoreError: generic error used throught the core
    • PJSIPError: subclass of SIPCoreError which offers more information related to errors from PJSIP
    • PJSIPTLSError: subclass of PJSIPError to distinguish between TLS-related errors and the rest
    • SIPCoreInvalidStateError: subclass of SIPCoreError used by objects which are based on a state-machine

Most of the objects cannot be used until the Engine has been started. The following diagram illustrates these classes:

Most of the SIP core does not allow duck-typing due to the nature of the integration between it and PJSIP. If these checks had not been employed, any errors could have resulted in a segmentation fault and a core dump. This also explains why several objects have a Frozen counterpart: the frozen objects are simply immutable versions of their non-frozen variants which make sure that low-level data is kept consistent and cannot be modified from Python. The Base versions are just base classes for the frozen and non-frozen versions provided mostly for convinience: they cannot be instantiated.

Integration

The core itself has one Python dependency, the application module, which in turn depends on the zope.interface module.
These modules should be present on the system before the core can be used.
An application that uses the SIP core must use the notification system provided by the application module in order to receive notifications from it.
It does this by creating one or more classes that act as an observer for particular messages and registering it with the NotificationCenter, which is a singleton class.
This means that any call to instance an object from this class will result in the same object.
As an example, this bit of code will create an observer for logging messages only:

from zope.interface import implements
from application.notification import NotificationCenter, IObserver

class SIPEngineLogObserver(object):
    implements(IObserver)

    def handle_notification(self, notification):
        print "%(timestamp)s (%(level)d) %(sender)14s: %(message)s" % notification.data.__dict__

log_observer = SIPEngineLogObserver()
notification_center = NotificationCenter()
notification_center.add_observer(log_observer, name="SIPEngineLog")

Each notification object has three attributes:

sender

The object that sent the notification.
For generic notifications the sender will be the Engine instance, otherwise the relevant object.

name

The name describing the notification.
Most of the notifications in the core have the prefix "SIP".

data

An instance of application.notification.NotificationData or a subclass of it.
The attributes of this object provide additional data about the notification.
Notifications described in this document will also have the data attributes described.

Besides setting up the notification observers, the application should import the relevant objects from the sipsimple.core module.
It can then instantiate the Engine class, which is also a singleton, and start the PJSIP worker thread by calling Engine.start(), optionally providing a number of initialization options.
Most of these options can later be changed at runtime, by setting attributes of the same name on the Engine object.
The application may then instantiate one of the SIP primitive classes and perform operations on it.

When starting the Engine class, the application can pass a number of keyword arguments that influence the behaviour of the SIP endpoint.
For example, the SIP network ports may be set through the local_udp_port, local_tcp_port and local_tls_port arguments.
The UDP/RTP ports are described by a range of ports through rtp_port_range, two of which will be randomly selected for each RTPTransport object and effectively each audio stream.

The methods called on the SIP primitive objects and the Engine object (proxied to the PJSIPUA instance) may be called from any thread.
They will return immediately and any delayed result, such as results depending on network traffic, will be returned later using a notification.
In this manner the SIP core continues the asynchronous pattern of PJSIP.
If there is an error in processing the request, an instance of SIPCoreError, or its subclass PJSIPError will be raised.
The former will be raised whenever an error occurs inside the core, the latter whenever an underlying PJSIP function returns an error.
The PJSIPError object also contains a status attribute, which is the PJSIP errno as an integer.

As a very basic example, one can REGISTER for a sip account by typing the following lines on a Python console:

from sipsimple.core import ContactHeader, Credentials, Engine, Registration, RouteHeader, SIPURI, FromHeader
e = Engine()
e.start()
identity = FromHeader(SIPURI(user="alice", host="example.com"), display_name=unicode("Alice"))
cred = Credentials("alice", "mypassword")
reg = Registration(identity, credentials=cred)
reg.register(ContactHeader(SIPURI("127.0.0.1",port=12345)), RouteHeader(SIPURI("1.2.3.4", port=5060)))

Note that in this example no observer for notifications from this Registration object are registered, so the result of the operation cannot be seen.
Also note that this will not keep the registration registered when it is about to expire, as it is the application's responsibility.
See the Registration documentation for more details.

Another convention that is worth mentioning at this point is that the SIP core will never perform DNS lookups.
For the sake of flexibility, it is the responsibility of the application to do this and pass the result to SIP core objects using the RouteHeader object, indicating the destination IP address, port and transport the resulting SIP request should be sent to. The [[SipMiddlewareApi#Lookup|sipsimple.lookup]] module of the middleware can be used to perform DNS lookups according to RFC3263.

Components

Engine

As explained above, this singleton class needs to be instantiated by the application using the SIP core of sipsimple and represents the whole SIP core stack.
Once the start() method is called, it instantiates the core.PJSIPUA object and will proxy attribute and methods from it to the application.

attributes

default_start_options (class attribute)

This dictionary is a class attribute that describes the default values for the initialization options passed as keyword arguments to the start() method.
Consult this method for documentation of the contents.

is_running

A boolean property indicating if the Engine is running and if it is safe to try calling any proxied methods or attributes on it.

methods

__init__(self)

This will either create the Engine if it is called for the first time or return the one Engine instance if it is called subsequently.

start(self, **kwargs)

Initialize all PJSIP libraries based on the keyword parameters provided and start the PJSIP worker thread.
If this fails an appropriate exception is raised.
After the Engine has been started successfully, it can never be started again after being stopped.
The keyword arguments will be discussed here.
Many of these values are also readable as (proxied) attributes on the Engine once the start() method has been called.
Many of them can also be set at runtime, either by modifying the attribute or by calling a particular method.
This will also be documented for each argument in the following list of options.

udp_port: (Default: 0)

The local UDP port to listen on for UDP datagrams.
If this is 0, a random port will be chosen.
If it is None, the UDP transport is disabled, both for incoming and outgoing traffic.
As an attribute, this value is read-only, but it can be changed at runtime using the set_udp_port() method.

tcp_port: (Default: 0)

The local TCP port to listen on for new TCP connections.
If this is 0, a random port will be chosen.
If it is None, the TCP transport is disabled, both for incoming and outgoing traffic.
As an attribute, this value is read-only, but it can be changed at runtime using the set_tcp_port() method.

tls_port: (Default: 0)

The local TCP port to listen on for new TLS over TCP connections.
If this is 0, a random port will be chosen.
If it is None, the TLS transport is disabled, both for incoming and outgoing traffic.
As an attribute, this value is read-only, but it can be changed at runtime using the set_tls_options() method, as internally the TLS transport needs to be restarted for this operation.

tls_protocol: (Default: "TLSv1")

This string describes the (minimum) TLS protocol that should be used.
Its values should be either None, "SSLv2", "SSLv23", "SSLv3" or "TLSv1".
If None is specified, the PJSIP default will be used, which is currently "TLSv1".

tls_verify_server: (Default: False)

This boolean indicates whether PJSIP should verify the certificate of the server against the local CA list when making an outgoing TLS connection.
As an attribute, this value is read-only, but it can be changed at runtime using the set_tls_options() method, as internally the TLS transport needs to be restarted for this operation.

tls_ca_file: (Default: None)

This string indicates the location of the file containing the local list of CA certificates, to be used for TLS connections.
If this is set to None, no CA certificates will be read.
As an attribute, this value is read-only, but it can be changed at runtime using the set_tls_options() method, as internally the TLS transport needs to be restarted for this operation.

tls_cert_file: (Default: None)

This string indicates the location of a file containing the TLS certificate to be used for TLS connections.
If this is set to None, no certificate file will be read.
As an attribute, this value is read-only, but it can be changed at runtime using the set_tls_options() method, as internally the TLS transport needs to be restarted for this operation.

tls_privkey_file: (Default: None)

This string indicates the location of a file containing the TLS private key associated with the above mentioned certificated to be used for TLS connections.
If this is set to None, no private key file will be read.
As an attribute, this value is read-only, but it can be changed at runtime using the set_tls_options() method, as internally the TLS transport needs to be restarted for this operation.

tls_timeout: (Default: 1000)

The timeout value for a TLS negotiation in milliseconds.
Note that this value should be reasonably small, as a TLS negotiation blocks the whole PJSIP polling thread.
As an attribute, this value is read-only, but it can be changed at runtime using the set_tls_options() method, as internally the TLS transport needs to be restarted for this operation.

user_agent: (Default: "sipsimple-%version-pjsip-%pjsip_version-r%pjsip_svn_revision")

This value indicates what should be set in the User-Agent header, which is included in each request or response sent.
It can be read and set directly as an attribute at runtime.

log_level: (Default: 5)

This integer dictates the maximum log level that may be reported to the application by PJSIP through the SIPEngineLog notification.
By default the maximum amount of logging information is reported.
This value can be read and set directly as an attribute at runtime.

trace_sip: (Default: False)

This boolean indicates if the SIP core should send the application SIP messages as seen on the wire through the SIPEngineSIPTrace notification.
It can be read and set directly as an attribute at runtime.

rtp_port_range: (Default: (40000, 40100))

This tuple of two integers indicates the range to select UDP ports from when creating a new RTPTransport object, which is used to transport media.
It can be read and set directly as an attribute at runtime, but the ports of previously created RTPTransport objects remain unaffected.

codecs: (Default: ["speex", "G722", "PCMU", "PCMA", "iLBC", "GSM"])

This list specifies the codecs to use for audio sessions and their preferred order.
It can be read and set directly as an attribute at runtime.
Note that this global option can be overridden by an argument passed to AudioTransport.__init__().
The strings in this list is case insensitive.

events: (Default: <some sensible events>)

PJSIP needs a mapping between SIP SIMPLE event packages and content types.
This dictionary provides some default packages and their event types.
As an attribute, this value is read-only, but it can be changed at runtime using the add_event() method.

incoming_events: (Default: set())

A list that specifies for which SIP SIMPLE event packages the application wishes to receive IncomingSubscribe objects.
When a SUBSCRIBE request is received containing an event name that is not in this list, a 489 "Bad event" response is internally generated.
When the event is in the list, an IncomingSubscribe object is created based on the request and passed to the application by means of a notification.
Note that each of the events specified here should also be a key in the events dictionary argument.
As an attribute, this value is read-only, but it can be changed at runtime using the add_incoming_event() and remove_incoming_event() methods.

incoming_requests: (Default: set())

A set of methods for which IncomingRequest objects are created and sent to the application if they are received.
Note that receiving requests using the INVITE, SUBSCRIBE, ACK or BYE methods in this way is not allowed.
Requests using the OPTIONS or MESSAGE method are handled internally, but may be overridden.

stop(self)

Stop the PJSIP worker thread and unload all PJSIP libraries.
Note that after this all references to SIP core objects can no longer be used, these should be properly removed by the application itself before stopping the Engine.
Also note that, once stopped the Engine cannot be started again.
This method is automatically called when the Python interpreter exits.

proxied attributes

Besides all the proxied attributes described for the __init__ method above, thse other attributes are provided once the Engine has been started.

input_devices

This read-only attribute is a list of strings, representing all audio input devices on the system that can be used.
One of these device names can be passed as the input_device argument when creating a AudioMixer object.

output_devices

This read-only attribute is a list of strings, representing all audio output devices on the system that can be used.
One of these device names can be passed as the output_device argument when creating a AudioMixer object.

sound_devices

This read-only attribute is a list of strings, representing all audio sound devices on the system that can be used.

available_codecs

A read-only list of codecs available in the core, regardless of the codecs configured through the codecs attribute.

proxied methods

add_event(self, event, accept_types)

Couple a certain event package to a list of content types.
Once added it cannot be removed or modified.

add_incoming_event(self, event)

Adds a SIP SIMPLE event package to the set of events for which the Engine should create an IncomingSubscribe object when a SUBSCRIBE request is received.
Note that this event should be known to the Engine by means of the events attribute.

remove_incoming_event(self, event)

Removes an event from the incoming_events attribute.
Incoming SUBSCRIBE requests with this event package will automatically be replied to with a 489 "Bad Event" response.

add_incoming_request(self, method)

Add a method to the set of methods for which incoming requests should be turned into IncomingRequest objects.
For the rules on which methods are allowed, see the description of the Engine attribute above.

remove_incoming_request(self, method)

Removes a method from the set of methods that should be received.

detect_nat_type(self, stun_server_address, stun_server_port=3478, user_data=None)

Will start a series of STUN requests which detect the type of NAT this host is behind.
The stun_server_address parameter indicates the IP address or hostname of the STUN server to be used and stun_server_port specifies the remote UDP port to use.
When the type of NAT is detected, this will be reported back to the application by means of a SIPEngineDetectedNATType notification, including the user_data object passed with this method.

set_udp_port(self, value)

Update the local_udp_port attribute to the newly specified value.

set_tcp_port(self, value)

Update the local_tcp_port attribute to the newly specified value.

set_tls_options(self, local_port=None, protocol="TLSv1", verify_server=False, ca_file=None, cert_file=None, privkey_file=None, timeout=1000)

Calling this method will (re)start the TLS transport with the specified arguments, or stop it in the case that the local_port argument is set to None.
The semantics of the arguments are the same as on the start() method.

notifications

Notifications sent by the Engine are notifications that are related to the Engine itself or unrelated to any SIP primitive object.
They are described here including the data attributes that is included with them.

SIPEngineWillStart

This notification is sent when the Engine is about to start.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPEngineDidStart

This notification is sent when the Engine is has just been started.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPEngineDidFail

This notification is sent whenever the Engine has failed fatally and either cannot start or is about to stop.
It is not recommended to call any methods on the Engine at this point.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPEngineWillEnd

This notification is sent when the Engine is about to stop because the application called the stop() method.
Methods on the Engine can be called at this point, but anything that has a delayed result will probably not return any notification.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPEngineDidEnd

This notification is sent when the Engine was running and is now stopped, either because of failure or because the application requested it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPEngineLog

This notification is a wrapper for PJSIP logging messages.
It can be used by the application to output PJSIP logging to somewhere meaningful, possibly doing filtering based on log level.

timestamp:

A datetime.datetime object representing the time when the log message was output by PJSIP.

sender:

The PJSIP module that originated this log message.

level:

The logging level of the message as an integer.
Currently this is 1 through 5, 1 being the most critical.

message:

The actual log message.

SIPEngineSIPTrace

Will be sent only when the do_siptrace attribute of the Engine instance is set to True.
The notification data attributes will contain the SIP messages as they are sent and received on the wire.

timestamp:

A datetime.datetime object indicating when the notification was sent.

received:

A boolean indicating if this message was sent from or received by PJSIP (i.e. the direction of the message).

source_ip:

The source IP address as a string.

source_port:

The source port of the message as an integer.

destination_ip:

The destination IP address as a string.

source_port:

The source port of the message as an integer.

data:

The contents of the message as a string.

For received message the destination_ip and for sent messages the source_ip may not be reliable.

SIPEngineDetectedNATType

This notification is sent some time after the application request the NAT type this host behind to be detected using a STUN server.
Note that there is no way to associate a request to do this with a notification, although every call to the detect_nat_type() method will generate exactly one notification.

timestamp:

A datetime.datetime object indicating when the notification was sent.

succeeded:

A boolean indicating if the NAT detection succeeded.

user_data:

The user_data argument passed while calling the detect_nat_type() method.
This can be any object and could be used for matching requests to responses.

nat_type:

A string describing the type of NAT found.
This value is only present if NAT detection succeeded.

error:

A string indicating the error that occurred while attempting to detect the type of NAT.
This value only present if NAT detection did not succeed.

SIPEngineGotException

This notification is sent whenever there is an unexpected exception within the PJSIP working thread.
The application should show the traceback to the user somehow.
An exception need not be fatal, but if it is it will be followed by a SIPEngineDidFail notification.

timestamp:

A datetime.datetime object indicating when the notification was sent.

traceback:

A string containing the traceback of the exception.
In general this should be printed on the console.

SIPEngineGotMessage

This notification is sent whenever the Engine receives a MESSAGE request.

request_uri:

The request URI of the MESSAGE request as a SIPURI object.

from_header:

The From header of the MESSAGE request as a FrozenFromHeader object.

to_header:

The To header of the MESSAGE request as a FrozenToHeader object.

content_type:

The Content-Type header value of the MESSAGE request as a ContentType object.

headers:

The headers of the MESSAGE request as a dict.
Each SIP header is represented in its parsed for as long as PJSIP supports it.
The format of the parsed value depends on the header.

body:

The body of the MESSAGE request as a string, or None if no body was included.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPURI

These are helper objects for representing a SIP URI.
This object needs to be used whenever a SIP URI should be specified to the SIP core.
It supports comparison to other SIPURI objects using the == and != expressions.
As all of its attributes are set by the __init__ method, the individual attributes will not be documented here. The FrozenSIPURI object does not allow any of its attributes to be changed after initialization.

methods

__init__(self, host, user=None, port=None, display=None, secure=False, parameters=None, headers=None)

Creates the SIPURI object with the specified parameters as attributes.

host is the only mandatory attribute.

host:

The host part of the SIP URI as a string.

user:

The username part of the SIP URI as a string, or None if not set.

port:

The port part of the SIP URI as an int, or None or 0 if not set.

display:

The optional display name of the SIP URI as a string, or None if not set.

secure:

A boolean indicating whether this is a SIP or SIPS URI, the latter being indicated by a value of True.

parameters:

The URI parameters. represented by a dictionary.

headers:

The URI headers, represented by a dictionary.

__str__(self)

The special Python method to represent this object as a string, the output is the properly formatted SIP URI.

new(cls, sipuri)

Classmethod that returns an instance of the class on which it has been called which is a copy of the sipuri object (which must be either a SIPURI or a FrozenSIPURI).

parse(cls, uri_str)

Classmethod that returns an instance of the class on which it has been called which is represents the parsed version of the URI provided as a string. A SIPCoreError is raised if the string is invalid or if the Engine has not been started yet.

matches(self, address)

This method returns True or False depending on whether the string address contains a SIP address whose components are a subset of the components of self. For example, SIPURI.parse('sip:alice@example.org:54321;transport=tls').matches('alice@example.org') returns True while SIPURI.parse('sip:alice@example.org;transport=tls').matches('sips:alice@example.org') returns False.

Credentials

The Credentials and FrozenCredentails simple objects represent authentication credentials for a particular SIP account.
These can be included whenever creating a SIP primitive object that originates SIP requests.
The attributes of this object are the same as the arguments to the __init__ method.
Note that the domain name of the SIP account is not stored on this object.

methods

__init__(self, username, password)

Creates the Credentials object with the specified parameters as attributes.
Each of these attributes can be accessed and changed on the object once instanced.

username:

A string representing the username of the account for which these are the credentials.

password:

The password for this SIP account as a string.

new(cls, credentials)

Classmethod that returns an instance of the class on which it has been called which is a copy of the credentials object (which must be either a Credentials or a FrozenCredentials).

Invitation

The Invitation class represents an INVITE session, which governs a complete session of media exchange between two SIP endpoints from start to finish.
It is implemented to be agnostic to the media stream or streams negotiated, which is achieved by using the SDPSession class and its companion classes, which directly represents the parsed SDP.
The Invitation class represents both incoming and outgoing sessions.

The state machine contained in each Invitation object is based on the one used by the underlying PJSIP pjsip_inv_session object.
In order to represent re-@INVITE@s and user-requested disconnections, three more states have been added to this state machine.
The progression through this state machine is fairly linear and is dependent on whether this is an incoming or an outgoing session.
State changes are triggered either by incoming or by outgoing SIP requests and responses.
The states and the transitions between them are shown in the following diagram:

The state changes of this machine are triggered by the following:
  1. An Invitation object is newly created, either by the application for an outgoing session, or by the core for an incoming session.
  2. The application requested an outgoing session by calling the send_invite() method and and initial INVITE request is sent.
  3. A new incoming session is received by the core.
    The application should look out for state change to this state in order to be notified of new incoming sessions.
  4. A provisional response (1xx) is received from the remove party.
  5. A provisional response (1xx) is sent to the remote party, after the application called the respond_to_invite_provisionally() method.
  6. A positive final response (2xx) is received from the remote party.
  7. A positive final response (2xx) is sent to the remote party, after the application called the accept_invite() method.
  8. A positive final response (2xx) is sent or received, depending on the orientation of the session.
  9. An ACK is sent or received, depending on the orientation of the session.
    If the ACK is sent from the local to the remote party, it is initiated by PJSIP, not by a call from the application.
  10. The local party sent a re-INVITE to the remote party by calling the send_reinvite() method.
  11. The remote party has sent a final response to the re-INVITE.
  12. The remote party has sent a re-INVITE.
  13. The local party has responded to the re-INVITE by calling the respond_to_reinvite() method.
  14. The application requests that the session ends by calling the end() method.
  15. A response is received from the remote party to whichever message was sent by the local party to end the session.
  16. A message is received from the remote party which ends the session.

The application is notified of a state change in either state machine through the SIPInvitationChangedState notification, which has as data the current and previous states.
If the event is triggered by and incoming message, extensive data about that message, such as method/code, headers and body, is also included with the notification.
The application should compare the previous and current states and perform the appropriate action.

An Invitiation object also emits the SIPInvitationGotSDPUpdate notification, which indicates that SDP negotiation between the two parties has been completed.
This will occur (at least) once during the initial session negotiation steps, during re-INVITE@s in both directions and whenever an @UPDATE request is received.
In the last case, the Invitation object will automatically include the current local SDP in the response.

attributes

state

The state the Invitation state machine is currently in.
See the diagram above for possible states.
This attribute is read-only.

sub_state

The sub-state the Invitation state machine is currently in.
See the diagram above for possible states.
This attribute is read-only.

directing

A string with the values "incoming" or "outgoing" depending on the direction of the original INVITE request.

credentials

The SIP credentials needed to authenticate at the SIP proxy in the form of a FrozenCredentials object.
If this Invitation object represents an incoming INVITE session this attribute will be None.
On an outgoing session this attribute will be None if it was not specified when the object was created.
This attribute is set on object instantiation and is read-only.

from_header

The From header of the caller represented by a FrozenFromHeader object.
If this is an outgoing INVITE session, this is the from_header from the send_invite() method.
Otherwise the URI is taken from the From: header of the initial INVITE.
This attribute is set on object instantiation and is read-only.

to_header

The To header of the callee represented by a FrozenToHeader object.
If this is an outgoing INVITE session, this is the to_header from the send_invite() method.
Otherwise the URI is taken from the To: header of the initial INVITE.
This attribute is set on object instantiation and is read-only.

local_identity

The From or To header representing the local identity used in this session.
If the original INVITE was incoming, this is the same as to_header, otherwise it will be the same as from_header.

remote_identity

The From or To header representing the remote party in this session.
If the original INVITE was incoming, this is the same as from_header, otherwise it will be the same as to_header.

route_header

The outbound proxy that was requested to be used in the form of a FrozenRouteHeader object, including the desired transport.
If this Invitation object represents an incoming INVITE session this attribute will always be None.
This attribute is set on object instantiation and is read-only.

call_id

The call ID of the INVITE session as a read-only string.
In the NULL and DISCONNECTED states, this attribute is None.

transport

A string indicating the transport used for the application.
This can be "udp", "tcp" or "tls".

local_contact_header

The Contact header that the local side provided to the remote side within this INVITE session as a FrozenContactHeader object.
Note that this can either be set on object creation or updated using the send_reinvite() method.

remote_contact_header

The Contact header that the remote side provided to us within this INVITE session as a FrozenContactHeader object.

call_id

A string representing the Call-Id header value of this INVITE dialog.

remote_user_agent

A string representing the remote user agent taken from the User-Agent or Server headers (depending on the direction of the original INVITE).

sdp.proposed_local

The currently proposed sdp by the local party in the form of a FrozenSDPSession object. This attribute is None when an SDP proposal is not in progress.

sdp.proposed_remote

The currently proposed sdp by the remote party in the form of a FrozenSDPSession object. This attribute is None when an SDP proposal is not in progress.

sdp.active_local

The currently active sdp of the local party in the form of a FrozenSDPSession object. This attribute is None if no SDP proposal has succeeded before.

sdp.active_remote

The currently active sdp of the remote party in the form of a FrozenSDPSession object. This attribute is None if no SDP proposal has succeeded before.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

methods

__init__(self)

Creates a new Invitation object.

send_invite(self, request_uri,*from_header*, to_header, route_header, contact_header, sdp, credentials=None, extra_headers=[], timeout=None)

request_uri:

Request URI to be set inthe outgoing INVITE request.

from_header:

The identity of the local account in the form of a FromHeader object.

to_header:

The identity we want to send the INVITE to, represented as a ToHeader object.

route_header:

The outbound proxy to use in the form of a RouteHeader object.
This includes the desired transport to use.

contact_header:

The Contact header to include in the INVITE request, a ContactHeader object.

sdp:

The SDP to send as offer to the remote party.

credentials:

The optional SIP credentials needed to authenticate at the SIP proxy in the form of a Credentials object.

extra_headers:

Any extra headers that should be included in the INVITE request in the form of a list of header objects.

timeout:

How many seconds to wait for the remote party to reply before changing the state to DISCONNECTED and internally replying with a 408, as an int or a float.
If this is set to None, the default PJSIP timeout will be used, which appears to be slightly longer than 30 seconds.

send_response(self, code, reason, contact_header, sdp, extra_headers)

Send a response to a INVITE request.

code:

The code of the response to use as an int.

reason:

The reason of the response as a str.

contact_header:

The Contact header to include in the response, a ContactHeader object.

sdp:

The SDP to send as offer/response to the remote party.

extra_headers:

Any extra headers that should be included in the response in the form of a list of header objects.

send_reinvite(self, contact_header=None, sdp=None, extra_header=[])

contact_header:

The Contact header if it needs to be changed by the re-INVITE or None if it shouldn't be changed; a BaseContactHeader object.

sdp:

The SDP to send as offer to the remote party or None if the re-INVITE should not change the SDP; a BaseSDPSession object.

extra_headers:

Any extra headers that should be included in the response in the form of a list of header objects.

cancel_reinvite(self)

Send a CANCEL after a re-INVITE has been sent to cancel the action of the re-INVITE.

end(self, extra_headers=[], timeout=None)

This moves the INVITE state machine into the DISCONNECTING state by sending the necessary SIP request.
When a response from the remote party is received, the state machine will go into the DISCONNECTED state.
Depending on the current state, this could be a CANCEL or a BYE request.

extra_headers:

Any extra headers that should be included in the request or response in the form of a dict.

timeout:

How many seconds to wait for the remote party to reply before changing the state to DISCONNECTED, as an int or a float.
If this is set to None, the default PJSIP timeout will be used, which currently appears to be 3.5 seconds for an established session.

notifications

SIPInvitationChangedState

This notification is sent by an Invitation object whenever its state machine changes state.

timestamp:

A datetime.datetime object indicating when the notification was sent.

prev_state:

The previous state of the INVITE state machine.

prev_sub_state:

THe previous sub-state of the INVITE state machine.

state:

The new state of the INVITE state machine, which may be the same as the previous state.

sub_state:

The new sub-state of teh INVITE state machine, which may be the same as the previous sub-state.

method: (only if the state change got triggered by an incoming SIP request)

The method of the SIP request as a string.

request_uri: (only if the state change got triggered by an incoming SIP request)

The request URI of the SIP request as a SIPURI object.

code: (only if the state change got triggered by an incoming SIP response or internal timeout or error)

The code of the SIP response or error as an int.

reason: (only if the state change got triggered by an incoming SIP response or internal timeout or error)

The reason text of the SIP response or error as a string.

headers: (only if the state change got triggered by an incoming SIP request or response)

The headers of the SIP request or response as a dict.
Each SIP header is represented in its parsed for as long as PJSIP supports it.
The format of the parsed value depends on the header.

body: (only if the state change got triggered by an incoming SIP request or response)

The body of the SIP request or response as a string, or None if no body was included.
The content type of the body can be learned from the Content-Type: header in the headers argument.

SIPInvitationGotSDPUpdate

This notification is sent by an Invitation object whenever SDP negotiation has been performed.
It should be used by the application as an indication to start, change or stop any associated media streams.

timestamp:

A datetime.datetime object indicating when the notification was sent.

succeeded:

A boolean indicating if the SDP negotiation has succeeded.

error: (only if SDP negotiation did not succeed)

A string indicating why SDP negotiation failed.

local_sdp: (only if SDP negotiation succeeded)

A SDPSession object indicating the local SDP that was negotiated.

remote_sdp: (only if SDP negotiation succeeded)

A SDPSession object indicating the remote SDP that was negotiated.

SDPSession

SDP stands for Session Description Protocol. Session Description Protocol (SDP) is a format for describing streaming media initialization parameters in an ASCII string. SDP is intended for describing multimedia communication sessions for the purposes of session announcement, session invitation, and other forms of multimedia session initiation. It is an IETF standard described by RFC 4566. RFC 3264 defines an Offer/Answer Model with the Session Description Protocol (SDP), a mechanism by which two entities can make use of the Session Description Protocol (SDP) to arrive at a common view of a multimedia session between them.

SDPSession and FrozenSDPSession objects directly represent the contents of a SDP body, as carried e.g. in an INVITE request, and is a simple wrapper for the PJSIP pjmedia_sdp_session structure.
They can be passed to those methods of an Invitation object that result in transmission of a message that includes SDP, or are passed to the application through a notification that is triggered by reception of a message that includes SDP.
A (Frozen)SDPSession object may contain (Frozen)SDPMediaStream, (Frozen)SDPConnection and (Frozen)SDPAttribute objects.
It supports comparison to other (Frozen)SDPSession objects using the == and != expressions.
As all the attributes of the (Frozen)SDPSession class are set by attributes of the __init__ method, they will be documented along with that method.

methods

__init__(self, address, id=None, version=None, user="-", net_type="IN", address_type="IP4", name=" ", info=None, connection=None, start_time=0, stop_time=0, attributes=None, media=None)

Creates the SDPSession object with the specified parameters as attributes.
Each of these attributes can be accessed and changed on the object once instanced.

address:

The address that is contained in the "o" (origin) line of the SDP as a string.

id:

The session identifier contained in the "o" (origin) line of the SDP as an int.
If this is set to None on init, a session identifier will be generated.

version:

The version identifier contained in the "o" (origin) line of the SDP as an int.
If this is set to None on init, a version identifier will be generated.

user:

The user name contained in the "o" (origin) line of the SDP as a string.

net_type:

The network type contained in the "o" (origin) line of the SDP as a string.

address_type:

The address type contained in the "o" (origin) line of the SDP as a string.

name:

The contents of the "s" (session name) line of the SDP as a string.

info:

The contents of the session level "i" (information) line of the SDP as a string.
If this is None or an empty string, the SDP has no "i" line.

connection:

The contents of the "c" (connection) line of the SDP as a (Frozen)SDPConnection object.
If this is set to None, the SDP has no session level "c" line.

start_time:

The first value of the "t" (time) line of the SDP as an int.

stop_time:

The second value of the "t" (time) line of the SDP as an int.

attributes:

The session level "a" lines (attributes) in the SDP represented by a list of (Frozen)SDPAttribute objects.

media:

The media sections of the SDP represented by a list of (Frozen)SDPMediaStream objects.

new(cls, sdp_session)

Classmethod that returns an instance of the class on which it has been called which is a copy of the sdp_session object (which must be either a SDPSession or a FrozenSDPSession).

attributes

has_ice_proposal

This read-only attribute returns True if the SDP contains any attributes which indicate the existence of an ice proposal and False otherwise.

SDPMediaStream

The SDPMediaStream and FrozenSDPMediaStream objects represent the contents of a media section of a SDP body, i.e. a "m" line and everything under it until the next "m" line.
It is a simple wrapper for the PJSIP pjmedia_sdp_media structure.
One or more (Frozen)SDPMediaStream objects are usually contained in a (Frozen)SDPSession object.
It supports comparison to other (Frozen)SDPMedia objects using the == and != expressions.
As all the attributes of this class are set by attributes of the __init__ method, they will be documented along with that method.

methods

__init__(self, media, port, transport, port_count=1, formats=None, info=None, connection=None, attributes=None)

Creates the SDPMedia object with the specified parameters as attributes.
Each of these attributes can be accessed and changed on the object once instanced.

media:

The media type contained in the "m" (media) line as a string.

port:

The transport port contained in the "m" (media) line as an int.

transport:

The transport protocol in the "m" (media) line as a string.

port_count:

The port count in the "m" (media) line as an int.
If this is set to 1, it is not included in the SDP.

formats:

The media formats in the "m" (media) line represented by a list of strings.

info:

The contents of the "i" (information) line of this media section as a string.
If this is None or an empty string, the media section has no "i" line.

connection:

The contents of the "c" (connection) line that is somewhere below the "m" line of this section as a (Frozen)SDPConnection object.
If this is set to None, this media section has no "c" line.

attributes:

The "a" lines (attributes) that are somewhere below the "m" line of this section represented by a list of (Frozen)SDPAttribute objects.

new(cls, sdp_media)

Classmethod that returns an instance of the class on which it has been called which is a copy of the sdp_media object (which must be either a SDPMediaStream or a FrozenSDPMediaStream).

attributes

direction

This is a convenience read-only attribute that goes through all the attributes of the media section and returns the direction, which is either "sendrecv", "sendonly", "recvonly" or "inactive".
If none of these attributes is present, the default direction is "sendrecv".

SDPConnection

The SDPConnection and FrozenSDPConnection objects represents the contents of a "c" (connection) line of a SDP body, either at the session level or for an individual media stream.
It is a simple wrapper for the PJSIP pjmedia_sdp_conn structure.
A (Frozen)SDPConnection object can be contained in a (Frozen)SDPSession object or (Frozen)SDPMediaStream object.
It supports comparison to other (Frozen)SDPConnection objects using the == and != expressions.
As all the attributes of this class are set by attributes of the __init__ method, they will be documented along with that method.

methods

__init__(self, address, net_type="IN", address_type="IP4")

Creates the SDPConnection object with the specified parameters as attributes.
Each of these attributes can be accessed and changed on the object once instanced.

address:

The address part of the connection line as a string.

net_type:

The network type part of the connection line as a string.

address_type:

The address type part of the connection line as a string.

new(cls, sdp_connection)

Classmethod that returns an instance of the class on which it has been called which is a copy of the sdp_connection object (which must be either a SDPConnection or a FrozenSDPConnection).

SDPAttributeList

SDPAttributeList and FrozenSDPAttributeList are subclasses of list and frozenlist respectively and are used as the types of the attributes attributes of (Frozen)SDPSession and (Frozen)SDPMediaStream. They provide convinience methods for accessing SDP attributes. Apart from the standard list and frozenlist methods, they also provide the following:

__contains__(self, item)

If item is an instance of BaseSDPAttribute, the normal (frozen)list method is called. Otherwise, the method returns whether or not item is in the list of the names of the attributes. This allows tests such as the following to be possible:

  'ice-pwd' in sdp_session.attributes

getall(self, name)

Returns all the values of the attributes with the given name in a list.

getfirst(self, name, default=None)

Return the first value of the attribute with the given name, or default is no such attribute exists.

SDPAttribute

The SDPAttribute and FrozenSDPAttribute objects represent the contents of a "a" (attribute) line of a SDP body, either at the session level or for an individual media stream.
It is a simple wrapper for the PJSIP pjmedia_sdp_attr structure.
One or more (Frozen)SDPAttribute objects can be contained in a (Frozen)SDPSession object or (Frozen)SDPMediaStream object.
It supports comparison to other (Frozen)SDPAttribute objects using the == and != expressions.
As all the attributes of this class are set by attributes of the __init__ method, they will be documented along with that method.

methods

__init__(self, name, value)

Creates the SDPAttribute object with the specified parameters as attributes.
Each of these attributes can be accessed and changed on the object once instanced.

name:

The name part of the attribute line as a string.

value:

The value part of the attribute line as a string.

new(cls, sdp_attribute)

Classmethod that returns an instance of the class on which it has been called which is a copy of the sdp_attribute object (which must be either a SDPAttribute or a FrozenSDPAttribute).

RTPTransport

This object represents a transport for RTP media, the basis of which is a pair of UDP sockets, one for RTP and one for RTCP.
Internally it wraps a pjmedia_transport object.
Initially this object will only be used by the AudioTransport object, but in the future it can also be used for video and Real-Time Text.
For this reason the AudioTransport and RTPTransport are two distinct objects.

The RTPTransport object also allows support for ICE and SRTP functionality from PJSIP.
Because these features are related to both the UDP transport and the SDP formatting, the SDP carried in SIP signaling message will need to "pass through" this object during the SDP negotiation.
The code using this object, which in most cases will be the AudioTransport object, will need to call certain methods on the object at appropriate times.
This process of SDP negotiation is represented by the internal state machine of the object, as shown in the following diagram:

The Real-time Transport Protocol (or RTP) defines a standardized packet format for delivering audio and video over the Internet.
It was developed by the Audio-Video Transport Working Group of the IETF and published in RFC 3550.
RTP is used in streaming media systems (together with the RTSP) as well as in videoconferencing and push to talk systems.
For these it carries media streams controlled by Session Initiation Protocol (SIP) signaling protocols, making it the technical foundation of the Voice over IP industry.

State changes are triggered by the following events:
  1. The application calls the set_INIT() method after object creation and ICE+STUN is not used.
  2. The application calls the set_INIT() method after object creation and ICE+STUN is used.
  3. A successful STUN response is received from the STUN server.
  4. The set_LOCAL() method is called.
  5. The set_ESTABLISHED() method is called.
  6. The set_INIT() method is called while the object is in the LOCAL or ESTABLISHED state.
  7. A method is called on the application, but in the meantime the Engine has stopped.
    The object can no longer be used.
  8. There was an error in getting the STUN candidates from the STUN server.

It would make sense to be able to use the object even if the STUN request fails (and have ICE not include a STUN candidate), but for some reason the pjmedia_transport is unusable once STUN negotiation has failed.
This means that the RTPTransport object is also unusable once it has reached the STUN_FAILED state.
A workaround would be destroy the RTPTransport object and create a new one that uses ICE without STUN.

These states allow for two SDP negotiation scenarios to occur, represented by two paths that can be followed through the state machine.
In this example we will assume that ICE with STUN is not used, as it is independent of the SDP negotiation procedure.
  • The first scenario is where the local party generates the SDP offer.
    For a stream that it wishes to include in this SDP offer, it instantiates a RTPTransport object.
    After instantiation the object is initialized by calling the set_INIT() method and the local RTP address and port can be fetched from it using the local_rtp_address and local_rtp_port attributes respectively, which can be used to generate the local SDP in the form of a SDPSession object.
    This local SDP then needs to be passed to the set_LOCAL() method, which moves the state machine into the LOCAL state (note that it needs the full object, not just the relevant SDPMediaStream object).
    Depending on the options used for the RTPTransport instantiation (such as ICE and SRTP), this may change the SDPSession object.
    This (possibly changed) SDPSession object then needs to be passed to the Invitation object.
    After SDP negotiation is completed, the application needs to pass both the local and remote SDP, in the form of (Frozen)SDPSession objects, to the RTPTransport object using the set_ESTABLISHED() method, moving the state machine into the ESTABLISHED state.
    This will not change either of the (Frozen)SDPSession objects (which is why they can also be frozen).
  • The second scenario is where the local party is offered a media stream in SDP and wants to accept it.
    In this case a RTPTransport is also instantiated and initialized using the set_INIT() method, and the application can generate the local SDP in response to the remote SDP, using the local_rtp_address and local_rtp_port attributes.
    Directly after this it should pass the generated local SDP and received remote SDP, in the form of SDPSession objects, to the set_ESTABLISHED() method.
    In this case the local SDP object may be changed, after which it can be passed to the Invitation object.

Whenever the RTPTransport object is in the LOCAL or ESTABLISHED states, it may be reset to the INIT state to facilitate re-use of the existing transport and its features.
Before doing this however, the internal transport object must no longer be in use.

methods

__init__(self, local_rtp_address=None, use_srtp=False, srtp_forced=False, use_ice=False, ice_stun_address=None, ice_stun_port=3478)

Creates a new RTPTransport object and opens the RTP and RTCP UDP sockets.
If additional features are requested, they will be initialized.
After object instantiation, it is either in the INIT or the WAIT_STUN state, depending on the values of the use_ice and ice_stun_address arguments.

local_rtp_address:

Optionally contains the local IPv4 address to listen on.
If this is not specified, PJSIP will listen on all network interfaces.

use_srtp:

A boolean indicating if SRTP should be used.
If this is set to True, SRTP information will be added to the SDP when it passes this object.

srtp_forced:

A boolean indicating if use of SRTP is set to mandatory in the SDP.
If this is set to True and the remote party does not support SRTP, the SDP negotiation for this stream will fail.
This argument is relevant only if use_srtp is set to True.

use_ice:

A boolean indicating if ICE should be used.
If this is set to True, ICE candidates will be added to the SDP when it passes this object.

ice_stun_address:

A string indicating the address (IP address or hostname) of the STUN server that should be used to add a STUN candidate to the ICE candidates.
If this is set to None no STUN candidate will be added, otherwise the object will be put into the WAIT_STUN state until a reply, either positive or negative, is received from the specified STUN server.
When this happens a RTPTransportGotSTUNResponse notification is sent.
This argument is relevant only if use_ice is set to True.

ice_stun_address:

An int indicating the UDP port of the STUN server that should be used to add a STUN candidate to the ICE candidates.
This argument is relevant only if use_ice is set to True and ice_stun_address is not None.

set_INIT(self)

This moves the internal state machine into the INIT state.
If the state machine is in the LOCAL or ESTABLISHED states, this effectively resets the RTPTransport object for re-use.

set_LOCAL(self, local_sdp, sdp_index)

This moves the the internal state machine into the LOCAL state.

local_sdp:

The local SDP to be proposed in the form of a SDPSession object.
Note that this object may be modified by this method.

sdp_index:

The index in the SDP for the media stream for which this object was created.

set_ESTABLISHED(self, local_sdp, remote_sdp, sdp_index)

This moves the the internal state machine into the ESTABLISHED state.

local_sdp:

The local SDP to be proposed in the form of a SDPSession object.
Note that this object may be modified by this method, but only when moving from the LOCAL to the ESTABLISHED state.

remote_sdp:

The remote SDP that was received in in the form of a SDPSession object.

sdp_index:

The index in the SDP for the media stream for which this object was created.

attributes

state

Indicates which state the internal state machine is in.
See the previous section for a list of states the state machine can be in.
This attribute is read-only.

local_rtp_address

The local IPv4 address of the interface the RTPTransport object is listening on and the address that should be included in the SDP.
If no address was specified during object instantiation, PJSIP will take guess out of the IP addresses of all interfaces.
This attribute is read-only and will be None if PJSIP is not listening on the transport.

local_rtp_port

The UDP port PJSIP is listening on for RTP traffic.
RTCP traffic will always be this port plus one.
This attribute is read-only and will be None if PJSIP is not listening on the transport.

remote_rtp_address_sdp

The remote IP address that was seen in the SDP.
This attribute is read-only and will be None unless the object is in the ESTABLISHED state.

remote_rtp_port_sdp

The remote UDP port for RTP that was seen in the SDP.
This attribute is read-only and will be None unless the object is in the ESTABLISHED state.

remote_rtp_address_ice

The remote IP address that was selected by the ICE negotation.
This attribute is read-only and will be None until the ICE negotation succeeds.

remote_rtp_port_ice

The remote port that was selected by the ICE negotation.
This attribute is read-only and will be None until the ICE negotation succeeds.

remote_rtp_address_received

The remote IP address from which RTP data was received.
This attribute is read-only and will be None unless RTP was actually received.

remote_rtp_port_received

The remote UDP port from which RTP data was received.
This attribute is read-only and will be None unless RTP was actually received.

use_srtp

A boolean indicating if the use of SRTP was requested when the object was instantiated.
This attribute is read-only.

force_srtp

A boolean indicating if SRTP being mandatory for this transport if it is enabled was requested when the object was instantiated.
This attribute is read-only.

srtp_active

A boolean indicating if SRTP encryption and decryption is running.
Querying this attribute only makes sense once the object is in the ESTABLISHED state and use of SRTP was requested.
This attribute is read-only.

use_ice

A boolean indicating if the use of ICE was requested when the object was instantiated.
This attribute is read-only.

*ice_active_

A boolean indicating if ICE is being used.
This attribute is read-only.

ice_stun_address

A string indicating the IP address of the STUN server that was requested to be used.
This attribute is read-only.

ice_stun_port

A string indicating the UDP port of the STUN server that was requested to be used.
This attribute is read-only.

local_rtp_candidate_type

Returns the ICE candidate type which has been selected for the local endpoint.

remote_rtp_candidate_type

Returns the ICE candidate type which has been selected for the remote endpoint.

notifications

RTPTransportDidInitialize

This notification is sent when a RTPTransport object has successfully initialized.
If STUN+ICE is not requested, this is sent immediately on set_INIT(), otherwise it is sent after the STUN query has succeeded.

timestamp:

A datetime.datetime object indicating when the notification was sent.

RTPTransportDidFail

This notification is sent by a RTPTransport object that fails to retrieve ICE candidates from the STUN server after set_INIT() is called.

timestamp:

A datetime.datetime object indicating when the notification was sent.

reason:

A string describing the failure reason.

RTPTransportICENegotiationStateDidChange

This notification is sent to indicate the progress of the ICE negotiation.

state:

A string describing the current ICE negotiation state.

RTPTransportICENegotiationDidFail

This notification is sent when the ICE negotiation fails.

reason:

A string describing the failure reason of ICE negotation.

RTPTransportICENegotiationDidSucceed

This notification is sent when the ICE negotation succeeds.

chosen_local_candidates and chosen_remote_candidates:

Dictionaries with the following keys:

  • rtp_cand_type: the type of the RTP candidate
  • rtp_cand_ip: the IP address of the RTP candidate
  • rtcp_cand_type: the type of the RTCP candidate
  • rtcp_cand_ip: the IP address of teh RTCP candidate

duration:

The amount of time the ICE negotiation took.

local_candidates and remote_candidates:

Lists of tuples with the following elements:

  • Item ID
  • Component ID
  • Address
  • Component Type

connectivity_checks_results:

A list of tuples with the following elements:

  • Item ID
  • Component ID
  • Source
  • Destination
  • Nomination
  • State

AudioTransport

This object represent an audio stream as it is transported over the network.
It contains an instance of RTPTransport and wraps a pjmedia_stream object, which in turn manages the RTP encapsulation, RTCP session, audio codec and adaptive jitter buffer.
It also generates a SDPMediaStream object to be included in the local SDP.

The AudioTransport is an object that, once started, is connected to a AudioMixer instance, and both produces and consumes sound.

Like the RTPTransport object there are two usage scenarios.
  • In the first scenario, only the RTPTransport instance to be used is passed to the AudioTransport object.
    The application can then generate the SDPMediaStream object by calling the get_local_media() method and should include it in the SDP offer.
    Once the remote SDP is received, it should be set along with the complete local SDP by calling the start() method, which will start the audio stream.
    The stream can then be connected to the conference bridge.
  • In the other scenario the remote SDP is already known because it was received in an SDP offer and can be passed directly on object instantiation.
    The local SDPMediaStream object can again be generated by calling the get_local_media() method and is to be included in the SDP answer.
    The audio stream is started directly when the object is created.

Unlike the RTPTransport object, this object cannot be reused.

methods

__init__(self, mixer, transport, remote_sdp=None, sdp_index=0, enable_silence_detection=True, codecs=None)

Creates a new AudioTransport object and start the underlying stream if the remote SDP is already known.

mixer:

The AudioMixer object that this object is to be connected to.

transport:

The transport to use in the form of a RTPTransport object.

remote_sdp:

The remote SDP that was received in the form of a SDPSession object.

sdp_index:

The index within the SDP of the audio stream that should be created.

enable_silence_detection

Boolean that indicates if silence detection should be used for this audio stream.
When enabled, this AudioTransport object will stop sending audio to the remote party if the input volume is below a certain threshold.

codecs

A list of strings indicating the codecs that should be proposed in the SDP of this AudioTransport, in order of preference.
This overrides the global codecs list set on the Engine.
The values of this list are case insensitive.

get_local_media(self, is_offer, direction="sendrecv")

Generates a SDPMediaStream object which describes the audio stream.
This object should be included in a SDPSession object that gets passed to the Invitation object.
This method should also be used to obtain the SDP to include in re-INVITEs and replies to re-INVITEs.

is_offer:

A boolean indicating if the SDP requested is to be included in an offer.
If this is False it is to be included in an answer.

direction:

The direction attribute to put in the SDP.

start(self, local_sdp, remote_sdp, sdp_index, no_media_timeout=10, media_check_interval=30)

This method should only be called once, when the application has previously sent an SDP offer and the answer has been received.

local_sdp:

The full local SDP that was included in the SDP negotiation in the form of a SDPSession object.

remote_sdp:

The remote SDP that was received in the form of a SDPSession object.

sdp_index:

The index within the SDP of the audio stream.

no_media_timeout:

This argument indicates after how many seconds after starting the AudioTransport the RTPAudioTransportDidNotGetRTP notification should be sent, if no RTP has been received at all.
Setting this to 0 disables this an all subsequent RTP checks.

media_check_interval:

This indicates the interval at which the RTP stream should be checked, after it has initially received RTP at after no_media_timeout seconds.
It means that if between two of these interval checks no RTP has been received, a RTPAudioTransportDidNotGetRTP notification will be sent.
Setting this to 0 will disable checking the RTP at intervals.
The initial check may still be performed if its timeout is non-zero.

stop(self)

This method stops and destroys the audio stream encapsulated by this object.
After this it can no longer be used and should be deleted, while the RTPTransport object used by it can be re-used for something else.
This method will be called automatically when the object is deleted after it was started, but this should not be relied on because of possible reference counting issues.

send_dtmf(self, digit)

For a negotiated audio transport this sends one DTMF digit to the other party

digit:

A string of length one indicating the DTMF digit to send.
This can be either a digit, the pound sign (#), the asterisk sign (*) or the letters A through D.

update_direction(self, direction)

This method should be called after SDP negotiation has completed to update the direction of the media stream.

direction:

The direction that has been negotiated.

attributes

mixer

The AudioMixer object that was passed when the object got instantiated.
This attribute is read-only.

transport

The RTPTransport object that was passed when the object got instantiated.
This attribute is read-only.

slot

A read-only property indicating the slot number at which this object is attached to the associated conference bridge.
If the AudioTransport is not active (i.e. has not been started), this attribute will be None.

volume

A writable property indicating the % of volume at which this object contributes audio to the conference bridge.
By default this is set to 100.

is_active

A boolean indicating if the object is currently sending and receiving audio.
This attribute is read-only.

is_started

A boolean indicating if the object has been started.
Both this attribute and the is_active attribute get set to True once the start() method is called, but unlike the is_active attribute this attribute does not get set to False once stop() is called.
This is to prevent the object from being re-used.
This attribute is read-only.

codec

Once the SDP negotiation is complete, this attribute indicates the audio codec that was negotiated, otherwise it will be None.
This attribute is read-only.

sample_rate

Once the SDP negotiation is complete, this attribute indicates the sample rate of the audio codec that was negotiated, otherwise it will be None.
This attribute is read-only.

direction

The current direction of the audio transport, which is one of "sendrecv", "sendonly", "recvonly" or "inactive".
This attribute is read-only, although it can be set using the update_direction() method.

notifications

RTPAudioTransportGotDTMF

This notification will be sent when an incoming DTMF digit is received from the remote party.

timestamp:

A datetime.datetime object indicating when the notification was sent.

digit:

The DTMF digit that was received, in the form of a string of length one.
This can be either a number or letters A through D.

RTPAudioTransportDidNotGetRTP

This notification will be sent when no RTP packets have been received from the remote party for some time.
See the start() method for a more exact description.

timestamp:

A datetime.datetime object indicating when the notification was sent.

got_any:

A boolean data attribute indicating if the AudioTransport every saw any RTP packets from the remote party.
In effect, if no RTP was received after no_media_timeout seconds, its value will be False.

Request

The sipsimple.core.Request object encapsulates a single SIP request transaction from the client side, which includes sending the request, receiving the response and possibly waiting for the result of the request to expire.
Although this class can be used by the application to construct and send an arbitrary SIP request, most applications will use the classes for primitive requests provided in the sipsimple.core module, which are built on top of one or several Request objects and deal with instances of specific SIP methods (REGISTER, MESSAGE and PUBLISH).

The lifetime of this object is linear and is described by the following diagram:

The bar denotes which state the object is in and at the top are the notifications which may be emitted at certain points in time.
Directly after the object is instantiated, it will be in the INIT state.
The request will be sent over the network once its send() method is called, moving the object into the IN_PROGRESS state.
On each provisional response that is received in reply to this request, the SIPRequestGotProvisionalResponse notification is sent, with data describing the response.
Note that this may not occur at all if not provisional responses are received.
When the send() method has been called and it does not return an exception, the object will send either a SIPRequestDidSucceed or a SIPRequestDidFail notification.
Both of these notifications include data on the response that triggered it.
Note that a SIP response that requests authentication (401 or 407) will be handled internally the first time, if a Credentials object was supplied.
If this is the sort of request that expires (detected by a Expires header in the response or a expires parameter in the Contact header of the response), and the request was successful, the object will go into the EXPIRING state.
A certain amount of time before the result of the request will expire, governed by the expire_warning_time class attribute and the actual returned expiration time, a SIPRequestWillExpire notification will be sent.
This should usually trigger whomever is using this Request object to construct a new Request for a refreshing operation.
When the Request actually expires, or when the EXPIRING state is skipped directly after sending SIPRequestDidSucceed or SIPRequestDidFail, a SIPRequestDidEnd notification will be sent.

methods

__init__(self, method, request_uri, from_header, to_header, route_header, credentials=None, contact_header=None, call_id=None, cseq=None, extra_headers=None, content_type=None, body=None)

Creates a new Request object in the INIT state.
The arguments to this method are documented in the attributes section.

send(self, timeout=None)
Compose the SIP request and send it to the destination.
This moves the Request object into the IN_PROGRESS state.

timeout:

This can be either an int or a float, indicating in how many seconds the request should timeout with an internally generated 408 response.
This is is None, the internal 408 is only triggered by the internal PJSIP transaction timeout.
Note that, even if the timeout is specified, the PJSIP timeout is also still valid.

end(self)

Terminate the transaction, whichever state it is in, sending the appropriate notifications.
Note that calling this method while in the INIT state does nothing.

attributes

expire_warning_time (class attribute)

The SIPRequestWillExpire notification will be sent halfway between the positive response and the actual expiration time, but at least this amount of seconds before.
The default value is 30 seconds.

state

Indicates the state the Request object is in, in the form of a string.
Refer to the diagram above for possible states.
This attribute is read-only.

method

The method of the SIP request as a string.
This attribute is set on instantiation and is read-only.

from_header

The FrozenFromHeader object to put in the From header of the request.
This attribute is set on instantiation and is read-only.

to_header

The FrozenToHeader object to put in the To header of the request.
This attribute is set on instantiation and is read-only.

request_uri

The SIP URI to put as request URI in the request, in the form of a FrozenSIPURI object.
This attribute is set on instantiation and is read-only.

route_header

Where to send the SIP request to, including IP, port and transport, in the form of a FrozenRouteHeader object.
This will also be included in the Route header of the request.
This attribute is set on instantiation and is read-only.

credentials

The credentials to be used when challenged for authentication, represented by a FrozenCredentials object.
If no credentials were supplied when the object was created this attribute is None.
This attribute is set on instantiation and is read-only.

contact_header

The FrozenContactHeader object to put in the Contact header of the request.
If this was not specified, this attribute is None.
It is set on instantiation and is read-only.

call_id

The Call-ID to be used for this transaction as a string.
If no call id was specified on instantiation, this attribute contains the generated id.
This attribute is set on instantiation and is read-only.

cseq

The sequence number to use in the request as an int.
If no sequence number was specified on instantiation, this attribute contains the generated sequence number.
Note that this number may be increased by one if an authentication challenge is received and a Credentials object is given.
This attribute is read-only.

extra_headers

Extra headers to include in the request as a frozenlist of header objects.
This attribute is set on instantiation and is read-only.

content_type

What string to put as content type in the Content-Type headers, if the request contains a body.
If no body was specified, this attribute is None
It is set on instantiation and is read-only.

body

The body of the request as a string.
If no body was specified, this attribute is None
It is set on instantiation and is read-only.

expires_in

This read-only property indicates in how many seconds from now this Request will expire, if it is in the EXPIRING state.
If this is not the case, this property is 0.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

notifications

SIPRequestGotProvisionalResponse

This notification will be sent on every provisional response received in reply to the sent request.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The SIP response code of the received provisional response as an int, which will be in the 1xx range.

reason:

The reason text string included with the SIP response code.

headers:

The headers included in the provisional response as a dict, the values of which are header objects.

body:

The body of the provisional response as a string, or None if there was no body.

SIPRequestDidSucceed

This notification will be sent when a positive final response was received in reply to the request.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The SIP response code of the received positive final response as an int, which will be in the 2xx range.

reason:

The reason text string included with the SIP response code.

headers:

The headers included in the positive final response as a dict, the values of which are header objects.

body:

The body of the positive final response as a string, or None if there was no body.

expires:

Indicates in how many seconds the Request will expire as an int.
If it does not expire and the EXPIRING state is skipped, this attribute is 0.

SIPRequestDidFail

This notification will be sent when a negative final response is received in reply to the request or if an internal error occurs.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The SIP response code of the received negative final response as an int.
This could also be a response code generated by PJSIP internally, or 0 when an internal error occurs.

reason:

The reason text string included with the SIP response code or error.

headers: (only if a negative final response was received)

The headers included in the negative final response as a dict, the values of which are header objects, if this is what triggered the notification.

body: (only if a negative final response was received)

The body of the negative final response as a string, or None if there was no body.
This attribute is absent if no response was received.

SIPRequestWillExpire

This notification will be sent when a Request in the EXPIRING state will expire soon.

timestamp:

A datetime.datetime object indicating when the notification was sent.

expires:

An int indicating in how many seconds from now the Request will actually expire.

SIPRequestDidEnd

This notification will be sent when a Request object enters the TERMINATED state and can no longer be used.

timestamp:

A datetime.datetime object indicating when the notification was sent.

IncomingRequest

This is a relatively simple object that can manage responding to incoming requests in a single transaction. For this reason it does not handle requests that create a dialog.
To register methods for which requests should be formed into an IncomingRequest object, the application should either start the Engine with the incoming_requests=[list_of_method_names] argument, or use the add_incoming_request/remove_incoming_request methods on the Engine after it's started to modify the list of methods for which the Engine will create IncomingRequest instances.

Example:

engine = Engine()
engine.start(incoming_requests=['OPTIONS'])

or after the Engine was started

engine.add_incoming_request('OPTIONS')

Note: Receiving INVITE, SUBSCRIBE, ACK and BYE through this object is not supported.

The application is notified of an incoming request through the SIPIncomingRequestGotRequest notification.
It can answer this request by calling the answer method on the sender of this notification.
Note that if the IncomingRequest object gets destroyed before it is answered, a 500 response is automatically sent.

attributes

state

This read-only attribute indicates the state the object is in.
This can be None if the object was created by the application, essentially meaning the object is inert, "incoming" or "answered".

methods

answer(self, code, reason=None, extra_headers=None)

Reply to the received request with a final response.

code:

The SIP response code to send.
This should be 200 or higher.

reason:

The reason text to include in the response.
If this is None, the default text for the given response code is used.

extra_headers:

The extra headers to include in the response as an iterable of header objects.

notifications

SIPIncomingRequestGotRequest

This notification will be sent when a new IncomingRequest is created as result of a received request.
The application should listen for this notification, retain a reference to the object that sent it and answer it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

method:

The method of the SIP request as a string.

request_uri:

The request URI of the request as a FrozenSIPURI object.

headers:

The headers of the request as a dict, the values of which are the relevant header objects.

body:

The body of the request as a string, or None if no body was included.

SIPIncomingRequestSentResponse

This notification is sent when a response to the request is sent by the object.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The code of the SIP response as an int.

reason:

The reason text of the SIP response as an int.

headers:

The headers of the response as a dict, the values of which are the relevant header objects.

body:

This will be None.

Message

The Message class is a simple wrapper for the Request class, with the purpose of sending MESSAGE requests, as described in RFC 3428.
It is a one-shot object that manages only one Request object.

methods

__init__(self, from_header, to_header, route_header, content_type, body, credentials=None, extra_headers=[])

Creates a new Message object with the specified arguments.
These arguments are documented in the attributes section for this class.

send(self, timeout=None)

Send the MESSAGE request to the remote party.

timeout:

This argument as the same meaning as it does for Request.send().

end(self)

Stop trying to send the MESSAGE request.
If it was not sent yet, calling this method does nothing.

attributes

from_header

The FrozenFromHeader to put in the From header of the MESSAGE request.
This attribute is set on instantiation and is read-only.

to_header

The FrozenToHeader to put in the To header of the MESSAGE request.
This attribute is set on instantiation and is read-only.

route_header

Where to send the MESSAGE request to, including IP, port and transport, in the form of a FrozenRouteHeader object.
This will also be included in the Route header of the request.
This attribute is set on instantiation and is read-only.

content_type

What string to put as content type in the Content-Type headers.
It is set on instantiation and is read-only.

body

The body of the MESSAGE request as a string.
If no body was specified, this attribute is None
It is set on instantiation and is read-only.

credentials

The credentials to be used when challenged for authentication, represented by a FrozenCredentials object.
If no credentials were specified, this attribute is None.
This attribute is set on instantiation and is read-only.

is_sent

A boolean read-only property indicating if the MESSAGE request was sent.

in_progress

A boolean read-only property indicating if the object is waiting for the response from the remote party.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

notifications

SIPMessageDidSucceed

This notification will be sent when the remote party acknowledged the reception of the MESSAGE request.
It has not data attributes.

SIPMessageDidFail

This notification will be sent when transmission of the MESSAGE request fails for whatever reason.

code:

An int indicating the SIP or internal PJSIP code that was given in response to the MESSAGE request.
This is 0 if the failure is caused by an internal error.

reason:

A status string describing the failure, either taken from the SIP response or the internal error.

Registration

The Registration class wraps a series of Request objects, managing the registration of a particular contact URI at a SIP registrar through the sending of REGISTER requests.
For details, see RFC 3261.
This object is designed in such a way that it will not initiate sending a refreshing REGISTER itself, rather it will inform the application that a registration is about to expire.
The application should then perform a DNS lookup to find the relevant SIP registrar and call the register() method on this object.

methods

__init__(self, from_header, credentials=None, duration=300)

Creates a new Registration object with the specified arguments.
These arguments are documented in the attributes section for this class.

register(self, contact_header, route_header, timeout=None)

Calling this method will attempt to send a new REGISTER request to the registrar provided, whatever state the object is in.
If the object is currently busy sending a REGISTER, this request will be preempted for the new one.
Once sent, the Registration object will send either a SIPRegistrationDidSucceed or a SIPRegistrationDidFail notification.
The contact_header argument is mentioned in the attributes section of this class.
The route_header argument specifies the IP address, port and transport of the SIP registrar in the form of a RouteHeader object and timeout has the same meaning as it does for Request.send().

end(self, timeout=None)

Calling this method while the object is registered will attempt to send a REGISTER request with the Expires headers set to 0, effectively unregistering the contact URI at the registrar.
The RouteHeader used for this will be the same as the last successfully sent REGISTER request.
If another REGISTER is currently being sent, it will be preempted.
When the unregistering REGISTER request is sent, a SIPRegistrationWillEnd notification is sent.
After this, either a SIPRegistrationDidEnd with the expired data attribute set to False will be sent, indicating a successful unregister, or a SIPRegistrationDidNotEnd notification is sent if unregistering fails for some reason.
Calling this method when the object is not registered will do nothing.
The timeout argument has the same meaning as for the register() method.

attributes

*from_header_

The (Frozen)FromHeader the Registration was sent with.

credentials

The credentials to be used when challenged for authentication by the registrar, represented by a (Frozen)Credentials object.
This attribute is set at instantiation, can be None if it was not specified and can be updated to be used for the next REGISTER request.
Note that, in contrast to other classes mentioned in this document, the Registration class does not make a copy of the Credentials object on instantiation, but instead retains a reference to it.

duration

The amount of time in seconds to request the registration for at the registrar.
This attribute is set at object instantiation and can be updated for subsequent REGISTER requests.

is_registered

A boolean read-only property indicating if this object is currently registered.

contact_header

If the Registration object is registered, this attribute contains the latest contact header that was sent to the registrar as a FrozenContactHeader object.
Otherwise, this attribute is None

expires_in

If registered, this read-only property indicates in how many seconds from now this Registration will expire.
If this is not the case, this property is 0.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

notifications

SIPRegistrationDidSucceed

This notification will be sent when the register() method was called and the registration succeeded.

code:

The SIP response code as received from the registrar as an int.

reason:

The reason string received from the SIP registrar.

route_header:

The (Frozen)RouteHeader object passed as an argument to the register() method.

contact_header:

The contact header that was sent to the registrar as a FrozenContactHeader object.

contact_header_list:

A full list of contact headers that are registered for this SIP account, including the one used for this registration.
The format of this data attribute is a list of FrozenContactHeader objects.

expires_in:

The number of seconds before this registration expires

SIPRegistrationDidFail

This notification will be sent when the register() method was called and the registration failed, for whatever reason.

code:

The SIP response code as received from the registrar as an int.
This can also be a PJSIP generated response code, or 0 if the failure was because of an internal error.

reason:

The reason string received from the SIP registrar or the error string.

route_header:

The (Frozen)RouteHeader object passed as an argument to the register() method.

SIPRegistrationWillExpire

This notification will be sent when a registration will expire soon.
It should be used as an indication to re-perform DNS lookup of the registrar and call the register() method.

expires:

The number of seconds in which the registration will expire.

SIPRegistrationWillEnd

Will be sent whenever the end() method was called and an unregistering REGISTER is sent.

SIPRegistrationDidNotEnd

This notification will be sent when the unregistering REGISTER request failed for some reason.

code:

The SIP response code as received from the registrar as an int.
This can also be a PJSIP generated response code, or 0 if the failure was because of an internal error.

reason:

The reason string received from the SIP registrar or the error string.

SIPRegistrationDidEnd

This notification will be sent when a Registration has become unregistered.

expired:

This boolean indicates if the object is unregistered because the registration expired, in which case it will be set to True.
If this data attribute is False, it means that unregistration was explicitly requested through the end() method.

example code

For an example on how to use this object, see the Integration section.

Publication

Publication of SIP events is an Internet standard published at RFC 3903.
PUBLISH is similar to REGISTER in that it allows a user to create, modify, and remove state in another entity which manages this state on behalf of the user.

A Publication object represents publishing some content for a particular SIP account and a particular event type at the SIP presence agent through a series of PUBLISH request.
This object is similar in behaviour to the Registration object, as it is also based on a sequence of Request objects.
As with this other object, the Publication object will notify the application when a published item is about to expire and it is the applications responsibility to perform a DNS lookup and call the publish() method in order to send the PUBLISH request.

methods

__init__(self, from_header, event, content_type, credentials=None, duration=300)

Creates a new Publication object with the specified arguments.
These arguments are documented in the attributes section for this class.

publish(self, body, route_header, timeout=None)

Send an actual PUBLISH request to the specified presence agent.

body:

The body to place in the PUBLISH request as a string.
This body needs to be of the content type specified at object creation.
For the initial request, a body will need to be specified.
For subsequent refreshing PUBLISH requests, the body can be None to indicate that the last published body should be refreshed.
If there was an ETag error with the previous refreshing PUBLISH, calling this method with a body of None will throw a PublicationError.

route_header:

The host where the request should be sent to in the form of a (Frozen)RouteHeader object.

timeout:

This can be either an int or a float, indicating in how many seconds the SUBSCRIBE request should timeout with an internally generated 408 response.
This is is None, the internal 408 is only triggered by the internal PJSIP transaction timeout.
Note that, even if the timeout is specified, the PJSIP timeout is also still valid.

end(self, timeout=None)

End the publication by sending a PUBLISH request with an Expires header of 0.
If the object is not published, this will result in a PublicationError being thrown.

timeout:

The meaning of this argument is the same as it is for the publish() method.

attributes

*from_header_

The (Frozen)FromHeader the Publication was sent with.

*event_

The name of the event this object is publishing for the specified SIP URI, as a string.

*content_type_

The Content-Type of the body that will be in the PUBLISH requests.
Typically this will remain the same throughout the publication session, but the attribute may be updated by the application if needed.
Note that this attribute needs to be in the typical MIME type form, containing a "/" character.

credentials

The credentials to be used when challenged for authentication by the presence agent, represented by a (Frozen)Credentials object.
This attribute is set at instantiation, can be None if it was not specified and can be updated to be used for the next PUBLISH request.
Note that, in contrast to most other classes mentioned in this document, the Publication class does not make a copy of the (Frozen)Credentials object on instantiation, but instead retains a reference to it.

duration

The amount of time in seconds that the publication should be valid for.
This attribute is set at object instantiation and can be updated for subsequent PUBLISH requests.

is_published

A boolean read-only property indicating if this object is currently published.

expires_in

If published, this read-only property indicates in how many seconds from now this Publication will expire.
If this is not the case, this property is 0.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

notifications

SIPPublicationDidSucceed

This notification will be sent when the publish() method was called and the publication succeeded.

code:

The SIP response code as received from the SIP presence agent as an int.

reason:

The reason string received from the SIP presence agent.

route_header:

The (Frozen)RouteHeader object passed as an argument to the publish() method.

expires_in:

The number of seconds before this publication expires

SIPPublicationDidFail

This notification will be sent when the publish() method was called and the publication failed, for whatever reason.

code:

The SIP response code as received from the presence agent as an int.
This can also be a PJSIP generated response code, or 0 if the failure was because of an internal error.

reason:

The reason string received from the presence agent or the error string.

route_header:

The (Frozen)RouteHeader object passed as an argument to the publish() method.

SIPPublicationWillExpire

This notification will be sent when a publication will expire soon.
It should be used as an indication to re-perform DNS lookup of the presence agent and call the publish() method.

expires:

The number of seconds in which the publication will expire.

SIPPublicationWillEnd

Will be sent whenever the end() method was called and an unpublishing PUBLISH is sent.

SIPPublicationDidNotEnd

This notification will be sent when the unpublishing PUBLISH request failed for some reason.

code:

The SIP response code as received from the presence agent as an int.
This can also be a PJSIP generated response code, or 0 if the failure was because of an internal error.

reason:

The reason string received from the presence agent or the error string.

SIPPublicationDidEnd

This notification will be sent when a Publication has become unpublished.

expired:

This boolean indicates if the object is unpublished because the publication expired, in which case it will be set to True.
If this data attribute is False, it means that unpublication was explicitly requested through the end() method.

Subscription

Subscription and notifications for SIP events is an Internet standard published at RFC 3856.

This SIP primitive class represents a subscription to a specific event type of a particular SIP URI.
This means that the application should instance this class for each combination of event and SIP URI that it wishes to subscribe to.
The event type and the content types that are acceptable for it need to be registered first, either through the init_options attribute of Engine (before starting it), or by calling the add_event() method of the Engine instance.
Whenever a NOTIFY is received, the application will receive the SIPSubscriptionGotNotify event.

Internally a Subscription object has a state machine, which reflects the state of the subscription.
It is a direct mirror of the state machine of the underlying pjsip_evsub object, whose possible states are at least NULL, SENT, ACCEPTED, PENDING, ACTIVE or TERMINATED.
The last three states are directly copied from the contents of the Subscription-State header of the received NOTIFY request.
Also, the state can be an arbitrary string if the contents of the Subscription-State header are not one of the three above.
The state of the object is presented in the state attribute and changes of the state are indicated by means of the SIPSubscriptionChangedState notification.
This notification is only informational, an application using this object should take actions based on the other notifications sent by this object.

methods

__init__(self, request_uri, from_header, to_header, contact_header, *event, route_header, credentials=None, refresh=300)

Creates a new Subscription object which will be in the NULL state.
The arguments for this method are documented in the attributes section above.

subscribe(self, extra_headers=None, content_type=None, body=None, timeout=None)

Calling this method triggers sending a SUBSCRIBE request to the presence agent.
The arguments passed will be stored and used for subsequent refreshing SUBSCRIBE requests.
This method may be used both to send the initial request and to update the arguments while the subscription is ongoing.
It may not be called when the object is in the TERMINATED state.

extra_headers:

A dictionary of additional headers to include in the SUBSCRIBE requests.

content_type:

The Content-Type of the supplied body argument as a string.
If this argument is supplied, the body argument cannot be None.

body:

The optional body to include in the SUBSCRIBE request as a string.
If this argument is supplied, the content_type argument cannot be None.

timeout:

This can be either an int or a float, indicating in how many seconds the request should timeout with an internally generated 408 response.
If this is None, the internal 408 is only triggered by the internal PJSIP transaction timeout.
Note that, even if the timeout is specified, the PJSIP timeout is also still valid.

end(self, timeout=None)

This will end the subscription by sending a SUBSCRIBE request with an Expires value of 0.
If this object is no longer subscribed, this method will return without performing any action.
This method cannot be called when the object is in the NULL state.
The timeout argument has the same meaning as it does for the subscribe() method.

attributes

state

Indicates which state the internal state machine is in.
See the previous section for a list of states the state machine can be in.

from_header

The FrozenFromHeader to be put in the From header of the SUBSCRIBE requests.
This attribute is set on object instantiation and is read-only.

to_header

The FrozenToHeader that is the target for the subscription.
This attribute is set on object instantiation and is read-only.

contact_header

The FrozenContactHeader to be put in the Contact header of the SUBSCRIBE requests.
This attribute is set on object instantiation and is read-only.

event

The event package for which the subscription is as a string.
This attribute is set on object instantiation and is read-only.

route_header

The outbound proxy to use in the form of a FrozenRouteHeader object.
This attribute is set on object instantiation and is read-only.

credentials

The SIP credentials needed to authenticate at the SIP proxy in the form of a FrozenCredentials object.
If none was specified when creating the Subscription object, this attribute is None.
This attribute is set on object instantiation and is read-only.

refresh

The refresh interval in seconds that was requested on object instantiation as an int.
This attribute is set on object instantiation and is read-only.

extra_headers

This contains the frozenlist of extra headers that was last passed to a successful call to the subscribe() method.
If the argument was not provided, this attribute is an empty list.
This attribute is read-only.

content_type

This attribute contains the Content-Type of the body that was last passed to a successful call to the subscribe() method.
If the argument was not provided, this attribute is None.

body

This attribute contains the body string argument that was last passed to a successful call to the subscribe() method.
If the argument was not provided, this attribute is None.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

notifications

SIPSubscriptionChangedState

This notification will be sent every time the internal state machine of a Subscription object changes state.

timestamp:

A datetime.datetime object indicating when the notification was sent.

prev_state:

The previous state that the sate machine was in.

state:

The new state the state machine moved into.

SIPSubscriptionWillStart

This notification will be emitted when the initial SUBSCRIBE request is sent.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPSubscriptionDidStart

This notification will be sent when the initial SUBSCRIBE was accepted by the presence agent.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPSubscriptionGotNotify

This notification will be sent when a NOTIFY is received that corresponds to a particular Subscription object.
Note that this notification could be sent when a NOTIFY without a body is received.

request_uri:

The request URI of the NOTIFY request as a SIPURI object.

from_header:

The From header of the NOTIFY request as a FrozenFromHeader object.

to_header:

The To header of the NOTIFY request as a FrozenToHeader object.

content_type:

The Content-Type header value of the NOTIFY request as a ContentType object.

event:

The Event header value of the NOTIFY request as a string object.

headers:

The headers of the NOTIFY request as a dict.
Each SIP header is represented in its parsed for as long as PJSIP supports it.
The format of the parsed value depends on the header.

body:

The body of the NOTIFY request as a string, or None if no body was included.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPSubscriptionDidFail

This notification will be sent whenever there is a failure, such as a rejected initial or refreshing SUBSCRIBE.
After this notification the Subscription object is in the TERMINATED state and can no longer be used.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

An integer SIP code from the fatal response that was received from the remote party of generated by PJSIP.
If the error is internal to the SIP core, this attribute will have a value of 0.

reason:

An text string describing the failure that occurred.

min_expires:

An integer containing the value from the Min-Expires header. Will be None if the response doesn't contain the header.

SIPSubscriptionDidEnd

This notification will be sent when the subscription ends normally, i.e. the end() method was called and the remote party sent a positive response.
After this notification the Subscription object is in the TERMINATED state and can no longer be used.

timestamp:

A datetime.datetime object indicating when the notification was sent.

IncomingSubscription

Subscription and notifications for SIP events is an Internet standard published at RFC 3856.

This SIP primitive class is the mirror companion to the Subscription class and allows the application to take on the server role in a SUBSCRIBE session.
This means that it can accept a SUBSCRIBE request and subsequent refreshing SUBSCRIBE@s and sent @NOTIFY requests containing event state.

In order to be able to receive SUBSCRIBE requests for a particular event package, the application needs to add the name of this event package to the incoming_events set attribute on the Engine, either at startup or at a later time, using the add_incoming_event() method.
This event needs to be known by the Engine, i.e. it should already be present in the events dictionary attribute.
Once the event package name is in the incoming_events set attribute, any incoming SUBSCRIBE request containing this name in the Event header causes the creation of a IncomingSubscribe object.
This will be indicated to the application through a SIPIncomingSubscriptionGotSubscribe notification.
It is then up to the application to check if the SUBSCRIBE request was valid, e.g. if it was actually directed at the correct SIP URI, and respond to it in a timely fashion.

The application can either reject the subscription by calling the reject() method or accept it through the accept() method, optionally first accepting it in the pending state by calling the accept_pending() method.
After the IncomingSubscription is accepted, the application can trigger sending a NOTIFY request with a body reflecting the event state through the push_content() method.
Whenever a refreshing SUBSCRIBE is received, the latest contents to be set are sent in the resulting NOTIFY request.
The subscription can be ended by using the end() method.

methods

__init__(self)

An application should never create an IncomingSubscription object itself.
Doing this will create a useless object in the None state.

reject(self, code)

Will reply to the initial SUBSCRIBE with a negative response.
This method can only be called in the "incoming" state and sets the subscription to the "terminated" state.

code:

The SIP response code to use.
This should be a negative response, i.e. in the 3xx, 4xx, 5xx or 6xx range.

accept_pending(self)

Accept the initial incoming SUBSCRIBE, but put the subscription in the "pending" state and reply with a 202, followed by a NOTIFY request indicating the state.
The application can later decide to fully accept the subscription or terminate it.
This method can only be called in the "incoming" state.

accept(self, content_type=None, content=None)

Accept the initial incoming SUBSCRIBE and respond to it with a 200 OK, or fully accept an IncomingSubscription that is in the "pending" state.
In either case, a NOTIFY will be sent to update the state to "active", optionally with the content specified in the arguments.
This method can only be called in the "incoming" or "pending" state.

content_type:

The Content-Type of the content to be set supplied as a string containing a "/" character.
Note that if this argument is set, the content argument should also be set.

content:

The body of the NOTIFY to send when accepting the subscription, as a string.
Note that if this argument is set, the content_type argument should also be set.

push_content(self, content_type, content)

Sets or updates the body of the NOTIFY@s to be sent within this subscription and causes a @NOTIFY to be sent to the subscriber.
This method can only be called in the "active" state.

content_type:

The Content-Type of the content to be set supplied as a string containing a "/" character.

content:

The body of the NOTIFY as a string.

attributes

state

Indicates which state the incoming subscription session is in.
This can be one of None, "incoming", "pending", "active" or "terminated".
This attribute is read-only.

event

The name of the event package that this IncomingSubscription relates to.
This attribute is a read-only string.

content_type

The Content-Type of the last set content in this subscription session.
Inititally this will be None.
This attribute is a read-only string.

content

The last set content in this subscription session as a read-only string.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

notifications

SIPIncomingSubscriptionChangedState

This notification will be sent every time the an IncomingSubscription object changes state.
This notification is mostly indicative, an application should not let its logic depend on it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

prev_state:

The previous state that the subscription was in.

state:

The new state the subscription has.

SIPIncomingSubscriptionGotSubscribe

This notification will be sent when a new IncomingSubscription is created as result of an incoming SUBSCRIBE request.
The application should listen for this notification, retain a reference to the object that sent it and either accept or reject it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

method:

The method of the SIP request as a string, which will be SUBSCRIBE.

request_uri:

The request URI of the SUBSCRIBE request as a FrozenSIPURI object.

headers:

The headers of the SUBSCRIBE request as a dict, the values of which are the relevant header objects.

body:

The body of the SUBSCRIBE request as a string, or None if no body was included.

SIPIncomingSubscriptionGotRefreshingSubscribe

This notification indicates that a refreshing SUBSCRIBE request was received from the subscriber.
It is purely informative, no action needs to be taken by the application as a result of it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

method:

The method of the SIP request as a string, which will be SUBSCRIBE.

request_uri:

The request URI of the SUBSCRIBE request as a FrozenSIPURI object.

headers:

The headers of the SUBSCRIBE request as a dict, the values of which are the relevant header objects.

body:

The body of the SUBSCRIBE request as a string, or None if no body was included.

SIPIncomingSubscriptionGotUnsubscribe

This notification indicates that a SUBSCRIBE request with an Expires header of 0 was received from the subscriber, effectively requesting to unsubscribe.
It is purely informative, no action needs to be taken by the application as a result of it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

method:

The method of the SIP request as a string, which will be SUBSCRIBE.

request_uri:

The request URI of the SUBSCRIBE request as a FrozenSIPURI object.

headers:

The headers of the SUBSCRIBE request as a dict, the values of which are the relevant header objects.

body:

The body of the SUBSCRIBE request or response as a string, or None if no body was included.

SIPIncomingSubscriptionAnsweredSubscribe

This notification is sent whenever a response to a SUBSCRIBE request is sent by the object, including an unsubscribing SUBSCRIBE.
It is purely informative, no action needs to be taken by the application as a result of it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The code of the SIP response as an int.

reason:

The reason text of the SIP response as an int.

headers:

The headers of the response as a dict, the values of which are the relevant header objects.

body:

This will be None.

SIPIncomingSubscriptionSentNotify

This notification indicates that a NOTIFY request was sent to the subscriber.
It is purely informative, no action needs to be taken by the application as a result of it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

method:

The method of the SIP request as a string, which will be NOTIFY.

request_uri:

The request URI of the NOTIFY request as a FrozenSIPURI object.

headers:

The headers of the NOTIFY request as a dict, the values of which are the relevant header objects.

body:

The body of the NOTIFY request or response as a string, or None if no body was included.

SIPIncomingSubscriptionNotifyDidSucceed

This indicates that a positive final response was received from the subscriber in reply to a sent NOTIFY request.
The notification is purely informative, no action needs to be taken by the application as a result of it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The code of the SIP response as an int.

reason:

The reason text of the SIP response as a string.

headers:

The headers of the response as a dict, the values of which are the relevant header objects.

body:

This will be None.

SIPIncomingSubscriptionNotifyDidFail

This indicates that a negative response was received from the subscriber in reply to a sent NOTIFY request or that the NOTIFY failed to send.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The code of the SIP response as an int.
If this is 0, the notification was sent as a result of an internal error.

reason:

The reason text of the SIP response as a string or the internal error if the code attribute is 0.

headers: (if the notification was caused by a negative response)

The headers of the response as a dict, the values of which are the relevant header objects.

body: (if the notification was caused by a negative response)

This will be None.

SIPIncomingSubscriptionDidEnd

This notification is sent whenever the IncomingSubscription object reaches the "terminated" state and is no longer valid.
After receiving this notification, the application should not longer try to use the object.

timestamp:

A datetime.datetime object indicating when the notification was sent.

Referral

Subscription and notifications for SIP events is an Internet standard published at RFC 3856.
The REFER method, defined in RFC 3515 uses the subscription mechanism to tell SIP endpoints to refer to specific resources.

This SIP primitive class represents a referral requested by the client to a target URI.
This means that the application should instance this class for each combination of target URI and resource it wishes the target to refer to.
Whenever a NOTIFY is received, the application will receive the SIPReferralGotNotify notification.

Not creating an implicit subscription is supported as per RFC 4488

Internally a Referral object has a state machine, which reflects the state of the subscription. (The same as the Subsription since it uses the same event framework)
It is a direct mirror of the state machine of the underlying pjsip_evsub object, whose possible states are at least NULL, SENT, ACCEPTED, PENDING, ACTIVE or TERMINATED.
The last three states are directly copied from the contents of the Subscription-State header of the received NOTIFY request.
Also, the state can be an arbitrary string if the contents of the Subscription-State header are not one of the three above.
The state of the object is presented in the state attribute and changes of the state are indicated by means of the SIPReferralChangedState notification.
This notification is only informational, an application using this object should take actions based on the other notifications sent by this object.

methods

__init__(self, request_uri, from_header, to_header, refer_to_header, *contact_header, route_header, credentials=None)

Creates a new Referral object which will be in the NULL state.
The arguments for this method are documented in the attributes section above.

send_refer(self, create_subscription=1, extra_headers=list(), timeout=None)

Calling this method triggers sending a REFER request to the presence agent.
The arguments passed will be stored and used for subsequent refreshing SUBSCRIBE requests. The dialog may also be refreshed manually by using the refresh function.
It may not be called when the object is in the TERMINATED state.

create_subscription:

Boolean flag indicating if an implicit subscription should be created.

extra_headers:

A list of additional headers to include in the REFER requests.

timeout:

This can be either an int or a float, indicating in how many seconds the request should timeout with an internally generated 408 response.
If this is None, the internal 408 is only triggered by the internal PJSIP transaction timeout.
Note that, even if the timeout is specified, the PJSIP timeout is also still valid.

refresh(self, contact_header=None, extra_headers=list(), timeout=None)

contact_header:

An optional ContactHeader object which will replace the local contact header and will be used from this moment on.

extra_headers:

A list of additional headers to include in the refreshing SUBSCRIBE request.

timeout:

The timeout argument has the same meaning as it does for the send_refer() method.

end(self, timeout=None)

This will end the referral subscription by sending a SUBSCRIBE request with an Expires value of 0.
If this object is no longer subscribed, this method will return without performing any action.
This method cannot be called when the object is in the NULL state.
The timeout argument has the same meaning as it does for the send_refer() method.

attributes

state

Indicates which state the internal state machine is in.
See the previous section for a list of states the state machine can be in.

from_header

The FrozenFromHeader to be put in the From header of the REFER and SUBSCRIBE requests.
This attribute is set on object instantiation and is read-only.

to_header

The FrozenToHeader that is the target for the referral.
This attribute is set on object instantiation and is read-only.

refer_to_header

The FrozenReferToHeader that is the target resource for the referral.
This attribute is set on object instantiation and is read-only.

local_contact_header

The FrozenContactHeader to be put in the Contact header of the REFER and SUBSCRIBE requests.
This attribute is set on object instantiation and is read-only.

remote_contact_header
The FrozenContactHeader received from the remote endpoint. This attribute is read-only.

route_header

The outbound proxy to use in the form of a FrozenRouteHeader object.
This attribute is set on object instantiation and is read-only.

credentials

The SIP credentials needed to authenticate at the SIP proxy in the form of a FrozenCredentials object.
If none was specified when creating the Referral object, this attribute is None.
This attribute is set on object instantiation and is read-only.

refresh

The refresh interval in seconds that was requested on object instantiation as an int.
This attribute is set when a NOTIFY request is received and is read-only.

extra_headers

This contains the frozenlist of extra headers that was last passed to a successful call to the subscribe() method.
If the argument was not provided, this attribute is an empty list.
This attribute is read-only.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

notifications

SIPReferralChangedState

This notification will be sent every time the internal state machine of a Referral object changes state.

timestamp:

A datetime.datetime object indicating when the notification was sent.

prev_state:

The previous state that the sate machine was in.

state:

The new state the state machine moved into.

SIPReferralWillStart

This notification will be emitted when the initial REFER request is sent.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPReferralDidStart

This notification will be sent when the initial REFER was accepted by the remote endpoint.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPReferralGotNotify

This notification will be sent when a NOTIFY is received that corresponds to a particular Referral object.
Note that this notification could be sent when a NOTIFY without a body is received.

request_uri:

The request URI of the NOTIFY request as a SIPURI object.

from_header:

The From header of the NOTIFY request as a FrozenFromHeader object.

to_header:

The To header of the NOTIFY request as a FrozenToHeader object.

content_type:

The Content-Type header value of the NOTIFY request as a ContentType object.

event:

The Event header value of the NOTIFY request as a string object.

headers:

The headers of the NOTIFY request as a dict.
Each SIP header is represented in its parsed for as long as PJSIP supports it.
The format of the parsed value depends on the header.

body:

The body of the NOTIFY request as a string, or None if no body was included.

timestamp:

A datetime.datetime object indicating when the notification was sent.

SIPReferralDidFail

This notification will be sent whenever there is a failure, such as a rejected initial REFER or refreshing SUBSCRIBE.
After this notification the Referral object is in the TERMINATED state and can no longer be used.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

An integer SIP code from the fatal response that was received from the remote party of generated by PJSIP.
If the error is internal to the SIP core, this attribute will have a value of 0.

reason:

An text string describing the failure that occurred.

SIPReferralDidEnd

This notification will be sent when the subscription ends normally, i.e. the end() method was called and the remote party sent a positive response. It will also be sent when the remote endpoint sends a NOTIFY request with a noresource reason in the Subscription-State header.
After this notification the Referral object is in the TERMINATED state and can no longer be used.

timestamp:

A datetime.datetime object indicating when the notification was sent.

IncomingReferral

Subscription and notifications for SIP events is an Internet standard published at RFC 3856.
The REFER method, defined in RFC 3515 uses the subscription mechanism to to tell SIP endpoints to refer to specific resources.

This SIP primitive class is the mirror companion to the Referral class and allows the application to take on the server role in a REFER dialog.
This means that it can accept a REFER request and subsequent refreshing SUBSCRIBE@s and sent @NOTIFY requests containing event state.

Any incoming REFER request causes the creation of a IncomingReferral object.
This will be indicated to the application through a SIPIncomingReferralGotRefer notification.
It is then up to the application to check if the REFER request was valid, e.g. if it was actually directed at the correct SIP URI, and respond to it in a timely fashion.

The application can either reject the referral by calling the reject() method or accept it through the accept() method.
After the IncomingReferral is accepted, the application can trigger sending a NOTIFY request with a body reflecting the event state through the send_notify() method.
Whenever a refreshing SUBSCRIBE is received, the latest contents to be set are sent in the resulting NOTIFY request.
The subscription can be ended by using the end() method.

methods

__init__(self)

An application should never create an IncomingSubscription object itself.
Doing this will create a useless object in the None state.

reject(self, code)

Will reply to the initial REFER with a negative response.
This method can only be called in the "incoming" state and sets the referral to the "terminated" state.

code:

The SIP response code to use.
This should be a negative response, i.e. in the 3xx, 4xx, 5xx or 6xx range.

accept(self, code=202, duration=180)

Accept the initial incoming REFER and respond to it with a 202 Accepted.
A NOTIFY will be sent to update the state to "active", with a payload indicating the referral is in 100 Trying state.
This method can only be called in the "incoming" state.

code:

The code to be used for the initial reply.

duration:

The desired duration for the implicit subscription. Unlike SUBSCRIBE initiated dialogs, in a referral the receiving party is the one choosing the expiration time.

send_notify(self, code, status=None)

Sets or updates the body of the NOTIFY@s to be sent within this referral and causes a @NOTIFY to be sent to the subscriber.
This method can only be called in the "active" state.

code:

The response code to be used to generate the sipfrag payload.

status:

Optional status reason to be used to build the sipfrag payload. If none was specified the standard reason string will be used.

attributes

state

Indicates which state the incoming referral dialog is in.
This can be one of None, "incoming", "pending", "active" or "terminated".
This attribute is read-only.

local_contact_header

The FrozenContactHeader to be put in the Contact header of the REFER and SUBSCRIBE responses and NOTIFY requests.
This attribute is set on object instantiation and is read-only.

remote_contact_header
The FrozenContactHeader received from the remote endpoint. This attribute is read-only.

peer_address

This read-only attribute contains the remote endpoint IP and port information. It can be accessed by accessing this object's ip and port attributes.

notifications

SIPIncomingReferralChangedState

This notification will be sent every time the an IncomingReferral object changes state.
This notification is mostly indicative, an application should not let its logic depend on it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

prev_state:

The previous state that the subscription was in.

state:

The new state the subscription has.

SIPIncomingReferralGotRefer

This notification will be sent when a new IncomingReferral is created as result of an incoming REFER request.
The application should listen for this notification, retain a reference to the object that sent it and either accept or reject it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

method:

The method of the SIP request as a string, which will be REFER.

request_uri:

The request URI of the REFER request as a FrozenSIPURI object.

refer_to:

The Refer-To header as a FrozenReferToHeader object.

headers:

The headers of the REFER request as a dict, the values of which are the relevant header objects.

body:

The body of the REFER request as a string, or None if no body was included.

SIPIncomingReferralGotRefreshingSubscribe

This notification indicates that a refreshing SUBSCRIBE request was received from the subscriber.
It is purely informative, no action needs to be taken by the application as a result of it.

SIPIncomingReferralGotUnsubscribe

This notification indicates that a SUBSCRIBE request with an Expires header of 0 was received from the subscriber, effectively requesting to unsubscribe.
It is purely informative, no action needs to be taken by the application as a result of it.

SIPIncomingReferralAnsweredRefer

This notification is sent whenever a response to a REFER request is sent by the object.
It is purely informative, no action needs to be taken by the application as a result of it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The code of the SIP response as an int.

reason:

The reason text of the SIP response as an int.

headers:

The headers of the response as a dict, the values of which are the relevant header objects.

body:

This will be None.

SIPIncomingReferralSentNotify

This notification indicates that a NOTIFY request was sent to the subscriber.
It is purely informative, no action needs to be taken by the application as a result of it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

method:

The method of the SIP request as a string, which will be NOTIFY.

request_uri:

The request URI of the NOTIFY request as a FrozenSIPURI object.

headers:

The headers of the NOTIFY request as a dict, the values of which are the relevant header objects.

body:

The body of the NOTIFY request or response as a string, or None if no body was included.

SIPIncomingReferralNotifyDidSucceed

This indicates that a positive final response was received from the subscriber in reply to a sent NOTIFY request.
The notification is purely informative, no action needs to be taken by the application as a result of it.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The code of the SIP response as an int.

reason:

The reason text of the SIP response as a string.

headers:

The headers of the response as a dict, the values of which are the relevant header objects.

body:

This will be None.

SIPIncomingReferralNotifyDidFail

This indicates that a negative response was received from the subscriber in reply to a sent NOTIFY request or that the NOTIFY failed to send.

timestamp:

A datetime.datetime object indicating when the notification was sent.

code:

The code of the SIP response as an int.
If this is 0, the notification was sent as a result of an internal error.

reason:

The reason text of the SIP response as a string or the internal error if the code attribute is 0.

headers: (if the notification was caused by a negative response)

The headers of the response as a dict, the values of which are the relevant header objects.

body: (if the notification was caused by a negative response)

This will be None.

SIPIncomingReferralDidEnd

This notification is sent whenever the IncomingReferral object reaches the "terminated" state and is no longer valid.
After receiving this notification, the application should not longer try to use the object.

timestamp:

A datetime.datetime object indicating when the notification was sent.

AudioMixer

A AudioMixer manages two audio devices, on for input and one for output, and is able to route audio data for a number of sources.
It wraps a PJSIP conference bridge, the concept of which is explained in the PJSIP documentation.
Any component in the core that either produces or consumes sound, i.e. AudioTransport, ToneGenerator, WaveFile and RecordingWaveFile objects, has a ConferenceBridge associated with it and a corresponding slot on that conference bridge.
The sound devices, both input and output, together always occupy slot 0.
It is up to the application to setup the desired routing between these components. Note that the middleware provides an abstracted API which hides the complexity of using the low-level PJSIP concepts. This is mainly provided in the [[SipMiddlewareApi#Audio|sipsimple.audio]] module, but also consists of other audio-enabled objects (such as the AudioStream).

methods

__init__(self, input_device, output_device, sample_rate, ec_tail_length=200, slot_count=254)

Creates a new ConferenceBridge object.

input_device:

The name of the audio input device to use as a string, or None if no input device is to be used.
A list of known input devices can be queried through the Engine.input_devices attribute.
If "system_default" is used, PJSIP will select the system default output device, or None if no audio input device is present.
The device that was selected can be queried afterwards through the input_device attribute.

output_device:

The name of the audio output device to use as a string, or None if no output device is to be used.
A list of known output devices can be queried through the Engine.output_devices attribute.
If "system_default" is used, PJSIP will select the system default output device, or None if no audio output device is present.
The device that was selected can be queried afterwards through the output_device attribute.

sample_rate:

The sample rate on which the conference bridge and sound devices should operate in Hz.
This must be a multiple of 50.

ec_tail_length:

The echo cancellation tail length in ms.
If this value is 0, no echo cancellation is used.

slot_count:

The number of slots to allocate on the conference bridge.
Not that this includes the slot that is occupied by the sound devices.

set_sound_devices(self, input_device, output_device, ec_tail_length)

Change the sound devices used (including echo cancellation) by the conference bridge.
The meaning of the parameters is that same as for __init__().

connect_slots(self, src_slot, dst_slot)

Connect two slots on the conference bridge, making audio flow from src_slot to dst_slot.

disconnect_slots(self, src_slot, dst_slot)

Break the connection between the specified slots.
Note that when an audio object is stopped or destroyed, its connections on the conference bridge will automatically be removed.

attributes

input_device

A string specifying the audio input device that is currently being used.
If there is no input device, this attribute will be None.
This attribute is read-only, but may be updated by calling the set_sound_devices() method.

output_device

A string specifying the audio output device that is currently being used.
If there is no output device, this attribute will be None.
This attribute is read-only, but may be updated by calling the set_sound_devices() method.

sample_rate

The sample rate in Hz that the conference bridge is currently operating on.
This read-only attribute is passed when the object is created.

ec_tail_length

The current echo cancellation tail length in ms.
If this value is 0, no echo cancellation is used.
This attribute is read-only, but may be updated by calling the set_sound_devices() method.

slot_count

The total number of slots that is available on the conference bridge
This read-only attribute is passed when the object is created.

used_slot_count

A read-only attribute indicating the number of slots that are used by objects.

input_volume

This writable property indicates the % of volume that is read from the audio input device.
By default this value is 100.

output_volume

This writable property indicates the % of volume that is sent to the audio output device.
By default this value is 100.

muted

This writable boolean property indicates if the input audio device is muted.

connected_slots

A read-only list of tupples indicating which slot is connected to which.
Connections are directional.

MixerPort

This a simple object which simply copies all the audio data it gets as input to it output. It's main purpose is that of facilitating the creation the of the middleware AudioBridge object.

methods

__init__(self, mixer)

Create a new MixerPort which is associated with the specified AudioMixer.

start(self)

Activate the mixer port. This will reserve a slot on the AudioMixer and allow it to be connected to other slots.

stop(self)

Deactivate the mixer port. This will release the slot previously allocated on the AudioMixer and all connections which it had will be discarded.

attributes

mixer

The AudioMixer this MixerPort is associated with
This attribute is read-only.

is_active

Whether or not this MixerPort has a slot associated in its AudioMixer.
This attribute is read-only.

slot

The slot this MixerPort has reserved on AudioMixer or None if it is not active.
This attribute is read-only.

WaveFile

This is a simple object that allows playing back of a .wav file over the PJSIP conference bridge.
Only 16-bit PCM and A-law/U-law formats are supported.
Its main purpose is the playback of ringtones or previously recorded conversations.

This object is associated with a AudioMixer instance and, once the start() method is called, connects to it and sends the sound to all its connections.
Note that the slot of the WaveFile object will not start playing until it is connected to another slot on the AudioMixer.
If the stop() method is called or the end of the .wav file is reached, a WaveFileDidFinishPlaying notification is sent by the object.
After this the start() method may be called again in order to re-use the object.

It is the application's responsibility to keep a reference to the WaveFile object for the duration of playback.
If the reference count of the object reaches 0, playback will be stopped automatically.
In this case no notification will be sent.

methods

__init__(self, mixer, filename)

Creates a new WaveFile object.

mixer:

The AudioMixer object that this object is to be connected to.

filename:

The name of the .wav file to be played back as a string.
This should include the full path to the file.

start(self)

Start playback of the .wav file.

stop(self)

Stop playback of the file.

attributes

mixer

The AudioMixer this object is associated with.
This attribute is read-only.

filename

The name of the .wav file, as specified when the object was created.
This attribute is read-only.

slot

A read-only property indicating the slot number at which this object is attached to the associated AudioMixer.
If the WaveFile is not active, this attribute will be None.

volume

A writable property indicating the % of volume at which this object contributes audio to the AudioMixer.
By default this is set to 100.

is_active

A boolean read-only property that indicates if the file is currently being played.

notifications

WaveFileDidFinishPlaying

This notification will be sent whenever playing of the .wav has stopped.
After sending this event, the playback may be re-started.

timestamp:

A datetime.datetime object indicating when the notification was sent.

RecordingWaveFile

This is a simple object that allows recording audio to a PCM .wav file.

This object is associated with a AudioMixer instance and, once the start() method is called, crecords sound from its connections.
Note that the RecordingWaveFile will not record anything if it does not have any connections.
Recording to the file can be stopped either by calling the stop() method or by removing all references to the object.
Once the stop() method has been called, the start() method may not be called again.
It is the application's responsibility to keep a reference to the RecordingWaveFile object for the duration of the recording, it will be stopped automatically when the reference count reaches 0.

methods

__init__(self, mixer, filename)

Creates a new RecordingWaveFile object.

mixer:

The AudioMixer object that this object is to be associated with.

filename:

The name of the .wav file to record to as a string.
This should include the full path to the file.

start(self)

Start recording the sound to the .wav file.

stop(self)

Stop recording to the file.

attributes

mixer

The AudioMixer this object is associated with.
This attribute is read-only.

filename

The name of the .wav file, as specified when the object was created.
This attribute is read-only.

slot

A read-only property indicating the slot number at which this object is attached to the associated AudioMixer.
If the RecordingWaveFile is not active, this attribute will be None.

is_active

A boolean read-only attribute that indicates if the file is currently being written to.

ToneGenerator

A ToneGenerator can generate a series of dual frequency tones and has a shortcut method for generating valid DTMF tones.
Each instance of this object is associated with a AudioMixer object, which it will connect to once started.
The tones will be sent to the slots on the AudioMixer its slot is connected to.
Once started, a ToneGenerator can be stopped by calling the stop() method and is automatically destroyed when the reference count reaches 0.

Note: this object has threading issues when the application uses multiple AudioMixers. It should not be used.

methods

__init__(self, mixer)

Creates a new ToneGenerator object.

mixer:

The AudioMixer object that this object is to be connected to.

start(self)

Start the tone generator and connect it to its associated AudioMixer.

stop(self)

Stop the tone generator and remove it from the conference bridge.

play_tones(self, *tones)

Play a sequence of single or dual frequency tones over the audio device.

tones:

This should be a list of 3-item tuples, in the form of [(<freq1>, <freq2>, <duration>), ...], with Hz as unit for the frequencies and ms as unit for the duration.
If freq2 is 0, this indicates that only freq1 should be used for the tone.
If freq1 is 0, this indicates a pause when no tone should be played for the set duration.

play_dtmf(self, *digit)

Play a single DTMF digit.

digit:

A string of length 1 containing a valid DTMF digit, i.e. 0 through 9, #, * or A through D.

attributes

mixer

The AudioMixer this object is associated with.
This attribute is read-only.

slot

A read-only property indicating the slot number at which this object is attached to the associated AudioMixer.
If the ToneGenerator has not been started, this attribute will be None.

volume

A writable property indicating the % of volume at which this object contributes audio.
By default this is set to 100.

is_active

A boolean read-only property that indicates if the object has been started.

is_busy

A boolean read-only property indicating if the ToneGenerator is busy playing tones.

notifications

ToneGeneratorDidFinishPlaying

This notification will be sent whenever playing of the queued tones has finished.

timestamp:

A datetime.datetime object indicating when the notification was sent.

Updated by Dan Pascu almost 6 years ago · 119 revisions