« Previous -
Version 36/119
(diff) -
Next » -
Current version
Adrian Georgescu, 04/13/2009 11:06 am
= SIP core API =
<acronym title="Sip*, depth=3">TOC</acronym>
IntroductionThis chapter describes the internal architecture and API of the SIP core of the {{{sipsimple}}} library. {{{sipsimple}}} is a Python package, the core of which wrapps 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 [http://tools.ietf.org/html/rfc3261 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:
[[Image(http://www.pjsip.org/images/diagram.jpg, nolink)]]
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 soundcard.
Both of these stracks are integrated in the high level library, called PJSUA.
PJSIP itself provides a high-level [http://www.pjsip.org/python/pjsua.htm 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.
ArchitectureNOTE: Currently the core starts the media handling as a separate C thread to avoid lag caused by the GIL.
The soundcard also has its own C thread.
The {{{sipsimple}}} core wrapper itself is mostly written using [http://cython.org/ Cython] (formerly [http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ 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 package is subdivided into three modules:
'''sipimple.!__init!__'''::
The the top-level module for the package which just defines the module version and the objects that should be imported when the package user performs {{{import * from sipsimple}}}.
'''sipsimple.engine'''::
Python module that contains the {{{Engine}}} singleton class, which manages the thread that constantly polls the PJSIP library, i.e. the PJSIP worker thread.
For the applications that use the core of {{{sipsimple}}}, the {{{Engine}}} object forms the main entry point.
'''sipsimple.core'''::
This is the Python C extension module ultimately compiled from the Cython file and PJSIP static libraries.
It contains these types of classes:
* The {{{PJSIPUA}}} class, which can only be instanced once, and is this case is only instanced once by the {{{Engine}}} object.
In this way the {{{Engine}}} singleton class acts as a wrapper to the one {{{PJSIPUA}}} instance.
The {{{PJSIPUA}}} class represents the SIP endpoint and manages the initialization and destruction of all the PJSIP libraries.
It also provides a number of methods.
The application however should never call these methods directly on the {{{PJSIPUA}}} object, rather it should call them on the {{{Engine}}} wrapper object.
This object handles everything that for one reason or another cannot or should not be handled from Cython.
* The classes that represent the main SIP primitives to be used by the application.
The application can instantiate these classes once the {{{Engine}}} class has been instantiated and the PJSIP worker thread has been started.
All of these classes represent a state machine.
* {{{Registration}}}
* {{{Publication}}}
* {{{Subscription}}}
* {{{Invitation}}}
* Several helper classes, which represent some structured collection of data to be passed as parameter to methods of the SIP primitive classes and to parameters of notifications.
* {{{SIPURI}}}
* {{{Credentials}}}
* {{{Route}}}
* A number of SDP manipulation classes, which directly wrap the PJSIP structures representing either the parsed or to be generated SDP.
{{{SDPSession}}} objects may contain references to the other classes and are passed as arguments to methods of a {{{Invitiation}}} object or notifications sent by it.
* {{{SDPSession}}}
* {{{SDPMedia}}}
* {{{SDPConnection}}}
* {{{SDPAttribute}}}
* Two classes related to transport of media traffic and audio traffic specifically, built on PJMEDIA.
These classes can be instantiated independently from the other classes in order to keep signaling and media separate.
* {{{RTPTransport}}}
* {{{AudioTransport}}}
* Two classes related to {{{.wav}}} files, one for playback and one for recording.
* {{{WaveFile}}}
* {{{RecordingWaveFile}}}
* Two exception classes, the second being a subclass of the first.
* {{{SIPCoreError}}}
* {{{PJSIPError}}}
* Classes used internally within the {{{core}}} module, e.g. to wrap a particular PJSIP library.
These classes are not exposed through the {{{__init__}}} module and should never be used by the application
These classes (except the ones internal to the {{{core}}} module) are illustrated in the following diagram:
Image(sipsimple-core-classes.png, nolink)
IntegrationThe core itself has one Python dependency, the [http://pypi.python.org/pypi/python-application application] module, which in turn depends on the [http://pypi.python.org/pypi/zope.interface 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__
notification_center = NotificationCenter()
log_observer = EngineLogObserver()
notification_center.add_observer(self, 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.
All messages will be described in this document and start with 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 core by issuing the {{{from sipsimple import *}}} statement.
It can then instance 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 instance 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 import *
e = Engine()
e.start()
cred = Credentials(SIPURI, "password")
reg = Registration(cred, Route("1.2.3.4"))
reg.register()
}}}
Note that in this example no observer for notifications from this {{{Registration}}} object are registered, so the result of the operation cannot be seen.
To see how this example can be converted to actually wait for the response without creating an observer, see the example for GreenRegistration at [wiki:SipSynchronousAPI#sipsimple.green.core.GreenRegistration SynchronousAPI].
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 provited 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.
[[BR]]''auto_sound'':[[BR]]
A boolean indicating if PJSIP should automatically select and enable a soundcard to use for for recording and playing back sound.
If this is set to {{{False}}} the application will have to select a sound device manually through the {{{set_sound_devices}}} method.
This option is not accessible as an attribute on the object, as it is transitory.
[[BR]]''local_ip'': (Default: {{{None}}})[[BR]]
IP address of a local interface to bind to.
If this is {{{None}}} on start, the {{{Engine}}} will try to determine the default outgoing interface and bind to it.
Setting this to {{{0.0.0.0}}} will cause PJSIP to listen for traffic on any interface, but this is not recommended.
As an attribute, this value is read-only.
[[BR]]''local_udp_port'': (Default: {{{0}}})[[BR]]
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_local_udp_port()}}} method.
[[BR]]''local_tcp_port'': (Default: {{{0}}})[[BR]]
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_local_tcp_port()}}} method.
[[BR]]''local_tls_port'': (Default: {{{0}}})[[BR]]
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.
[[BR]]''tls_protocol'': (Default: "TLSv1")[[BR]]
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".
[[BR]]''tls_verify_server'': (Default: {{{False}}})[[BR]]
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.
[[BR]]''tls_ca_file'': (Default: {{{None}}})[[BR]]
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.
[[BR]]''tls_cert_file'': (Default: {{{None}}})[[BR]]
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.
[[BR]]''tls_privkey_file'': (Default: {{{None}}})[[BR]]
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.
[[BR]]''tls_timeout'': (Default: 1000)[[BR]]
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.
[[BR]]''ec_tail_length'': (Default: {{{50}}})[[BR]]
Echo cancellation tail length in milliseconds.
A longer value should provide better echo cancellation but incurs more processing cost.
Setting this to 0 will disable echo cancellation.
As an attribute, this value is read-only, but it can be set as an argument to the {{{set_sound_devices}}} method.
[[BR]]''user_agent'': (Default: {{{"ag-projects/sipclient-%version-pjsip-%pjsip-version"}}})[[BR]]
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.
[[BR]]''log_level'': (Default: 5)[[BR]]
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.
[[BR]]''trace_sip'': (Default: {{{False}}})[[BR]]
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.
[[BR]]''sample_rate'': (Default: {{{32}}})[[BR]]
The sample rate in kHz at which the sound card should operate.
Higher values allow some codecs (such as speex) to achieve better quality but will incur higher processing cost, particularly in combination with echo cancellation.
This parameter should be either 8, 16 or 32.
The corresponding attribute of this value is read-only.
[[BR]]''playback_dtmf'': (Default: {{{True}}})[[BR]]
If this boolean is set to {{{True}}}, both incoming and outgoing DTMF signals have their corresponding audio tones played back on the sound card.
This value can be read and set directly as an attribute at runtime.
[[BR]]''rtp_port_range'': (Default: (40000, 40100))[[BR]]
This tuple of two ints 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.
[[BR]]''codecs'': (Default: {{{["speex", "g711", "ilbc", "gsm", "g722"]}}})[[BR]]
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.
[[BR]]''events'': (Default: <some sensible events>)[[BR]]
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 {{{set_local_tls_port()}}} method.
'''start_cfg'''(''self'', '''enable_sound'''={{{True}}}, '''**kwargs''')::
This provides a [wiki:SipConfigurationAPI Configuration API] aware start method.
It will retrieve all the arguments that can be passed to {{{start()}}} from the configuration framework, unless they are overridden by the keyword arguments to this method.
Any argument that can be passed to {{{start()}}} may be specified, except for {{{auto_sound}}}.
[[BR]]''enable_sound'':[[BR]]
If this is set to {{{True}}}, the sound devices set up in the configuration framework will be started.
'''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, two other attributes are provided once the {{{Engine}}} has been started.
'''playback_devices'''::
This read-only attribute is a list of string, representing all audio playback devices on the system that can be used.
These device names can be passed as the {{{playback_device}}} argument of the {{{set_sound_devices()}}} method.
'''recording_devices'''::
This read-only attribute is a list of string, representing all audio recording devices on the system that can be used.
These device names can be passed as the {{{recording_device}}} argument of the {{{set_sound_devices()}}} method.
==== 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.
'''set_sound_devices'''(''self'', '''playback_device'''={{{None}}}, '''recording_device'''={{{None}}}, '''tail_length'''={{{None}}})::
Set and open the playback and recording device, using the specified echo cancellation tail length in milliseconds.
If no echo cancellation value is specified, either the value set while calling the {{{start()}}} method will be used or the default value will be used (see the documentation of this method).
A {{{tail_length}}} of 0 disables echo cancellation.
The device attributes need to be strings and should be obtained from the {{{playback_devices}}} and {{{recording_devices}}} attributes respectively.
Passing either of these as {{{None}}} means that PJSIP should select a sound device automatically.
If sound devices were already opened these will be closed first.
'''connect_audio_transport'''(''self'', '''transport''')::
Connect a started audio transport, in the form of a {{{AudioTransport}}} object, to the recording and playback audio devices and other connected audio transports.
This means that when more than one audio stream is connected they will form a conference.
'''disconnect_audio_transport'''(''self'', '''transport''')::
Disconnect a previously connected audio transport, in the form of a {{{AudioTransport}}} object.
Stopped audio streams are disconnected automatically.
'''detect_nat_type'''(''self'', '''stun_server_address''', '''stun_server_port'''=3478)::
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.
'''set_local_udp_port'''(''self'', '''value''')::
Update the {{{local_udp_port}}} attribute to the newly specified value.
'''set_local_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.
'''parse_sip_uri(''self'', '''uri_string''')::
Will parse the provided SIP URI string using the PJSIP parsing capabilities and return a {{{SIPURI}}} object, or raise an exception if there was an error parsing the URI.
==== 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.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
'''SIPEngineDidStart'''::
This notification is sent when the {{{Engine}}} is has just been started.
[[BR]]''timestamp'':[[BR]]
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.
[[BR]]''timestamp'':[[BR]]
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.
[[BR]]''timestamp'':[[BR]]
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.
[[BR]]''timestamp'':[[BR]]
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.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object representing the time when the log message was output by PJSIP.
[[BR]]''sender'':[[BR]]
The PJSIP module that originated this log message.
[[BR]]''level'':[[BR]]
The logging level of the message as an integer.
Currently this is 1 through 5, 1 being the most critical.
[[BR]]''message'':[[BR]]
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.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''received'':[[BR]]
A boolean indicating if this message was sent from or received by PJSIP (i.e. the direction of the message).
[[BR]]''source_ip'':[[BR]]
The source IP address as a string.
[[BR]]''source_port'':[[BR]]
The source port of the message as an integer.
[[BR]]''destination_ip'':[[BR]]
The destination IP address as a string.
[[BR]]''source_port'':[[BR]]
The source port of the message as an integer.
[[BR]]''data'':[[BR]]
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.
'''SIPEngineGotMessage'''::
This notification is sent when there is an incoming {{{MESSAGE}}} request.
Since this is a one-shot occurrence, it is not modeled as an object.
BR''timestamp'':BR
A {{{datetime.datetime}}} object indicating when the notification was sent.
BR''to_uri'':BR
The contents of the {{{To:}}} header of the received {{{MESSAGE}}} request represented as a {{{SIPURI}}} object.
BR''from_uri'':BR
The contents of the {{{From:}}} header of the received {{{MESSAGE}}} request represented as a {{{SIPURI}}} object.
BR''content_type'':BR
The first part of the {{{Content-Type:}}} header of the received {{{MESSAGE}}} request (before the {{{/}}}).
BR''content_subtype'':BR
The second part of the {{{Content-Type:}}} header of the received {{{MESSAGE}}} request (after the {{{/}}}).
BR''body'':BR
The body of the {{{MESSAGE}}} request.
content_type and content_subtype should be combined in a single argument, also in other places where this occurs.
'''SIPEngineGotMessageResponse'''::
When sending a {{{MESSAGE}}} through the {{{send_message}}} function, this notification will be sent whenever there is a final response to the sent {{{MESSAGE}}} request (which may be an internally generated timeout).
BR''timestamp'':BR
A {{{datetime.datetime}}} object indicating when the notification was sent.
BR''to_uri'':BR
The original {{{to_uri}}} parameter used when calling the {{{send_message}}} function.
BR''code'':BR
The status code of the response as integer.
BR''reason'':BR
The reason text of the response.
'''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.
BR''timestamp'':BR
A {{{datetime.datetime}}} object indicating when the notification was sent.
BR''succeeded'':BR
A boolean indicating if the NAT detection succeeded.
BR''nat_type'':BR
A string describing the type of NAT found.
This value is only present if NAT detection succeeded.
BR''error'':BR
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.
BR''timestamp'':BR
A {{{datetime.datetime}}} object indicating when the notification was sent.
BR''traceback'':BR
A string containing the traceback of the exception.
In general this should be printed on the console.
=== send_message ===
In the future, this function will probably be implemented as a class or as a method of PJSIPUA.
The only function of the API is {{{send_message}}}, which sends a {{{MESSAGE}}} request containing a body to the specified SIP URI.
As described above, a {{{message_response}}} is generated when the final response is received.
Until the final response is received it is not allowed to send a new {{{MESSAGE}}} request to the {{{to_uri}}} used, a {{{SIPCoreError}}} exception will be thrown if the application tries this.
It has the following format and arguments:
{{{
send_message(credentials, to_uri, content_type, content_subtype, body, route)
}}}
'''credentials'''::
Credentials to be used if authentication is needed at the proxy in the form of a {{{Credentials}}} object.
This object also contains the From URI.
'''to_uri'''::
The SIP URI to send the {{{MESSAGE}}} request to in the form of a {{{SIPURI}}} object.
'''content_type'''::
The first part of the {{{Content-Type:}}} header (before the {{{/}}}).
'''content_subtype'''::
The first part of the {{{Content-Type:}}} header (before the {{{/}}}).
'''body'''::
The body of the {{{MESSAGE}}} request that is to be sent.
'''route'''::
This represents the first host to send the request to in the form of a {{{Route}}} object.
The exception thrown when the application tries to send a MESSAGE too fast should be customized.
In this way the application may keep a queue of MESSAGE requests and send the next one when the last one was answered.
=== SIPURI ===
This is a helper object 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.
==== 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.
Each of these attributes can be accessed and changed on the object once instanced.
{{{host}}} is the only mandatory attribute.
[[BR]]''host'':[[BR]]
The host part of the SIP URI as a string.
[[BR]]''user'':[[BR]]
The username part of the SIP URI as a string, or None if not set.
[[BR]]''port'':[[BR]]
The port part of the SIP URI as an int, or None or 0 if not set.
[[BR]]''display'':[[BR]]
The optional display name of the SIP URI as a string, or None if not set.
[[BR]]''secure'':[[BR]]
A boolean indicating whether this is a SIP or SIPS URI, the latter being indicated by a value of {{{True}}}.
[[BR]]''parameters'':[[BR]]
The URI parameters. represented by a dictionary.
[[BR]]''headers'':[[BR]]
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.
'''copy'''(''self'')::
Returns a copy of the {{{SIPURI}}} object.
=== Credentials ===
This object represents authentication credentials for a particular SIP account.
These should be included whenever creating a SIP primitive object that originates SIP requests.
As with the {{{SIPURI}}} object, the attributes of this object are the same as the arguments to the {{{__init__}}} method.
==== methods ====
'''!__init!__'''(''self'', '''uri''', '''password'''={{{None}}})::
Creates the Credentials object with the specified parameters as attributes.
Each of these attributes can be accessed and changed on the object once instanced.
[[BR]]''uri'':[[BR]]
A {{{SIPURI}}} object representing the account for which these are the credentials.
[[BR]]''password'':[[BR]]
The password for this SIP account as a string.
If a password is not needed, for example when sending SIP messages without a proxy, this can be {{{None}}}.
'''copy'''(''self'')::
Returns a copy of the {{{Credentials}}} object.
=== Route ===
This class provides a means for the application using the SIP core to set the destination address, port and transport for a particular request, i.e. the outbound proxy.
As it is the application's responsibility to look this up and pass it as an argument for every SIP primitive class it creates.
The contents of the {{{Route}}} object will be placed in the {{{Route}}} header of the request.
As with the {{{SIPURI}}} object, the attributes of this object are the same as the arguments to the {{{__init__}}} method.
==== methods ====
'''!__init!__'''(''self'', '''address''', '''port'''=5060, '''transport'''={{{None}}})::
Creates the Route object with the specified parameters as attributes.
Each of these attributes can be accessed on the object once instanced.
[[BR]]''address'':[[BR]]
The IPv4 or IPv6 address that the request in question should be sent to as a string.
[[BR]]''port'':[[BR]]
The port to send the requests to, represented as an int.
[[BR]]''transport'':[[BR]]
The transport to use, this can be a string of either "udp", "tcp" or "tls" (case insensitive), depending on what transports are enabled on the {{{PJSIPUA}}} object.
'''copy'''(''self'')::
Returns a copy of the {{{Route}}} object.
IPv6 transports are not supported yet.
=== Registration ===
A {{{Registration}}} object represents a SIP endpoint's registration for a particular SIP account using the {{{REGISTER}}} method at its SIP registrar.
In effect, the SIP endpoint can send a {{{REGISTER}}} to the registrar to indicate that it is a valid endpoint for the specified SIP account.
After the {{{REGISTER}}} request is successfully received, the SIP proxy will be able to contact the SIP endpoint whenever there is an {{{INVITE}}} or other relevant request sent to the SIP account.
In short, unless a SIP endpoint is registered, it cannot be contacted.
Internally it uses a state machine to represent the registration process.
The states of this state machine can be seen in the following diagram:
Image(sipsimple-registration-state-machine.png, nolink)
State changes are triggered by the following events:
1. The initial state.
2. User requests in the form of the {{{register()}}} and {{{unregister()}}} methods.
3. A final response for a {{{REGISTER}}} is received from the network.
4. The refresh timer expires.
The state machine of a {{{Registration}}} object has a queue, which means that for example when the object is in the {{{registering}}} state and the application calls the {{{unregister()}}} method, the object will unregister itself once a final response has been received for the registering {{{REGISTER}}}.
The implementation of this object needs to be revised.
==== attributes ====
'''state'''::
Indicates which state the internal state machine is in.
This is one of {{{unregistered}}}, {{{registering}}}, {{{registered}}}, {{{unregistering}}}.
'''credentials'''::
The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object, including the SIP account for which we want to register.
This attribute is set on object instantiation and is read-only.
'''route'''::
The outbound proxy to use in the form of a {{{Route}}} object.
This attribute is set on object instantiation and is read-only.
'''extra_headers'''::
A dictionary of extra headers that should be added to any outgoing {{{REGISTER}}} request.
This attribute is set on object instantiation and is read-only.
'''expires'''::
The amount of seconds to request the registration for, i.e. the value that should be put in the {{{Expires}}} header.
This attribute is set on object instantiation and can be modified at runtime.
A new value will be used during the next refreshing {{{REGISTER}}}.
'''expires_received'''::
The amount of seconds the last successful {{{REGISTER}}} is valid for.
This value is read-only.
==== methods ====
'''!__init!__'''(''self'', '''credentials''', '''route''', '''expires'''=300, '''contact_uri'''={{{None}}}, '''extra_headers'''={{{None}}})::
Creates a new {{{Registration}}} object.
[[BR]]''credentials'':[[BR]]
The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object, including the SIP account for which we want to register.
[[BR]]''route'':[[BR]]
The outbound proxy to use in the form of a {{{Route}}} object
[[BR]]''expires'':[[BR]]
The amount of seconds to request the registration for, i.e. the value that should be put in the {{{Expires}}} header.
[[BR]]''contact_uri'':[[BR]]
The Contact URI that should be used to register as a {{{SIPURI}}} object.
If this is {{{None}}}, a Contact URI will be generated.
[[BR]]''extra_headers'':[[BR]]
A dictionary of extra headers that should be added to any outgoing request.
'''register'''(''self'')::
Whenever the object is ready to send a {{{REGISTER}}} for the specified SIP account it will do so, moving the state machine into the {{{registering}}} state.
If the {{{REGISTER}}} succeeds the state machines moves into the {{{registered}}} state and the object will automatically refresh the registration before it expires (again moving into the {{{registering}}} state).
If it is unsuccessful the state machine reverts to the {{{unregistered}}} state.
'''unregister'''(''self'')::
If the object is registered it will send a {{{REGISTER}}} with an {{{Expires}}} header of 0, effectively unregistering the contact from the SIP account.
==== notifications ====
'''SIPRegistrationChangedState'''::
This notification will be sent every time the internal state machine of a {{{Registeration}}} object changes state.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''state'':[[BR]]
The new state the state machine moved into.
[[BR]]''code'': (only on SIP response triggered state change)[[BR]]
The status code of the response that caused the state change.
This may be internally generated by PJSIP, e.g. on timeout.
[[BR]]''reason'': (only on SIP response triggered state change)[[BR]]
The status text of the response that caused the state change.
This may be internally generated by PJSIP, e.g. on timeout.
[[BR]]''contact_uri'': (only on successful registration)[[BR]]
The {{{Contact}}} URI used to register as a string.
[[BR]]''expires'': (only on successful registration)[[BR]]
How many seconds until this registration expires.
[[BR]]''contact_uri_list'': (only on successful registration)[[BR]]
The full list of {{{Contact}}} URIs registered for this SIP account, including the one just performed by this object.
==== example code ====
This code shows how to make a {{{Registration}}} object for a particular SIP account and have it register.
{{{
accnt = SIPURI
creds = Credentials(accnt, "password")
reg = Registration(creds, Route("1.2.3.4"))
reg.register()
}}}
After executing this code, the application will have to wait until the {{{Registration}}} object sends the {{{SIPRegistrationChangedState}}} notification, which includes the result of the requested operation.
=== Publication ===
Publication of SIP events is an Internet standard published at [http://tools.ietf.org/html/rfc3903 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 {{{PUBLISH}}} request.
The state machine of this object is very similar to that of the {{{Registration}}} object, as can be seen in the following diagram:
Image(sipsimple-publication-state-machine.png, nolink)
State changes are triggered by the following events:
1. The initial state.
2. User requests in the form of the {{{publish()}}} and {{{unpublish()}}} methods.
3. A final response for a {{{PUBLISH}}} is received from the network.
4. The refresh timer expires.
Like the {{{Registration}}} state machine, the {{{Publication}}} state machine is queued.
This means that the application may call either the {{{publish()}}} or {{{unpublish()}}} method at any point in the state machine.
The object will perform the requested action when ready.
When some content is published and the application wants to update the contents, it can directly call the {{{publish()}}} method with the new content.
The implementation of this object needs to be revised.
If this object is re-used after unpublication, the etag value is not reset by PJSIP.
This needs to be fixed.
==== attributes ====
'''state'''::
Indicates which state the internal state machine is in.
This is one of {{{unpublished}}}, {{{publishing}}}, {{{published}}}, {{{unpublishing}}}.
'''credentials'''::
The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object, including the SIP account for which we want to register.
This attribute is set on object instantiation and is read-only.
'''route'''::
The outbound proxy to use in the form of a {{{Route}}} object.
This attribute is set on object instantiation and is read-only.
'''extra_headers'''::
A dictionary of extra headers that should be added to any outgoing {{{PUBLISH}}} request.
This attribute is set on object instantiation and is read-only.
'''expires'''::
The amount of seconds the contents of the {{{PUBLISH}}} are valid, i.e. the value that should be put in the {{{Expires}}} header.
This attribute is set on object instantiation and can be modified at runtime.
A new value will be used during the next refreshing {{{PUBLISH}}}.
==== methods ====
'''!__init!__'''(''self'', '''credentials''', '''event''', '''route''', '''expires'''=300, '''extra_headers'''={{{None}}})::
Creates a new {{{Publication}}} object.
[[BR]]''credentials'':[[BR]]
The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object, including the SIP account that we want to publish the content for.
[[BR]]''event'':[[BR]]
The event package for which we want to publish content.
[[BR]]''route'':[[BR]]
The outbound proxy to use in the form of a {{{Route}}} object
[[BR]]''expires'':[[BR]]
The amount of seconds the contents of the {{{PUBLISH}}} are valid, i.e. the value that should be put in the {{{Expires}}} header.
[[BR]]''extra_headers'':[[BR]]
A dictionary of extra headers that should be added to any outgoing {{{PUBLISH}}} request.
'''publish'''(''self'', '''content_type''', '''content_subtype''', '''body''')::
Whenever the object is ready to send a {{{PUBLISH}}} for the specified SIP account it will do so, moving the state machine into the {{{publishing}}} state.
If the {{{PUBLISH}}} succeeds the state machines moves into the {{{published}}} state and the object will automatically refresh the publication before it expires (again moving into the {{{publishing}}} state).
If it is unsuccessful the state machine reverts to the {{{unregistered}}} state.
[[BR]]''content_type'':[[BR]]
The first part of the {{{Content-Type:}}} header of the {{{PUBLISH}}} request that is to be sent (before the {{{/}}}), indicating the type of content of the body.
[[BR]]''content_subtype'':[[BR]]
The second part of the {{{Content-Type:}}} header of the {{{PUBLISH}}} request that is to be sent (after the {{{/}}}), indicating the type of content of the body.
'''unpublish'''(''self'')::
If the object has some content published, it will send a {{{PUBLISH}}} with an {{{Expires}}} header of 0, effectively unpublishing the content for the specified SIP account.
==== notifications ====
'''SIPPublicationChangedState'''::
This notification will be sent every time the internal state machine of a {{{Publication}}} object changes state.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''state'':[[BR]]
The new state the state machine moved into.
[[BR]]''code'': (only on SIP response triggered state change)[[BR]]
The status code of the response that caused the state change.
This may be internally generated by PJSIP, e.g. on timeout.
[[BR]]''reason'': (only on SIP response triggered state change)[[BR]]
The status text of the response that caused the state change.
This may be internally generated by PJSIP, e.g. on timeout.
On init the event package is not checked with known event packages, this is only used for {{{Subscription}}} objects.
This could be done for the sake of consistency.
==== example code ====
This code shows how to make a {{{Publication}}} object for a particular SIP account and have it attempt to publish its presence.
{{{
accnt = SIPURI
creds = Credentials(accnt, "password")
pub = Publication(creds, "presence", Route("1.2.3.4"))
pub.publish("text", "plain", "hi!")
}}}
After executing this code, the application will have to wait until the {{{Publication}}} object sends the {{{SIPPublicationChangedState}}} notification, which includes the result of the requested operation.
In this case the presence agent will most likely reply with "Unsupported media type", as the code tries to submit Content-Type which is not valid for the presence event package.
=== Subscription ===
Subscription and notifications for SIP events is an Internet standard published at [http://tools.ietf.org/html/rfc3856 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 {{{Subcription_notify}}} 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 machine of the {{{Subscription}}} object is not queued, meaning that if an action is performed that is not allowed in the state the state machine is currently in, an exception will be raised.
The implementation of this object needs to be revised.
==== 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.
'''credentials'''::
The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object.
The {{{SIPURI}}} object included in the {{{Credentials}}} object is used for the {{{From}}} header of the {{{SUBSCRIBE}}} request.
This attribute is set on object instantiation and is read-only.
'''to_uri'''::
The SIP URI we want to subscribe to a particular event of represented as a {{{SIPURI}}} object.
This attribute is set on object instantiation and is read-only.
'''event'''::
The event package to which we want to subscribe at the given SIP URI.
This attribute is set on object instantiation and is read-only.
'''route'''::
The outbound proxy to use in the form of a {{{Route}}} object.
This attribute is set on object instantiation and is read-only.
'''expires'''::
The expires value that was requested on object instantiation.
This attribute is read-only.
'''extra_headers'''::
A dictionary of extra headers that should be added to any outgoing {{{SUBSCRIBE}}} request.
This attribute is set on object instantiation and is read-only.
==== methods ====
'''!__init!__'''(''self'', '''credentials''', '''to_uri''', '''event''', '''route''', '''expires'''=300, '''contact_uri'''={{{None}}}, '''extra_headers'''={{{None}}})::
Creates a new {{{Subscription}}} object.
[[BR]]''credentials'':[[BR]]
The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object.
The {{{SIPURI}}} object included in the {{{Credentials}}} object is used for the {{{From}}} header of the {{{SUBSCRIBE}}} request.
[[BR]]''to_uri'':[[BR]]
The SIP URI we want to subscribe to a particular event of represented as a {{{SIPURI}}} object.
[[BR]]''event'':[[BR]]
The event package to which we want to subscribe at the given SIP URI.
[[BR]]''route'':[[BR]]
The outbound proxy to use in the form of a {{{Route}}} object
[[BR]]''expires'':[[BR]]
The amount of seconds the {{{SUBSCRIBE}}} is valid, i.e. the value that should be put in the {{{Expires}}} header.
[[BR]]''contact_uri'':[[BR]]
The Contact URI that should be used in the {{{SUBSCRIBE}}} requests.
If this is {{{None}}}, a Contact URI will be generated internally.
[[BR]]''extra_headers'':[[BR]]
A dictionary of extra headers that should be added to any outgoing {{{SUBSCRIBE}}} request.
'''subscribe'''(''self'')::
This method activates the subscription and causes the object to send a {{{SUBSCRIBE}}} request to the relevant presence agent.
It can only be used when the object is in the {{{TERMINATED}}} state.
'''unsubscribe'''(''self'')::
This method causes the object to send a {{{SUBSCRIBE}}} request with an {{{Expires}}} value of 0, effectively canceling the active subscription.
It can be used when the object is not in the {{{TERMINATED}}} state.
==== notifications ====
'''SIPSubscriptionChangedState'''::
This notification will be sent every time the internal state machine of a {{{Subscription}}} object changes state.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''state'':[[BR]]
The new state the state machine moved into.
[[BR]]''code'': (only on SIP response triggered state change)[[BR]]
The status code of the response that caused the state change.
This may be internally generated by PJSIP, e.g. on timeout.
[[BR]]''reason'': (only on SIP response triggered state change)[[BR]]
The status text of the response that caused the state change.
This may be internally generated by PJSIP, e.g. on timeout.
'''SIPSubscriptionGotNotify'''::
This notification will be sent when a {{{NOTIFY}}} is received that corresponds to a particular {{{Subscription}}} object.
Note that this notification will not be sent when a {{{NOTIFY}}} with an empty body is received.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''content_type'':[[BR]]
The first part of the {{{Content-Type:}}} header of the received {{{NOTIFY}}} request (before the {{{/}}}), indicating the type of the body.
[[BR]]''content_subtype'':[[BR]]
The second part of the {{{Content-Type:}}} header of the received {{{NOTIFY}}} request (after the {{{/}}}), indicating the type of the body.
[[BR]]''body'':[[BR]]
The body of the {{{NOTIFY}}} request.
==== example code ====
This code shows how to make a {{{Subscription}}} object that subscribes to the presence of another SIP account.
{{{
accnt = SIPURI
creds = Credentials(accnt, "password")
to_uri = SIPURI
sub = Subscription(creds, to_uri, "presence", Route("1.2.3.4"))
sub.subscribe()
}}}
After executing this code, the application will have to wait until the {{{Subscription}}} object sends the {{{SIPSubscriptionChangedState}}} notification, which includes the result of the requested operation.
Independently of this, the object sends a {{{SIPSubscriptionGotNotify}}} notification anytime it receives a {{{NOTIFY}}} request for this subscription, as long as the subscription is active.
=== 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 [http://www.pjsip.org/pjsip/docs/html/group__PJSIP__INV.htm 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:
Image(sipsimple-core-invite-state-machine.png, nolink)
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 {{{disconnect()}}} 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.
'''is_outgoing'''::
Boolean indicating if the original {{{INVITE}}} was outgoing, or incoming if set to {{{False}}}.
'''credentials'''::
The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object.
If this {{{Invitation}}} object represents an incoming {{{INVITE}}} session this attribute will be {{{None}}}.
This attribute is set on object instantiation and is read-only.
'''caller_uri'''::
The SIP URI of the caller represented by a {{{SIPURI}}} object.
If this is in an outgoing {{{INVITE}}} session, the caller_uri is taken from the supplied {{{Credentials}}} object.
Otherwise the URI is taken from the {{{From:}}} header of the initial {{{INVITE}}}.
This attribute is set on object instantiation and is read-only.
'''callee_uri'''::
The SIP URI of the callee represented by a {{{SIPURI}}} object.
If this is an outgoing {{{INVITE}}} session, this is the callee_uri from the
__ 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_uri'''::
The local SIP URI used in this session.
If the original {{{INVITE}}} was incoming, this is the same as {{{callee_uri}}}, otherwise it will be the same as {{{caller_uri}}}.
'''remote_uri'''::
The SIP URI of the remote party in this session.
If the original {{{INVITE}}} was incoming, this is the same as {{{caller_uri}}}, otherwise it will be the same as {{{callee_uri}}}.
'''route'''::
The outbound proxy that was requested to be used in the form of a {{{Route}}} 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_uri'''::
The Contact URI that the local side provided to the remote side within this {{{INVITE}}} session as a {{{SIPURI}}} object.
==== methods ====
'''!__init!__'''(''self'', '''credentials''', '''callee_uri''', '''route''', '''contact_uri'''={{{None}}})::
Creates a new {{{Invitation}}} object for an outgoing session.
[[BR]]''credentials'':[[BR]]
The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object.
The {{{SIPURI}}} object included in the {{{Credentials}}} object is used for the {{{From}}} header of the {{{INVITE}}} request.
[[BR]]''callee_uri'':[[BR]]
The SIP URI we want to send the {{{INVITE}}} to, represented as a {{{SIPURI}}} object.
[[BR]]''route'':[[BR]]
The outbound proxy to use in the form of a {{{Route}}} object.
This includes the desired transport to use.
[[BR]]''contact_uri'':[[BR]]
The Contact URI to include in the {{{INVITE}}} request, a {{{SIPURI}}} object.
If this is {{{None}}}, a Contact URI will be internally generated.
'''get_active_local_sdp'''(''self'')::
Returns a new {{{SDPSession}}} object representing the currently active local SDP.
If no SDP was negotiated yet, this returns {{{None}}}.
'''get_active_remote_sdp'''(''self'')::
Returns a new {{{SDPSession}}} object representing the currently active local SDP.
If no SDP was negotiated yet, this returns {{{None}}}.
'''get_offered_local_sdp'''(''self'')::
Returns a new {{{SDPSession}}} object representing the currently proposed local SDP.
If no local offered SDP has been set, this returns {{{None}}}.
'''set_offered_local_sdp'''(''self'', '''local_sdp''')::
Sets the offered local SDP, either for an initial {{{INVITE}}} or re-{{{INVITE}}}, or as an SDP answer in response to an initial {{{INVITE}}} or re-{{{INVITE}}}.
[[BR]]''local_sdp'':[[BR]]
The SDP to send as offer or answer to the remote party.
'''get_offered_remote_sdp'''(''self'')::
Returns a new {{{SDPSession}}} object representing the currently proposed remote SDP.
If no remote SDP has been offered in the current state, this returns {{{None}}}.
'''send_invite'''(''self'', '''extra_headers'''={{{None}}})::
This tries to move the state machine into the {{{CALLING}}} state by sending the initial {{{INVITE}}} request.
It may only be called from the {{{NULL}}} state on an outgoing {{{Invitation}}} object.
[[BR]]''extra_headers'':[[BR]]
Any extra headers that should be included in the {{{INVITE}}} request in the form of a dict.
'''respond_to_invite_provisionally'''(''self'', '''response_code'''=180, '''extra_headers'''={{{None}}})::
This tries to move the state machine into the {{{EARLY}}} state by sending a provisional response to the initial {{{INVITE}}}.
It may only be called from the {{{INCOMING}}} state on an incoming {{{Invitation}}} object.
[[BR]]''response_code'':[[BR]]
The code of the provisional response to use as an int.
This should be in the 1xx range.
[[BR]]''extra_headers'':[[BR]]
Any extra headers that should be included in the response in the form of a dict.
'''accept_invite'''(''self'', '''extra_headers'''={{{None}}})::
This tries to move the state machine into the {{{CONNECTING}}} state by sending a 200 OK response to the initial {{{INVITE}}}.
It may only be called from the {{{INCOMING}}} or {{{EARLY}}} states on an incoming {{{Invitation}}} object.
[[BR]]''extra_headers'':[[BR]]
Any extra headers that should be included in the response in the form of a dict.
'''disconnect'''(''self'', '''response_code'''=486, '''extra_headers'''={{{None}}})::
This moves the {{{INVITE}}} state machine into the {{{DISCONNECTING}}} state by sending the necessary SIP message.
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 BYE request or a negative response.
[[BR]]''response_code'':[[BR]]
The code of the response to use as an int, if transmission of a response is needed.
[[BR]]''extra_headers'':[[BR]]
Any extra headers that should be included in the request or response in the form of a dict.
'''respond_to_reinvite'''(''self'', '''response_code'''=200, '''extra_headers'''={{{None}}})::
Respond to a received re-{{{INVITE}}} with a response that is either provisional (1xx), positive (2xx) or negative (3xx and upwards).
This method can be called by the application when the state machine is in the {{{REINVITED}}} state and will move the state machine back into the {{{CONFIRMED}}} state.
Before giving a positive final response, the SDP needs to be set using the {{{set_offered_local_sdp()}}} method.
[[BR]]''response_code'':[[BR]]
The code of the response to use as an int.
This should be a 3 digit number.
[[BR]]''extra_headers'':[[BR]]
'''send_reinvite'''(''self'', '''extra_headers'''={{{None}}})::
The application may only call this method when the state machine is in the {{{CONFIRMED}}} state to induce sending a re-{{{INVITE}}}.
Before doing this it needs to set the new local SDP offer by calling the {{{set_offered_local_sdp()}}} method.
After this method is called, the state machine will be in the {{{REINVITING}}} state, until a final response from the remote party is received.
[[BR]]''extra_headers'':[[BR]]
Any extra headers that should be included in the re-{{{INVITE}}} in the form of a dict.
==== notifications ====
'''SIPInvitationChangedState'''::
This notification is sent by an {{{Invitation}}} object whenever its state machine changes state.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''prev_state'':[[BR]]
The previous state of the INVITE state machine.
[[BR]]''state'':[[BR]]
The new state of the INVITE state machine, which may be the same as the previous state.
[[BR]]''method'': (only if the state change got triggered by an incoming SIP request)[[BR]]
The method of the SIP request as a string.
[[BR]]''request_uri'': (only if the state change got triggered by an incoming SIP request)[[BR]]
The request URI of the SIP request as a {{{SIPURI}}} object.
[[BR]]''code'': (only if the state change got triggered by an incoming SIP response or internal timeout or error)[[BR]]
The code of the SIP response or error as an int.
[[BR]]''reason'': (only if the state change got triggered by an incoming SIP response or internal timeout or error)[[BR]]
The reason text of the SIP response or error as an int.
[[BR]]''headers'': (only if the state change got triggered by an incoming SIP request or response)[[BR]]
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.
[[BR]]''body'': (only if the state change got triggered by an incoming SIP request or response)[[BR]]
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 negotation has been perfomed.
It should be used by the application as an indication to start, change or stop any associated media streams.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''succeeded'':[[BR]]
A boolean indicating if the SDP negotation has succeeded.
[[BR]]''error'': (only if SDP negotation did not succeed)[[BR]]
A string indicating why SDP negotation failed.
[[BR]]''local_sdp'': (only if SDP negotation succeeded)[[BR]]
A SDPSession object indicating the local SDP that was negotiated.
[[BR]]''remote_sdp'': (only if SDP negotation succeeded)[[BR]]
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 [http://tools.ietf.org/html/rfc4566 RFC 4566]. [http://tools.ietf.org/html/rfc3264 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 object directly represents the contents of a SDP body, as carried e.g. in a INVITE request, and is a simple wrapper for the PJSIP [http://www.pjsip.org/pjmedia/docs/html/structpjmedia__sdp__session.htm pjmedia_sdp_session] structure.
It can be passed to those methods of an {{{Invitation}}} object that result in transmission of a message that includes SDP, or is passed to the application through a notification that is triggered by reception of a message that includes SDP.
A {{{SDPSession}}} object may contain {{{SDPMedia}}}, {{{SDPConnection}}} and {{{SDPAttribute}}} objects.
It supports comparison to other {{{SDPSession}}} objects using the == and != expressions.
As all the attributes of the {{{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.
[[BR]]''address'':[[BR]]
The address that is contained in the "o" (origin) line of the SDP as a string.
[[BR]]''id'':[[BR]]
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.
[[BR]]''version'':[[BR]]
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.
[[BR]]''user'':[[BR]]
The user name contained in the "o" (origin) line of the SDP as a string.
[[BR]]''net_type'':[[BR]]
The network type contained in the "o" (origin) line of the SDP as a string.
[[BR]]''address_type'':[[BR]]
The address type contained in the "o" (origin) line of the SDP as a string.
[[BR]]''name'':[[BR]]
The contents of the "s" (session name) line of the SDP as a string.
[[BR]]''info'':[[BR]]
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.
[[BR]]''connection'':[[BR]]
The contents of the "c" (connection) line of the SDP as a {{{SDPConnection}}} object.
If this is set to {{{None}}}, the SDP has no session level "c" line.
[[BR]]''start_time'':[[BR]]
The first value of the "t" (time) line of the SDP as an int.
[[BR]]''stop_time'':[[BR]]
The second value of the "t" (time) line of the SDP as an int.
[[BR]]''attributes'':[[BR]]
The session level "a" lines (attributes) in the SDP represented by a list of {{{SDPAttribute}}} objects.
[[BR]]''media'':[[BR]]
The media sections of the SDP represented by a list of {{{SDPMedia}}} objects.
=== SDPMedia ===
This object represents 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 [http://www.pjsip.org/pjmedia/docs/html/structpjmedia__sdp__media.htm pjmedia_sdp_media] structure.
One or more {{{SDPMedia}}} objects are usually contained in a {{{SDPSession}}} object.
It supports comparison to other {{{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.
[[BR]]''media'':[[BR]]
The media type contained in the "m" (media) line as a string.
[[BR]]''port'':[[BR]]
The transport port contained in the "m" (media) line as an int.
[[BR]]''transport'':[[BR]]
The transport protocol in the "m" (media) line as a string.
[[BR]]''port_count'':[[BR]]
The port count in the "m" (media) line as an int.
If this is set to 1, it is not included in the SDP.
[[BR]]''formats'':[[BR]]
The media formats in the "m" (media) line represented by a list of strings.
[[BR]]''info'':[[BR]]
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.
[[BR]]''connection'':[[BR]]
The contents of the "c" (connection) line that is somewhere below the "m" line of this section as a {{{SDPConnection}}} object.
If this is set to {{{None}}}, this media section has no "c" line.
[[BR]]''attributes'':[[BR]]
The "a" lines (attributes) that are somewhere below the "m" line of this section represented by a list of {{{SDPAttribute}}} objects.
'''get_direction'''(''self'')::
This is a convenience methods 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 ===
This object 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 [http://www.pjsip.org/pjmedia/docs/html/structpjmedia__sdp__conn.htm pjmedia_sdp_conn] structure.
A {{{SDPConnection}}} object can be contained in a {{{SDPSession}}} object or {{{SDPMedia}}} object.
It supports comparison to other {{{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.
[[BR]]''address'':[[BR]]
The address part of the connection line as a string.
[[BR]]''net_type'':[[BR]]
The network type part of the connection line as a string.
[[BR]]''address_type'':[[BR]]
The address type part of the connection line as a string.
=== SDPAttribute ===
This object represents 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 [http://www.pjsip.org/pjmedia/docs/html/structpjmedia__sdp__attr.htm pjmedia_sdp_attr] structure.
One or more {{{SDPAttribute}}} objects can be contained in a {{{SDPSession}}} object or {{{SDPMedia}}} object.
It supports comparison to other {{{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.
[[BR]]''name'':[[BR]]
The name part of the attribute line as a string.
[[BR]]''value'':[[BR]]
The value part of the attribute line as a string.
=== 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 [http://www.pjsip.org/pjmedia/docs/html/group__PJMEDIA__TRANSPORT.htm 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 [wiki:RTTProposal 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 [http://tools.ietf.org/html/rfc3550 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.
Image(sipsimple-rtp-transport-state-machine.png, nolink)
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 negotation 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}}} respectively, which can be used to generate the local SDP in the form of a {{{SDPSession}}} object (note that it needs the full object, not just the relevant {{{SDPMedia}}} object).
This local SDP then needs to be passed to the {{{set_LOCAL()}}} method, which moves the state machine into the {{{LOCAL}}} state.
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 {{{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 {{{SDPSession}}} objects.
* 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.
==== 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 or IPv6 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_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_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.
==== 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 aditional 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.
[[BR]]''local_rtp_address'':[[BR]]
Optionally contains the local IP address to listen on, either in IPv4 or IPv6 form.
If this is not specified, PJSIP will listen on all network interfaces.
[[BR]]''use_srtp'':[[BR]]
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.
[[BR]]''srtp_forced'':[[BR]]
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 negotation for this stream will fail.
This argument is relevant only if {{{use_srtp}}} is set to {{{True}}}.
[[BR]]''use_ice'':[[BR]]
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.
[[BR]]''ice_stun_address'':[[BR]]
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}}}.
[[BR]]''ice_stun_address'':[[BR]]
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.
[[BR]]''local_sdp'':[[BR]]
The local SDP to be proposed in the form of a {{{SDPSession}}} object.
Note that this object may be modified by this method.
[[BR]]''sdp_index'':[[BR]]
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.
[[BR]]''local_sdp'':[[BR]]
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.
[[BR]]''remote_sdp'':[[BR]]
The remote SDP that was received in in the form of a {{{SDPSession}}} object.
[[BR]]''sdp_index'':[[BR]]
The index in the SDP for the media stream for which this object was created.
==== 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.
[[BR]]''timestamp'':[[BR]]
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.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''reason'':[[BR]]
A string describing the failure reason.
=== AudioTransport ===
This object represent an audio stream as it is transported over the network.
It contains an instance of {{{RTPTransport}}} and wraps a [http://www.pjsip.org/pjmedia/docs/html/group__PJMED__STRM.htm pjmedia_stream] object, which in turn manages the RTP encapsulation, RTCP session, audio codec and adaptive jitter buffer.
It also generates a {{{SDPMedia}}} object to be included in the local SDP.
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 {{{SDPMedia}}} 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 {{{SDPMedia}}} 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.
==== attributes ====
'''transport'''::
The {{{RTPTransport}}} object that was passed when the object got instatiated.
This attribute is read-only.
'''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.
==== methods ====
'''!__init!__'''(''self'', '''transport''', '''remote_sdp'''={{{None}}}, '''sdp_index'''=0, '''enable_silence_detection'''=True)::
Creates a new {{{AudioTransport}}} object and start the underlying stream if the remote SDP is already known.
[[BR]]''transport'':[[BR]]
The transport to use in the form of a {{{RTPTransport}}} object.
[[BR]]''remote_sdp'':[[BR]]
The remote SDP that was received in the form of a {{{SDPSession}}} object.
[[BR]]''sdp_index'':[[BR]]
The index within the SDP of the audio stream that should be created.
[[BR]]''enable_silence_detection''[[BR]]
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.
'''get_local_media'''(''self'', '''is_offer''', '''direction'''="sendrecv")::
Generates a {{{SDPMedia}}} 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.
[[BR]]''is_offer'':[[BR]]
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.
[[BR]]''direction'':[[BR]]
The direction attribute to put in the SDP.
'''start'''(''self'', '''local_sdp''', '''remote_sdp''', '''sdp_index''')::
This method should only be called once, when the application has previously sent an SDP offer and the answer has been received.
[[BR]]''local_sdp'':[[BR]]
The full local SDP that was included in the SDP negotiation in the form of a {{{SDPSession}}} object.
[[BR]]''remote_sdp'':[[BR]]
The remote SDP that was received in the form of a {{{SDPSession}}} object.
[[BR]]''sdp_index'':[[BR]]
The index within the SDP of the audio stream.
'''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
[[BR]]''digit'':[[BR]]
A string of length one indicating the DTMF digit to send.
This can be either a number or 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.
[[BR]]''direction'':[[BR]]
The direction that has been negotiated.
==== notifications ====
'''RTPAudioTransportGotDTMF'''::
This notification will be sent when an incoming DTMF digit is received from the remote party.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
[[BR]]''digit'':[[BR]]
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.
=== WaveFile ===
This is a simple object that allows playing back of a {{{.wav}}} file over the PJSIP conference bridge, possibly looping a number of times.
Only 16-bit PCM and A-law/U-law formats are supported.
Its main purpose is the playback of ringtones.
This class can be instantiated by the application before the {{{Engine}}} is running, but in order to actually start playback, through the {{{start()}}} method, the {{{Engine}}} must have been started as well.
Once the {{{start()}}} method is called, the {{{.wav}}} file will continue playing until the loop count specified is reached( or forever if the specified loop count is 0), or until the {{{stop()}}} method is called.
When playback stops for either of these reasons, 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.
In this case no notification will be sent.
==== attributes ====
'''file_name'''::
The name of the {{{.wav}}} file, as specified when the object was created.
'''is_active'''::
A boolean read-only property that indicates if the file is currently being played back.
Note that if the playback loop is currently in a pause between playbacks, this attribute will also be {{{True}}}.
==== methods ====
'''!__init!__'''(''self'', '''file_name''')::
Creates a new {{{WaveFile}}} object.
[[BR]]''file_name'':[[BR]]
The name of the {{{.wav}}} file to be played back as a string.
This should include the full path to the file.
'''start'''(''self'', '''level'''=100, '''loop_count'''=1, '''pause_time'''=0)::
Start playback of the {{{.wav}}} file, optionally looping it.
[[BR]]''level'':[[BR]]
The level to play the file back at, in percentage.
A percentage lower than 100 means playback will be attenuated, a percentage higher than 100 means it will amplified.
[[BR]]''loop_count'':[[BR]]
The number of time to loop playing this file.
A value of 0 means looping infinitely.
[[BR]]''pause_time'':[[BR]]
The number of seconds to pause between consecutive loops.
This can be either an int or a float.
'''stop'''(''self'')::
Stop playback of the file.
==== notifications ====
'''WaveFileDidFinishPlaying'''::
This notification will be sent whenever the {{{.wav}}} file has been played back the specified number of times.
After sending this event, the playback may be re-started.
[[BR]]''timestamp'':[[BR]]
A {{{datetime.datetime}}} object indicating when the notification was sent.
=== RecordingWaveFile ===
This is a simple object that allows recording whatever is heard on the PJSIP conference bridge to a PCM {{{.wav}}} file.
This class can be instantiated by the application before the {{{Engine}}} is running, but in order to actually start playback, through the {{{start()}}} method, the {{{Engine}}} must have been started as well.
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.
==== attributes ====
'''file_name'''::
The name of the {{{.wav}}} file, as specified when the object was created.
'''is_active'''::
A boolean read-only attribute that indicates if the file is currently being written to.
'''is_paused'''::
A boolean read-only attribute that indicates if the active recording is currently paused.
==== methods ====
'''!__init!__'''(''self'', '''file_name''')::
Creates a new {{{RecordingWaveFile}}} object.
[[BR]]''file_name'':[[BR]]
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 on the conference bridge to the {{{.wav}}} file.
'''pause'''(''self'')::
Pause recording to the {{{.wav}}} file.
'''resume'''(''self'')::
Resume a previously paused recording.
'''stop'''(''self'')::
Stop recording to the file.