Project

General

Profile

SipCoreApiDocumentation » History » Version 47

Ruud Klaver, 05/07/2009 04:19 PM

1 12 Adrian Georgescu
= SIP core API =
2 1 Adrian Georgescu
3 28 Adrian Georgescu
[[TOC(Sip*, depth=3)]]
4 5 Adrian Georgescu
5 1 Adrian Georgescu
== Introduction ==
6
7 13 Adrian Georgescu
This chapter describes the internal architecture and API of the SIP core of the {{{sipsimple}}} library.
8 1 Adrian Georgescu
{{{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.
9
10
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,
11
modify and terminate multimedia sessions such as Internet telephony calls
12
(VoIP). Media can be added to (and removed from) an existing session.
13
14
SIP transparently supports name mapping and redirection services, which
15
supports personal mobility, users can maintain a single externally visible
16
address identifier, which can be in the form of a standard email address or
17
E.164 telephone number regardless of their physical network location.
18
19
SIP allows the endpoints to negotiate and combine any type of session they
20
mutually understand like video, instant messaging (IM), file transfer,
21
desktop sharing and provides a generic event notification system with
22
real-time publications and subscriptions about state changes that can be
23
used for asynchronous services like presence, message waiting indicator and
24
busy line appearance.
25
26
For a comprehensive overview of SIP related protocols and use cases visit http://www.tech-invite.com
27
28 30 Adrian Georgescu
== PJSIP library ==
29 1 Adrian Georgescu
30
{{{sipsimple}}} builds on PJSIP [http://www.pjsip.org], a set of static libraries, written in C, which provide SIP signaling and media capabilities.
31
PJSIP is considered to be the most mature and advanced open source SIP stack available.
32
The following diagram, taken from the PJSIP documentation, illustrates the library stack of PJSIP:
33
34
[[Image(http://www.pjsip.org/images/diagram.jpg, nolink)]]
35
36
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.
37
The latter also includes an abstraction layer for the soundcard.
38
Both of these stracks are integrated in the high level library, called PJSUA.
39
40
PJSIP itself provides a high-level [http://www.pjsip.org/python/pjsua.htm Python wrapper for PJSUA].
41
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.
42
The main reasons for this are the following:
43
 * 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.
44
 * 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.
45
 * 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.
46
47
PJSIP itself is by nature asynchronous.
48
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.
49
Whenever the application performs some action through a function, this function will return immediately.
50
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.
51
52
> NOTE: Currently the core starts the media handling as a separate C thread to avoid lag caused by the GIL.
53
> The soundcard also has its own C thread.
54
55
== Architecture ==
56
57
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]).
58
It allows a Python-like file with some added C manipulation statements to be compiled to C.
59
This in turn compiles to a Python C extension module, which links with the PJSIP static libraries.
60
61
The SIP core part of the {{{sipsimple}}} Python package is subdivided into three modules:
62
 '''sipsimple.engine'''::
63
  Python module that contains the {{{Engine}}} singleton class, which manages the thread that constantly polls the PJSIP library, i.e. the PJSIP worker thread.
64
  For the applications that use the core of {{{sipsimple}}}, the {{{Engine}}} object forms the main entry point.
65
 '''sipsimple.core'''::
66
  This is the Python C extension module ultimately compiled from the Cython file and PJSIP static libraries.
67
  It contains these types of classes:
68
   * The {{{PJSIPUA}}} class, which can only be instanced once, and is this case is only instanced once by the {{{Engine}}} object.
69
     In this way the {{{Engine}}} singleton class acts as a wrapper to the one {{{PJSIPUA}}} instance.
70
     The {{{PJSIPUA}}} class represents the SIP endpoint and manages the initialization and destruction of all the PJSIP libraries.
71
     It also provides a number of methods.
72
     The application however should never call these methods directly on the {{{PJSIPUA}}} object, rather it should call them on the {{{Engine}}} wrapper object.
73
     This object handles everything that for one reason or another cannot or should not be handled from Cython.
74 42 Ruud Klaver
   * The classes that represent the main SIP primitives to be used by the application, or in the case of {{{Request}}} a generic SIP transction.
75 1 Adrian Georgescu
     The application can instantiate these classes once the {{{Engine}}} class has been instantiated and the PJSIP worker thread has been started.
76
     All of these classes represent a state machine.
77 42 Ruud Klaver
     * {{{Request}}}
78 1 Adrian Georgescu
     * {{{Publication}}}
79
     * {{{Subscription}}}
80
     * {{{Invitation}}}
81
   * 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.
82
     * {{{SIPURI}}}
83
     * {{{Credentials}}}
84
     * {{{Route}}}
85
   * A number of SDP manipulation classes, which directly wrap the PJSIP structures representing either the parsed or to be generated SDP.
86
     {{{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.
87
     * {{{SDPSession}}}
88
     * {{{SDPMedia}}}
89
     * {{{SDPConnection}}}
90
     * {{{SDPAttribute}}}
91
   * Two classes related to transport of media traffic and audio traffic specifically, built on PJMEDIA.
92
     These classes can be instantiated independently from the other classes in order to keep signaling and media separate.
93
     * {{{RTPTransport}}}
94
     * {{{AudioTransport}}}
95
   * Two classes related to {{{.wav}}} files, one for playback and one for recording.
96
     * {{{WaveFile}}}
97
     * {{{RecordingWaveFile}}}
98
   * Two exception classes, the second being a subclass of the first.
99
     * {{{SIPCoreError}}}
100
     * {{{PJSIPError}}}
101
   * Classes used internally within the {{{core}}} module, e.g. to wrap a particular PJSIP library.
102 42 Ruud Klaver
     These classes should not be imported directly and are not included in the {{{__all__}}} variable of this module.
103
 '''sipsimple.primitives'''::
104
  This module contains several SIP primitive classes that are based on the {{{Request}}} object from the core:
105
   * {{{Registration}}}
106
   * {{{Message}}}
107 1 Adrian Georgescu
108
These classes (except the ones internal to the {{{core}}} module) are illustrated in the following diagram:
109
110
[[Image(sipsimple-core-classes.png, nolink)]]
111
112 11 Adrian Georgescu
== Integration ==
113 1 Adrian Georgescu
114
The 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.
115
These modules should be present on the system before the core can be used.
116
An application that uses the SIP core must use the notification system provided by the {{{application}}} module in order to receive notifications from it.
117
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.
118
This means that any call to instance an object from this class will result in the same object.
119
As an example, this bit of code will create an observer for logging messages only:
120
121
{{{
122
from zope.interface import implements
123
from application.notification import NotificationCenter, IObserver
124
125 29 Luci Stanescu
class SIPEngineLogObserver(object):
126 1 Adrian Georgescu
    implements(IObserver)
127
128
    def handle_notification(self, notification):
129
        print "%(timestamp)s (%(level)d) %(sender)14s: %(message)s" % notification.data.__dict__
130
131
notification_center = NotificationCenter()
132
log_observer = EngineLogObserver()
133 29 Luci Stanescu
notification_center.add_observer(self, name="SIPEngineLog")
134 1 Adrian Georgescu
}}}
135
136
Each notification object has three attributes:
137
 '''sender'''::
138
  The object that sent the notification.
139
  For generic notifications the sender will be the {{{Engine}}} instance, otherwise the relevant object.
140
 '''name'''::
141
  The name describing the notification.
142 29 Luci Stanescu
  All messages will be described in this document and start with the prefix "SIP".
143 1 Adrian Georgescu
 '''data'''::
144
  An instance of {{{application.notification.NotificationData}}} or a subclass of it.
145
  The attributes of this object provide additional data about the notification.
146
  Notifications described in this document will also have the data attributes described.
147
148 43 Ruud Klaver
Besides setting up the notification observers, the application should import the relevant objects from the {{{sipsimple.core}}}, {{{sipsimple.engine}}} and {{{sipsimple.primitives}}} modules.
149 1 Adrian Georgescu
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.
150
Most of these options can later be changed at runtime, by setting attributes of the same name on the {{{Engine}}} object.
151
The application may then instance one of the SIP primitive classes and perform operations on it.
152
153
When starting the {{{Engine}}} class, the application can pass a number of keyword arguments that influence the behaviour of the SIP endpoint.
154
For example, the SIP network ports may be set through the {{{local_udp_port}}}, {{{local_tcp_port}}} and {{{local_tls_port}}} arguments.
155
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.
156
157
The methods called on the SIP primitive objects and the {{{Engine}}} object (proxied to the {{{PJSIPUA}}} instance) may be called from any thread.
158 31 Ruud Klaver
They will return immediately and any delayed result, such as results depending on network traffic, will be returned later using a notification.
159
In this manner the SIP core continues the asynchronous pattern of PJSIP.
160 1 Adrian Georgescu
If there is an error in processing the request, an instance of {{{SIPCoreError}}}, or its subclass {{{PJSIPError}}} will be raised.
161
The former will be raised whenever an error occurs inside the core, the latter whenever an underlying PJSIP function returns an error.
162
The {{{PJSIPError}}} object also contains a status attribute, which is the PJSIP errno as an integer.
163
164 43 Ruud Klaver
As a very basic example, one can {{{REGISTER}}} for a sip account by typing the following lines on a Python console:
165 1 Adrian Georgescu
{{{
166 43 Ruud Klaver
from sipsimple.engine import Engine
167
from sipsimple.primitives import Registration
168
from sipsimple.core import Credentials, SIPURI, Route
169 1 Adrian Georgescu
e = Engine()
170
e.start()
171
cred = Credentials(SIPURI(user="alice", host="example.com"), "password")
172 43 Ruud Klaver
reg = Registration(cred)
173
reg.register(SIPURI("127.0.0.1",port=12345), Route("1.2.3.4"))
174 1 Adrian Georgescu
}}}
175
Note that in this example no observer for notifications from this {{{Registration}}} object are registered, so the result of the operation cannot be seen.
176 43 Ruud Klaver
Also note that this will not keep the registration registered when it is about to expire, as it is the application's responsibility.
177
See the {{{Registration}}} documentation for more details.
178
When performing operations with a running {{{Engine}}} on a Python console, be sure to call the {{{stop()}}} method of the {{{Engine}}} before exiting the console.
179
Failure to do so will keep the {{{Engine}}} running and will cause the program to hang.
180 1 Adrian Georgescu
181
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].
182 43 Ruud Klaver
183
> NOTE: GreenRegistration is outdated and should probably not be used anymore.
184
185
Another convention that is worth mentioning at this point is that the SIP core will never perform DNS lookups.
186
For the sake of flexibility, it is the responsibility of the application to do this and pass the result to SIP core objects using the {{{Route}}} helper object, indicating the destination IP address the resulting SIP request should be sent to.
187 32 Ruud Klaver
188 1 Adrian Georgescu
== Components ==
189
190
=== Engine ===
191
192
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.
193
Once the {{{start()}}} method is called, it instantiates the {{{core.PJSIPUA}}} object and will proxy attribute and methods from it to the application.
194
195
==== attributes ====
196
197
 '''default_start_options''' (class attribute)::
198
  This dictionary is a class attribute that describes the default values for the initialization options passed as keyword arguments to the {{{start()}}} method.
199
  Consult this method for documentation of the contents.
200 32 Ruud Klaver
 '''is_running'''::
201
  A boolean property indicating if the {{{Engine}}} is running and if it is safe to try calling any proxied methods or attributes on it.
202 1 Adrian Georgescu
203
==== methods ====
204
205
 '''!__init!__'''(''self'')::
206
  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.
207
 '''start'''(''self'', '''**kwargs''')::
208
  Initialize all PJSIP libraries based on the keyword parameters provited and start the PJSIP worker thread.
209
  If this fails an appropriate exception is raised.
210
  After the {{{Engine}}} has been started successfully, it can never be started again after being stopped.
211
  The keyword arguments will be discussed here.
212
  Many of these values are also readable as (proxied) attributes on the Engine once the {{{start()}}} method has been called.
213
  Many of them can also be set at runtime, either by modifying the attribute or by calling a particular method.
214
  This will also be documented for each argument in the following list of options.
215
  [[BR]]''auto_sound'':[[BR]]
216
  A boolean indicating if PJSIP should automatically select and enable a soundcard to use for for recording and playing back sound.
217 39 Ruud Klaver
  If this is set to {{{False}}} the Dummy sound device is selected.
218
  To be able to hear and contribute audio, the application will have to select a sound device manually through the {{{set_sound_devices}}} method.
219 1 Adrian Georgescu
  This option is not accessible as an attribute on the object, as it is transitory.
220
  [[BR]]''local_ip'': (Default: {{{None}}})[[BR]]
221
  IP address of a local interface to bind to.
222 44 Ruud Klaver
  If this is {{{None}}} or {{{0.0.0.0}}} on start, the {{{Engine}}} will listen on all network interfaces.
223
  As an attribute, this value is read-only and cannot be changed at runtime.
224 1 Adrian Georgescu
  [[BR]]''local_udp_port'': (Default: {{{0}}})[[BR]]
225
  The local UDP port to listen on for UDP datagrams.
226
  If this is 0, a random port will be chosen.
227
  If it is {{{None}}}, the UDP transport is disabled, both for incoming and outgoing traffic.
228
  As an attribute, this value is read-only, but it can be changed at runtime using the {{{set_local_udp_port()}}} method.
229
  [[BR]]''local_tcp_port'': (Default: {{{0}}})[[BR]]
230
  The local TCP port to listen on for new TCP connections.
231
  If this is 0, a random port will be chosen.
232
  If it is {{{None}}}, the TCP transport is disabled, both for incoming and outgoing traffic.
233
  As an attribute, this value is read-only, but it can be changed at runtime using the {{{set_local_tcp_port()}}} method.
234
  [[BR]]''local_tls_port'': (Default: {{{0}}})[[BR]]
235
  The local TCP port to listen on for new TLS over TCP connections.
236 28 Adrian Georgescu
  If this is 0, a random port will be chosen.
237 1 Adrian Georgescu
  If it is {{{None}}}, the TLS transport is disabled, both for incoming and outgoing traffic.
238 35 Ruud Klaver
  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. 
239 32 Ruud Klaver
  [[BR]]''tls_protocol'': (Default: "TLSv1")[[BR]] 
240
  This string describes the (minimum) TLS protocol that should be used. 
241
  Its values should be either {{{None}}}, "SSLv2", "SSLv23", "SSLv3" or "TLSv1". 
242
  If {{{None}}} is specified, the PJSIP default will be used, which is currently "TLSv1". 
243 1 Adrian Georgescu
  [[BR]]''tls_verify_server'': (Default: {{{False}}})[[BR]]
244 28 Adrian Georgescu
  This boolean indicates whether PJSIP should verify the certificate of the server against the local CA list when making an outgoing TLS connection.
245 32 Ruud Klaver
  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.
246 1 Adrian Georgescu
  [[BR]]''tls_ca_file'': (Default: {{{None}}})[[BR]]
247
  This string indicates the location of the file containing the local list of CA certificates, to be used for TLS connections.
248 32 Ruud Klaver
  If this is set to {{{None}}}, no CA certificates will be read. 
249
  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. 
250
  [[BR]]''tls_cert_file'': (Default: {{{None}}})[[BR]] 
251
  This string indicates the location of a file containing the TLS certificate to be used for TLS connections. 
252
  If this is set to {{{None}}}, no certificate file will be read. 
253
  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. 
254
  [[BR]]''tls_privkey_file'': (Default: {{{None}}})[[BR]] 
255
  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. 
256
  If this is set to {{{None}}}, no private key file will be read. 
257
  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. 
258
  [[BR]]''tls_timeout'': (Default: 1000)[[BR]] 
259
  The timeout value for a TLS negotiation in milliseconds. 
260
  Note that this value should be reasonably small, as a TLS negotiation blocks the whole PJSIP polling thread. 
261
  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.
262 1 Adrian Georgescu
  [[BR]]''ec_tail_length'': (Default: {{{50}}})[[BR]]
263
  Echo cancellation tail length in milliseconds.
264
  A longer value should provide better echo cancellation but incurs more processing cost.
265
  Setting this to 0 will disable echo cancellation.
266 20 Ruud Klaver
  As an attribute, this value is read-only, but it can be set as an argument to the {{{set_sound_devices}}} method.
267 1 Adrian Georgescu
  [[BR]]''user_agent'': (Default: {{{"ag-projects/sipclient-%version-pjsip-%pjsip-version"}}})[[BR]]
268
  This value indicates what should be set in the {{{User-Agent}}} header, which is included in each request or response sent.
269
  It can be read and set directly as an attribute at runtime.
270
  [[BR]]''log_level'': (Default: 5)[[BR]]
271 29 Luci Stanescu
  This integer dictates the maximum log level that may be reported to the application by PJSIP through the {{{SIPEngineLog}}} notification.
272 1 Adrian Georgescu
  By default the maximum amount of logging information is reported.
273
  This value can be read and set directly as an attribute at runtime.
274
  [[BR]]''trace_sip'': (Default: {{{False}}})[[BR]]
275 29 Luci Stanescu
  This boolean indicates if the SIP core should send the application SIP messages as seen on the wire through the {{{SIPEngineSIPTrace}}} notification.
276 1 Adrian Georgescu
  It can be read and set directly as an attribute at runtime.
277
  [[BR]]''sample_rate'': (Default: {{{32}}})[[BR]]
278
  The sample rate in kHz at which the sound card should operate.
279
  Higher values allow some codecs (such as speex) to achieve better quality but will incur higher processing cost, particularly in combination with echo cancellation.
280
  This parameter should be either 8, 16 or 32.
281
  The corresponding attribute of this value is read-only.
282
  [[BR]]''playback_dtmf'': (Default: {{{True}}})[[BR]]
283
  If this boolean is set to {{{True}}}, both incoming and outgoing DTMF signals have their corresponding audio tones played back on the sound card.
284
  This value can be read and set directly as an attribute at runtime.
285
  [[BR]]''rtp_port_range'': (Default: (40000, 40100))[[BR]]
286
  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.
287
  It can be read and set directly as an attribute at runtime, but the ports of previously created {{{RTPTransport}}} objects remain unaffected.
288 40 Ruud Klaver
  [[BR]]''codecs'': (Default: {{{["speex", "G722", "PCMU", "PCMA", "iLBC", "GSM"]}}})[[BR]]
289 1 Adrian Georgescu
  This list specifies the codecs to use for audio sessions and their preferred order.
290
  It can be read and set directly as an attribute at runtime.
291 40 Ruud Klaver
  Note that this global option can be overridden by an argument passed to {{{AudioTransport.__init__()}}}.
292
  The strings in this list is case insensitive.
293 1 Adrian Georgescu
  [[BR]]''events'': (Default: <some sensible events>)[[BR]]
294
  PJSIP needs a mapping between SIP SIMPLE event packages and content types.
295
  This dictionary provides some default packages and their event types.
296
  As an attribute, this value is read-only, but it can be changed at runtime using the {{{set_local_tls_port()}}} method.
297 32 Ruud Klaver
 '''start_cfg'''(''self'', '''enable_sound'''={{{True}}}, '''**kwargs''')::
298 36 Adrian Georgescu
  This provides a [wiki:SipConfigurationAPI Configuration API] aware start method.
299 32 Ruud Klaver
  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.
300
  Any argument that can be passed to {{{start()}}} may be specified, except for {{{auto_sound}}}.
301 35 Ruud Klaver
  [[BR]]''enable_sound'':[[BR]]
302 1 Adrian Georgescu
  If this is set to {{{True}}}, the sound devices set up in the configuration framework will be started.
303 39 Ruud Klaver
  If it is {{{False}}}, the Dummy sound device will be used.
304 1 Adrian Georgescu
 '''stop'''(''self'')::
305
  Stop the PJSIP worker thread and unload all PJSIP libraries.
306
  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}}}.
307
  Also note that, once stopped the {{{Engine}}} cannot be started again.
308
  This method is automatically called when the Python interpreter exits.
309
310
==== proxied attributes ====
311
312
Besides all the proxied attributes described for the {{{__init__}}} method above, two other attributes are provided once the {{{Engine}}} has been started.
313
314
 '''playback_devices'''::
315 20 Ruud Klaver
  This read-only attribute is a list of string, representing all audio playback devices on the system that can be used.
316
  These device names can be passed as the {{{playback_device}}} argument of the {{{set_sound_devices()}}} method.
317 1 Adrian Georgescu
 '''recording_devices'''::
318
  This read-only attribute is a list of string, representing all audio recording devices on the system that can be used.
319
  These device names can be passed as the {{{recording_device}}} argument of the {{{set_sound_devices()}}} method.
320 44 Ruud Klaver
 '''current_playback_device'''::
321
  The name of the audio playback device currently in use.
322
 '''current_recording_device'''::
323
  The name of the audio recording device currently in use.
324 40 Ruud Klaver
 '''available_codecs'''::
325
  A read-only list of codecs available in the core, regardless of the codecs configured through the {{{codecs}}} attribute.
326 1 Adrian Georgescu
327
==== proxied methods ====
328
329
 '''add_event'''(''self'', '''event''', '''accept_types''')::
330
  Couple a certain event package to a list of content types.
331
  Once added it cannot be removed or modified.
332 20 Ruud Klaver
 '''set_sound_devices'''(''self'', '''playback_device'''={{{None}}}, '''recording_device'''={{{None}}}, '''tail_length'''={{{None}}})::
333 1 Adrian Georgescu
  Set and open the playback and recording device, using the specified echo cancellation tail length in milliseconds.
334
  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).
335
  A {{{tail_length}}} of 0 disables echo cancellation.
336
  The device attributes need to be strings and should be obtained from the {{{playback_devices}}} and {{{recording_devices}}} attributes respectively.
337
  Passing either of these as {{{None}}} means that PJSIP should select a sound device automatically.
338
  If sound devices were already opened these will be closed first.
339
 '''connect_audio_transport'''(''self'', '''transport''')::
340
  Connect a started audio transport, in the form of a {{{AudioTransport}}} object, to the recording and playback audio devices and other connected audio transports.
341
  This means that when more than one audio stream is connected they will form a conference.
342 29 Luci Stanescu
 '''disconnect_audio_transport'''(''self'', '''transport''')::
343 1 Adrian Georgescu
  Disconnect a previously connected audio transport, in the form of a {{{AudioTransport}}} object.
344
  Stopped audio streams are disconnected automatically.
345 38 Ruud Klaver
 '''detect_nat_type'''(''self'', '''stun_server_address''', '''stun_server_port'''=3478, '''user_data'''=None)::
346 1 Adrian Georgescu
  Will start a series of STUN requests which detect the type of NAT this host is behind.
347
  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.
348 38 Ruud Klaver
  When the type of NAT is detected, this will be reported back to the application by means of a {{{SIPEngineDetectedNATType}}} notification, including the user_data object passed with this method.
349 1 Adrian Georgescu
 '''set_local_udp_port'''(''self'', '''value''')::
350 28 Adrian Georgescu
  Update the {{{local_udp_port}}} attribute to the newly specified value.
351
 '''set_local_tcp_port'''(''self'', '''value''')::
352
  Update the {{{local_tcp_port}}} attribute to the newly specified value.
353 32 Ruud Klaver
 '''set_tls_options'''(''self'', '''local_port'''={{{None}}}, '''protocol'''="TLSv1", '''verify_server'''={{{False}}}, '''ca_file'''={{{None}}}, '''cert_file'''={{{None}}}, '''privkey_file'''={{{None}}}, '''timeout'''=1000):: 
354
  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}}}. 
355 1 Adrian Georgescu
  The semantics of the arguments are the same as on the {{{start()}}} method. 
356
 '''parse_sip_uri(''self'', '''uri_string''')::
357
  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.
358 44 Ruud Klaver
 '''play_tones(''self'', '''tones''')::
359
  Play a sequence of single or dual frequency tones over the audio device.
360
  The tones should be a list of 3-item tuples, in the form of {{{[(<freq1>, <freq2>, <duration>), ...]}}}, with Hz as unit for the frequencies and ms as unit for the duration.
361
  If {{{freq2}}} is 0, this indicates that only {{{freq1}}} should be used for the tone.
362
  If {{{freq1}}} is 0, this indicates a pause when no tone should be played for the set duration.
363 1 Adrian Georgescu
364
==== notifications ====
365
366 16 Ruud Klaver
Notifications sent by the {{{Engine}}} are notifications that are related to the {{{Engine}}} itself or unrelated to any SIP primitive object.
367 1 Adrian Georgescu
They are described here including the data attributes that is included with them.
368
369 29 Luci Stanescu
 '''SIPEngineWillStart'''::
370 16 Ruud Klaver
  This notification is sent when the {{{Engine}}} is about to start.
371
  [[BR]]''timestamp'':[[BR]]
372
  A {{{datetime.datetime}}} object indicating when the notification was sent.
373 29 Luci Stanescu
 '''SIPEngineDidStart'''::
374 16 Ruud Klaver
  This notification is sent when the {{{Engine}}} is has just been started.
375
  [[BR]]''timestamp'':[[BR]]
376
  A {{{datetime.datetime}}} object indicating when the notification was sent.
377 29 Luci Stanescu
 '''SIPEngineDidFail'''::
378 16 Ruud Klaver
  This notification is sent whenever the {{{Engine}}} has failed fatally and either cannot start or is about to stop.
379
  It is not recommended to call any methods on the {{{Engine}}} at this point.
380
  [[BR]]''timestamp'':[[BR]]
381
  A {{{datetime.datetime}}} object indicating when the notification was sent.
382 29 Luci Stanescu
 '''SIPEngineWillEnd'''::
383 16 Ruud Klaver
  This notification is sent when the {{{Engine}}} is about to stop because the application called the {{{stop()}}} method.
384
  Methods on the {{{Engine}}} can be called at this point, but anything that has a delayed result will probably not return any notification.
385
  [[BR]]''timestamp'':[[BR]]
386
  A {{{datetime.datetime}}} object indicating when the notification was sent.
387 29 Luci Stanescu
 '''SIPEngineDidEnd'''::
388 16 Ruud Klaver
  This notification is sent when the {{{Engine}}} was running and is now stopped, either because of failure or because the application requested it.
389
  [[BR]]''timestamp'':[[BR]]
390
  A {{{datetime.datetime}}} object indicating when the notification was sent.
391 29 Luci Stanescu
 '''SIPEngineLog'''::
392 1 Adrian Georgescu
  This notification is a wrapper for PJSIP logging messages.
393
  It can be used by the application to output PJSIP logging to somewhere meaningful, possibly doing filtering based on log level.
394
  [[BR]]''timestamp'':[[BR]]
395
  A {{{datetime.datetime}}} object representing the time when the log message was output by PJSIP.
396
  [[BR]]''sender'':[[BR]]
397
  The PJSIP module that originated this log message.
398
  [[BR]]''level'':[[BR]]
399
  The logging level of the message as an integer.
400
  Currently this is 1 through 5, 1 being the most critical.
401
  [[BR]]''message'':[[BR]]
402
  The actual log message.
403 29 Luci Stanescu
 '''SIPEngineSIPTrace'''::
404 1 Adrian Georgescu
  Will be sent only when the {{{do_siptrace}}} attribute of the {{{Engine}}} instance is set to {{{True}}}.
405
  The notification data attributes will contain the SIP messages as they are sent and received on the wire.
406
  [[BR]]''timestamp'':[[BR]]
407
  A {{{datetime.datetime}}} object indicating when the notification was sent.
408
  [[BR]]''received'':[[BR]]
409
  A boolean indicating if this message was sent from or received by PJSIP (i.e. the direction of the message).
410
  [[BR]]''source_ip'':[[BR]]
411
  The source IP address as a string.
412
  [[BR]]''source_port'':[[BR]]
413 29 Luci Stanescu
  The source port of the message as an integer.
414 1 Adrian Georgescu
  [[BR]]''destination_ip'':[[BR]]
415
  The destination IP address as a string.
416
  [[BR]]''source_port'':[[BR]]
417
  The source port of the message as an integer.
418
  [[BR]]''data'':[[BR]]
419
  The contents of the message as a string.
420
421
> For received message the destination_ip and for sent messages the source_ip may not be reliable.
422
423 29 Luci Stanescu
 '''SIPEngineDetectedNATType'''::
424 1 Adrian Georgescu
  This notification is sent some time after the application request the NAT type this host behind to be detected using a STUN server.
425
  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.
426
  [[BR]]''timestamp'':[[BR]]
427
  A {{{datetime.datetime}}} object indicating when the notification was sent.
428
  [[BR]]''succeeded'':[[BR]]
429
  A boolean indicating if the NAT detection succeeded.
430 38 Ruud Klaver
  [[BR]]''user_data'':[[BR]]
431
  The {{{user_data}}} argument passed while calling the {{{detect_nat_type()}}} method.
432
  This can be any object and could be used for matching requests to responses.
433 1 Adrian Georgescu
  [[BR]]''nat_type'':[[BR]]
434
  A string describing the type of NAT found.
435
  This value is only present if NAT detection succeeded.
436
  [[BR]]''error'':[[BR]]
437
  A string indicating the error that occurred while attempting to detect the type of NAT.
438
  This value only present if NAT detection did not succeed.
439
 '''SIPEngineGotException'''::
440
  This notification is sent whenever there is an unexpected exception within the PJSIP working thread.
441
  The application should show the traceback to the user somehow.
442
  An exception need not be fatal, but if it is it will be followed by a '''SIPEngineDidFail''' notification.
443
  [[BR]]''timestamp'':[[BR]]
444
  A {{{datetime.datetime}}} object indicating when the notification was sent.
445
  [[BR]]''traceback'':[[BR]]
446
  A string containing the traceback of the exception.
447
  In general this should be printed on the console.
448
449
=== SIPURI ===
450
451
This is a helper object for representing a SIP URI.
452
This object needs to be used whenever a SIP URI should be specified to the SIP core.
453
It supports comparison to other {{{SIPURI}}} objects using the == and != expressions.
454
As all of its attributes are set by the {{{__init__}}} method, the individual attributes will not be documented here.
455
456
==== methods ====
457
458 23 Ruud Klaver
 '''!__init!__'''(''self'', '''host''', '''user'''={{{None}}}, '''port'''={{{None}}}, '''display'''={{{None}}}, '''secure'''={{{False}}}, '''parameters'''={{{None}}}, '''headers'''={{{None}}})::
459 1 Adrian Georgescu
  Creates the SIPURI object with the specified parameters as attributes.
460
  Each of these attributes can be accessed and changed on the object once instanced.
461
  {{{host}}} is the only mandatory attribute.
462
  [[BR]]''host'':[[BR]]
463
  The host part of the SIP URI as a string.
464
  [[BR]]''user'':[[BR]]
465
  The username part of the SIP URI as a string, or None if not set.
466
  [[BR]]''port'':[[BR]]
467
  The port part of the SIP URI as an int, or None or 0 if not set.
468
  [[BR]]''display'':[[BR]]
469
  The optional display name of the SIP URI as a string, or None if not set.
470
  [[BR]]''secure'':[[BR]]
471
  A boolean indicating whether this is a SIP or SIPS URI, the latter being indicated by a value of {{{True}}}.
472
  [[BR]]''parameters'':[[BR]]
473
  The URI parameters. represented by a dictionary.
474
  [[BR]]''headers'':[[BR]]
475
  The URI headers, represented by a dictionary.
476
 '''!__str!__'''(''self'')::
477
  The special Python method to represent this object as a string, the output is the properly formatted SIP URI.
478
 '''copy'''(''self'')::
479
  Returns a copy of the {{{SIPURI}}} object.
480
481
=== Credentials ===
482
483
This object represents authentication credentials for a particular SIP account.
484
These should be included whenever creating a SIP primitive object that originates SIP requests.
485
As with the {{{SIPURI}}} object, the attributes of this object are the same as the arguments to the {{{__init__}}} method.
486
487
==== methods ====
488
489 33 Ruud Klaver
 '''!__init!__'''(''self'', '''uri''', '''password'''={{{None}}})::
490 1 Adrian Georgescu
  Creates the Credentials object with the specified parameters as attributes.
491
  Each of these attributes can be accessed and changed on the object once instanced.
492
  [[BR]]''uri'':[[BR]]
493
  A {{{SIPURI}}} object representing the account for which these are the credentials.
494
  [[BR]]''password'':[[BR]]
495
  The password for this SIP account as a string.
496
  If a password is not needed, for example when sending SIP messages without a proxy, this can be {{{None}}}.
497
 '''copy'''(''self'')::
498
  Returns a copy of the {{{Credentials}}} object.
499
500
=== Route ===
501
502 22 Ruud Klaver
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.
503 33 Ruud Klaver
As it is the application's responsibility to look this up and pass it as an argument for every SIP primitive class it creates.
504 22 Ruud Klaver
The contents of the {{{Route}}} object will be placed in the {{{Route}}} header of the request.
505 1 Adrian Georgescu
As with the {{{SIPURI}}} object, the attributes of this object are the same as the arguments to the {{{__init__}}} method.
506
507
==== methods ====
508
509 22 Ruud Klaver
 '''!__init!__'''(''self'', '''address''', '''port'''=5060, '''transport'''={{{None}}})::
510 1 Adrian Georgescu
  Creates the Route object with the specified parameters as attributes.
511
  Each of these attributes can be accessed on the object once instanced.
512 22 Ruud Klaver
  [[BR]]''address'':[[BR]]
513 45 Ruud Klaver
  The IPv4 address that the request in question should be sent to as a string.
514 1 Adrian Georgescu
  [[BR]]''port'':[[BR]]
515 22 Ruud Klaver
  The port to send the requests to, represented as an int.
516 1 Adrian Georgescu
  [[BR]]''transport'':[[BR]]
517 35 Ruud Klaver
  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.
518 1 Adrian Georgescu
 '''copy'''(''self'')::
519
  Returns a copy of the {{{Route}}} object.
520 22 Ruud Klaver
521 46 Ruud Klaver
=== Request ===
522
523
The {{{sipsimple.core.Request}}} object encapsulates a single SIP request transaction from the client side, which includes sending the request, receiving the response and possibly waiting for the result of the request to expire.
524
Although this class can be used by the application to construct and send an arbitrary SIP request, most applications will use the classes provided in the {{{sipsimple.primitives}}} module, which are built on top of one or several {{{Request}}} objects and deal with instances of specific SIP methods.
525
526
The lifetime of this object is linear and is described by the following diagram:
527
528
[[Image(sipsimple-request-lifetime.png, nolink)]]
529
530
The bar denotes which state the object is in and at the top are the notifications which may be emitted at certain points in time.
531
Directly after the object is instantiated, it will be in the {{{INIT}}} state.
532
The request will be sent over the network once its {{{send()}}} method is called, moving the object into the {{{IN_PROGRESS}}} state.
533
On each provisional response that is received in reply to this request, the {{{SIPRequestGotProvisionalResponse}}} notification is sent, with data describing the response.
534
Note that this may not occur at all if not provisional responses are received.
535
When the {{{send()}}} method has been called and it does not return an exception, the object will send either a {{{SIPRequestDidSucceed}}} or a {{{SIPRequestDidFail}}} notification.
536
Both of these notifications include data on the response that triggered it.
537
Note that a SIP response that requests authentication (401 or 407) will be handled internally the first time, if a {{{Credentials}}} object was supplied.
538
If this is the sort of request that expires (detected by a {{{Expires}}} header in the response or a {{{expires}}} parameter in the {{{Contact}}} header of the response), and the request was successful, the object will go into the {{{EXPIRING}}} state.
539
A certain amount of time before the result of the request will expire, governed by the {{{expire_warning_time}}} class attribute and the actual returned expiration time, a {{{SIPRequestWillExpire}}} notification will be sent.
540
This should usually trigger whomever is using this {{{Request}}} object to construct a new {{{Request}}} for a refreshing operation.
541
When the {{{Request}}} actually expires, or when the {{{EXPIRING}}} state is skipped directly after sending {{{SIPRequestDidSucceed}}} or {{{SIPRequestDidFail}}}, a {{{SIPRequestDidEnd}}} notification will be sent.
542
543
==== attributes ====
544
545 47 Ruud Klaver
 '''state'''::
546
  Indicates the state the {{{Request}}} object is in, in the form of a string.
547
  Refer to the diagram above for possible states.
548
  This attribute is read-only.
549
 '''method'''::
550
  The method of the SIP request as a string.
551
  This attribute is set on instantiation and is read-only.
552
 '''credentials'''::
553
  The credentials to be used when challenged for authentication, represented by a {{{Credentials}}} object.
554
  This attribute is set on instantiation and is read-only.
555
 '''from_uri'''::
556
  The SIP URI to put in the {{{From}}} header of the request, in the form of a {{{SIPURI}}} object.
557
  This attribute is a shortcut to the {{{uri}}} attribute on the {{{credentials}}} attribute of this object and is read-only.
558
 '''to_uri'''::
559
  The SIP URI to put in the {{{To}}} header of the request, in the form of a {{{SIPURI}}} object.
560
  This attribute is set on instantiation and is read-only.
561
 '''request_uri'''::
562
  The SIP URI to put as request URI in the request, in the form of a {{{SIPURI}}} object.
563
  This attribute is set on instantiation and is read-only.
564
 '''route'''::
565
  Where to send the SIP request to, including IP, port and transport, in the form of a {{{SIPURI}}} object.
566
  This will also be included in the {{{Route}}} header of the request.
567
  This attribute is set on instantiation and is read-only.
568
 '''contact_uri'''::
569
  The SIP URI to put in the {{{Contact}}} header of the request, in the form of a {{{SIPURI}}} object.
570
  If this was not specified, this attribute is {{{None}}}.
571
  It is set on instantiation and is read-only.
572
 '''call_id'''::
573
  The {{{Call-ID}}} to be used for this transaction as a string.
574
  If no call id was specified on instantiation, this attribute contains the generated id.
575
  This attribute is set on instantiation and is read-only.
576
 '''cseq'''::
577
  The sequence number to use in the request as an int.
578
  If no sequence number was specified on instantiation, this attribute contains the generated sequence number.
579
  Note that this number may be increased by one if an authentication challenge is received and a {{{Credentials}}} object is given.
580
  This attribute is read-only.
581
 '''extra_headers'''::
582
  Extra headers to include in the request as a dictionary.
583
  This attribute is set on instantiation and is read-only.
584
 '''content_type'''::
585
  What string to put as content type in the {{{Content-Type}}} headers, if the request contains a body.
586
  If no body was specified, this attribute is {{{None}}}
587
  It is set on instantiation and is read-only.
588
 '''body'''::
589
  The body of the request as a string.
590
  If no body was specified, this attribute is {{{None}}}
591
  It is set on instantiation and is read-only.
592
 '''expires_in'''::
593
  This read-only property indicates in how many seconds from now this {{{Request}}} will expire, if it is in the {{{EXPIRING}}} state.
594
  If this is not the case, this property is 0.
595
596 46 Ruud Klaver
==== methods ====
597
598
==== notifications ====
599
600 1 Adrian Georgescu
=== Registration ===
601
602
A {{{Registration}}} object represents a SIP endpoint's registration for a particular SIP account using the {{{REGISTER}}} method at its SIP registrar.
603
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.
604
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.
605
In short, unless a SIP endpoint is registered, it cannot be contacted.
606
Internally it uses a state machine to represent the registration process.
607
The states of this state machine can be seen in the following diagram:
608
609 2 Adrian Georgescu
[[Image(sipsimple-registration-state-machine.png, nolink)]]
610 1 Adrian Georgescu
611
State changes are triggered by the following events:
612
 1. The initial state.
613
 2. User requests in the form of the {{{register()}}} and {{{unregister()}}} methods.
614
 3. A final response for a {{{REGISTER}}} is received from the network.
615
 4. The refresh timer expires.
616
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}}}.
617
618
> The implementation of this object needs to be revised.
619
620
==== attributes ====
621
622
 '''state'''::
