Debian Codegraph @

Xpjproject/pjsip-apps/src/python/pjsua.py

raw symbols SCIP
1 #
2 # Object oriented PJSUA wrapper.
3 #
4 # Copyright (C) 2003-2008 Benny Prijono <[email protected]>
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #
20
21 """Multimedia communication client library based on SIP protocol.
22
23 This implements a fully featured multimedia communication client
24 library based on PJSIP stack (http://www.pjsip.org)
25
26
27 1. FEATURES
28
29 - Session Initiation Protocol (SIP) features:
30 - Basic registration and call
31 - Multiple accounts
32 - Call hold, attended and unattended call transfer
33 - Presence
34 - Instant messaging
35 - Multiple SIP accounts
36 - Media features:
37 - Audio
38 - Conferencing
39 - Narrowband and wideband
40 - Codecs: PCMA, PCMU, GSM, iLBC, Speex, G.722, L16
41 - RTP/RTCP
42 - Secure RTP (SRTP)
43 - WAV playback, recording, and playlist
44 - NAT traversal features
45 - Symmetric RTP
46 - STUN
47 - TURN
48 - ICE
49
50
51 2. USING
52
53 See http://www.pjsip.org/trac/wiki/Python_SIP_Tutorial for a more thorough
54 tutorial. The paragraphs below explain basic tasks on using this module.
55
56
57 """
58 try:
59 import _thread as thread
60 except ImportError:
61 import thread
62 import _pjsua
63 import threading
64 import weakref
65 import time
66
67 class Error:
68 """Error exception class.
69
70 Member documentation:
71
72 op_name -- name of the operation that generated this error.
73 obj -- the object that generated this error.
74 err_code -- the error code.
75
76 """
77 op_name = ""
78 obj = None
79 err_code = -1
80 _err_msg = ""
81
82 def __init__(self, op_name, obj, err_code, err_msg=""):
83 self.op_name = op_name
84 self.obj = obj
85 self.err_code = err_code
86 self._err_msg = err_msg
87
88 def err_msg(self):
89 "Retrieve the description of the error."
90 if self._err_msg != "":
91 return self._err_msg
92 self._err_msg = Lib.strerror(self.err_code)
93 return self._err_msg
94
95 def __str__(self):
96 return "Object: " + str(self.obj) + ", operation=" + self.op_name + \
97 ", error=" + self.err_msg()
98
99 #
100 # Constants
101 #
102
103 class TransportType:
104 """SIP transport type constants.
105
106 Member documentation:
107 UNSPECIFIED -- transport type is unknown or unspecified
108 UDP -- UDP transport
109 TCP -- TCP transport
110 TLS -- TLS transport
111 IPV6 -- this is not a transport type but rather a flag
112 to select the IPv6 version of a transport
113 UDP_IPV6 -- IPv6 UDP transport
114 TCP_IPV6 -- IPv6 TCP transport
115 """
116 UNSPECIFIED = 0
117 UDP = 1
118 TCP = 2
119 TLS = 3
120 IPV6 = 128
121 UDP_IPV6 = UDP + IPV6
122 TCP_IPV6 = TCP + IPV6
123
124 class TransportFlag:
125 """Transport flags to indicate the characteristics of the transport.
126
127 Member documentation:
128
129 RELIABLE -- transport is reliable.
130 SECURE -- transport is secure.
131 DATAGRAM -- transport is datagram based.
132
133 """
134 RELIABLE = 1
135 SECURE = 2
136 DATAGRAM = 4
137
138 class CallRole:
139 """Call role constants.
140
141 Member documentation:
142
143 CALLER -- role is caller
144 CALLEE -- role is callee
145
146 """
147 CALLER = 0
148 CALLEE = 1
149
150 class CallState:
151 """Call state constants.
152
153 Member documentation:
154
155 NULL -- call is not initialized.
156 CALLING -- initial INVITE is sent.
157 INCOMING -- initial INVITE is received.
158 EARLY -- provisional response has been sent or received.
159 CONNECTING -- 200/OK response has been sent or received.
160 CONFIRMED -- ACK has been sent or received.
161 DISCONNECTED -- call is disconnected.
162 """
163 NULL = 0
164 CALLING = 1
165 INCOMING = 2
166 EARLY = 3
167 CONNECTING = 4
168 CONFIRMED = 5
169 DISCONNECTED = 6
170
171
172 class MediaState:
173 """Call media state constants.
174
175 Member documentation:
176
177 NULL -- media is not available.
178 ACTIVE -- media is active.
179 LOCAL_HOLD -- media is put on-hold by local party.
180 REMOTE_HOLD -- media is put on-hold by remote party.
181 ERROR -- media error (e.g. ICE negotiation failure).
182 """
183 NULL = 0
184 ACTIVE = 1
185 LOCAL_HOLD = 2
186 REMOTE_HOLD = 3
187 ERROR = 4
188
189
190 class MediaDir:
191 """Media direction constants.
192
193 Member documentation:
194
195 NULL -- media is not active
196 ENCODING -- media is active in transmit/encoding direction only.
197 DECODING -- media is active in receive/decoding direction only
198 ENCODING_DECODING -- media is active in both directions.
199 """
200 NULL = 0
201 ENCODING = 1
202 DECODING = 2
203 ENCODING_DECODING = 3
204
205
206 class PresenceActivity:
207 """Presence activities constants.
208
209 Member documentation:
210
211 UNKNOWN -- the person activity is unknown
212 AWAY -- the person is currently away
213 BUSY -- the person is currently engaging in other activity
214 """
215 UNKNOWN = 0
216 AWAY = 1
217 BUSY = 2
218
219
220 class SubscriptionState:
221 """Presence subscription state constants.
222
223 """
224 NULL = 0
225 SENT = 1
226 ACCEPTED = 2
227 PENDING = 3
228 ACTIVE = 4
229 TERMINATED = 5
230 UNKNOWN = 6
231
232
233 class TURNConnType:
234 """These constants specifies the connection type to TURN server.
235
236 Member documentation:
237 UDP -- use UDP transport.
238 TCP -- use TCP transport.
239 TLS -- use TLS transport.
240 """
241 UDP = 17
242 TCP = 6
243 TLS = 255
244
245
246 class UAConfig:
247 """User agent configuration to be specified in Lib.init().
248
249 Member documentation:
250
251 max_calls -- maximum number of calls to be supported.
252 nameserver -- list of nameserver hostnames or IP addresses. Nameserver
253 must be configured if DNS SRV resolution is desired.
254 stun_domain -- if nameserver is configured, this can be used to query
255 the STUN server with DNS SRV.
256 stun_host -- the hostname or IP address of the STUN server. This will
257 also be used if DNS SRV resolution for stun_domain fails.
258 user_agent -- Optionally specify the user agent name.
259 """
260 max_calls = 4
261 nameserver = []
262 stun_domain = ""
263 stun_host = ""
264 user_agent = "pjsip python"
265
266 def _cvt_from_pjsua(self, cfg):
267 self.max_calls = cfg.max_calls
268 self.thread_cnt = cfg.thread_cnt
269 self.nameserver = cfg.nameserver
270 self.stun_domain = cfg.stun_domain
271 self.stun_host = cfg.stun_host
272 self.user_agent = cfg.user_agent
273
274 def _cvt_to_pjsua(self):
275 cfg = _pjsua.config_default()
276 cfg.max_calls = self.max_calls
277 cfg.thread_cnt = 0
278 cfg.nameserver = self.nameserver
279 cfg.stun_domain = self.stun_domain
280 cfg.stun_host = self.stun_host
281 cfg.user_agent = self.user_agent
282 return cfg
283
284
285 class LogConfig:
286 """Logging configuration to be specified in Lib.init().
287
288 Member documentation:
289
290 msg_logging -- specify if SIP messages should be logged. Set to
291 True.
292 level -- specify the input verbosity level.
293 console_level -- specify the output verbosity level.
294 decor -- specify log decoration.
295 filename -- specify the log filename.
296 callback -- specify callback to be called to write the logging
297 messages. Sample function:
298
299 def log_cb(level, str, len):
300 print str,
301
302 """
303 msg_logging = True
304 level = 5
305 console_level = 5
306 decor = 0
307 filename = ""
308 callback = None
309
310 def __init__(self, level=-1, filename="", callback=None,
311 console_level=-1):
312 self._cvt_from_pjsua(_pjsua.logging_config_default())
313 if level != -1:
314 self.level = level
315 if filename != "":
316 self.filename = filename
317 if callback != None:
318 self.callback = callback
319 if console_level != -1:
320 self.console_level = console_level
321
322 def _cvt_from_pjsua(self, cfg):
323 self.msg_logging = cfg.msg_logging
324 self.level = cfg.level
325 self.console_level = cfg.console_level
326 self.decor = cfg.decor
327 self.filename = cfg.log_filename
328 self.callback = cfg.cb
329
330 def _cvt_to_pjsua(self):
331 cfg = _pjsua.logging_config_default()
332 cfg.msg_logging = self.msg_logging
333 cfg.level = self.level
334 cfg.console_level = self.console_level
335 cfg.decor = self.decor
336 cfg.log_filename = self.filename
337 cfg.cb = self.callback
338 return cfg
339
340
341 class MediaConfig:
342 """Media configuration to be specified in Lib.init().
343
344 Member documentation:
345
346 clock_rate -- specify the core clock rate of the audio,
347 most notably the conference bridge.
348 snd_clock_rate -- optionally specify different clock rate for
349 the sound device.
350 snd_auto_close_time -- specify the duration in seconds when the
351 sound device should be closed after inactivity
352 period.
353 channel_count -- specify the number of channels to open the sound
354 device and the conference bridge.
355 audio_frame_ptime -- specify the length of audio frames in millisecond.
356 max_media_ports -- specify maximum number of audio ports to be
357 supported by the conference bridge.
358 quality -- specify the audio quality setting (1-10)
359 ptime -- specify the audio packet length of transmitted
360 RTP packet.
361 no_vad -- disable Voice Activity Detector (VAD) or Silence
362 Detector (SD)
363 ilbc_mode -- specify iLBC codec mode (must be 30 for now)
364 tx_drop_pct -- randomly drop transmitted RTP packets (for
365 simulation). Number is in percent.
366 rx_drop_pct -- randomly drop received RTP packets (for
367 simulation). Number is in percent.
368 ec_options -- Echo Canceller option (specify zero).
369 ec_tail_len -- specify Echo Canceller tail length in milliseconds.
370 Value zero will disable the echo canceller.
371 jb_min -- specify the minimum jitter buffer size in
372 milliseconds. Put -1 for default.
373 jb_max -- specify the maximum jitter buffer size in
374 milliseconds. Put -1 for default.
375 enable_ice -- enable Interactive Connectivity Establishment (ICE)
376 enable_turn -- enable TURN relay. TURN server settings must also
377 be configured.
378 turn_server -- specify the domain or hostname or IP address of
379 the TURN server, in "host[:port]" format.
380 turn_conn_type -- specify connection type to the TURN server, from
381 the TURNConnType constant.
382 turn_cred -- specify AuthCred for the TURN credential.
383 """
384 clock_rate = 16000
385 snd_clock_rate = 0
386 snd_auto_close_time = 5
387 channel_count = 1
388 audio_frame_ptime = 20
389 max_media_ports = 32
390 quality = 6
391 ptime = 0
392 no_vad = False
393 ilbc_mode = 30
394 tx_drop_pct = 0
395 rx_drop_pct = 0
396 ec_options = 0
397 ec_tail_len = 256
398 jb_min = -1
399 jb_max = -1
400 enable_ice = True
401 enable_turn = False
402 turn_server = ""
403 turn_conn_type = TURNConnType.UDP
404 turn_cred = None
405
406 def __init__(self):
407 default = _pjsua.media_config_default()
408 self._cvt_from_pjsua(default)
409
410 def _cvt_from_pjsua(self, cfg):
411 self.clock_rate = cfg.clock_rate
412 self.snd_clock_rate = cfg.snd_clock_rate
413 self.snd_auto_close_time = cfg.snd_auto_close_time
414 self.channel_count = cfg.channel_count
415 self.audio_frame_ptime = cfg.audio_frame_ptime
416 self.max_media_ports = cfg.max_media_ports
417 self.quality = cfg.quality
418 self.ptime = cfg.ptime
419 self.no_vad = cfg.no_vad
420 self.ilbc_mode = cfg.ilbc_mode
421 self.tx_drop_pct = cfg.tx_drop_pct
422 self.rx_drop_pct = cfg.rx_drop_pct
423 self.ec_options = cfg.ec_options
424 self.ec_tail_len = cfg.ec_tail_len
425 self.jb_min = cfg.jb_min
426 self.jb_max = cfg.jb_max
427 self.enable_ice = cfg.enable_ice
428 self.enable_turn = cfg.enable_turn
429 self.turn_server = cfg.turn_server
430 self.turn_conn_type = cfg.turn_conn_type
431 if cfg.turn_username:
432 self.turn_cred = AuthCred(cfg.turn_realm, cfg.turn_username,
433 cfg.turn_passwd, cfg.turn_passwd_type)
434 else:
435 self.turn_cred = None
436
437 def _cvt_to_pjsua(self):
438 cfg = _pjsua.media_config_default()
439 cfg.clock_rate = self.clock_rate
440 cfg.snd_clock_rate = self.snd_clock_rate
441 cfg.snd_auto_close_time = self.snd_auto_close_time
442 cfg.channel_count = self.channel_count
443 cfg.audio_frame_ptime = self.audio_frame_ptime
444 cfg.max_media_ports = self.max_media_ports
445 cfg.quality = self.quality
446 cfg.ptime = self.ptime
447 cfg.no_vad = self.no_vad
448 cfg.ilbc_mode = self.ilbc_mode
449 cfg.tx_drop_pct = self.tx_drop_pct
450 cfg.rx_drop_pct = self.rx_drop_pct
451 cfg.ec_options = self.ec_options
452 cfg.ec_tail_len = self.ec_tail_len
453 cfg.jb_min = self.jb_min
454 cfg.jb_max = self.jb_max
455 cfg.enable_ice = self.enable_ice
456 cfg.enable_turn = self.enable_turn
457 cfg.turn_server = self.turn_server
458 cfg.turn_conn_type = self.turn_conn_type
459 if self.turn_cred:
460 cfg.turn_realm = self.turn_cred.realm
461 cfg.turn_username = self.turn_cred.username
462 cfg.turn_passwd_type = self.turn_cred.passwd_type
463 cfg.turn_passwd = self.turn_cred.passwd
464 return cfg
465
466
467 class TransportConfig:
468 """SIP transport configuration class.
469
470 Member configuration:
471
472 port -- port number.
473 bound_addr -- optionally specify the address to bind the socket to.
474 Default is empty to bind to INADDR_ANY.
475 public_addr -- optionally override the published address for this
476 transport. If empty, the default behavior is to get
477 the public address from STUN or from the selected
478 local interface. Format is "host:port".
479 qos_type -- High level traffic classification.
480 Enumerator:
481 0: PJ_QOS_TYPE_BEST_EFFORT
482 Best effort traffic (default value). Any QoS function calls with
483 specifying this value are effectively no-op
484 1: PJ_QOS_TYPE_BACKGROUND
485 Background traffic.
486 2: PJ_QOS_TYPE_VIDEO
487 Video traffic.
488 3: PJ_QOS_TYPE_VOICE
489 Voice traffic.
490 4: PJ_QOS_TYPE_CONTROL
491 Control traffic.
492 5: PJ_QOS_TYPE_SIGNALLING
493 Signalling traffic.
494 qos_params_flags -- Determines which values to set, bitmask of pj_qos_flag.
495 PJ_QOS_PARAM_HAS_DSCP = 1
496 PJ_QOS_PARAM_HAS_SO_PRIO = 2
497 PJ_QOS_PARAM_HAS_WMM = 4
498 qos_params_dscp_val -- The 6 bits DSCP value to set.
499 qos_params_so_prio -- Socket SO_PRIORITY value.
500 qos_params_wmm_prio -- Standard WMM priorities.
501 Enumerator:
502 0: PJ_QOS_WMM_PRIO_BULK_EFFORT: Bulk effort priority
503 1: PJ_QOS_WMM_PRIO_BULK: Bulk priority.
504 2: PJ_QOS_WMM_PRIO_VIDEO: Video priority
505 3: PJ_QOS_WMM_PRIO_VOICE: Voice priority.
506 """
507 port = 0
508 bound_addr = ""
509 public_addr = ""
510
511 qos_type = 0
512 qos_params_flags = 0
513 qos_params_dscp_val = 0
514 qos_params_so_prio = 0
515 qos_params_wmm_prio = 0
516
517
518
519 def __init__(self, port=0,
520 bound_addr="", public_addr=""):
521 self.port = port
522 self.bound_addr = bound_addr
523 self.public_addr = public_addr
524
525 def _cvt_from_pjsua(self, cfg):
526 self.port = cfg.port
527 self.bound_addr = cfg.bound_addr
528 self.public_addr = cfg.public_addr
529 self.qos_type = cfg.qos_type
530 self.qos_params_flags = cfg.qos_params_flags
531 self.qos_params_dscp_val = cfg.qos_params_dscp_val
532 self.qos_params_so_prio = cfg.qos_params_so_prio
533 self.qos_params_wmm_prio = cfg.qos_params_wmm_prio
534
535 def _cvt_to_pjsua(self):
536 cfg = _pjsua.transport_config_default()
537 cfg.port = self.port
538 cfg.bound_addr = self.bound_addr
539 cfg.public_addr = self.public_addr
540 cfg.qos_type = self.qos_type
541 cfg.qos_params_flags = self.qos_params_flags
542 cfg.qos_params_dscp_val = self.qos_params_dscp_val
543 cfg.qos_params_so_prio = self.qos_params_so_prio
544 cfg.qos_params_wmm_prio = self.qos_params_wmm_prio
545
546 return cfg
547
548
549 class TransportInfo:
550 """SIP transport info.
551
552 Member documentation:
553
554 type -- transport type, from TransportType constants.
555 description -- longer description for this transport.
556 is_reliable -- True if transport is reliable.
557 is_secure -- True if transport is secure.
558 is_datagram -- True if transport is datagram based.
559 host -- the IP address of this transport.
560 port -- the port number.
561 ref_cnt -- number of objects referencing this transport.
562 """
563 type = ""
564 description = ""
565 is_reliable = False
566 is_secure = False
567 is_datagram = False
568 host = ""
569 port = 0
570 ref_cnt = 0
571
572 def __init__(self, ti):
573 self.type = ti.type_name
574 self.description = ti.info
575 self.is_reliable = (ti.flag & TransportFlag.RELIABLE)
576 self.is_secure = (ti.flag & TransportFlag.SECURE)
577 self.is_datagram = (ti.flag & TransportFlag.DATAGRAM)
578 self.host = ti.addr
579 self.port = ti.port
580 self.ref_cnt = ti.usage_count
581
582
583 class Transport:
584 "SIP transport class."
585 _id = -1
586 _lib = None
587 _obj_name = ""
588
589 def __init__(self, lib, id):
590 self._lib = weakref.proxy(lib)
591 self._id = id
592 self._obj_name = "{Transport " + self.info().description + "}"
593 _Trace((self, 'created'))
594
595 def __del__(self):
596 _Trace((self, 'destroyed'))
597
598 def __str__(self):
599 return self._obj_name
600
601 def info(self):
602 """Get TransportInfo.
603 """
604 lck = self._lib.auto_lock()
605 ti = _pjsua.transport_get_info(self._id)
606 if not ti:
607 self._lib._err_check("info()", self, -1, "Invalid transport")
608 return TransportInfo(ti)
609
610 # NOTE: enable() and disable() methods are commented out because the underlying
611 # pjsua_transport_set_enable function has been deprecated and is no longer available.
612 # Please use PJSUA2 SWIG binding for modern transport management functionality.
613 """
614 def enable(self):
615 \"\"\"Enable this transport.\"\"\"
616 lck = self._lib.auto_lock()
617 err = _pjsua.transport_set_enable(self._id, True)
618 self._lib._err_check("enable()", self, err)
619
620 def disable(self):
621 \"\"\"Disable this transport.\"\"\"
622 lck = self._lib.auto_lock()
623 err = _pjsua.transport_set_enable(self._id, 0)
624 self._lib._err_check("disable()", self, err)
625 """
626
627 def close(self, force=False):
628 """Close and destroy this transport.
629
630 Keyword argument:
631 force -- force deletion of this transport (not recommended).
632 """
633 lck = self._lib.auto_lock()
634 err = _pjsua.transport_close(self._id, force)
635 self._lib._err_check("close()", self, err)
636
637
638 class SIPUri:
639 """Helper class to parse the most important components of SIP URI.
640
641 Member documentation:
642
643 scheme -- URI scheme ("sip" or "sips")
644 user -- user part of the URI (may be empty)
645 host -- host name part
646 port -- optional port number (zero if port is not specified).
647 transport -- transport parameter, or empty if transport is not
648 specified.
649
650 """
651 scheme = ""
652 user = ""
653 host = ""
654 port = 0
655 transport = ""
656
657 def __init__(self, uri=None):
658 if uri:
659 self.decode(uri)
660
661 def decode(self, uri):
662 """Parse SIP URL.
663
664 Keyword argument:
665 uri -- the URI string.
666
667 """
668 self.scheme, self.user, self.host, self.port, self.transport = \
669 _pjsua.parse_simple_uri(uri)
670
671 def encode(self):
672 """Encode this object into SIP URI string.
673
674 Return:
675 URI string.
676
677 """
678 output = self.scheme + ":"
679 if self.user and len(self.user):
680 output = output + self.user + "@"
681 output = output + self.host
682 if self.port:
683 output = output + ":" + output(self.port)
684 if self.transport:
685 output = output + ";transport=" + self.transport
686 return output
687
688
689 class AuthCred:
690 """Authentication credential for SIP or TURN account.
691
692 Member documentation:
693
694 scheme -- authentication scheme (default is "Digest")
695 realm -- realm
696 username -- username
697 passwd_type -- password encoding (zero for plain-text)
698 passwd -- the password
699 """
700 scheme = "Digest"
701 realm = "*"
702 username = ""
703 passwd_type = 0
704 passwd = ""
705
706 def __init__(self, realm, username, passwd, scheme="Digest", passwd_type=0):
707 self.scheme = scheme
708 self.realm = realm
709 self.username = username
710 self.passwd_type = passwd_type
711 self.passwd = passwd
712
713
714 class AccountConfig:
715 """ This describes account configuration to create an account.
716
717 Member documentation:
718
719 priority -- account priority for matching incoming
720 messages.
721 id -- SIP URI of this account. This setting is
722 mandatory.
723 force_contact -- force to use this URI as Contact URI. Setting
724 this value is generally not recommended.
725 reg_uri -- specify the registrar URI. Mandatory if
726 registration is required.
727 reg_timeout -- specify the SIP registration refresh interval
728 in seconds.
729 require_100rel -- specify if reliable provisional response is
730 to be enforced (with Require header).
731 publish_enabled -- specify if PUBLISH should be used. When
732 enabled, the PUBLISH will be sent to the
733 registrar.
734 pidf_tuple_id -- optionally specify the tuple ID in outgoing
735 PIDF document.
736 proxy -- list of proxy URI.
737 auth_cred -- list of AuthCred containing credentials to
738 authenticate against the registrars and
739 the proxies.
740 auth_initial_send -- specify if empty Authorization header should be
741 sent. May be needed for IMS.
742 auth_initial_algorithm -- when auth_initial_send is enabled, optionally
743 specify the authentication algorithm to use.
744 Valid values are "md5", "akav1-md5", or
745 "akav2-md5".
746 transport_id -- optionally specify the transport ID to be used
747 by this account. Shouldn't be needed unless
748 for specific requirements (e.g. in multi-homed
749 scenario).
750 allow_contact_rewrite -- specify whether the account should learn its
751 Contact address from REGISTER response and
752 update the registration accordingly. Default is
753 True.
754 ka_interval -- specify the interval to send NAT keep-alive
755 packet.
756 ka_data -- specify the NAT keep-alive packet contents.
757 use_srtp -- specify the SRTP usage policy. Valid values
758 are: 0=disable, 1=optional, 2=mandatory.
759 Default is 0.
760 srtp_secure_signaling -- specify the signaling security level required
761 by SRTP. Valid values are: 0=no secure
762 transport is required, 1=hop-by-hop secure
763 transport such as TLS is required, 2=end-to-
764 end secure transport is required (i.e. "sips").
765 rtp_transport_cfg -- the rtp-transport-configuration that is usede, when
766 a rtp-connection is being established.
767 """
768 priority = 0
769 id = ""
770 force_contact = ""
771 reg_uri = ""
772 reg_timeout = 0
773 require_100rel = False
774 publish_enabled = False
775 pidf_tuple_id = ""
776 proxy = []
777 auth_cred = []
778 auth_initial_send = False
779 auth_initial_algorithm = ""
780 transport_id = -1
781 allow_contact_rewrite = True
782 ka_interval = 15
783 ka_data = "\r\n"
784 use_srtp = 0
785 srtp_secure_signaling = 1
786 rtp_transport_cfg = None
787 mwi_enabled = False
788
789 def __init__(self, domain="", username="", password="",
790 display="", registrar="", proxy=""):
791 """
792 Construct account config. If domain argument is specified,
793 a typical configuration will be built.
794
795 Keyword arguments:
796 domain -- domain name of the server.
797 username -- user name.
798 password -- plain-text password.
799 display -- optional display name for the user name.
800 registrar -- the registrar URI. If domain name is specified
801 and this argument is empty, the registrar URI
802 will be constructed from the domain name.
803 proxy -- the proxy URI. If domain name is specified
804 and this argument is empty, the proxy URI
805 will be constructed from the domain name.
806
807 """
808 default = _pjsua.acc_config_default()
809 self._cvt_from_pjsua(default)
810 if domain!="":
811 self.build_config(domain, username, password,
812 display, registrar, proxy)
813 self.rtp_transport_cfg = TransportConfig()
814
815 def build_config(self, domain, username, password, display="",
816 registrar="", proxy="", rtp_transport_cfg = None):
817 """
818 Construct account config. If domain argument is specified,
819 a typical configuration will be built.
820
821 Keyword arguments:
822 domain -- domain name of the server.
823 username -- user name.
824 password -- plain-text password.
825 display -- optional display name for the user name.
826 registrar -- the registrar URI. If domain name is specified
827 and this argument is empty, the registrar URI
828 will be constructed from the domain name.
829 proxy -- the proxy URI. If domain name is specified
830 and this argument is empty, the proxy URI
831 will be constructed from the domain name.
832
833 """
834 if display != "":
835 display = display + " "
836 userpart = username
837 if userpart != "":
838 userpart = userpart + "@"
839 self.id = display + "<sip:" + userpart + domain + ">"
840 self.reg_uri = registrar
841 if self.reg_uri == "":
842 self.reg_uri = "sip:" + domain
843 if proxy == "":
844 proxy = "sip:" + domain + ";lr"
845 if proxy.find(";lr") == -1:
846 proxy = proxy + ";lr"
847 self.proxy.append(proxy)
848 if username != "":
849 self.auth_cred.append(AuthCred("*", username, password))
850
851 if (rtp_transport_cfg is not None):
852 self.rtp_transport_cfg = rtp_transport_cfg
853 else:
854 self.rtp_transport_cfg = TransportConfig()
855
856 def _cvt_from_pjsua(self, cfg):
857 self.priority = cfg.priority
858 self.id = cfg.id
859 self.force_contact = cfg.force_contact
860 self.reg_uri = cfg.reg_uri
861 self.reg_timeout = cfg.reg_timeout
862 self.require_100rel = cfg.require_100rel
863 self.publish_enabled = cfg.publish_enabled
864 self.pidf_tuple_id = cfg.pidf_tuple_id
865 self.proxy = cfg.proxy
866 for cred in cfg.cred_info:
867 self.auth_cred.append(AuthCred(cred.realm, cred.username,
868 cred.data, cred.scheme,
869 cred.data_type))
870 self.auth_initial_send = cfg.auth_initial_send
871 self.auth_initial_algorithm = cfg.auth_initial_algorithm
872 self.transport_id = cfg.transport_id
873 self.allow_contact_rewrite = cfg.allow_contact_rewrite
874 self.ka_interval = cfg.ka_interval
875 self.ka_data = cfg.ka_data
876 self.use_srtp = cfg.use_srtp
877 self.srtp_secure_signaling = cfg.srtp_secure_signaling
878 self.mwi_enabled = cfg.mwi_enabled
879 if (self.rtp_transport_cfg is not None):
880 self.rtp_transport_cfg._cvt_from_pjsua(cfg.rtp_transport_cfg)
881
882 def _cvt_to_pjsua(self):
883 cfg = _pjsua.acc_config_default()
884 cfg.priority = self.priority
885 cfg.id = self.id
886 cfg.force_contact = self.force_contact
887 cfg.reg_uri = self.reg_uri
888 cfg.reg_timeout = self.reg_timeout
889 cfg.require_100rel = self.require_100rel
890 cfg.publish_enabled = self.publish_enabled
891 cfg.pidf_tuple_id = self.pidf_tuple_id
892 cfg.proxy = self.proxy
893 for cred in self.auth_cred:
894 c = _pjsua.Pjsip_Cred_Info()
895 c.realm = cred.realm
896 c.scheme = cred.scheme
897 c.username = cred.username
898 c.data_type = cred.passwd_type
899 c.data = cred.passwd
900 cfg.cred_info.append(c)
901
902 cfg.auth_initial_send = self.auth_initial_send
903 cfg.auth_initial_algorithm = self.auth_initial_algorithm
904 cfg.transport_id = self.transport_id
905 cfg.allow_contact_rewrite = self.allow_contact_rewrite
906 cfg.ka_interval = self.ka_interval
907 cfg.ka_data = self.ka_data
908 cfg.use_srtp = self.use_srtp
909 cfg.srtp_secure_signaling = self.srtp_secure_signaling
910 cfg.mwi_enabled = self.mwi_enabled
911
912 if (self.rtp_transport_cfg is not None):
913 cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
914
915 return cfg
916
917
918 # Account information
919 class AccountInfo:
920 """This describes Account info. Application retrives account info
921 with Account.info().
922
923 Member documentation:
924
925 is_default -- True if this is the default account.
926 uri -- the account URI.
927 reg_active -- True if registration is active for this account.
928 reg_expires -- contains the current registration expiration value,
929 in seconds.
930 reg_status -- the registration status. If the value is less than
931 700, it specifies SIP status code. Value greater than
932 this specifies the error code.
933 reg_reason -- contains the registration status text (e.g. the
934 error message).
935 online_status -- the account's presence online status, True if it's
936 publishing itself as online.
937 online_text -- the account's presence status text.
938
939 """
940 is_default = False
941 uri = ""
942 reg_active = False
943 reg_expires = -1
944 reg_status = 0
945 reg_reason = ""
946 online_status = False
947 online_text = ""
948
949 def __init__(self, ai):
950 self.is_default = ai.is_default
951 self.uri = ai.acc_uri
952 self.reg_active = ai.has_registration
953 self.reg_expires = ai.expires
954 self.reg_status = ai.status
955 self.reg_reason = ai.status_text
956 self.online_status = ai.online_status
957 self.online_text = ai.online_status_text
958
959 # Account callback
960 class AccountCallback:
961 """Class to receive notifications on account's events.
962
963 Derive a class from this class and register it to the Account object
964 using Account.set_callback() to start receiving events from the Account
965 object.
966
967 Member documentation:
968
969 account -- the Account object.
970
971 """
972 account = None
973
974 def __init__(self, account=None):
975 self._set_account(account)
976
977 def __del__(self):
978 pass
979
980 def _set_account(self, account):
981 if account:
982 self.account = weakref.proxy(account)
983 else:
984 self.account = None
985
986 def on_reg_state(self):
987 """Notification that the registration status has changed.
988 """
989 pass
990
991 def on_incoming_call(self, call):
992 """Notification about incoming call.
993
994 Application should implement one of on_incoming_call() or
995 on_incoming_call2(), otherwise, the default behavior is to
996 reject the call with default status code. Note that if both are
997 implemented, only on_incoming_call2() will be called.
998
999 Keyword arguments:
1000 call -- the new incoming call
1001 """
1002 call.hangup()
1003
1004 def on_incoming_call2(self, call, rdata):
1005 """Notification about incoming call, with received SIP message info.
1006
1007 Application should implement one of on_incoming_call() or
1008 on_incoming_call2(), otherwise, the default behavior is to
1009 reject the call with default status code. Note that if both are
1010 implemented, only on_incoming_call2() will be called.
1011
1012 Keyword arguments:
1013 call -- the new incoming call
1014 rdata -- the received message
1015 """
1016 call.hangup()
1017
1018 def on_incoming_subscribe(self, buddy, from_uri, contact_uri, pres_obj):
1019 """Notification when incoming SUBSCRIBE request is received.
1020
1021 Application may use this callback to authorize the incoming
1022 subscribe request (e.g. ask user permission if the request
1023 should be granted)
1024
1025 Keyword arguments:
1026 buddy -- The buddy object, if buddy is found. Otherwise
1027 the value is None.
1028 from_uri -- The URI string of the sender.
1029 pres_obj -- Opaque presence subscription object, which is
1030 needed by Account.pres_notify()
1031
1032 Return:
1033 Tuple (code, reason), where:
1034 code: The status code. If code is >= 300, the
1035 request is rejected. If code is 200, the
1036 request is accepted and NOTIFY will be sent
1037 automatically. If code is 202, application
1038 must accept or reject the request later with
1039 Account.press_notify().
1040 reason: Optional reason phrase, or None to use the
1041 default reasoh phrase for the status code.
1042 """
1043 return (200, None)
1044
1045 def on_pager(self, from_uri, contact, mime_type, body):
1046 """
1047 Notification that incoming instant message is received on
1048 this account.
1049
1050 Keyword arguments:
1051 from_uri -- sender's URI
1052 contact -- sender's Contact URI
1053 mime_type -- MIME type of the instant message body
1054 body -- the instant message body
1055
1056 """
1057 pass
1058
1059 def on_pager_status(self, to_uri, body, im_id, code, reason):
1060 """
1061 Notification about the delivery status of previously sent
1062 instant message.
1063
1064 Keyword arguments:
1065 to_uri -- the destination URI of the message
1066 body -- the message body
1067 im_id -- message ID
1068 code -- SIP status code
1069 reason -- SIP reason phrase
1070
1071 """
1072 pass
1073
1074 def on_typing(self, from_uri, contact, is_typing):
1075 """
1076 Notification that remote is typing or stop typing.
1077
1078 Keyword arguments:
1079 buddy -- Buddy object for the sender, if found. Otherwise
1080 this will be None
1081 from_uri -- sender's URI of the indication
1082 contact -- sender's contact URI
1083 is_typing -- boolean to indicate whether remote is currently
1084 typing an instant message.
1085
1086 """
1087 pass
1088
1089 def on_mwi_info(self, body):
1090 """
1091 Notification about change in Message Summary / Message Waiting
1092 Indication (RFC 3842) status. MWI subscription must be enabled
1093 in the account config to receive this notification.
1094
1095 Keyword arguments:
1096 body -- String containing message body as received in the
1097 NOTIFY request.
1098
1099 """
1100 pass
1101
1102
1103
1104 class Account:
1105 """This describes SIP account class.
1106
1107 PJSUA accounts provide identity (or identities) of the user who is
1108 currently using the application. In SIP terms, the identity is used
1109 as the From header in outgoing requests.
1110
1111 Account may or may not have client registration associated with it.
1112 An account is also associated with route set and some authentication
1113 credentials, which are used when sending SIP request messages using
1114 the account. An account also has presence's online status, which
1115 will be reported to remote peer when they subscribe to the account's
1116 presence, or which is published to a presence server if presence
1117 publication is enabled for the account.
1118
1119 Account is created with Lib.create_account(). At least one account
1120 MUST be created. If no user association is required, application can
1121 create a userless account by calling Lib.create_account_for_transport().
1122 A userless account identifies local endpoint instead of a particular
1123 user, and it correspond with a particular transport instance.
1124
1125 Also one account must be set as the default account, which is used as
1126 the account to use when PJSUA fails to match a request with any other
1127 accounts.
1128
1129 """
1130 _id = -1
1131 _lib = None
1132 _cb = AccountCallback(None)
1133 _obj_name = ""
1134
1135 def __init__(self, lib, id, cb=None):
1136 """Construct this class. This is normally called by Lib class and
1137 not by application.
1138
1139 Keyword arguments:
1140 lib -- the Lib instance.
1141 id -- the pjsua account ID.
1142 cb -- AccountCallback instance to receive events from this Account.
1143 If callback is not specified here, it must be set later
1144 using set_callback().
1145 """
1146 self._id = id
1147 self._lib = weakref.ref(lib)
1148 self._obj_name = "{Account " + self.info().uri + "}"
1149 self.set_callback(cb)
1150 _pjsua.acc_set_user_data(self._id, self)
1151 _Trace((self, 'created'))
1152
1153 def __del__(self):
1154 if self._id != -1:
1155 _pjsua.acc_set_user_data(self._id, 0)
1156 _Trace((self, 'destroyed'))
1157
1158 def __str__(self):
1159 return self._obj_name
1160
1161 def info(self):
1162 """Retrieve AccountInfo for this account.
1163 """
1164 lck = self._lib().auto_lock()
1165 ai = _pjsua.acc_get_info(self._id)
1166 if ai==None:
1167 self._lib()._err_check("info()", self, -1, "Invalid account")
1168 return AccountInfo(ai)
1169
1170 def is_valid(self):
1171 """
1172 Check if this account is still valid.
1173
1174 """
1175 lck = self._lib().auto_lock()
1176 return _pjsua.acc_is_valid(self._id)
1177
1178 def set_callback(self, cb):
1179 """Register callback to receive notifications from this object.
1180
1181 Keyword argument:
1182 cb -- AccountCallback instance.
1183
1184 """
1185 if cb:
1186 self._cb = cb
1187 else:
1188 self._cb = AccountCallback(self)
1189 self._cb._set_account(self)
1190
1191 def set_default(self):
1192 """ Set this account as default account to send outgoing requests
1193 and as the account to receive incoming requests when more exact
1194 matching criteria fails.
1195 """
1196 lck = self._lib().auto_lock()
1197 err = _pjsua.acc_set_default(self._id)
1198 self._lib()._err_check("set_default()", self, err)
1199
1200 def is_default(self):
1201 """ Check if this account is the default account.
1202
1203 """
1204 lck = self._lib().auto_lock()
1205 def_id = _pjsua.acc_get_default()
1206 return self.is_valid() and def_id==self._id
1207
1208 def delete(self):
1209 """ Delete this account.
1210
1211 """
1212 lck = self._lib().auto_lock()
1213 err = _pjsua.acc_set_user_data(self._id, 0)
1214 self._lib()._err_check("delete()", self, err)
1215 err = _pjsua.acc_del(self._id)
1216 self._lib()._err_check("delete()", self, err)
1217 self._id = -1
1218
1219 def set_basic_status(self, is_online):
1220 """ Set basic presence status of this account.
1221
1222 Keyword argument:
1223 is_online -- boolean to indicate basic presence availability.
1224
1225 """
1226 lck = self._lib().auto_lock()
1227 err = _pjsua.acc_set_online_status(self._id, is_online)
1228 self._lib()._err_check("set_basic_status()", self, err)
1229
1230 def set_presence_status(self, is_online,
1231 activity=PresenceActivity.UNKNOWN,
1232 pres_text="", rpid_id=""):
1233 """ Set presence status of this account.
1234
1235 Keyword arguments:
1236 is_online -- boolean to indicate basic presence availability
1237 activity -- value from PresenceActivity
1238 pres_text -- optional string to convey additional information about
1239 the activity (such as "On the phone")
1240 rpid_id -- optional string to be placed as RPID ID.
1241
1242 """
1243 lck = self._lib().auto_lock()
1244 err = _pjsua.acc_set_online_status2(self._id, is_online, activity,
1245 pres_text, rpid_id)
1246 self._lib()._err_check("set_presence_status()", self, err)
1247
1248 def set_registration(self, renew):
1249 """Manually renew registration or unregister from the server.
1250
1251 Keyword argument:
1252 renew -- boolean to indicate whether registration is renewed.
1253 Setting this value for False will trigger unregistration.
1254
1255 """
1256 lck = self._lib().auto_lock()
1257 err = _pjsua.acc_set_registration(self._id, renew)
1258 self._lib()._err_check("set_registration()", self, err)
1259
1260 def set_transport(self, transport):
1261 """Set this account to only use the specified transport to send
1262 outgoing requests.
1263
1264 Keyword argument:
1265 transport -- Transport object.
1266
1267 """
1268 lck = self._lib().auto_lock()
1269 err = _pjsua.acc_set_transport(self._id, transport._id)
1270 self._lib()._err_check("set_transport()", self, err)
1271
1272 def make_call(self, dst_uri, cb=None, hdr_list=None):
1273 """Make outgoing call to the specified URI.
1274
1275 Keyword arguments:
1276 dst_uri -- Destination SIP URI.
1277 cb -- CallCallback instance to be installed to the newly
1278 created Call object. If this CallCallback is not
1279 specified (i.e. None is given), it must be installed
1280 later using call.set_callback().
1281 hdr_list -- Optional list of headers to be sent with outgoing
1282 INVITE
1283
1284 Return:
1285 Call instance.
1286 """
1287 lck = self._lib().auto_lock()
1288 call = Call(self._lib(), -1, cb)
1289 err, cid = _pjsua.call_make_call(self._id, dst_uri, 0,
1290 call, Lib._create_msg_data(hdr_list))
1291 self._lib()._err_check("make_call()", self, err)
1292 call.attach_to_id(cid)
1293 return call
1294
1295 def add_buddy(self, uri, cb=None):
1296 """Add new buddy.
1297
1298 Keyword argument:
1299 uri -- SIP URI of the buddy
1300 cb -- BuddyCallback instance to be installed to the newly
1301 created Buddy object. If this callback is not specified
1302 (i.e. None is given), it must be installed later using
1303 buddy.set_callback().
1304
1305 Return:
1306 Buddy object
1307 """
1308 lck = self._lib().auto_lock()
1309 buddy_cfg = _pjsua.buddy_config_default()
1310 buddy_cfg.uri = uri
1311 buddy_cfg.subscribe = False
1312 err, buddy_id = _pjsua.buddy_add(buddy_cfg)
1313 self._lib()._err_check("add_buddy()", self, err)
1314 buddy = Buddy(self._lib(), buddy_id, self, cb)
1315 return buddy
1316
1317 def pres_notify(self, pres_obj, state, reason="", hdr_list=None):
1318 """Send NOTIFY to inform account presence status or to terminate
1319 server side presence subscription.
1320
1321 Keyword arguments:
1322 pres_obj -- The subscription object from on_incoming_subscribe()
1323 callback
1324 state -- Subscription state, from SubscriptionState
1325 reason -- Optional reason phrase.
1326 hdr_list -- Optional header list.
1327 """
1328 lck = self._lib().auto_lock()
1329 _pjsua.acc_pres_notify(self._id, pres_obj, state, reason,
1330 Lib._create_msg_data(hdr_list))
1331
1332 def send_pager(self, uri, text, im_id=0, content_type="text/plain", \
1333 hdr_list=None):
1334 """Send instant message to arbitrary URI.
1335
1336 Keyword arguments:
1337 text -- Instant message to be sent
1338 uri -- URI to send the Instant Message to.
1339 im_id -- Optional instant message ID to identify this
1340 instant message when delivery status callback
1341 is called.
1342 content_type -- MIME type identifying the instant message
1343 hdr_list -- Optional list of headers to be sent with the
1344 request.
1345
1346 """
1347 lck = self._lib().auto_lock()
1348 err = _pjsua.im_send(self._id, uri, \
1349 content_type, text, \
1350 Lib._create_msg_data(hdr_list), \
1351 im_id)
1352 self._lib()._err_check("send_pager()", self, err)
1353
1354 class CallCallback:
1355 """Class to receive event notification from Call objects.
1356
1357 Use Call.set_callback() method to install instance of this callback
1358 class to receive event notifications from the call object.
1359
1360 Member documentation:
1361
1362 call -- the Call object.
1363
1364 """
1365 call = None
1366
1367 def __init__(self, call=None):
1368 self._set_call(call)
1369
1370 def __del__(self):
1371 pass
1372
1373 def _set_call(self, call):
1374 if call:
1375 self.call = weakref.proxy(call)
1376 else:
1377 self.call = None
1378
1379 def on_state(self):
1380 """Notification that the call's state has changed.
1381
1382 """
1383 pass
1384
1385 def on_media_state(self):
1386 """Notification that the call's media state has changed.
1387
1388 """
1389 pass
1390
1391 def on_dtmf_digit(self, digits):
1392 """Notification on incoming DTMF digits.
1393
1394 Keyword argument:
1395 digits -- string containing the received digits.
1396
1397 """
1398 pass
1399
1400 def on_transfer_request(self, dst, code):
1401 """Notification that call is being transferred by remote party.
1402
1403 Application can decide to accept/reject transfer request by returning
1404 code greater than or equal to 500. The default behavior is to accept
1405 the transfer by returning 202.
1406
1407 Keyword arguments:
1408 dst -- string containing the destination URI
1409 code -- the suggested status code to return to accept the request.
1410
1411 Return:
1412 the callback should return 202 to accept the request, or 300-699 to
1413 reject the request.
1414
1415 """
1416 return code
1417
1418 def on_transfer_status(self, code, reason, final, cont):
1419 """
1420 Notification about the status of previous call transfer request.
1421
1422 Keyword arguments:
1423 code -- SIP status code to indicate completion status.
1424 text -- SIP status reason phrase.
1425 final -- if True then this is a final status and no further
1426 notifications will be sent for this call transfer
1427 status.
1428 cont -- suggested return value.
1429
1430 Return:
1431 If the callback returns false then no further notification will
1432 be sent for the transfer request for this call.
1433
1434 """
1435 return cont
1436
1437 def on_replace_request(self, code, reason):
1438 """Notification when incoming INVITE with Replaces header is received.
1439
1440 Application may reject the request by returning value greather than
1441 or equal to 500. The default behavior is to accept the request.
1442
1443 Keyword arguments:
1444 code -- default status code to return
1445 reason -- default reason phrase to return
1446
1447 Return:
1448 The callback should return (code, reason) tuple.
1449
1450 """
1451 return code, reason
1452
1453 def on_replaced(self, new_call):
1454 """
1455 Notification that this call will be replaced with new_call.
1456 After this callback is called, this call will be disconnected.
1457
1458 Keyword arguments:
1459 new_call -- the new call that will replace this call.
1460 """
1461 pass
1462
1463 def on_pager(self, mime_type, body):
1464 """
1465 Notification that incoming instant message is received on
1466 this call.
1467
1468 Keyword arguments:
1469 mime_type -- MIME type of the instant message body.
1470 body -- the instant message body.
1471
1472 """
1473 pass
1474
1475 def on_pager_status(self, body, im_id, code, reason):
1476 """
1477 Notification about the delivery status of previously sent
1478 instant message.
1479
1480 Keyword arguments:
1481 body -- message body
1482 im_id -- message ID
1483 code -- SIP status code
1484 reason -- SIP reason phrase
1485
1486 """
1487 pass
1488
1489 def on_typing(self, is_typing):
1490 """
1491 Notification that remote is typing or stop typing.
1492
1493 Keyword arguments:
1494 is_typing -- boolean to indicate whether remote is currently
1495 typing an instant message.
1496
1497 """
1498 pass
1499
1500
1501 class CallInfo:
1502 """This structure contains various information about Call.
1503
1504 Application may retrieve this information with Call.info().
1505
1506 Member documentation:
1507
1508 role -- CallRole
1509 account -- Account object.
1510 uri -- SIP URI of local account.
1511 contact -- local Contact URI.
1512 remote_uri -- remote SIP URI.
1513 remote_contact -- remote Contact URI
1514 sip_call_id -- call's Call-ID identification
1515 state -- CallState
1516 state_text -- state text.
1517 last_code -- last SIP status code
1518 last_reason -- text phrase for last_code
1519 media_state -- MediaState
1520 media_dir -- MediaDir
1521 conf_slot -- conference slot number for this call.
1522 call_time -- call's connected duration in seconds.
1523 total_time -- total call duration in seconds.
1524 """
1525 role = CallRole.CALLER
1526 account = None
1527 uri = ""
1528 contact = ""
1529 remote_uri = ""
1530 remote_contact = ""
1531 sip_call_id = ""
1532 state = CallState.NULL
1533 state_text = ""
1534 last_code = 0
1535 last_reason = ""
1536 media_state = MediaState.NULL
1537 media_dir = MediaDir.NULL
1538 conf_slot = -1
1539 call_time = 0
1540 total_time = 0
1541
1542 def __init__(self, lib=None, ci=None):
1543 if lib and ci:
1544 self._cvt_from_pjsua(lib, ci)
1545
1546 def _cvt_from_pjsua(self, lib, ci):
1547 self.role = ci.role
1548 self.account = lib._lookup_account(ci.acc_id)
1549 self.uri = ci.local_info
1550 self.contact = ci.local_contact
1551 self.remote_uri = ci.remote_info
1552 self.remote_contact = ci.remote_contact
1553 self.sip_call_id = ci.call_id
1554 self.state = ci.state
1555 self.state_text = ci.state_text
1556 self.last_code = ci.last_status
1557 self.last_reason = ci.last_status_text
1558 self.media_state = ci.media_status
1559 self.media_dir = ci.media_dir
1560 self.conf_slot = ci.conf_slot
1561 self.call_time = ci.connect_duration / 1000
1562 self.total_time = ci.total_duration / 1000
1563
1564
1565 class Call:
1566 """This class represents SIP call.
1567
1568 Application initiates outgoing call with Account.make_call(), and
1569 incoming calls are reported in AccountCallback.on_incoming_call().
1570 """
1571 _id = -1
1572 _cb = None
1573 _lib = None
1574 _obj_name = ""
1575
1576 def __init__(self, lib, call_id, cb=None):
1577 self._lib = weakref.ref(lib)
1578 self.set_callback(cb)
1579 self.attach_to_id(call_id)
1580 _Trace((self, 'created'))
1581
1582 def __del__(self):
1583 if self._id != -1:
1584 _pjsua.call_set_user_data(self._id, 0)
1585 _Trace((self, 'destroyed'))
1586
1587 def __str__(self):
1588 return self._obj_name
1589
1590 def attach_to_id(self, call_id):
1591 lck = self._lib().auto_lock()
1592 if self._id != -1:
1593 _pjsua.call_set_user_data(self._id, 0)
1594 self._id = call_id
1595 if self._id != -1:
1596 _pjsua.call_set_user_data(self._id, self)
1597 self._obj_name = "{Call " + self.info().remote_uri + "}"
1598 else:
1599 self._obj_name = "{Call object}"
1600
1601 def set_callback(self, cb):
1602 """
1603 Set callback object to retrieve event notifications from this call.
1604
1605 Keyword arguments:
1606 cb -- CallCallback instance.
1607 """
1608 if cb:
1609 self._cb = cb
1610 else:
1611 self._cb = CallCallback(self)
1612 self._cb._set_call(self)
1613
1614 def info(self):
1615 """
1616 Get the CallInfo.
1617 """
1618 lck = self._lib().auto_lock()
1619 ci = _pjsua.call_get_info(self._id)
1620 if not ci:
1621 self._lib()._err_check("info", self, -1, "Invalid call")
1622 call_info = CallInfo(self._lib(), ci)
1623 return call_info
1624
1625 def is_valid(self):
1626 """
1627 Check if this call is still valid.
1628 """
1629 lck = self._lib().auto_lock()
1630 return _pjsua.call_is_active(self._id)
1631
1632 def dump_status(self, with_media=True, indent="", max_len=1024):
1633 """
1634 Dump the call status.
1635 """
1636 lck = self._lib().auto_lock()
1637 return _pjsua.call_dump(self._id, with_media, max_len, indent)
1638
1639 def answer(self, code=200, reason="", hdr_list=None):
1640 """
1641 Send provisional or final response to incoming call.
1642
1643 Keyword arguments:
1644 code -- SIP status code.
1645 reason -- Reason phrase. Put empty to send default reason
1646 phrase for the status code.
1647 hdr_list -- Optional list of headers to be sent with the
1648 INVITE response.
1649
1650 """
1651 lck = self._lib().auto_lock()
1652 err = _pjsua.call_answer(self._id, code, reason,
1653 Lib._create_msg_data(hdr_list))
1654 self._lib()._err_check("answer()", self, err)
1655
1656 def hangup(self, code=603, reason="", hdr_list=None):
1657 """
1658 Terminate the call.
1659
1660 Keyword arguments:
1661 code -- SIP status code.
1662 reason -- Reason phrase. Put empty to send default reason
1663 phrase for the status code.
1664 hdr_list -- Optional list of headers to be sent with the
1665 message.
1666
1667 """
1668 lck = self._lib().auto_lock()
1669 err = _pjsua.call_hangup(self._id, code, reason,
1670 Lib._create_msg_data(hdr_list))
1671 self._lib()._err_check("hangup()", self, err)
1672
1673 def hold(self, hdr_list=None):
1674 """
1675 Put the call on hold.
1676
1677 Keyword arguments:
1678 hdr_list -- Optional list of headers to be sent with the
1679 message.
1680 """
1681 lck = self._lib().auto_lock()
1682 err = _pjsua.call_set_hold(self._id, Lib._create_msg_data(hdr_list))
1683 self._lib()._err_check("hold()", self, err)
1684
1685 def unhold(self, hdr_list=None):
1686 """
1687 Release the call from hold.
1688
1689 Keyword arguments:
1690 hdr_list -- Optional list of headers to be sent with the
1691 message.
1692
1693 """
1694 lck = self._lib().auto_lock()
1695 err = _pjsua.call_reinvite(self._id, True,
1696 Lib._create_msg_data(hdr_list))
1697 self._lib()._err_check("unhold()", self, err)
1698
1699 def reinvite(self, hdr_list=None):
1700 """
1701 Send re-INVITE and optionally offer new codecs to use.
1702
1703 Keyword arguments:
1704 hdr_list -- Optional list of headers to be sent with the
1705 message.
1706
1707 """
1708 lck = self._lib().auto_lock()
1709 err = _pjsua.call_reinvite(self._id, True,
1710 Lib._create_msg_data(hdr_list))
1711 self._lib()._err_check("reinvite()", self, err)
1712
1713 def update(self, hdr_list=None, options=0):
1714 """
1715 Send UPDATE and optionally offer new codecs to use.
1716
1717 Keyword arguments:
1718 hdr_list -- Optional list of headers to be sent with the
1719 message.
1720 options -- Must be zero for now.
1721
1722 """
1723 lck = self._lib().auto_lock()
1724 err = _pjsua.call_update(self._id, options,
1725 Lib._create_msg_data(hdr_list))
1726 self._lib()._err_check("update()", self, err)
1727
1728 def transfer(self, dest_uri, hdr_list=None):
1729 """
1730 Transfer the call to new destination.
1731
1732 Keyword arguments:
1733 dest_uri -- Specify the SIP URI to transfer the call to.
1734 hdr_list -- Optional list of headers to be sent with the
1735 message.
1736
1737 """
1738 lck = self._lib().auto_lock()
1739 err = _pjsua.call_xfer(self._id, dest_uri,
1740 Lib._create_msg_data(hdr_list))
1741 self._lib()._err_check("transfer()", self, err)
1742
1743 def transfer_to_call(self, call, hdr_list=None, options=0):
1744 """
1745 Attended call transfer.
1746
1747 Keyword arguments:
1748 call -- The Call object to transfer call to.
1749 hdr_list -- Optional list of headers to be sent with the
1750 message.
1751 options -- Must be zero for now.
1752
1753 """
1754 lck = self._lib().auto_lock()
1755 err = _pjsua.call_xfer_replaces(self._id, call._id, options,
1756 Lib._create_msg_data(hdr_list))
1757 self._lib()._err_check("transfer_to_call()", self, err)
1758
1759 def dial_dtmf(self, digits):
1760 """
1761 Send DTMF digits with RTP event package.
1762
1763 Keyword arguments:
1764 digits -- DTMF digit string.
1765
1766 """
1767 lck = self._lib().auto_lock()
1768 err = _pjsua.call_dial_dtmf(self._id, digits)
1769 self._lib()._err_check("dial_dtmf()", self, err)
1770
1771 def send_request(self, method, hdr_list=None, content_type=None,
1772 body=None):
1773 """
1774 Send arbitrary request to remote call.
1775
1776 This is useful for example to send INFO request. Note that this
1777 function should not be used to send request that will change the
1778 call state such as CANCEL or BYE.
1779
1780 Keyword arguments:
1781 method -- SIP method name.
1782 hdr_list -- Optional header list to be sent with the request.
1783 content_type -- Content type to describe the body, if the body
1784 is present
1785 body -- Optional SIP message body.
1786
1787 """
1788 lck = self._lib().auto_lock()
1789 if hdr_list or body:
1790 msg_data = _pjsua.Msg_Data()
1791 if hdr_list:
1792 msg_data.hdr_list = hdr_list
1793 if content_type:
1794 msg_data.content_type = content_type
1795 if body:
1796 msg_data.msg_body = body
1797 else:
1798 msg_data = None
1799
1800 err = _pjsua.call_send_request(self._id, method, msg_data)
1801 self._lib()._err_check("send_request()", self, err)
1802
1803 def send_pager(self, text, im_id=0, content_type="text/plain",
1804 hdr_list=None):
1805 """Send instant message inside a call.
1806
1807 Keyword arguments:
1808 text -- Instant message to be sent
1809 im_id -- Optional instant message ID to identify this
1810 instant message when delivery status callback
1811 is called.
1812 content_type -- MIME type identifying the instant message
1813 hdr_list -- Optional list of headers to be sent with the
1814 request.
1815
1816 """
1817 lck = self._lib().auto_lock()
1818 err = _pjsua.call_send_im(self._id, \
1819 content_type, text, \
1820 Lib._create_msg_data(hdr_list), \
1821 im_id)
1822 self._lib()._err_check("send_pager()", self, err)
1823
1824
1825 class BuddyInfo:
1826 """This class contains information about Buddy. Application may
1827 retrieve this information by calling Buddy.info().
1828
1829 Member documentation:
1830
1831 uri -- the Buddy URI.
1832 contact -- the Buddy Contact URI, if available.
1833 online_status -- the presence online status.
1834 online_text -- the presence online status text.
1835 activity -- the PresenceActivity
1836 subscribed -- specify whether buddy's presence status is currently
1837 being subscribed.
1838 sub_state -- SubscriptionState
1839 sub_term_reason -- The termination reason string of the last presence
1840 subscription to this buddy, if any.
1841 """
1842 uri = ""
1843 contact = ""
1844 online_status = 0
1845 online_text = ""
1846 activity = PresenceActivity.UNKNOWN
1847 subscribed = False
1848 sub_state = SubscriptionState.NULL
1849 sub_term_reason = ""
1850
1851 def __init__(self, pjsua_bi=None):
1852 if pjsua_bi:
1853 self._cvt_from_pjsua(pjsua_bi)
1854
1855 def _cvt_from_pjsua(self, inf):
1856 self.uri = inf.uri
1857 self.contact = inf.contact
1858 self.online_status = inf.status
1859 self.online_text = inf.status_text
1860 self.activity = inf.activity
1861 self.subscribed = inf.monitor_pres
1862 self.sub_state = inf.sub_state
1863 self.sub_term_reason = inf.sub_term_reason
1864
1865
1866 class BuddyCallback:
1867 """This class can be used to receive notifications about Buddy's
1868 presence status change. Application needs to derive a class from
1869 this class, and register the instance with Buddy.set_callback().
1870
1871 Member documentation:
1872
1873 buddy -- the Buddy object.
1874 """
1875 buddy = None
1876
1877 def __init__(self, buddy=None):
1878 self._set_buddy(buddy)
1879
1880 def _set_buddy(self, buddy):
1881 if buddy:
1882 self.buddy = weakref.proxy(buddy)
1883 else:
1884 self.buddy = None
1885
1886 def on_state(self):
1887 """
1888 Notification that buddy's presence state has changed. Application
1889 may then retrieve the new status with Buddy.info() function.
1890 """
1891 pass
1892
1893 def on_pager(self, mime_type, body):
1894 """Notification that incoming instant message is received from
1895 this buddy.
1896
1897 Keyword arguments:
1898 mime_type -- MIME type of the instant message body
1899 body -- the instant message body
1900
1901 """
1902 pass
1903
1904 def on_pager_status(self, body, im_id, code, reason):
1905 """Notification about the delivery status of previously sent
1906 instant message.
1907
1908 Keyword arguments:
1909 body -- the message body
1910 im_id -- message ID
1911 code -- SIP status code
1912 reason -- SIP reason phrase
1913
1914 """
1915 pass
1916
1917 def on_typing(self, is_typing):
1918 """Notification that remote is typing or stop typing.
1919
1920 Keyword arguments:
1921 is_typing -- boolean to indicate whether remote is currently
1922 typing an instant message.
1923
1924 """
1925 pass
1926
1927
1928 class Buddy:
1929 """A Buddy represents person or remote agent.
1930
1931 This class provides functions to subscribe to buddy's presence and
1932 to send or receive instant messages from the buddy.
1933 """
1934 _id = -1
1935 _lib = None
1936 _cb = None
1937 _obj_name = ""
1938 _acc = None
1939
1940 def __init__(self, lib, id, account, cb):
1941 self._id = id
1942 self._lib = weakref.ref(lib)
1943 self._acc = weakref.ref(account)
1944 self._obj_name = "{Buddy " + self.info().uri + "}"
1945 self.set_callback(cb)
1946 _pjsua.buddy_set_user_data(self._id, self)
1947 _Trace((self, 'created'))
1948
1949 def __del__(self):
1950 if self._id != -1:
1951 _pjsua.buddy_set_user_data(self._id, 0)
1952 _Trace((self, 'destroyed'))
1953
1954 def __str__(self):
1955 return self._obj_name
1956
1957 def info(self):
1958 """
1959 Get buddy info as BuddyInfo.
1960 """
1961 lck = self._lib().auto_lock()
1962 return BuddyInfo(_pjsua.buddy_get_info(self._id))
1963
1964 def set_callback(self, cb):
1965 """Install callback to receive notifications from this object.
1966
1967 Keyword argument:
1968 cb -- BuddyCallback instance.
1969 """
1970 if cb:
1971 self._cb = cb
1972 else:
1973 self._cb = BuddyCallback(self)
1974 self._cb._set_buddy(self)
1975
1976 def subscribe(self):
1977 """
1978 Subscribe to buddy's presence status notification.
1979 """
1980 lck = self._lib().auto_lock()
1981 err = _pjsua.buddy_subscribe_pres(self._id, True)
1982 self._lib()._err_check("subscribe()", self, err)
1983
1984 def unsubscribe(self):
1985 """
1986 Unsubscribe from buddy's presence status notification.
1987 """
1988 lck = self._lib().auto_lock()
1989 err = _pjsua.buddy_subscribe_pres(self._id, False)
1990 self._lib()._err_check("unsubscribe()", self, err)
1991
1992 def delete(self):
1993 """
1994 Remove this buddy from the buddy list.
1995 """
1996 lck = self._lib().auto_lock()
1997 if self._id != -1:
1998 _pjsua.buddy_set_user_data(self._id, 0)
1999 err = _pjsua.buddy_del(self._id)
2000 self._lib()._err_check("delete()", self, err)
2001
2002 def send_pager(self, text, im_id=0, content_type="text/plain", \
2003 hdr_list=None):
2004 """Send instant message to remote buddy.
2005
2006 Keyword arguments:
2007 text -- Instant message to be sent
2008 im_id -- Optional instant message ID to identify this
2009 instant message when delivery status callback
2010 is called.
2011 content_type -- MIME type identifying the instant message
2012 hdr_list -- Optional list of headers to be sent with the
2013 request.
2014
2015 """
2016 lck = self._lib().auto_lock()
2017 err = _pjsua.im_send(self._acc()._id, self.info().uri, \
2018 content_type, text, \
2019 Lib._create_msg_data(hdr_list), \
2020 im_id)
2021 self._lib()._err_check("send_pager()", self, err)
2022
2023 def send_typing_ind(self, is_typing=True, hdr_list=None):
2024 """Send typing indication to remote buddy.
2025
2026 Keyword argument:
2027 is_typing -- boolean to indicate wheter user is typing.
2028 hdr_list -- Optional list of headers to be sent with the
2029 request.
2030
2031 """
2032 lck = self._lib().auto_lock()
2033 err = _pjsua.im_typing(self._acc()._id, self.info().uri, \
2034 is_typing, Lib._create_msg_data(hdr_list))
2035 self._lib()._err_check("send_typing_ind()", self, err)
2036
2037
2038
2039 # Sound device info
2040 class SoundDeviceInfo:
2041 """This described the sound device info.
2042
2043 Member documentation:
2044 name -- device name.
2045 input_channels -- number of capture channels supported.
2046 output_channels -- number of playback channels supported.
2047 default_clock_rate -- default sampling rate.
2048 """
2049 name = ""
2050 input_channels = 0
2051 output_channels = 0
2052 default_clock_rate = 0
2053
2054 def __init__(self, sdi):
2055 self.name = sdi.name
2056 self.input_channels = sdi.input_count
2057 self.output_channels = sdi.output_count
2058 self.default_clock_rate = sdi.default_samples_per_sec
2059
2060
2061 # Codec info
2062 class CodecInfo:
2063 """This describes codec info.
2064
2065 Member documentation:
2066 name -- codec name
2067 priority -- codec priority (0-255)
2068 clock_rate -- clock rate
2069 channel_count -- number of channels
2070 avg_bps -- average bandwidth in bits per second
2071 frm_ptime -- base frame length in milliseconds
2072 ptime -- RTP frame length in milliseconds.
2073 pt -- payload type.
2074 vad_enabled -- specify if Voice Activity Detection is currently
2075 enabled.
2076 plc_enabled -- specify if Packet Lost Concealment is currently
2077 enabled.
2078 """
2079 name = ""
2080 priority = 0
2081 clock_rate = 0
2082 channel_count = 0
2083 avg_bps = 0
2084 frm_ptime = 0
2085 ptime = 0
2086 pt = 0
2087 vad_enabled = False
2088 plc_enabled = False
2089
2090 def __init__(self, codec_info, codec_param):
2091 self.name = codec_info.codec_id
2092 self.priority = codec_info.priority
2093 self.clock_rate = codec_param.info.clock_rate
2094 self.channel_count = codec_param.info.channel_cnt
2095 self.avg_bps = codec_param.info.avg_bps
2096 self.frm_ptime = codec_param.info.frm_ptime
2097 self.ptime = codec_param.info.frm_ptime * \
2098 codec_param.setting.frm_per_pkt
2099 self.ptime = codec_param.info.pt
2100 self.vad_enabled = codec_param.setting.vad
2101 self.plc_enabled = codec_param.setting.plc
2102
2103 def _cvt_to_pjsua(self):
2104 ci = _pjsua.Codec_Info()
2105 ci.codec_id = self.name
2106 ci.priority = self.priority
2107 return ci
2108
2109
2110 # Codec parameter
2111 class CodecParameter:
2112 """This specifies various parameters that can be configured for codec.
2113
2114 Member documentation:
2115
2116 ptime -- specify the outgoing RTP packet length in milliseconds.
2117 vad_enabled -- specify if VAD should be enabled.
2118 plc_enabled -- specify if PLC should be enabled.
2119 """
2120 ptime = 0
2121 vad_enabled = False
2122 plc_enabled = False
2123 _codec_param = None
2124
2125 def __init__(self, codec_param):
2126 self.ptime = codec_param.info.frm_ptime * \
2127 codec_param.setting.frm_per_pkt
2128 self.vad_enabled = codec_param.setting.vad
2129 self.plc_enabled = codec_param.setting.plc
2130 self._codec_param = codec_param
2131
2132 def _cvt_to_pjsua(self):
2133 self._codec_param.setting.frm_per_pkt = self.ptime / \
2134 self._codec_param.info.frm_ptime
2135 self._codec_param.setting.vad = self.vad_enabled
2136 self._codec_param.setting.plc = self.plc_enabled
2137 return self._codec_param
2138
2139
2140 # Library mutex
2141 class _LibMutex:
2142 def __init__(self, lck):
2143 self._lck = lck
2144 self._lck.acquire()
2145 #_Trace(('lock acquired',))
2146
2147 def __del__(self):
2148 try:
2149 self._lck.release()
2150 #_Trace(('lock released',))
2151 except:
2152 #_Trace(('lock release error',))
2153 pass
2154
2155
2156 # PJSUA Library
2157 _lib = None
2158 enable_trace = False
2159
2160 class Lib:
2161 """Library instance.
2162
2163 """
2164 _quit = False
2165 _has_thread = False
2166 _lock = None
2167
2168 def __init__(self):
2169 global _lib
2170 if _lib:
2171 raise Error("__init()__", None, -1,
2172 "Library instance already exist")
2173
2174 self._lock = threading.RLock()
2175 err = _pjsua.create()
2176 self._err_check("_pjsua.create()", None, err)
2177 _lib = self
2178
2179 def __del__(self):
2180 _pjsua.destroy()
2181 del self._lock
2182 _Trace(('Lib destroyed',))
2183
2184 def __str__(self):
2185 return "Lib"
2186
2187 @staticmethod
2188 def instance():
2189 """Return singleton instance of Lib.
2190 """
2191 return _lib
2192
2193 def init(self, ua_cfg=None, log_cfg=None, media_cfg=None):
2194 """
2195 Initialize pjsua with the specified configurations.
2196
2197 Keyword arguments:
2198 ua_cfg -- optional UAConfig instance
2199 log_cfg -- optional LogConfig instance
2200 media_cfg -- optional MediaConfig instance
2201
2202 """
2203 if not ua_cfg: ua_cfg = UAConfig()
2204 if not log_cfg: log_cfg = LogConfig()
2205 if not media_cfg: media_cfg = MediaConfig()
2206
2207 py_ua_cfg = ua_cfg._cvt_to_pjsua()
2208 py_ua_cfg.cb.on_call_state = _cb_on_call_state
2209 py_ua_cfg.cb.on_incoming_call = _cb_on_incoming_call
2210 py_ua_cfg.cb.on_call_media_state = _cb_on_call_media_state
2211 py_ua_cfg.cb.on_dtmf_digit = _cb_on_dtmf_digit
2212 py_ua_cfg.cb.on_call_transfer_request = _cb_on_call_transfer_request
2213 py_ua_cfg.cb.on_call_transfer_status = _cb_on_call_transfer_status
2214 py_ua_cfg.cb.on_call_replace_request = _cb_on_call_replace_request
2215 py_ua_cfg.cb.on_call_replaced = _cb_on_call_replaced
2216 py_ua_cfg.cb.on_reg_state = _cb_on_reg_state
2217 py_ua_cfg.cb.on_incoming_subscribe = _cb_on_incoming_subscribe
2218 py_ua_cfg.cb.on_buddy_state = _cb_on_buddy_state
2219 py_ua_cfg.cb.on_pager = _cb_on_pager
2220 py_ua_cfg.cb.on_pager_status = _cb_on_pager_status
2221 py_ua_cfg.cb.on_typing = _cb_on_typing
2222 py_ua_cfg.cb.on_mwi_info = _cb_on_mwi_info;
2223
2224 err = _pjsua.init(py_ua_cfg, log_cfg._cvt_to_pjsua(),
2225 media_cfg._cvt_to_pjsua())
2226 self._err_check("init()", self, err)
2227
2228 def destroy(self):
2229 """Destroy the library, and pjsua."""
2230 global _lib
2231 if self._has_thread:
2232 self._quit = 1
2233 loop = 0
2234 while self._quit != 2 and loop < 400:
2235 self.handle_events(5)
2236 loop = loop + 1
2237 time.sleep(0.050)
2238 _pjsua.destroy()
2239 _lib = None
2240
2241 def start(self, with_thread=True):
2242 """Start the library.
2243
2244 Keyword argument:
2245 with_thread -- specify whether the module should create worker
2246 thread.
2247
2248 """
2249 lck = self.auto_lock()
2250 err = _pjsua.start()
2251 self._err_check("start()", self, err)
2252 self._has_thread = with_thread
2253 if self._has_thread:
2254 thread.start_new(_worker_thread_main, (0,))
2255
2256 def handle_events(self, timeout=50):
2257 """Poll the events from underlying pjsua library.
2258
2259 Application must poll the stack periodically if worker thread
2260 is disable when starting the library.
2261
2262 Keyword argument:
2263 timeout -- in milliseconds.
2264
2265 """
2266 lck = self.auto_lock()
2267 return _pjsua.handle_events(timeout)
2268
2269 def thread_register(self, name):
2270 """Register external threads (threads that are not created by PJSIP,
2271 such as threads that are created by Python API) to PJSIP.
2272
2273 The call must be made from the new thread before calling any pjlib
2274 functions.
2275
2276 Keyword arguments:
2277 name -- Non descriptive name for the thread
2278 """
2279 dummy = 1
2280 err = _pjsua.thread_register(name, dummy)
2281 self._err_check("thread_register()", self, err)
2282
2283 def verify_sip_url(self, sip_url):
2284 """Verify that the specified string is a valid URI.
2285
2286 Keyword argument:
2287 sip_url -- the URL string.
2288
2289 Return:
2290 0 is the the URI is valid, otherwise the appropriate error
2291 code is returned.
2292
2293 """
2294 lck = self.auto_lock()
2295 return _pjsua.verify_sip_url(sip_url)
2296
2297 def create_transport(self, type, cfg=None):
2298 """Create SIP transport instance of the specified type.
2299
2300 Keyword arguments:
2301 type -- transport type from TransportType constant.
2302 cfg -- TransportConfig instance
2303
2304 Return:
2305 Transport object
2306
2307 """
2308 lck = self.auto_lock()
2309 if not cfg: cfg=TransportConfig()
2310 err, tp_id = _pjsua.transport_create(type, cfg._cvt_to_pjsua())
2311 self._err_check("create_transport()", self, err)
2312 return Transport(self, tp_id)
2313
2314 def create_account(self, acc_config, set_default=True, cb=None):
2315 """
2316 Create a new local pjsua account using the specified configuration.
2317
2318 Keyword arguments:
2319 acc_config -- AccountConfig
2320 set_default -- boolean to specify whether to use this as the
2321 default account.
2322 cb -- AccountCallback instance.
2323
2324 Return:
2325 Account instance
2326
2327 """
2328 lck = self.auto_lock()
2329 err, acc_id = _pjsua.acc_add(acc_config._cvt_to_pjsua(), set_default)
2330 self._err_check("create_account()", self, err)
2331 return Account(self, acc_id, cb)
2332
2333 def create_account_for_transport(self, transport, set_default=True,
2334 cb=None):
2335 """Create a new local pjsua transport for the specified transport.
2336
2337 Keyword arguments:
2338 transport -- the Transport instance.
2339 set_default -- boolean to specify whether to use this as the
2340 default account.
2341 cb -- AccountCallback instance.
2342
2343 Return:
2344 Account instance
2345
2346 """
2347 lck = self.auto_lock()
2348 err, acc_id = _pjsua.acc_add_local(transport._id, set_default)
2349 self._err_check("create_account_for_transport()", self, err)
2350 return Account(self, acc_id, cb)
2351
2352 def modify_account(self, acc_id, acc_config):
2353 """Modify configuration of a pjsua account.
2354
2355 Keyword arguments:
2356 acc_id -- ID of the account to be modified.
2357 acc_config -- New account configuration.
2358
2359 """
2360 lck = self.auto_lock()
2361 err = _pjsua.acc_modify(acc_id, acc_config._cvt_to_pjsua())
2362 self._err_check("modify_account()", self, err)
2363
2364 def hangup_all(self):
2365 """Hangup all calls.
2366
2367 """
2368 lck = self.auto_lock()
2369 _pjsua.call_hangup_all()
2370
2371 # Sound device API
2372
2373 def enum_snd_dev(self):
2374 """Enumerate sound devices in the system.
2375
2376 Return:
2377 list of SoundDeviceInfo. The index of the element specifies
2378 the device ID for the device.
2379 """
2380 lck = self.auto_lock()
2381 sdi_list = _pjsua.enum_snd_devs()
2382 info = []
2383 for sdi in sdi_list:
2384 info.append(SoundDeviceInfo(sdi))
2385 return info
2386
2387 def get_snd_dev(self):
2388 """Get the device IDs of current sound devices used by pjsua.
2389
2390 Return:
2391 (capture_dev_id, playback_dev_id) tuple
2392 """
2393 lck = self.auto_lock()
2394 return _pjsua.get_snd_dev()
2395
2396 def set_snd_dev(self, capture_dev, playback_dev):
2397 """Change the current sound devices.
2398
2399 Keyword arguments:
2400 capture_dev -- the device ID of capture device to be used
2401 playback_dev -- the device ID of playback device to be used.
2402
2403 """
2404 lck = self.auto_lock()
2405 err = _pjsua.set_snd_dev(capture_dev, playback_dev)
2406 self._err_check("set_current_sound_devices()", self, err)
2407
2408 def set_null_snd_dev(self):
2409 """Disable the sound devices. This is useful if the system
2410 does not have sound device installed.
2411
2412 """
2413 lck = self.auto_lock()
2414 err = _pjsua.set_null_snd_dev()
2415 self._err_check("set_null_snd_dev()", self, err)
2416
2417
2418 # Conference bridge
2419
2420 def conf_get_max_ports(self):
2421 """Get the conference bridge capacity.
2422
2423 Return:
2424 conference bridge capacity.
2425
2426 """
2427 lck = self.auto_lock()
2428 return _pjsua.conf_get_max_ports()
2429
2430 def conf_connect(self, src_slot, dst_slot):
2431 """Establish unidirectional media flow from souce to sink.
2432
2433 One source may transmit to multiple destinations/sink. And if
2434 multiple sources are transmitting to the same sink, the media
2435 will be mixed together. Source and sink may refer to the same ID,
2436 effectively looping the media.
2437
2438 If bidirectional media flow is desired, application needs to call
2439 this function twice, with the second one having the arguments
2440 reversed.
2441
2442 Keyword arguments:
2443 src_slot -- integer to identify the conference slot number of
2444 the source/transmitter.
2445 dst_slot -- integer to identify the conference slot number of
2446 the destination/receiver.
2447
2448 """
2449 lck = self.auto_lock()
2450 err = _pjsua.conf_connect(src_slot, dst_slot)
2451 self._err_check("conf_connect()", self, err)
2452
2453 def conf_disconnect(self, src_slot, dst_slot):
2454 """Disconnect media flow from the source to destination port.
2455
2456 Keyword arguments:
2457 src_slot -- integer to identify the conference slot number of
2458 the source/transmitter.
2459 dst_slot -- integer to identify the conference slot number of
2460 the destination/receiver.
2461
2462 """
2463 lck = self.auto_lock()
2464 err = _pjsua.conf_disconnect(src_slot, dst_slot)
2465 self._err_check("conf_disconnect()", self, err)
2466
2467 def conf_set_tx_level(self, slot, level):
2468 """Adjust the signal level to be transmitted from the bridge to
2469 the specified port by making it louder or quieter.
2470
2471 Keyword arguments:
2472 slot -- integer to identify the conference slot number.
2473 level -- Signal level adjustment. Value 1.0 means no level
2474 adjustment, while value 0 means to mute the port.
2475 """
2476 lck = self.auto_lock()
2477 err = _pjsua.conf_set_tx_level(slot, level)
2478 self._err_check("conf_set_tx_level()", self, err)
2479
2480 def conf_set_rx_level(self, slot, level):
2481 """Adjust the signal level to be received from the specified port
2482 (to the bridge) by making it louder or quieter.
2483
2484 Keyword arguments:
2485 slot -- integer to identify the conference slot number.
2486 level -- Signal level adjustment. Value 1.0 means no level
2487 adjustment, while value 0 means to mute the port.
2488 """
2489 lck = self.auto_lock()
2490 err = _pjsua.conf_set_rx_level(slot, level)
2491 self._err_check("conf_set_rx_level()", self, err)
2492
2493 def conf_get_signal_level(self, slot):
2494 """Get last signal level transmitted to or received from the
2495 specified port. The signal levels are float values from 0.0 to 1.0,
2496 with 0.0 indicates no signal, and 1.0 indicates the loudest signal
2497 level.
2498
2499 Keyword arguments:
2500 slot -- integer to identify the conference slot number.
2501
2502 Return value:
2503 (tx_level, rx_level) tuple.
2504 """
2505 lck = self.auto_lock()
2506 err, tx_level, rx_level = _pjsua.conf_get_signal_level(slot)
2507 self._err_check("conf_get_signal_level()", self, err)
2508 return (tx_level, rx_level)
2509
2510
2511
2512 # Codecs API
2513
2514 def enum_codecs(self):
2515 """Return list of codecs supported by pjsua.
2516
2517 Return:
2518 list of CodecInfo
2519
2520 """
2521 lck = self.auto_lock()
2522 ci_list = _pjsua.enum_codecs()
2523 codec_info = []
2524 for ci in ci_list:
2525 cp = _pjsua.codec_get_param(ci.codec_id)
2526 if cp:
2527 codec_info.append(CodecInfo(ci, cp))
2528 return codec_info
2529
2530 def set_codec_priority(self, name, priority):
2531 """Change the codec priority.
2532
2533 Keyword arguments:
2534 name -- Codec name
2535 priority -- Codec priority, which range is 0-255.
2536
2537 """
2538 lck = self.auto_lock()
2539 err = _pjsua.codec_set_priority(name, priority)
2540 self._err_check("set_codec_priority()", self, err)
2541
2542 def get_codec_parameter(self, name):
2543 """Get codec parameter for the specified codec.
2544
2545 Keyword arguments:
2546 name -- codec name.
2547
2548 """
2549 lck = self.auto_lock()
2550 cp = _pjsua.codec_get_param(name)
2551 if not cp:
2552 self._err_check("get_codec_parameter()", self, -1,
2553 "Invalid codec name")
2554 return CodecParameter(cp)
2555
2556 def set_codec_parameter(self, name, param):
2557 """Modify codec parameter for the specified codec.
2558
2559 Keyword arguments:
2560 name -- codec name
2561 param -- codec parameter.
2562
2563 """
2564 lck = self.auto_lock()
2565 err = _pjsua.codec_set_param(name, param._cvt_to_pjsua())
2566 self._err_check("set_codec_parameter()", self, err)
2567
2568 # WAV playback and recording
2569
2570 def create_player(self, filename, loop=False):
2571 """Create WAV file player.
2572
2573 Keyword arguments
2574 filename -- WAV file name
2575 loop -- boolean to specify whether playback should
2576 automatically restart upon EOF
2577 Return:
2578 WAV player ID
2579
2580 """
2581 lck = self.auto_lock()
2582 opt = 0
2583 if not loop:
2584 opt = opt + 1
2585 err, player_id = _pjsua.player_create(filename, opt)
2586 self._err_check("create_player()", self, err)
2587 return player_id
2588
2589 def player_get_slot(self, player_id):
2590 """Get the conference port ID for the specified player.
2591
2592 Keyword arguments:
2593 player_id -- the WAV player ID
2594
2595 Return:
2596 Conference slot number for the player
2597
2598 """
2599 lck = self.auto_lock()
2600 slot = _pjsua.player_get_conf_port(player_id)
2601 if slot < 0:
2602 self._err_check("player_get_slot()", self, -1,
2603 "Invalid player id")
2604 return slot
2605
2606 def player_set_pos(self, player_id, pos):
2607 """Set WAV playback position.
2608
2609 Keyword arguments:
2610 player_id -- WAV player ID
2611 pos -- playback position, in samples
2612
2613 """
2614 lck = self.auto_lock()
2615 err = _pjsua.player_set_pos(player_id, pos)
2616 self._err_check("player_set_pos()", self, err)
2617
2618 def player_destroy(self, player_id):
2619 """Destroy the WAV player.
2620
2621 Keyword arguments:
2622 player_id -- the WAV player ID.
2623
2624 """
2625 lck = self.auto_lock()
2626 err = _pjsua.player_destroy(player_id)
2627 self._err_check("player_destroy()", self, err)
2628
2629 def create_playlist(self, filelist, label="playlist", loop=True):
2630 """Create WAV playlist.
2631
2632 Keyword arguments:
2633 filelist -- List of WAV file names.
2634 label -- Optional name to be assigned to the playlist
2635 object (useful for logging)
2636 loop -- boolean to specify whether playback should
2637 automatically restart upon EOF
2638
2639 Return:
2640 playlist_id
2641 """
2642 lck = self.auto_lock()
2643 opt = 0
2644 if not loop:
2645 opt = opt + 1
2646 err, playlist_id = _pjsua.playlist_create(label, filelist, opt)
2647 self._err_check("create_playlist()", self, err)
2648 return playlist_id
2649
2650 def playlist_get_slot(self, playlist_id):
2651 """Get the conference port ID for the specified playlist.
2652
2653 Keyword arguments:
2654 playlist_id -- the WAV playlist ID
2655
2656 Return:
2657 Conference slot number for the playlist
2658
2659 """
2660 lck = self.auto_lock()
2661 slot = _pjsua.player_get_conf_port(playlist_id)
2662 if slot < 0:
2663 self._err_check("playlist_get_slot()", self, -1,
2664 "Invalid playlist id")
2665 return slot
2666
2667 def playlist_destroy(self, playlist_id):
2668 """Destroy the WAV playlist.
2669
2670 Keyword arguments:
2671 playlist_id -- the WAV playlist ID.
2672
2673 """
2674 lck = self.auto_lock()
2675 err = _pjsua.player_destroy(playlist_id)
2676 self._err_check("playlist_destroy()", self, err)
2677
2678 def create_recorder(self, filename):
2679 """Create WAV file recorder.
2680
2681 Keyword arguments
2682 filename -- WAV file name
2683
2684 Return:
2685 WAV recorder ID
2686
2687 """
2688 lck = self.auto_lock()
2689 err, rec_id = _pjsua.recorder_create(filename, 0, None, -1, 0)
2690 self._err_check("create_recorder()", self, err)
2691 return rec_id
2692
2693 def recorder_get_slot(self, rec_id):
2694 """Get the conference port ID for the specified recorder.
2695
2696 Keyword arguments:
2697 rec_id -- the WAV recorder ID
2698
2699 Return:
2700 Conference slot number for the recorder
2701
2702 """
2703 lck = self.auto_lock()
2704 slot = _pjsua.recorder_get_conf_port(rec_id)
2705 if slot < 1:
2706 self._err_check("recorder_get_slot()", self, -1,
2707 "Invalid recorder id")
2708 return slot
2709
2710 def recorder_destroy(self, rec_id):
2711 """Destroy the WAV recorder.
2712
2713 Keyword arguments:
2714 rec_id -- the WAV recorder ID.
2715
2716 """
2717 lck = self.auto_lock()
2718 err = _pjsua.recorder_destroy(rec_id)
2719 self._err_check("recorder_destroy()", self, err)
2720
2721
2722 # Internal functions
2723
2724 @staticmethod
2725 def strerror(err):
2726 return _pjsua.strerror(err)
2727
2728 def _err_check(self, op_name, obj, err_code, err_msg=""):
2729 if err_code != 0:
2730 raise Error(op_name, obj, err_code, err_msg)
2731
2732 @staticmethod
2733 def _create_msg_data(hdr_list):
2734 if not hdr_list:
2735 return None
2736 msg_data = _pjsua.Msg_Data()
2737 msg_data.hdr_list = hdr_list
2738 return msg_data
2739
2740 def auto_lock(self):
2741 return _LibMutex(self._lock)
2742
2743 # Internal dictionary manipulation for calls, accounts, and buddies
2744
2745 def _lookup_call(self, call_id):
2746 return _pjsua.call_get_user_data(call_id)
2747
2748 def _lookup_account(self, acc_id):
2749 return _pjsua.acc_get_user_data(acc_id)
2750
2751 def _lookup_buddy(self, buddy_id, uri=None):
2752 if buddy_id != -1:
2753 buddy = _pjsua.buddy_get_user_data(buddy_id)
2754 elif uri:
2755 buddy_id = _pjsua.buddy_find(uri)
2756 if buddy_id != -1:
2757 buddy = _pjsua.buddy_get_user_data(buddy_id)
2758 else:
2759 buddy = None
2760 else:
2761 buddy = None
2762
2763 return buddy
2764
2765 # Account allbacks
2766
2767 def _cb_on_reg_state(self, acc_id):
2768 acc = self._lookup_account(acc_id)
2769 if acc:
2770 acc._cb.on_reg_state()
2771
2772 def _cb_on_incoming_subscribe(self, acc_id, buddy_id, from_uri,
2773 contact_uri, pres_obj):
2774 acc = self._lookup_account(acc_id)
2775 if acc:
2776 buddy = self._lookup_buddy(buddy_id)
2777 return acc._cb.on_incoming_subscribe(buddy, from_uri, contact_uri,
2778 pres_obj)
2779 else:
2780 return (404, None)
2781
2782 def _cb_on_incoming_call(self, acc_id, call_id, rdata):
2783 acc = self._lookup_account(acc_id)
2784 if acc:
2785 if 'on_incoming_call2' in acc._cb.__class__.__dict__:
2786 acc._cb.on_incoming_call2( Call(self, call_id), rdata )
2787 else:
2788 acc._cb.on_incoming_call( Call(self, call_id) )
2789 else:
2790 _pjsua.call_hangup(call_id, 603, None, None)
2791
2792 # Call callbacks
2793
2794 def _cb_on_call_state(self, call_id):
2795 call = self._lookup_call(call_id)
2796 if call:
2797 if call._id == -1:
2798 call.attach_to_id(call_id)
2799 done = (call.info().state == CallState.DISCONNECTED)
2800 call._cb.on_state()
2801 if done:
2802 _pjsua.call_set_user_data(call_id, 0)
2803 else:
2804 pass
2805
2806 def _cb_on_call_media_state(self, call_id):
2807 call = self._lookup_call(call_id)
2808 if call:
2809 call._cb.on_media_state()
2810
2811 def _cb_on_dtmf_digit(self, call_id, digits):
2812 call = self._lookup_call(call_id)
2813 if call:
2814 call._cb.on_dtmf_digit(digits)
2815
2816 def _cb_on_call_transfer_request(self, call_id, dst, code):
2817 call = self._lookup_call(call_id)
2818 if call:
2819 return call._cb.on_transfer_request(dst, code)
2820 else:
2821 return 603
2822
2823 def _cb_on_call_transfer_status(self, call_id, code, text, final, cont):
2824 call = self._lookup_call(call_id)
2825 if call:
2826 return call._cb.on_transfer_status(code, text, final, cont)
2827 else:
2828 return cont
2829
2830 def _cb_on_call_replace_request(self, call_id, rdata, code, reason):
2831 call = self._lookup_call(call_id)
2832 if call:
2833 return call._cb.on_replace_request(code, reason)
2834 else:
2835 return code, reason
2836
2837 def _cb_on_call_replaced(self, old_call_id, new_call_id):
2838 old_call = self._lookup_call(old_call_id)
2839 new_call = self._lookup_call(new_call_id)
2840 if old_call and new_call:
2841 old_call._cb.on_replaced(new_call)
2842
2843 def _cb_on_pager(self, call_id, from_uri, to_uri, contact, mime_type,
2844 body, acc_id):
2845 call = None
2846 if call_id != -1:
2847 call = self._lookup_call(call_id)
2848 if call:
2849 call._cb.on_pager(mime_type, body)
2850 else:
2851 acc = self._lookup_account(acc_id)
2852 buddy = self._lookup_buddy(-1, from_uri)
2853 if buddy:
2854 buddy._cb.on_pager(mime_type, body)
2855 else:
2856 acc._cb.on_pager(from_uri, contact, mime_type, body)
2857
2858 def _cb_on_pager_status(self, call_id, to_uri, body, user_data,
2859 code, reason, acc_id):
2860 call = None
2861 if call_id != -1:
2862 call = self._lookup_call(call_id)
2863 if call:
2864 call._cb.on_pager_status(body, user_data, code, reason)
2865 else:
2866 acc = self._lookup_account(acc_id)
2867 buddy = self._lookup_buddy(-1, to_uri)
2868 if buddy:
2869 buddy._cb.on_pager_status(body, user_data, code, reason)
2870 else:
2871 acc._cb.on_pager_status(to_uri, body, user_data, code, reason)
2872
2873 def _cb_on_typing(self, call_id, from_uri, to_uri, contact, is_typing,
2874 acc_id):
2875 call = None
2876 if call_id != -1:
2877 call = self._lookup_call(call_id)
2878 if call:
2879 call._cb.on_typing(is_typing)
2880 else:
2881 acc = self._lookup_account(acc_id)
2882 buddy = self._lookup_buddy(-1, from_uri)
2883 if buddy:
2884 buddy._cb.on_typing(is_typing)
2885 else:
2886 acc._cb.on_typing(from_uri, contact, is_typing)
2887
2888 def _cb_on_mwi_info(self, acc_id, body):
2889 acc = self._lookup_account(acc_id)
2890 if acc:
2891 return acc._cb.on_mwi_info(body)
2892
2893 def _cb_on_buddy_state(self, buddy_id):
2894 buddy = self._lookup_buddy(buddy_id)
2895 if buddy:
2896 buddy._cb.on_state()
2897
2898 #
2899 # Internal
2900 #
2901
2902 def _cb_on_call_state(call_id, e):
2903 _lib._cb_on_call_state(call_id)
2904
2905 def _cb_on_incoming_call(acc_id, call_id, rdata):
2906 _lib._cb_on_incoming_call(acc_id, call_id, rdata)
2907
2908 def _cb_on_call_media_state(call_id):
2909 _lib._cb_on_call_media_state(call_id)
2910
2911 def _cb_on_dtmf_digit(call_id, digits):
2912 _lib._cb_on_dtmf_digit(call_id, digits)
2913
2914 def _cb_on_call_transfer_request(call_id, dst, code):
2915 return _lib._cb_on_call_transfer_request(call_id, dst, code)
2916
2917 def _cb_on_call_transfer_status(call_id, code, reason, final, cont):
2918 return _lib._cb_on_call_transfer_status(call_id, code, reason,
2919 final, cont)
2920 def _cb_on_call_replace_request(call_id, rdata, code, reason):
2921 return _lib._cb_on_call_replace_request(call_id, rdata, code, reason)
2922
2923 def _cb_on_call_replaced(old_call_id, new_call_id):
2924 _lib._cb_on_call_replaced(old_call_id, new_call_id)
2925
2926 def _cb_on_reg_state(acc_id):
2927 _lib._cb_on_reg_state(acc_id)
2928
2929 def _cb_on_incoming_subscribe(acc_id, buddy_id, from_uri, contact_uri, pres):
2930 return _lib._cb_on_incoming_subscribe(acc_id, buddy_id, from_uri,
2931 contact_uri, pres)
2932
2933 def _cb_on_buddy_state(buddy_id):
2934 _lib._cb_on_buddy_state(buddy_id)
2935
2936 def _cb_on_pager(call_id, from_uri, to, contact, mime_type, body, acc_id):
2937 _lib._cb_on_pager(call_id, from_uri, to, contact, mime_type, body, acc_id)
2938
2939 def _cb_on_pager_status(call_id, to, body, user_data, status, reason, acc_id):
2940 _lib._cb_on_pager_status(call_id, to, body, user_data,
2941 status, reason, acc_id)
2942
2943 def _cb_on_typing(call_id, from_uri, to, contact, is_typing, acc_id):
2944 _lib._cb_on_typing(call_id, from_uri, to, contact, is_typing, acc_id)
2945
2946 def _cb_on_mwi_info(acc_id, body):
2947 _lib._cb_on_mwi_info(acc_id, body)
2948
2949 # Worker thread
2950 def _worker_thread_main(arg):
2951 global _lib
2952 _Trace(('worker thread started..',))
2953 thread_desc = 0;
2954 err = _pjsua.thread_register("python worker", thread_desc)
2955 _lib._err_check("thread_register()", _lib, err)
2956 while _lib and _lib._quit == 0:
2957 _lib.handle_events(1)
2958 time.sleep(0.050)
2959 if _lib:
2960 _lib._quit = 2
2961 _Trace(('worker thread exited..',))
2962
2963 def _Trace(args):
2964 global enable_trace
2965 if enable_trace:
2966 print("** ", end='')
2967 for arg in args:
2968 print(arg, end=' ')
2969 print(" **")
2970