Project

General

Profile

SipCoreApiDocumentation » History » Version 1

Adrian Georgescu, 02/16/2009 07:08 PM

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