623
  Indicates which state the internal state machine is in.
624
  This is one of {{{unregistered}}}, {{{registering}}}, {{{registered}}}, {{{unregistering}}}.
625
 '''credentials'''::
626
  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.
627
  This attribute is set on object instantiation and is read-only.
628
 '''route'''::
629
  The outbound proxy to use in the form of a {{{Route}}} object.
630
  This attribute is set on object instantiation and is read-only.
631
 '''extra_headers'''::
632
  A dictionary of extra headers that should be added to any outgoing {{{REGISTER}}} request.
633
  This attribute is set on object instantiation and is read-only.
634
 '''expires'''::
635
  The amount of seconds to request the registration for, i.e. the value that should be put in the {{{Expires}}} header.
636
  This attribute is set on object instantiation and can be modified at runtime.
637
  A new value will be used during the next refreshing {{{REGISTER}}}.
638
 '''expires_received'''::
639
  The amount of seconds the last successful {{{REGISTER}}} is valid for.
640
  This value is read-only.
641
642
==== methods ====
643
644 33 Ruud Klaver
 '''!__init!__'''(''self'', '''credentials''', '''route''', '''expires'''=300, '''contact_uri'''={{{None}}}, '''extra_headers'''={{{None}}})::
645 1 Adrian Georgescu
  Creates a new {{{Registration}}} object.
646
  [[BR]]''credentials'':[[BR]]
647 23 Ruud Klaver
  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.
648 1 Adrian Georgescu
  [[BR]]''route'':[[BR]]
649
  The outbound proxy to use in the form of a {{{Route}}} object
650
  [[BR]]''expires'':[[BR]]
651
  The amount of seconds to request the registration for, i.e. the value that should be put in the {{{Expires}}} header.
652 33 Ruud Klaver
  [[BR]]''contact_uri'':[[BR]]
653
  The Contact URI that should be used to register as a {{{SIPURI}}} object.
654
  If this is {{{None}}}, a Contact URI will be generated.
655 1 Adrian Georgescu
  [[BR]]''extra_headers'':[[BR]]
656
  A dictionary of extra headers that should be added to any outgoing request.
657
 '''register'''(''self'')::
658
  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.
659
  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).
660
  If it is unsuccessful the state machine reverts to the {{{unregistered}}} state.
661
 '''unregister'''(''self'')::
662
  If the object is registered it will send a {{{REGISTER}}} with an {{{Expires}}} header of 0, effectively unregistering the contact from the SIP account.
663
664
==== notifications ====
665
666 29 Luci Stanescu
 '''SIPRegistrationChangedState'''::
667 1 Adrian Georgescu
  This notification will be sent every time the internal state machine of a {{{Registeration}}} object changes state.
668
  [[BR]]''timestamp'':[[BR]]
669
  A {{{datetime.datetime}}} object indicating when the notification was sent.
670
  [[BR]]''state'':[[BR]]
671
  The new state the state machine moved into.
672
  [[BR]]''code'': (only on SIP response triggered state change)[[BR]]
673
  The status code of the response that caused the state change.
674
  This may be internally generated by PJSIP, e.g. on timeout.
675
  [[BR]]''reason'': (only on SIP response triggered state change)[[BR]]
676
  The status text of the response that caused the state change.
677
  This may be internally generated by PJSIP, e.g. on timeout.
678
  [[BR]]''contact_uri'': (only on successful registration)[[BR]]
679
  The {{{Contact}}} URI used to register as a string.
680
  [[BR]]''expires'': (only on successful registration)[[BR]]
681
  How many seconds until this registration expires.
682
  [[BR]]''contact_uri_list'': (only on successful registration)[[BR]]
683
  The full list of {{{Contact}}} URIs registered for this SIP account, including the one just performed by this object.
684
685
==== example code ====
686
687
This code shows how to make a {{{Registration}}} object for a particular SIP account and have it register.
688
689
{{{
690
accnt = SIPURI(user="username", host="domain.com")
691
creds = Credentials(accnt, "password")
692 22 Ruud Klaver
reg = Registration(creds, Route("1.2.3.4"))
693 1 Adrian Georgescu
reg.register()
694
}}}
695
696 29 Luci Stanescu
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.
697 1 Adrian Georgescu
698
=== Publication ===
699
700
Publication of SIP events is an Internet standard published at [http://tools.ietf.org/html/rfc3903 RFC 3903]. 
701
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.
702
703
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.
704
The state machine of this object is very similar to that of the {{{Registration}}} object, as can be seen in the following diagram:
705
706 2 Adrian Georgescu
[[Image(sipsimple-publication-state-machine.png, nolink)]]
707 1 Adrian Georgescu
708
State changes are triggered by the following events:
709
 1. The initial state.
710
 2. User requests in the form of the {{{publish()}}} and {{{unpublish()}}} methods.
711
 3. A final response for a {{{PUBLISH}}} is received from the network.
712
 4. The refresh timer expires.
713
Like the {{{Registration}}} state machine, the {{{Publication}}} state machine is queued.
714
This means that the application may call either the {{{publish()}}} or {{{unpublish()}}} method at any point in the state machine.
715
The object will perform the requested action when ready.
716
When some content is published and the application wants to update the contents, it can directly call the {{{publish()}}} method with the new content.
717
718
> The implementation of this object needs to be revised.
719
720
> If this object is re-used after unpublication, the etag value is not reset by PJSIP.
721
> This needs to be fixed.
722
723
==== attributes ====
724
725
 '''state'''::
726
  Indicates which state the internal state machine is in.
727
  This is one of {{{unpublished}}}, {{{publishing}}}, {{{published}}}, {{{unpublishing}}}.
728
 '''credentials'''::
729
  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.
730
  This attribute is set on object instantiation and is read-only.
731
 '''route'''::
732
  The outbound proxy to use in the form of a {{{Route}}} object.
733
  This attribute is set on object instantiation and is read-only.
734
 '''extra_headers'''::
735
  A dictionary of extra headers that should be added to any outgoing {{{PUBLISH}}} request.
736
  This attribute is set on object instantiation and is read-only.
737
 '''expires'''::
738
  The amount of seconds the contents of the {{{PUBLISH}}} are valid, i.e. the value that should be put in the {{{Expires}}} header.
739
  This attribute is set on object instantiation and can be modified at runtime.
740
  A new value will be used during the next refreshing {{{PUBLISH}}}.
741
742
==== methods ====
743
744 23 Ruud Klaver
 '''!__init!__'''(''self'', '''credentials''', '''event''', '''route''', '''expires'''=300, '''extra_headers'''={{{None}}})::
745 1 Adrian Georgescu
  Creates a new {{{Publication}}} object.
746
  [[BR]]''credentials'':[[BR]]
747
  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.
748
  [[BR]]''event'':[[BR]]
749
  The event package for which we want to publish content.
750
  [[BR]]''route'':[[BR]]
751
  The outbound proxy to use in the form of a {{{Route}}} object
752
  [[BR]]''expires'':[[BR]]
753
  The amount of seconds the contents of the {{{PUBLISH}}} are valid, i.e. the value that should be put in the {{{Expires}}} header.
754
  [[BR]]''extra_headers'':[[BR]]
755
  A dictionary of extra headers that should be added to any outgoing {{{PUBLISH}}} request.
756
 '''publish'''(''self'', '''content_type''', '''content_subtype''', '''body''')::
757
  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.
758
  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).
759
  If it is unsuccessful the state machine reverts to the {{{unregistered}}} state.
760
  [[BR]]''content_type'':[[BR]]
761
  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.
762
  [[BR]]''content_subtype'':[[BR]]
763
  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.
764
 '''unpublish'''(''self'')::
765
  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.
766
767
==== notifications ====
768
769 29 Luci Stanescu
 '''SIPPublicationChangedState'''::
770 1 Adrian Georgescu
  This notification will be sent every time the internal state machine of a {{{Publication}}} object changes state.
771
  [[BR]]''timestamp'':[[BR]]
772
  A {{{datetime.datetime}}} object indicating when the notification was sent.
773
  [[BR]]''state'':[[BR]]
774
  The new state the state machine moved into.
775
  [[BR]]''code'': (only on SIP response triggered state change)[[BR]]
776
  The status code of the response that caused the state change.
777
  This may be internally generated by PJSIP, e.g. on timeout.
778
  [[BR]]''reason'': (only on SIP response triggered state change)[[BR]]
779
  The status text of the response that caused the state change.
780
  This may be internally generated by PJSIP, e.g. on timeout.
781
782
> On init the event package is not checked with known event packages, this is only used for {{{Subscription}}} objects.
783
> This could be done for the sake of consistency.
784
785
==== example code ====
786
787
This code shows how to make a {{{Publication}}} object for a particular SIP account and have it attempt to publish its presence.
788
789
{{{
790
accnt = SIPURI(user="username", host="domain.com")
791
creds = Credentials(accnt, "password")
792 22 Ruud Klaver
pub = Publication(creds, "presence", Route("1.2.3.4"))
793 1 Adrian Georgescu
pub.publish("text", "plain", "hi!")
794
}}}
795
796 29 Luci Stanescu
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.
797 1 Adrian Georgescu
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.
798
799
=== Subscription ===
800
801
Subscription and notifications for SIP events is an Internet standard published at [http://tools.ietf.org/html/rfc3856 RFC 3856].
802
803
This SIP primitive class represents a subscription to a specific event type of a particular SIP URI.
804
This means that the application should instance this class for each combination of event and SIP URI that it wishes to subscribe to.
805
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.
806
Whenever a {{{NOTIFY}}} is received, the application will receive the {{{Subcription_notify}}} event.
807
808
Internally a {{{Subscription}}} object has a state machine, which reflects the state of the subscription.
809
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}}}.
810
The last three states are directly copied from the contents of the {{{Subscription-State}}} header of the received {{{NOTIFY}}} request.
811
Also, the state can be an arbitrary string if the contents of the {{{Subscription-State}}} header are not one of the three above.
812
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.
813
814
> The implementation of this object needs to be revised.
815
816
==== attributes ====
817
818
 '''state'''::
819
  Indicates which state the internal state machine is in.
820
  See the previous section for a list of states the state machine can be in.
821
 '''credentials'''::
822
  The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object.
823
  The {{{SIPURI}}} object included in the {{{Credentials}}} object is used for the {{{From}}} header of the {{{SUBSCRIBE}}} request.
824
  This attribute is set on object instantiation and is read-only.
825
 '''to_uri'''::
826
  The SIP URI we want to subscribe to a particular event of represented as a {{{SIPURI}}} object.
827
  This attribute is set on object instantiation and is read-only.
828
 '''event'''::
829
  The event package to which we want to subscribe at the given SIP URI.
830
  This attribute is set on object instantiation and is read-only.
831
 '''route'''::
832
  The outbound proxy to use in the form of a {{{Route}}} object.
833
  This attribute is set on object instantiation and is read-only.
834
 '''expires'''::
835
  The expires value that was requested on object instantiation.
836
  This attribute is read-only.
837
 '''extra_headers'''::
838
  A dictionary of extra headers that should be added to any outgoing {{{SUBSCRIBE}}} request.
839
  This attribute is set on object instantiation and is read-only.
840
841
==== methods ====
842
843 33 Ruud Klaver
 '''!__init!__'''(''self'', '''credentials''', '''to_uri''', '''event''', '''route''', '''expires'''=300, '''contact_uri'''={{{None}}}, '''extra_headers'''={{{None}}})::
844 1 Adrian Georgescu
  Creates a new {{{Subscription}}} object.
845
  [[BR]]''credentials'':[[BR]]
846
  The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object.
847
  The {{{SIPURI}}} object included in the {{{Credentials}}} object is used for the {{{From}}} header of the {{{SUBSCRIBE}}} request.
848
  [[BR]]''to_uri'':[[BR]]
849
  The SIP URI we want to subscribe to a particular event of represented as a {{{SIPURI}}} object.
850
  [[BR]]''event'':[[BR]]
851
  The event package to which we want to subscribe at the given SIP URI.
852
  [[BR]]''route'':[[BR]]
853
  The outbound proxy to use in the form of a {{{Route}}} object
854
  [[BR]]''expires'':[[BR]]
855
  The amount of seconds  the {{{SUBSCRIBE}}} is valid, i.e. the value that should be put in the {{{Expires}}} header.
856 33 Ruud Klaver
  [[BR]]''contact_uri'':[[BR]]
857
  The Contact URI that should be used in the {{{SUBSCRIBE}}} requests.
858
  If this is {{{None}}}, a Contact URI will be generated internally.
859 1 Adrian Georgescu
  [[BR]]''extra_headers'':[[BR]]
860
  A dictionary of extra headers that should be added to any outgoing {{{SUBSCRIBE}}} request.
861
 '''subscribe'''(''self'')::
862
  This method activates the subscription and causes the object to send a {{{SUBSCRIBE}}} request to the relevant presence agent.
863
  It can only be used when the object is in the {{{TERMINATED}}} state.
864
 '''unsubscribe'''(''self'')::
865
  This method causes the object to send a {{{SUBSCRIBE}}} request with an {{{Expires}}} value of 0, effectively canceling the active subscription.
866
  It can be used when the object is not in the {{{TERMINATED}}} state.
867
868
==== notifications ====
869
870 29 Luci Stanescu
 '''SIPSubscriptionChangedState'''::
871 1 Adrian Georgescu
  This notification will be sent every time the internal state machine of a {{{Subscription}}} object changes state.
872
  [[BR]]''timestamp'':[[BR]]
873
  A {{{datetime.datetime}}} object indicating when the notification was sent.
874
  [[BR]]''state'':[[BR]]
875
  The new state the state machine moved into.
876
  [[BR]]''code'': (only on SIP response triggered state change)[[BR]]
877
  The status code of the response that caused the state change.
878
  This may be internally generated by PJSIP, e.g. on timeout.
879
  [[BR]]''reason'': (only on SIP response triggered state change)[[BR]]
880
  The status text of the response that caused the state change.
881
  This may be internally generated by PJSIP, e.g. on timeout.
882 29 Luci Stanescu
 '''SIPSubscriptionGotNotify'''::
883 1 Adrian Georgescu
  This notification will be sent when a {{{NOTIFY}}} is received that corresponds to a particular {{{Subscription}}} object.
884
  Note that this notification will not be sent when a {{{NOTIFY}}} with an empty body is received.
885
  [[BR]]''timestamp'':[[BR]]
886
  A {{{datetime.datetime}}} object indicating when the notification was sent.
887
  [[BR]]''content_type'':[[BR]]
888
  The first part of the {{{Content-Type:}}} header of the received {{{NOTIFY}}} request (before the {{{/}}}), indicating the type of the body.
889
  [[BR]]''content_subtype'':[[BR]]
890
  The second part of the {{{Content-Type:}}} header of the received {{{NOTIFY}}} request (after the {{{/}}}), indicating the type of the body.
891
  [[BR]]''body'':[[BR]]
892
  The body of the {{{NOTIFY}}} request.
893
894
==== example code ====
895
896
This code shows how to make a {{{Subscription}}} object that subscribes to the presence of another SIP account.
897
898
{{{
899
accnt = SIPURI(user="watcher", host="domain.com")
900
creds = Credentials(accnt, "password")
901
to_uri = SIPURI(user="watched", host="domain.com")
902 22 Ruud Klaver
sub = Subscription(creds, to_uri, "presence", Route("1.2.3.4"))
903 1 Adrian Georgescu
sub.subscribe()
904
}}}
905
906 29 Luci Stanescu
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.
907
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.
908 1 Adrian Georgescu
909
=== Invitation ===
910
911
The {{{Invitation}}} class represents an {{{INVITE}}} session, which governs a complete session of media exchange between two SIP endpoints from start to finish.
912
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.
913
The {{{Invitation}}} class represents both incoming and outgoing sessions.
914
915
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.
916
In order to represent re-{{{INVITE}}}s and user-requested disconnections, three more states have been added to this state machine.
917
The progression through this state machine is fairly linear and is dependent on whether this is an incoming or an outgoing session.
918
State changes are triggered either by incoming or by outgoing SIP requests and responses.
919
The states and the transitions between them are shown in the following diagram:
920
921
[[Image(sipsimple-core-invite-state-machine.png, nolink)]]
922
923
The state changes of this machine are triggered by the following:
924
 1. An {{{Invitation}}} object is newly created, either by the application for an outgoing session, or by the core for an incoming session.
925
 2. The application requested an outgoing session by calling the {{{send_invite()}}} method and and initial {{{INVITE}}} request is sent.
926
 3. A new incoming session is received by the core.
927
    The application should look out for state change to this state in order to be notified of new incoming sessions.
928
 4. A provisional response (1xx) is received from the remove party.
929
 5. A provisional response (1xx) is sent to the remote party, after the application called the {{{respond_to_invite_provisionally()}}} method.
930
 6. A positive final response (2xx) is received from the remote party.
931
 7. A positive final response (2xx) is sent to the remote party, after the application called the {{{accept_invite()}}} method.
932
 8. A positive final response (2xx) is sent or received, depending on the orientation of the session.
933
 9. An {{{ACK}}} is sent or received, depending on the orientation of the session.
934
    If the {{{ACK}}} is sent from the local to the remote party, it is initiated by PJSIP, not by a call from the application.
935
 10. The local party sent a re-{{{INVITE}}} to the remote party by calling the {{{send_reinvite()}}} method.
936
 11. The remote party has sent a final response to the re-{{{INVITE}}}.
937
 12. The remote party has sent a re-{{{INVITE}}}.
938
 13. The local party has responded to the re-{{{INVITE}}} by calling the {{{respond_to_reinvite()}}} method.
939
 14. The application requests that the session ends by calling the {{{disconnect()}}} method.
940
 15. A response is received from the remote party to whichever message was sent by the local party to end the session.
941
 16. A message is received from the remote party which ends the session.
942
943 29 Luci Stanescu
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.
944 1 Adrian Georgescu
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.
945
The application should compare the previous and current states and perform the appropriate action.
946
947 29 Luci Stanescu
An {{{Invitiation}}} object also emits the {{{SIPInvitationGotSDPUpdate}}} notification, which indicates that SDP negotiation between the two parties has been completed.
948 1 Adrian Georgescu
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.
949
In the last case, the {{{Invitation}}} object will automatically include the current local SDP in the response.
950
951
==== attributes ====
952
953
 '''state'''::
954
  The state the {{{Invitation}}} state machine is currently in.
955
  See the diagram above for possible states.
956
  This attribute is read-only.
957
 '''is_outgoing'''::
958
  Boolean indicating if the original {{{INVITE}}} was outgoing, or incoming if set to {{{False}}}.
959
 '''credentials'''::
960
  The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object.
961
  If this {{{Invitation}}} object represents an incoming {{{INVITE}}} session this attribute will be {{{None}}}.
962
  This attribute is set on object instantiation and is read-only.
963
 '''caller_uri'''::
964
  The SIP URI of the caller represented by a {{{SIPURI}}} object.
965
  If this is in an outgoing {{{INVITE}}} session, the caller_uri is taken from the supplied {{{Credentials}}} object.
966
  Otherwise the URI is taken from the {{{From:}}} header of the initial {{{INVITE}}}.
967
  This attribute is set on object instantiation and is read-only.
968
 '''callee_uri'''::
969
  The SIP URI of the callee represented by a {{{SIPURI}}} object.
970
  If this is an outgoing {{{INVITE}}} session, this is the callee_uri from the !__init!__ method.
971
  Otherwise the URI is taken from the {{{To:}}} header of the initial {{{INVITE}}}.
972
  This attribute is set on object instantiation and is read-only.
973
 '''local_uri'''::
974
  The local SIP URI used in this session.
975
  If the original {{{INVITE}}} was incoming, this is the same as {{{callee_uri}}}, otherwise it will be the same as {{{caller_uri}}}.
976
 '''remote_uri'''::
977
  The SIP URI of the remote party in this session.
978
  If the original {{{INVITE}}} was incoming, this is the same as {{{caller_uri}}}, otherwise it will be the same as {{{callee_uri}}}.
979
 '''route'''::
980
  The outbound proxy that was requested to be used in the form of a {{{Route}}} object, including the desired transport.
981
  If this {{{Invitation}}} object represents an incoming {{{INVITE}}} session this attribute will always be {{{None}}}.
982
  This attribute is set on object instantiation and is read-only.
983
 '''call_id'''::
984
  The call ID of the {{{INVITE}}} session as a read-only string.
985
  In the {{{NULL}}} and {{{DISCONNECTED}}} states, this attribute is {{{None}}}.
986 33 Ruud Klaver
 '''transport'''::
987
  A string indicating the transport used for the application.
988
  This can be "udp", "tcp" or "tls".
989
 '''local_contact_uri'''::
990
  The Contact URI that the local side provided to the remote side within this {{{INVITE}}} session as a {{{SIPURI}}} object.
991 1 Adrian Georgescu
992
==== methods ====
993
994 33 Ruud Klaver
 '''!__init!__'''(''self'', '''credentials''', '''callee_uri''', '''route''', '''contact_uri'''={{{None}}})::
995 1 Adrian Georgescu
  Creates a new {{{Invitation}}} object for an outgoing session.
996
  [[BR]]''credentials'':[[BR]]
997 22 Ruud Klaver
  The SIP credentials needed to authenticate at the SIP proxy in the form of a {{{Credentials}}} object.
998 1 Adrian Georgescu
  The {{{SIPURI}}} object included in the {{{Credentials}}} object is used for the {{{From}}} header of the {{{INVITE}}} request.
999
  [[BR]]''callee_uri'':[[BR]]
1000
  The SIP URI we want to send the {{{INVITE}}} to, represented as a {{{SIPURI}}} object.
1001
  [[BR]]''route'':[[BR]]
1002
  The outbound proxy to use in the form of a {{{Route}}} object.
1003
  This includes the desired transport to use.
1004 33 Ruud Klaver
  [[BR]]''contact_uri'':[[BR]]
1005
  The Contact URI to include in the {{{INVITE}}} request, a {{{SIPURI}}} object.
1006
  If this is {{{None}}}, a Contact URI will be internally generated.
1007 1 Adrian Georgescu
 '''get_active_local_sdp'''(''self'')::
1008
  Returns a new {{{SDPSession}}} object representing the currently active local SDP.
1009
  If no SDP was negotiated yet, this returns {{{None}}}.
1010
 '''get_active_remote_sdp'''(''self'')::
1011
  Returns a new {{{SDPSession}}} object representing the currently active local SDP.
1012
  If no SDP was negotiated yet, this returns {{{None}}}.
1013
 '''get_offered_local_sdp'''(''self'')::
1014
  Returns a new {{{SDPSession}}} object representing the currently proposed local SDP.
1015
  If no local offered SDP has been set, this returns {{{None}}}.
1016
 '''set_offered_local_sdp'''(''self'', '''local_sdp''')::
1017
  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}}}.
1018
  [[BR]]''local_sdp'':[[BR]]
1019
  The SDP to send as offer or answer to the remote party.
1020
 '''get_offered_remote_sdp'''(''self'')::
1021
  Returns a new {{{SDPSession}}} object representing the currently proposed remote SDP.
1022
  If no remote SDP has been offered in the current state, this returns {{{None}}}.
1023
 '''send_invite'''(''self'', '''extra_headers'''={{{None}}})::
1024
  This tries to move the state machine into the {{{CALLING}}} state by sending the initial {{{INVITE}}} request.
1025
  It may only be called from the {{{NULL}}} state on an outgoing {{{Invitation}}} object.
1026
  [[BR]]''extra_headers'':[[BR]]
1027
  Any extra headers that should be included in the {{{INVITE}}} request in the form of a dict.
1028
 '''respond_to_invite_provisionally'''(''self'', '''response_code'''=180, '''extra_headers'''={{{None}}})::
1029
  This tries to move the state machine into the {{{EARLY}}} state by sending a provisional response to the initial {{{INVITE}}}.
1030
  It may only be called from the {{{INCOMING}}} state on an incoming {{{Invitation}}} object.
1031
  [[BR]]''response_code'':[[BR]]
1032
  The code of the provisional response to use as an int.
1033
  This should be in the 1xx range.
1034
  [[BR]]''extra_headers'':[[BR]]
1035
  Any extra headers that should be included in the response in the form of a dict.
1036
 '''accept_invite'''(''self'', '''extra_headers'''={{{None}}})::
1037
  This tries to move the state machine into the {{{CONNECTING}}} state by sending a 200 OK response to the initial {{{INVITE}}}.
1038
  It may only be called from the {{{INCOMING}}} or {{{EARLY}}} states on an incoming {{{Invitation}}} object.
1039
  [[BR]]''extra_headers'':[[BR]]
1040
  Any extra headers that should be included in the response in the form of a dict.
1041 41 Ruud Klaver
 '''disconnect'''(''self'', '''response_code'''=603, '''extra_headers'''={{{None}}}, '''timeout'''={{{None}}})::
1042 1 Adrian Georgescu
  This moves the {{{INVITE}}} state machine into the {{{DISCONNECTING}}} state by sending the necessary SIP message.
1043
  When a response from the remote party is received, the state machine will go into the {{{DISCONNECTED}}} state.
1044
  Depending on the current state, this could be a CANCEL or BYE request or a negative response.
1045
  [[BR]]''response_code'':[[BR]]
1046
  The code of the response to use as an int, if transmission of a response is needed.
1047
  [[BR]]''extra_headers'':[[BR]]
1048
  Any extra headers that should be included in the request or response in the form of a dict.
1049 41 Ruud Klaver
  [[BR]]''timeout'':[[BR]]
1050
  How many seconds to wait for the remote party to reply before changing the state to {{{DISCONNECTED}}}, as an int or a float.
1051
  If this is set to {{{None}}}, the default PJSIP timeout will be used, which currently appears to be 3.5 seconds.
1052 33 Ruud Klaver
 '''respond_to_reinvite'''(''self'', '''response_code'''=200, '''extra_headers'''={{{None}}})::
1053 1 Adrian Georgescu
  Respond to a received re-{{{INVITE}}} with a response that is either provisional (1xx), positive (2xx) or negative (3xx and upwards).
1054
  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.
1055
  Before giving a positive final response, the SDP needs to be set using the {{{set_offered_local_sdp()}}} method.
1056
  [[BR]]''response_code'':[[BR]]
1057
  The code of the response to use as an int.
1058
  This should be a 3 digit number.
1059
  [[BR]]''extra_headers'':[[BR]]
1060
 '''send_reinvite'''(''self'', '''extra_headers'''={{{None}}})::
1061
  The application may only call this method when the state machine is in the {{{CONFIRMED}}} state to induce sending a re-{{{INVITE}}}.
1062
  Before doing this it needs to set the new local SDP offer by calling the {{{set_offered_local_sdp()}}} method.
1063
  After this method is called, the state machine will be in the {{{REINVITING}}} state, until a final response from the remote party is received.
1064
  [[BR]]''extra_headers'':[[BR]]
1065
  Any extra headers that should be included in the re-{{{INVITE}}} in the form of a dict.
1066
1067
==== notifications ====
1068
1069 29 Luci Stanescu
 '''SIPInvitationChangedState'''::
1070 1 Adrian Georgescu
  This notification is sent by an {{{Invitation}}} object whenever its state machine changes state.
1071
  [[BR]]''timestamp'':[[BR]]
1072
  A {{{datetime.datetime}}} object indicating when the notification was sent.
1073
  [[BR]]''prev_state'':[[BR]]
1074
  The previous state of the INVITE state machine.
1075
  [[BR]]''state'':[[BR]]
1076
  The new state of the INVITE state machine, which may be the same as the previous state.
1077
  [[BR]]''method'': (only if the state change got triggered by an incoming SIP request)[[BR]]
1078
  The method of the SIP request as a string.
1079
  [[BR]]''request_uri'': (only if the state change got triggered by an incoming SIP request)[[BR]]
1080
  The request URI of the SIP request as a {{{SIPURI}}} object.
1081
  [[BR]]''code'': (only if the state change got triggered by an incoming SIP response or internal timeout or error)[[BR]]
1082
  The code of the SIP response or error as an int.
1083
  [[BR]]''reason'': (only if the state change got triggered by an incoming SIP response or internal timeout or error)[[BR]]
1084
  The reason text of the SIP response or error as an int.
1085
  [[BR]]''headers'': (only if the state change got triggered by an incoming SIP request or response)[[BR]]
1086
  The headers of the SIP request or response as a dict.
1087
  Each SIP header is represented in its parsed for as long as PJSIP supports it.
1088
  The format of the parsed value depends on the header.
1089
  [[BR]]''body'': (only if the state change got triggered by an incoming SIP request or response)[[BR]]
1090
  The body of the SIP request or response as a string, or {{{None}}} if no body was included.
1091
  The content type of the body can be learned from the {{{Content-Type:}}} header in the headers argument.
1092 29 Luci Stanescu
 '''SIPInvitationGotSDPUpdate'''::
1093 1 Adrian Georgescu
  This notification is sent by an {{{Invitation}}} object whenever SDP negotation has been perfomed.
1094
  It should be used by the application as an indication to start, change or stop any associated media streams.
1095
  [[BR]]''timestamp'':[[BR]]
1096
  A {{{datetime.datetime}}} object indicating when the notification was sent.
1097
  [[BR]]''succeeded'':[[BR]]
1098
  A boolean indicating if the SDP negotation has succeeded.
1099
  [[BR]]''error'': (only if SDP negotation did not succeed)[[BR]]
1100
  A string indicating why SDP negotation failed.
1101
  [[BR]]''local_sdp'': (only if SDP negotation succeeded)[[BR]]
1102
  A SDPSession object indicating the local SDP that was negotiated.
1103
  [[BR]]''remote_sdp'': (only if SDP negotation succeeded)[[BR]]
1104
  A SDPSession object indicating the remote SDP that was negotiated.
1105
1106
=== SDPSession ===
1107
1108
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. 
1109
1110
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.
1111
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.
1112
A {{{SDPSession}}} object may contain {{{SDPMedia}}}, {{{SDPConnection}}} and {{{SDPAttribute}}} objects.
1113
It supports comparison to other {{{SDPSession}}} objects using the == and != expressions.
1114
As all the attributes of the {{{SDPSession}}} class are set by attributes of the {{{__init__}}} method, they will be documented along with that method.
1115
1116
==== methods ====
1117
1118 23 Ruud Klaver
 '''!__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}}})::
1119 1 Adrian Georgescu
  Creates the SDPSession object with the specified parameters as attributes.
1120
  Each of these attributes can be accessed and changed on the object once instanced.
1121
  [[BR]]''address'':[[BR]]
1122
  The address that is contained in the "o" (origin) line of the SDP as a string.
1123
  [[BR]]''id'':[[BR]]
1124
  The session identifier contained in the "o" (origin) line of the SDP as an int.
1125
  If this is set to {{{None}}} on init, a session identifier will be generated.
1126
  [[BR]]''version'':[[BR]]
1127
  The version identifier contained in the "o" (origin) line of the SDP as an int.
1128
  If this is set to {{{None}}} on init, a version identifier will be generated.
1129
  [[BR]]''user'':[[BR]]
1130
  The user name contained in the "o" (origin) line of the SDP as a string.
1131
  [[BR]]''net_type'':[[BR]]
1132
  The network type contained in the "o" (origin) line of the SDP as a string.
1133
  [[BR]]''address_type'':[[BR]]
1134
  The address type contained in the "o" (origin) line of the SDP as a string.
1135
  [[BR]]''name'':[[BR]]
1136
  The contents of the "s" (session name) line of the SDP as a string.
1137
  [[BR]]''info'':[[BR]]
1138
  The contents of the session level "i" (information) line of the SDP as a string.
1139
  If this is {{{None}}} or an empty string, the SDP has no "i" line.
1140
  [[BR]]''connection'':[[BR]]
1141
  The contents of the "c" (connection) line of the SDP as a {{{SDPConnection}}} object.
1142
  If this is set to {{{None}}}, the SDP has no session level "c" line.
1143
  [[BR]]''start_time'':[[BR]]
1144
  The first value of the "t" (time) line of the SDP as an int.
1145
  [[BR]]''stop_time'':[[BR]]
1146
  The second value of the "t" (time) line of the SDP as an int.
1147
  [[BR]]''attributes'':[[BR]]
1148
  The session level "a" lines (attributes) in the SDP represented by a list of {{{SDPAttribute}}} objects.
1149
  [[BR]]''media'':[[BR]]
1150
  The media sections of the SDP represented by a list of {{{SDPMedia}}} objects.
1151
1152
=== SDPMedia ===
1153
1154
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.
1155
It is a simple wrapper for the PJSIP [http://www.pjsip.org/pjmedia/docs/html/structpjmedia__sdp__media.htm pjmedia_sdp_media] structure.
1156
One or more {{{SDPMedia}}} objects are usually contained in a {{{SDPSession}}} object.
1157
It supports comparison to other {{{SDPMedia}}} objects using the == and != expressions.
1158
As all the attributes of this class are set by attributes of the {{{__init__}}} method, they will be documented along with that method.
1159
1160
==== methods ====
1161
1162 24 Ruud Klaver
 '''!__init!__'''(''self'', '''media''', '''port''', '''transport''', '''port_count'''=1, '''formats'''={{{None}}}, '''info'''={{{None}}}, '''connection'''={{{None}}}, '''attributes'''={{{None}}})::
1163 1 Adrian Georgescu
  Creates the SDPMedia object with the specified parameters as attributes.
1164
  Each of these attributes can be accessed and changed on the object once instanced.
1165
  [[BR]]''media'':[[BR]]
1166
  The media type contained in the "m" (media) line as a string.
1167
  [[BR]]''port'':[[BR]]
1168
  The transport port contained in the "m" (media) line as an int.
1169
  [[BR]]''transport'':[[BR]]
1170
  The transport protocol in the "m" (media) line as a string.
1171
  [[BR]]''port_count'':[[BR]]
1172
  The port count in the "m" (media) line as an int.
1173
  If this is set to 1, it is not included in the SDP.
1174
  [[BR]]''formats'':[[BR]]
1175
  The media formats in the "m" (media) line represented by a list of strings.
1176
  [[BR]]''info'':[[BR]]
1177
  The contents of the "i" (information) line of this media section as a string.
1178
  If this is {{{None}}} or an empty string, the media section has no "i" line.
1179
  [[BR]]''connection'':[[BR]]
1180
  The contents of the "c" (connection) line that is somewhere below the "m" line of this section as a {{{SDPConnection}}} object.
1181
  If this is set to {{{None}}}, this media section has no "c" line.
1182
  [[BR]]''attributes'':[[BR]]
1183
  The "a" lines (attributes) that are somewhere below the "m" line of this section represented by a list of {{{SDPAttribute}}} objects.
1184
 '''get_direction'''(''self'')::
1185
  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".
1186
  If none of these attributes is present, the default direction is "sendrecv".
1187
1188
=== SDPConnection ===
1189
1190
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.
1191
It is a simple wrapper for the PJSIP [http://www.pjsip.org/pjmedia/docs/html/structpjmedia__sdp__conn.htm pjmedia_sdp_conn] structure.
1192
A {{{SDPConnection}}} object can be contained in a {{{SDPSession}}} object or {{{SDPMedia}}} object.
1193
It supports comparison to other {{{SDPConnection}}} objects using the == and != expressions.
1194
As all the attributes of this class are set by attributes of the {{{__init__}}} method, they will be documented along with that method.
1195
1196
==== methods ====
1197
1198
 '''!__init!__'''(''self'', '''address''', '''net_type'''="IN", '''address_type'''="IP4")::
1199
  Creates the SDPConnection object with the specified parameters as attributes.
1200
  Each of these attributes can be accessed and changed on the object once instanced.
1201
  [[BR]]''address'':[[BR]]
1202
  The address part of the connection line as a string.
1203
  [[BR]]''net_type'':[[BR]]
1204
  The network type part of the connection line as a string.
1205
  [[BR]]''address_type'':[[BR]]
1206
  The address type part of the connection line as a string.
1207
1208
=== SDPAttribute ===
1209
1210
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.
1211
It is a simple wrapper for the PJSIP [http://www.pjsip.org/pjmedia/docs/html/structpjmedia__sdp__attr.htm pjmedia_sdp_attr] structure.
1212
One or more {{{SDPAttribute}}} objects can be contained in a {{{SDPSession}}} object or {{{SDPMedia}}} object.
1213
It supports comparison to other {{{SDPAttribute}}} objects using the == and != expressions.
1214
As all the attributes of this class are set by attributes of the {{{__init__}}} method, they will be documented along with that method.
1215
1216
==== methods ====
1217
1218
 '''!__init!__'''(''self'', '''name''', '''value''')::
1219
  Creates the SDPAttribute object with the specified parameters as attributes.
1220
  Each of these attributes can be accessed and changed on the object once instanced.
1221
  [[BR]]''name'':[[BR]]
1222
  The name part of the attribute line as a string.
1223
  [[BR]]''value'':[[BR]]
1224
  The value part of the attribute line as a string.
1225
1226
=== RTPTransport ===
1227
1228
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.
1229
Internally it wraps a [http://www.pjsip.org/pjmedia/docs/html/group__PJMEDIA__TRANSPORT.htm pjmedia_transport] object.
1230
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].
1231
For this reason the {{{AudioTransport}}} and {{{RTPTransport}}} are two distinct objects.
1232
1233
The {{{RTPTransport}}} object also allows support for ICE and SRTP functionality from PJSIP.
1234
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.
1235
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.
1236
This process of SDP negotiation is represented by the internal state machine of the object, as shown in the following diagram:
1237
1238
> The Real-time Transport Protocol (or RTP) defines a standardized packet format for delivering audio and video over the Internet.
1239
> It was developed by the Audio-Video Transport Working Group of the IETF and published in [http://tools.ietf.org/html/rfc3550 RFC 3550].
1240
> RTP is used in streaming media systems (together with the RTSP) as well as in videoconferencing and push to talk systems.
1241
> 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.
1242
1243 18 Adrian Georgescu
[[Image(sipsimple-rtp-transport-state-machine.png, nolink)]]
1244 1 Adrian Georgescu
1245
State changes are triggered by the following events:
1246 17 Ruud Klaver
 1. The application calls the {{{set_INIT()}}} method after object creation and ICE+STUN is not used.
1247
 2. The application calls the {{{set_INIT()}}} method after object creation and ICE+STUN is used.
1248
 3. A successful STUN response is received from the STUN server.
1249
 4. The {{{set_LOCAL()}}} method is called.
1250
 5. The {{{set_ESTABLISHED()}}} method is called.
1251
 6. The {{{set_INIT()}}} method is called while the object is in the {{{LOCAL}}} or {{{ESTABLISHED}}} state.
1252
 7. A method is called on the application, but in the meantime the {{{Engine}}} has stopped.
1253
    The object can no longer be used.
1254
 8. There was an error in getting the STUN candidates from the STUN server.
1255 1 Adrian Georgescu
1256
> 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.
1257
> This means that the RTPTransport object is also unusable once it has reached the STUN_FAILED state.
1258
> A workaround would be destroy the RTPTransport object and create a new one that uses ICE without STUN.
1259
1260
These states allow for two SDP negotiation scenarios to occur, represented by two paths that can be followed through the state machine.
1261
In this example we will assume that ICE with STUN is not used, as it is independent of the SDP negotiation procedure.
1262
 * The first scenario is where the local party generates the SDP offer.
1263
   For a stream that it wishes to include in this SDP offer, it instantiates a {{{RTPTransport}}} object.
1264 17 Ruud Klaver
   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).
1265 1 Adrian Georgescu
   This local SDP then needs to be passed to the {{{set_LOCAL()}}} method, which moves the state machine into the {{{LOCAL}}} state.
1266
   Depending on the options used for the {{{RTPTransport}}} instantiation (such as ICE and SRTP), this may change the {{{SDPSession}}} object.
1267
   This (possibly changed) {{{SDPSession}}} object then needs to be passed to the {{{Invitation}}} object.
1268
   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.
1269
   This will not change either of the {{{SDPSession}}} objects.
1270
 * The second scenario is where the local party is offered a media stream in SDP and wants to accept it.
1271 17 Ruud Klaver
   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.
1272 1 Adrian Georgescu
   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.
1273
   In this case the local SDP object may be changed, after which it can be passed to the {{{Invitation}}} object.
1274
1275
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.
1276
Before doing this however, the internal transport object must no longer be in use.
1277
1278
==== attributes ====
1279
1280
 '''state'''::
1281
  Indicates which state the internal state machine is in.
1282
  See the previous section for a list of states the state machine can be in.
1283
  This attribute is read-only.
1284
 '''local_rtp_address'''::
1285 45 Ruud Klaver
  The local IPv4 address of the interface the {{{RTPTransport}}} object is listening on and the address that should be included in the SDP.
1286 1 Adrian Georgescu
  If no address was specified during object instantiation, PJSIP will take guess out of the IP addresses of all interfaces.
1287
  This attribute is read-only and will be {{{None}}} if PJSIP is not listening on the transport.
1288
 '''local_rtp_port'''::
1289
  The UDP port PJSIP is listening on for RTP traffic.
1290
  RTCP traffic will always be this port plus one.
1291
  This attribute is read-only and will be {{{None}}} if PJSIP is not listening on the transport.
1292
 '''remote_rtp_address_sdp'''::
1293
  The remote IP address that was seen in the SDP.
1294
  This attribute is read-only and will be {{{None}}} unless the object is in the {{{ESTABLISHED}}} state.
1295
 '''remote_rtp_port_sdp'''::
1296
  The remote UDP port for RTP that was seen in the SDP.
1297
  This attribute is read-only and will be {{{None}}} unless the object is in the {{{ESTABLISHED}}} state.
1298
 '''remote_rtp_address_received'''::
1299
  The remote IP address from which RTP data was received.
1300
  This attribute is read-only and will be {{{None}}} unless RTP was actually received.
1301
 '''remote_rtp_port_received'''::
1302
  The remote UDP port from which RTP data was received.
1303
  This attribute is read-only and will be {{{None}}} unless RTP was actually received.
1304
 '''use_srtp'''::
1305
  A boolean indicating if the use of SRTP was requested when the object was instantiated.
1306
  This attribute is read-only.
1307
 '''force_srtp'''::
1308
  A boolean indicating if SRTP being mandatory for this transport if it is enabled was requested when the object was instantiated.
1309
  This attribute is read-only.
1310
 '''srtp_active'''::
1311
  A boolean indicating if SRTP encryption and decryption is running.
1312
  Querying this attribute only makes sense once the object is in the {{{ESTABLISHED}}} state and use of SRTP was requested.
1313
  This attribute is read-only.
1314
 '''use_ice'''::
1315
  A boolean indicating if the use of ICE was requested when the object was instantiated.
1316
  This attribute is read-only.
1317
 '''ice_stun_address'''::
1318 19 Ruud Klaver
  A string indicating the IP address of the STUN server that was requested to be used.
1319 1 Adrian Georgescu
  This attribute is read-only.
1320
 '''ice_stun_port'''::
1321
  A string indicating the UDP port of the STUN server that was requested to be used.
1322
  This attribute is read-only.
1323
1324
==== methods ====
1325
1326
 '''!__init!__'''(''self'', '''local_rtp_address'''={{{None}}}, '''use_srtp'''={{{False}}}, '''srtp_forced'''={{{False}}}, '''use_ice'''={{{False}}}, '''ice_stun_address'''={{{None}}}, '''ice_stun_port'''=3478)::
1327
  Creates a new {{{RTPTransport}}} object and opens the RTP and RTCP UDP sockets.
1328
  If aditional features are requested, they will be initialized.
1329
  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.
1330
  [[BR]]''local_rtp_address'':[[BR]]
1331 45 Ruud Klaver
  Optionally contains the local IPv4 address to listen on.
1332 1 Adrian Georgescu
  If this is not specified, PJSIP will listen on all network interfaces.
1333
  [[BR]]''use_srtp'':[[BR]]
1334
  A boolean indicating if SRTP should be used.
1335
  If this is set to {{{True}}}, SRTP information will be added to the SDP when it passes this object.
1336
  [[BR]]''srtp_forced'':[[BR]]
1337
  A boolean indicating if use of SRTP is set to mandatory in the SDP.
1338
  If this is set to {{{True}}} and the remote party does not support SRTP, the SDP negotation for this stream will fail.
1339
  This argument is relevant only if {{{use_srtp}}} is set to {{{True}}}.
1340
  [[BR]]''use_ice'':[[BR]]
1341
  A boolean indicating if ICE should be used.
1342
  If this is set to {{{True}}}, ICE candidates will be added to the SDP when it passes this object.
1343
  [[BR]]''ice_stun_address'':[[BR]]
1344
  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.
1345
  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.
1346 29 Luci Stanescu
  When this happens a {{{RTPTransportGotSTUNResponse}}} notification is sent.
1347 1 Adrian Georgescu
  This argument is relevant only if {{{use_ice}}} is set to {{{True}}}.
1348
  [[BR]]''ice_stun_address'':[[BR]]
1349
  An int indicating the UDP port of the STUN server that should be used to add a STUN candidate to the ICE candidates.
1350
  This argument is relevant only if {{{use_ice}}} is set to {{{True}}} and {{{ice_stun_address}}} is not {{{None}}}.
1351 34 Ruud Klaver
 '''set_INIT'''(''self'')::
1352
  This moves the internal state machine into the {{{INIT}}} state.
1353
  If the state machine is in the {{{LOCAL}}} or {{{ESTABLISHED}}} states, this effectively resets the {{{RTPTransport}}} object for re-use.
1354
 '''set_LOCAL'''(''self'', '''local_sdp''', '''sdp_index''')::
1355 1 Adrian Georgescu
  This moves the the internal state machine into the {{{LOCAL}}} state.
1356
  [[BR]]''local_sdp'':[[BR]]
1357
  The local SDP to be proposed in the form of a {{{SDPSession}}} object.
1358
  Note that this object may be modified by this method.
1359
  [[BR]]''sdp_index'':[[BR]]
1360
  The index in the SDP for the media stream for which this object was created.
1361 34 Ruud Klaver
 '''set_ESTABLISHED'''(''self'', '''local_sdp''', '''remote_sdp''', '''sdp_index''')::
1362 1 Adrian Georgescu
  This moves the the internal state machine into the {{{ESTABLISHED}}} state.
1363
  [[BR]]''local_sdp'':[[BR]]
1364
  The local SDP to be proposed in the form of a {{{SDPSession}}} object.
1365
  Note that this object may be modified by this method, but only when moving from the {{{LOCAL}}} to the {{{ESTABLISHED}}} state.
1366
  [[BR]]''remote_sdp'':[[BR]]
1367
  The remote SDP that was received in in the form of a {{{SDPSession}}} object.
1368 17 Ruud Klaver
  [[BR]]''sdp_index'':[[BR]]
1369
  The index in the SDP for the media stream for which this object was created.
1370 1 Adrian Georgescu
1371
==== notifications ====
1372
1373 29 Luci Stanescu
 '''RTPTransportDidInitialize'''::
1374 17 Ruud Klaver
  This notification is sent when a {{{RTPTransport}}} object has successfully initialized.
1375
  If STUN+ICE is not requested, this is sent immediately on {{{set_INIT()}}}, otherwise it is sent after the STUN query has succeeded.
1376 1 Adrian Georgescu
  [[BR]]''timestamp'':[[BR]]
1377
  A {{{datetime.datetime}}} object indicating when the notification was sent.
1378 29 Luci Stanescu
 '''RTPTransportDidFail'''::
1379 17 Ruud Klaver
  This notification is sent by a {{{RTPTransport}}} object that fails to retrieve ICE candidates from the STUN server after {{{set_INIT()}}} is called.
1380
  [[BR]]''timestamp'':[[BR]]
1381
  A {{{datetime.datetime}}} object indicating when the notification was sent.
1382
  [[BR]]''reason'':[[BR]]
1383
  A string describing the failure reason.
1384 1 Adrian Georgescu
1385
=== AudioTransport ===
1386
1387
This object represent an audio stream as it is transported over the network.
1388
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.
1389
It also generates a {{{SDPMedia}}} object to be included in the local SDP.
1390
1391
Like the {{{RTPTransport}}} object there are two usage scenarios.
1392
 * In the first scenario, only the {{{RTPTransport}}} instance to be used is passed to the AudioTransport object.
1393
   The application can then generate the {{{SDPMedia}}} object by calling the {{{get_local_media()}}} method and should include it in the SDP offer.
1394
   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.
1395
   The stream can then be connected to the conference bridge.
1396
 * 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.
1397
   The local {{{SDPMedia}}} object can again be generated by calling the {{{get_local_media()}}} method and is to be included in the SDP answer.
1398
   The audio stream is started directly when the object is created.
1399
1400
Unlike the {{{RTPTransport}}} object, this object cannot be reused.
1401
1402
==== attributes ====
1403
1404
 '''transport'''::
1405
  The {{{RTPTransport}}} object that was passed when the object got instatiated.
1406
  This attribute is read-only.
1407
 '''is_active'''::
1408
  A boolean indicating if the object is currently sending and receiving audio.
1409
  This attribute is read-only.
1410
 '''is_started'''::
1411
  A boolean indicating if the object has been started.
1412
  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.
1413
  This is to prevent the object from being re-used.
1414
  This attribute is read-only.
1415
 '''codec'''::
1416
  Once the SDP negotiation is complete, this attribute indicates the audio codec that was negotiated, otherwise it will be {{{None}}}.
1417
  This attribute is read-only.
1418
 '''sample_rate'''::
1419
  Once the SDP negotiation is complete, this attribute indicates the sample rate of the audio codec that was negotiated, otherwise it will be {{{None}}}.
1420
  This attribute is read-only.
1421
 '''direction'''::
1422
  The current direction of the audio transport, which is one of "sendrecv", "sendonly", "recvonly" or "inactive".
1423
  This attribute is read-only, although it can be set using the {{{update_direction()}}} method.
1424
1425
==== methods ====
1426
1427 40 Ruud Klaver
 '''!__init!__'''(''self'', '''transport''', '''remote_sdp'''={{{None}}}, '''sdp_index'''=0, '''enable_silence_detection'''=True, '''codecs'''={{{None}}})::
1428 1 Adrian Georgescu
  Creates a new {{{AudioTransport}}} object and start the underlying stream if the remote SDP is already known.
1429
  [[BR]]''transport'':[[BR]]
1430
  The transport to use in the form of a {{{RTPTransport}}} object.
1431
  [[BR]]''remote_sdp'':[[BR]]
1432
  The remote SDP that was received in the form of a {{{SDPSession}}} object.
1433
  [[BR]]''sdp_index'':[[BR]]
1434
  The index within the SDP of the audio stream that should be created.
1435
  [[BR]]''enable_silence_detection''[[BR]]
1436
  Boolean that indicates if silence detection should be used for this audio stream.
1437
  When enabled, this {{{AudioTransport}}} object will stop sending audio to the remote party if the input volume is below a certain threshold.
1438 40 Ruud Klaver
  [[BR]]''codecs''[[BR]]
1439
  A list of strings indicating the codecs that should be proposed in the SDP of this {{{AudioTransport}}}, in order of preference.
1440
  This overrides the global codecs list set on the {{{Engine}}}.
1441
  The values of this list are case insensitive.
1442 1 Adrian Georgescu
 '''get_local_media'''(''self'', '''is_offer''', '''direction'''="sendrecv")::
1443
  Generates a {{{SDPMedia}}} object which describes the audio stream.
1444
  This object should be included in a {{{SDPSession}}} object that gets passed to the {{{Invitation}}} object.
1445
  This method should also be used to obtain the SDP to include in re-INVITEs and replies to re-INVITEs.
1446
  [[BR]]''is_offer'':[[BR]]
1447
  A boolean indicating if the SDP requested is to be included in an offer.
1448
  If this is {{{False}}} it is to be included in an answer.
1449
  [[BR]]''direction'':[[BR]]
1450
  The direction attribute to put in the SDP.
1451
 '''start'''(''self'', '''local_sdp''', '''remote_sdp''', '''sdp_index''')::
1452
  This method should only be called once, when the application has previously sent an SDP offer and the answer has been received.
1453
  [[BR]]''local_sdp'':[[BR]]
1454
  The full local SDP that was included in the SDP negotiation in the form of a {{{SDPSession}}} object.
1455
  [[BR]]''remote_sdp'':[[BR]]
1456
  The remote SDP that was received in the form of a {{{SDPSession}}} object.
1457
  [[BR]]''sdp_index'':[[BR]]
1458
  The index within the SDP of the audio stream.
1459
 '''stop'''(''self'')::
1460
  This method stops and destroys the audio stream encapsulated by this object.
1461
  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.
1462
  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.
1463
 '''send_dtmf'''(''self'', '''digit''')::
1464
  For a negotiated audio transport this sends one DTMF digit to the other party
1465
  [[BR]]''digit'':[[BR]]
1466
  A string of length one indicating the DTMF digit to send.
1467
  This can be either a number or letters A through D.
1468
 '''update_direction'''(''self'', '''direction''')::
1469
  This method should be called after SDP negotiation has completed to update the direction of the media stream.
1470
  [[BR]]''direction'':[[BR]]
1471
  The direction that has been negotiated.
1472
1473
==== notifications ====
1474
1475 29 Luci Stanescu
 '''RTPAudioTransportGotDTMF'''::
1476 1 Adrian Georgescu
  This notification will be sent when an incoming DTMF digit is received from the remote party.
1477
  [[BR]]''timestamp'':[[BR]]
1478
  A {{{datetime.datetime}}} object indicating when the notification was sent.
1479
  [[BR]]''digit'':[[BR]]
1480
  The DTMF digit that was received, in the form of a string of length one.
1481
  This can be either a number or letters A through D.
1482
1483
=== WaveFile ===
1484
1485
This is a simple object that allows playing back of a {{{.wav}}} file over the PJSIP conference bridge, possibly looping a number of times.
1486
Only 16-bit PCM and A-law/U-law formats are supported.
1487
Its main purpose is the playback of ringtones.
1488
1489
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.
1490
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.
1491 29 Luci Stanescu
When playback stops for either of these reasons, a {{{WaveFileDidFinishPlaying}}} notification is sent by the object.
1492 1 Adrian Georgescu
After this the {{{start()}}} method may be called again in order to re-use the object.
1493
1494
It is the application's responsibility to keep a reference to the {{{WaveFile}}} object for the duration of playback.
1495
If the reference count of the object reaches 0, playback will be stopped.
1496
In this case no notification will be sent.
1497
1498
==== attributes ====
1499
1500
 '''file_name'''::
1501
  The name of the {{{.wav}}} file, as specified when the object was created.
1502
 '''is_active'''::
1503
  A boolean read-only property that indicates if the file is currently being played back.
1504
  Note that if the playback loop is currently in a pause between playbacks, this attribute will also be {{{True}}}.
1505
1506
==== methods ====
1507
1508
 '''!__init!__'''(''self'', '''file_name''')::
1509
  Creates a new {{{WaveFile}}} object.
1510
  [[BR]]''file_name'':[[BR]]
1511
  The name of the {{{.wav}}} file to be played back as a string.
1512
  This should include the full path to the file.
1513
 '''start'''(''self'', '''level'''=100, '''loop_count'''=1, '''pause_time'''=0)::
1514
  Start playback of the {{{.wav}}} file, optionally looping it.
1515
  [[BR]]''level'':[[BR]]
1516
  The level to play the file back at, in percentage.
1517
  A percentage lower than 100 means playback will be attenuated, a percentage higher than 100 means it will amplified.
1518
  [[BR]]''loop_count'':[[BR]]
1519
  The number of time to loop playing this file.
1520
  A value of 0 means looping infinitely.
1521
  [[BR]]''pause_time'':[[BR]]
1522
  The number of seconds to pause between consecutive loops.
1523
  This can be either an int or a float.
1524
 '''stop'''(''self'')::
1525
  Stop playback of the file.
1526
1527
==== notifications ====
1528
1529 29 Luci Stanescu
 '''WaveFileDidFinishPlaying'''::
1530 1 Adrian Georgescu
  This notification will be sent whenever the {{{.wav}}} file has been played back the specified number of times.
1531
  After sending this event, the playback may be re-started.
1532
  [[BR]]''timestamp'':[[BR]]
1533
  A {{{datetime.datetime}}} object indicating when the notification was sent.
1534
1535
=== RecordingWaveFile ===
1536
1537
This is a simple object that allows recording whatever is heard on the PJSIP conference bridge to a PCM {{{.wav}}} file.
1538
1539
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.
1540
Recording to the file can be stopped either by calling the {{{stop()}}} method or by removing all references to the object.
1541
Once the {{{stop()}}} method has been called, the {{{start()}}} method may not be called again.
1542
It is the application's responsibility to keep a reference to the {{{RecordingWaveFile}}} object for the duration of the recording.
1543
1544
==== attributes ====
1545
1546
 '''file_name'''::
1547 15 Ruud Klaver
  The name of the {{{.wav}}} file, as specified when the object was created.
1548
 '''is_active'''::
1549
  A boolean read-only attribute that indicates if the file is currently being written to.
1550 1 Adrian Georgescu
 '''is_paused'''::
1551
  A boolean read-only attribute that indicates if the active recording is currently paused.
1552
1553
==== methods ====
1554
1555
 '''!__init!__'''(''self'', '''file_name''')::
1556
  Creates a new {{{RecordingWaveFile}}} object.
1557
  [[BR]]''file_name'':[[BR]]
1558
  The name of the {{{.wav}}} file to record to as a string.
1559
  This should include the full path to the file.
1560 15 Ruud Klaver
 '''start'''(''self'')::
1561
  Start recording the sound on the conference bridge to the {{{.wav}}} file.
1562
 '''pause'''(''self'')::
1563
  Pause recording to the {{{.wav}}} file.
1564 1 Adrian Georgescu
 '''resume'''(''self'')::
1565
  Resume a previously paused recording.
1566
 '''stop'''(''self'')::
1567
  Stop recording to the file.