-
Notifications
You must be signed in to change notification settings - Fork 7
/
AudioController.py
1653 lines (1414 loc) · 80.5 KB
/
AudioController.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2009-2011 AG Projects. See LICENSE for details.
#
from AppKit import (NSAccessibilityChildrenAttribute,
NSAccessibilityDescriptionAttribute,
NSAccessibilityRoleDescriptionAttribute,
NSAccessibilityTitleAttribute,
NSAccessibilityUnignoredDescendant,
NSApp,
NSOffState,
NSOnState,
NSCommandKeyMask,
NSEventTrackingRunLoopMode,
NSLeftMouseUp,
NSSound)
from Foundation import (NSBundle,
NSColor,
NSDate,
NSEvent,
NSHeight,
NSImage,
NSMaxX,
NSMenu,
NSMinX,
NSRunLoop,
NSRunLoopCommonModes,
NSString,
NSLocalizedString,
NSThread,
NSTimer,
NSZeroPoint,
NSURL,
NSWorkspace)
import objc
import datetime
import os
import string
import time
import uuid
import urllib.request, urllib.parse, urllib.error
from application.notification import IObserver, NotificationCenter, NotificationData
from application.python import Null
from collections import deque
from zope.interface import implementer
from util import sip_prefix_pattern, format_size
from sipsimple.account import BonjourAccount, AccountManager
from sipsimple.application import SIPApplication
from sipsimple.audio import WavePlayer
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.streams import MediaStreamRegistry
from sipsimple.threading import call_in_thread
from sipsimple.util import ISOTimestamp
import AudioSession
from AnsweringMachine import AnsweringMachine
from BlinkLogger import BlinkLogger
from ContactListModel import BlinkPresenceContact
from HistoryManager import ChatHistory
from SessionInfoController import ice_candidates
from MediaStream import MediaStream, STREAM_IDLE, STREAM_PROPOSING, STREAM_INCOMING, STREAM_WAITING_DNS_LOOKUP, STREAM_FAILED, STREAM_RINGING, STREAM_DISCONNECTING, STREAM_CANCELLING, STREAM_CONNECTED, STREAM_CONNECTING
from MediaStream import STATE_CONNECTING, STATE_FAILED, STATE_DNS_FAILED, STATE_FINISHED
from ZRTPAuthentication import ZRTPAuthentication
from resources import Resources
from util import beautify_audio_codec, format_identity_to_string, normalize_sip_uri_for_outgoing_session, translate_alpha2digit, run_in_gui_thread
RecordingImages = []
def loadImages():
if not RecordingImages:
RecordingImages.append(NSImage.imageNamed_("recording1"))
RecordingImages.append(NSImage.imageNamed_("recording2"))
RecordingImages.append(NSImage.imageNamed_("recording3"))
STATISTICS_INTERVAL = 1.0
# For voice over IP over Ethernet, an RTP packet contains 54 bytes (or 432 bits) header. These 54 bytes consist of 14 bytes Ethernet header, 20 bytes IP header, 8 bytes UDP header and 12 bytes RTP header.
RTP_PACKET_OVERHEAD = 54
@implementer(IObserver)
class AudioController(MediaStream):
type = "audio"
view = objc.IBOutlet()
label = objc.IBOutlet()
elapsed = objc.IBOutlet()
info = objc.IBOutlet()
sessionInfoButton = objc.IBOutlet()
audioStatus = objc.IBOutlet()
srtpIcon = objc.IBOutlet()
tlsIcon = objc.IBOutlet()
segmentedButtons = objc.IBOutlet()
segmentedConferenceButtons = objc.IBOutlet()
transferMenu = objc.IBOutlet()
sessionMenu = objc.IBOutlet()
encryptionMenu = objc.IBOutlet()
zrtp_show_verify_phrase = False # show verify phrase
recordingImage = 0
audioEndTime = None
timer = None
last_stats = None
transfer_timer = None
user_hanged_up = False
transferred = False
transfer_in_progress = False
answeringMachine = None
outbound_ringtone = None
zrtp_controller = None
holdByRemote = False
holdByLocal = False
mutedInConference = False
transferEnabled = False
duration = 0
show_zrtp_ok_status_countdown = 0
recording_path = None
status = STREAM_IDLE
hangup_reason = None
early_media = False
audio_has_quality_issues = False
previous_rx_bytes = 0
previous_tx_bytes = 0
previous_tx_packets = 0
previous_rx_packets = 0
encryption_segment = 0
transfer_segment = 1
hold_segment = 2
record_segment = 3
hangup_segment = 4
normal_segments = (encryption_segment, transfer_segment, hold_segment, record_segment, hangup_segment)
conference_mute_segment = 0
conference_hold_segment = 1
conference_record_segment = 2
conference_hangup_segment = 3
conference_segments = (conference_mute_segment, conference_hold_segment, conference_record_segment, conference_hangup_segment)
timestamp = time.time()
@objc.python_method
@classmethod
def createStream(self):
return MediaStreamRegistry.AudioStream()
@objc.python_method
def resetStream(self):
self.sessionController.log_debug("Reset stream %s" % self)
self.notification_center.discard_observer(self, sender=self.stream)
self.stream = MediaStreamRegistry.AudioStream()
self.notification_center.add_observer(self, sender=self.stream)
self.previous_rx_bytes = 0
self.previous_tx_bytes = 0
self.timestamp = time.time()
self.show_zrtp_ok_status_countdown = 0
@property
def zrtp_sas(self):
if not self.zrtp_active:
return None
return self.stream.encryption.zrtp.sas
@property
def zrtp_verified(self):
if not self.zrtp_active:
return False
return self.stream.encryption.zrtp.verified
@property
def zrtp_active(self):
return self.stream.encryption.type == 'ZRTP' and self.stream.encryption.active
@property
def encryption_active(self):
return self.stream.encryption.active
@property
def srtp_active(self):
return self.stream.encryption.type == 'SRTP/SDES' and self.stream.encryption.active
@objc.python_method
def reset(self):
self.early_media = False
objc.super(AudioController, self).reset()
def initWithOwner_stream_(self, scontroller, stream):
self = objc.super(AudioController, self).initWithOwner_stream_(scontroller, stream)
scontroller.log_debug("Creating %s" % self)
self.statistics = {'loss_rx': 0, 'loss_tx': 0, 'rtt':0 , 'jitter':0 , 'rx_bytes': 0, 'tx_bytes': 0}
# 5 minutes of history data for Session Info graphs
self.loss_rx_history = deque(maxlen=300)
self.loss_tx_history = deque(maxlen=300)
self.rtt_history = deque(maxlen=300)
self.jitter_history = deque(maxlen=300)
self.rx_speed_history = deque(maxlen=300)
self.tx_speed_history = deque(maxlen=300)
self.notification_center = NotificationCenter()
self.notification_center.add_observer(self, sender=self.sessionController)
self.ice_negotiation_status = NSLocalizedString("Disabled", "Label") if not self.sessionController.account.nat_traversal.use_ice else None
NSBundle.loadNibNamed_owner_("AudioSession", self)
self.contact = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI(self.sessionController.target_uri, exact_match=True)
item = self.view.menu().itemWithTag_(20) # add to contacts
item.setEnabled_(not self.contact)
item.setTitle_(NSLocalizedString("Add %s to Contacts", "Audio contextual menu") % format_identity_to_string(self.sessionController.remoteIdentity))
_label = format_identity_to_string(self.sessionController.remoteIdentity)
self.view.accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Session to %s", "Accesibility outlet description") % _label, NSAccessibilityTitleAttribute)
segmentChildren = NSAccessibilityUnignoredDescendant(self.segmentedButtons).accessibilityAttributeValue_(NSAccessibilityChildrenAttribute);
segmentChildren.objectAtIndex_(0).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Transfer Call", "Accesibility outlet description"), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(1).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Hold Call", "Accesibility outlet description"), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(2).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Record Audio", "Accesibility outlet description"), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(3).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Hangup Call", "Accesibility outlet description"), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(0).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Push button", "Accesibility outlet description"), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(1).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Push button", "Accesibility outlet description"), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(2).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Push button", "Accesibility outlet description"), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(3).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Push button", "Accesibility outlet description"), NSAccessibilityRoleDescriptionAttribute)
segmentChildren = NSAccessibilityUnignoredDescendant(self.segmentedConferenceButtons).accessibilityAttributeValue_(NSAccessibilityChildrenAttribute);
segmentChildren.objectAtIndex_(0).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Mute Participant", "Accesibility outlet description"), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(1).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Hold Call", "Accesibility outlet description"), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(2).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Record Audio", "Accesibility outlet description"), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(3).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Hangup Call", "Accesibility outlet description"), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(0).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Push button", "Accesibility outlet description"), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(1).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Push button", "Accesibility outlet description"), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(2).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Push button", "Accesibility outlet description"), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(3).accessibilitySetOverrideValue_forAttribute_(NSLocalizedString("Push button", "Accesibility outlet description"), NSAccessibilityRoleDescriptionAttribute)
self.elapsed.setStringValue_("")
self.info.setStringValue_("")
self.view.setDelegate_(self)
if not self.timer:
self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSRunLoopCommonModes)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSEventTrackingRunLoopMode)
loadImages()
self.transferEnabled = NSApp.delegate().call_transfer_enabled
self.recordingEnabled = NSApp.delegate().answering_machine_enabled
self.setSegmentedButtons("normal")
self.sessionInfoButton.setEnabled_(True)
return self
@objc.python_method
def setSegmentedButtons(self, type):
if type == 'normal':
self.segmentedButtons.setHidden_(False)
self.segmentedConferenceButtons.setHidden_(True)
elif type == 'conference':
self.segmentedButtons.setHidden_(True)
self.segmentedConferenceButtons.setHidden_(False)
@objc.python_method
def invalidateTimers(self):
if self.transfer_timer is not None and self.transfer_timer.isValid():
self.transfer_timer.invalidate()
self.transfer_timer = None
def dealloc(self):
self.notification_center = None
self.stream = None
if self.timer is not None and self.timer.isValid():
self.timer.invalidate()
self.timer = None
self.hangup_reason = None
self.view.removeFromSuperview()
self.view.release()
self.sessionController.log_debug("Dealloc %s" % self)
self.sessionController = None
objc.super(AudioController, self).dealloc()
@objc.python_method
def startIncoming(self, is_update, is_answering_machine=False, add_to_conference=False):
self.sessionController.log_debug("Start incoming %s" % self)
self.notification_center.add_observer(self, sender=self.stream)
self.notification_center.add_observer(self, sender=self.sessionController)
if is_answering_machine:
self.sessionController.accounting_for_answering_machine = True
self.sessionController.log_info("Session handled by answering machine")
self.segmentedButtons.setImage_forSegment_(NSImage.imageNamed_("audio"), self.transfer_segment)
self.segmentedButtons.setEnabled_forSegment_(False, self.hold_segment)
self.segmentedButtons.setEnabled_forSegment_(False, self.record_segment)
self.segmentedButtons.cell().setToolTip_forSegment_(NSLocalizedString("Take over the call", "Audio call tooltip"), self.transfer_segment)
self.answeringMachine = AnsweringMachine(self.sessionController.session, self.stream)
self.answeringMachine.start()
self.label.setStringValue_(self.sessionController.titleShort)
self.label.setToolTip_(self.sessionController.remoteAOR)
self.updateTLSIcon()
NSApp.delegate().contactsWindowController.showAudioSession(self, add_to_conference=add_to_conference)
self.changeStatus(STREAM_PROPOSING if is_update else STREAM_INCOMING)
@objc.python_method
def startOutgoing(self, is_update):
#self.sessionController.log_info("Start outgoing %s" % self)
self.notification_center.add_observer(self, sender=self.stream)
self.notification_center.add_observer(self, sender=self.sessionController)
self.label.setStringValue_(self.sessionController.titleShort)
self.label.setToolTip_(self.sessionController.remoteAOR)
NSApp.delegate().contactsWindowController.showAudioSession(self)
self.changeStatus(STREAM_PROPOSING if is_update else STREAM_WAITING_DNS_LOOKUP)
@objc.python_method
def sessionStateChanged(self, state, detail):
if state == STATE_CONNECTING:
self.updateTLSIcon()
self.changeStatus(STREAM_CONNECTING)
if state in (STATE_FAILED, STATE_DNS_FAILED):
self.audioEndTime = time.time()
if detail.startswith("DNS Lookup"):
self.changeStatus(STREAM_FAILED, NSLocalizedString("DNS Lookup failed", "Audio status label"))
else:
self.changeStatus(STREAM_FAILED, detail)
elif state == STATE_FINISHED:
self.audioEndTime = time.time()
self.changeStatus(STREAM_IDLE, detail)
@objc.python_method
def end(self):
#self.sessionController.log_info("End %s in state %s" % (self, self.status))
status = self.status
if status in [STREAM_FAILED]:
self.audioEndTime = time.time()
self.changeStatus(STREAM_DISCONNECTING)
elif status in [STREAM_IDLE]:
self.audioEndTime = time.time()
self.changeStatus(STREAM_DISCONNECTING)
elif status == STREAM_PROPOSING:
self.sessionController.cancelProposal(self)
self.changeStatus(STREAM_CANCELLING)
elif status == STREAM_WAITING_DNS_LOOKUP:
self.sessionController.endStream(self)
self.audioEndTime = time.time()
self.changeStatus(STREAM_IDLE)
else:
self.sessionController.endStream(self)
self.audioEndTime = time.time()
self.changeStatus(STREAM_DISCONNECTING)
@property
def isActive(self):
if self.view:
return self.view.selected
return False
@property
def isConferencing(self):
return self.view.conferencing
@property
def canConference(self):
return self.status not in (STREAM_FAILED, STREAM_IDLE, STREAM_DISCONNECTING)
@property
def canTransfer(self):
return self.status in (STREAM_CONNECTED)
@objc.python_method
def answerCall(self):
self.sessionController.log_info("Taking over call on answering machine...")
self.segmentedButtons.setImage_forSegment_(NSImage.imageNamed_("transfer"), self.transfer_segment)
self.segmentedButtons.cell().setToolTip_forSegment_(NSLocalizedString("Call transfer", "Audio call tooltip"), self.transfer_segment)
self.segmentedButtons.setEnabled_forSegment_(self.transferEnabled, self.transfer_segment)
self.segmentedButtons.cell().setToolTip_forSegment_(NSLocalizedString("Put the call on hold", "Audio call tooltip"), self.hold_segment)
self.segmentedButtons.setImage_forSegment_(NSImage.imageNamed_("pause"), self.hold_segment)
self.segmentedButtons.setEnabled_forSegment_(self.recordingEnabled, self.record_segment)
self.segmentedButtons.setImage_forSegment_(NSImage.imageNamed_("record"), self.record_segment)
self.updateAudioStatusWithCodecInformation()
self.answeringMachine.stop()
self.sessionController.accounting_for_answering_machine = False
self.answeringMachine = None
@objc.python_method
def hold(self):
if self.session and not self.holdByLocal and self.status not in (STREAM_IDLE, STREAM_FAILED):
self.stream.device.output_muted = True
if not self.answeringMachine:
self.session.hold()
self.holdByLocal = True
self.changeStatus(self.status)
self.notification_center.post_notification("BlinkAudioStreamChangedHoldState", sender=self)
@objc.python_method
def unhold(self):
if self.session and self.holdByLocal and self.status not in (STREAM_IDLE, STREAM_FAILED):
self.stream.device.output_muted = False
if not self.answeringMachine:
self.session.unhold()
self.holdByLocal = False
self.changeStatus(self.status)
self.notification_center.post_notification("BlinkAudioStreamChangedHoldState", sender=self)
@objc.python_method
def sessionBoxKeyPressEvent(self, sender, event):
s = event.characters()
if s and self.stream:
key = s[0]
if event.modifierFlags() & NSCommandKeyMask:
if key == 'i':
if self.sessionController.info_panel is not None:
self.sessionController.info_panel.toggle()
else:
key = key.upper()
if key == " ":
if not self.isConferencing:
self.toggleHold()
elif key == chr(27):
if not self.isConferencing:
self.end()
elif key in string.digits+string.ascii_uppercase+'#*':
self.send_dtmf(key)
@objc.python_method
def send_dtmf(self, key):
if not self.stream:
return
key = translate_alpha2digit(key)
try:
self.stream.send_dtmf(key)
except RuntimeError:
pass
else:
self.sessionController.log_info("Sent DTMF code %s" % key)
filename = 'dtmf_%s_tone.wav' % {'*': 'star', '#': 'pound'}.get(key, key)
wave_player = WavePlayer(SIPApplication.voice_audio_mixer, Resources.get(filename))
if self.session.account.rtp.inband_dtmf:
self.stream.bridge.add(wave_player)
SIPApplication.voice_audio_bridge.add(wave_player)
wave_player.start()
@objc.python_method
def sessionBoxDidActivate(self, sender):
if self.isConferencing:
NSApp.delegate().contactsWindowController.unholdConference()
self.updateLabelColor()
elif self.answeringMachine:
self.answeringMachine.unmute_output()
else:
NSApp.delegate().contactsWindowController.holdConference()
self.unhold()
self.notification_center.post_notification("ActiveAudioSessionChanged", sender=self)
@objc.python_method
def sessionBoxDidDeactivate(self, sender):
if self.isConferencing:
if not sender.conferencing: # only hold if the sender is a non-conference session
NSApp.delegate().contactsWindowController.holdConference()
self.updateLabelColor()
elif self.answeringMachine:
self.answeringMachine.mute_output()
else:
self.hold()
@objc.python_method
def sessionBoxDidAddConferencePeer(self, sender, peer):
if self == peer:
return
if type(peer) == str:
self.sessionController.log_info("New session and conference of %s to contact %s initiated through drag&drop" % (self.sessionController.titleLong,
peer))
# start Audio call to peer and add it to conference
self.view.setConferencing_(True)
session = NSApp.delegate().contactsWindowController.startSessionWithTarget(peer)
if session:
peer = session.streamHandlerOfType("audio")
peer.view.setConferencing_(True)
self.addToConference()
peer.addToConference()
else:
self.view.setConferencing_(False)
return False
else:
self.sessionController.log_info("Conference of %s with %s initiated through drag&drop" % (self.sessionController.titleLong,
peer.sessionController.titleLong))
# if conference already exists and neither self nor peer are part of it:
# return False
# else conference the sessions
# set both as under conference before actually adding to avoid getting the session
# that gets added to the conference last getting held by the 1st
self.view.setConferencing_(True)
peer.view.setConferencing_(True)
self.addToConference()
peer.addToConference()
return True
@objc.python_method
def sessionBoxDidRemoveFromConference(self, sender):
self.sessionController.log_info("Removed %s from conference through drag&drop" % self.sessionController.titleLong)
self.removeFromConference()
@objc.python_method
def addToConference(self):
if self.holdByLocal:
self.unhold()
self.mutedInConference = False
NSApp.delegate().contactsWindowController.addAudioSessionToConference(self)
self.setSegmentedButtons("conference")
self.view.setConferencing_(True)
self.updateLabelColor()
@objc.python_method
def removeFromConference(self):
NSApp.delegate().contactsWindowController.removeAudioSessionFromConference(self)
self.setSegmentedButtons("normal")
if not self.isActive:
self.hold()
if self.mutedInConference:
self.stream.muted = False
self.mutedInConference = False
self.segmentedConferenceButtons.setImage_forSegment_(NSImage.imageNamed_("mute"), self.conference_mute_segment)
self.updateLabelColor()
@objc.python_method
def toggleHold(self):
if self.session:
if self.holdByLocal:
self.unhold()
self.view.setSelected_(True)
else:
self.hold()
@objc.python_method
def transferSession(self, target):
self.sessionController.transferSession(target)
def updateTimer_(self, timer):
self.updateStatistics()
self.updateTileStatistics()
settings = SIPSimpleSettings()
if self.status == STREAM_CONNECTED and self.answeringMachine:
duration = self.answeringMachine.duration
if duration and duration >= settings.answering_machine.max_recording_duration:
self.sessionController.log_info("Answering machine recording time limit reached, hanging up...")
self.end()
return
if self.status in [STREAM_IDLE, STREAM_FAILED, STREAM_DISCONNECTING, STREAM_CANCELLING] or self.user_hanged_up:
if not self.sessionController.try_next_hop or self.user_hanged_up:
if self.audioEndTime and (time.time() - self.audioEndTime > settings.gui.close_delay):
self.removeFromSession()
NSApp.delegate().contactsWindowController.finalizeAudioSession(self)
if timer.isValid():
timer.invalidate()
self.audioEndTime = None
if self.stream and self.stream.recorder is not None and self.stream.recorder.is_active:
if self.isConferencing:
self.segmentedConferenceButtons.setImage_forSegment_(RecordingImages[self.recordingImage], self.conference_record_segment)
else:
self.segmentedButtons.setImage_forSegment_(RecordingImages[self.recordingImage], self.record_segment)
self.recordingImage += 1
if self.recordingImage >= len(RecordingImages):
self.recordingImage = 0
if self.stream and self.stream.codec and self.stream.sample_rate:
try:
if self.sessionController.outbound_audio_calls < 3 and self.duration < 3 and self.sessionController.account is not BonjourAccount() and self.sessionController.session.direction == 'outgoing' and self.sessionController.remoteIdentity.user.isdigit():
self.audioStatus.setTextColor_(NSColor.orangeColor())
self.audioStatus.setStringValue_(NSLocalizedString("Enter DTMF using keyboard", "Audio status label"))
self.audioStatus.sizeToFit()
else:
if not self.hangup_reason:
self.updateAudioStatusWithCodecInformation()
except AttributeError:
# TODO: self.sessionController.remoteIdentity is sometimes an URI sometimes a To/From header...
pass
def transferFailed_(self, timer):
self.changeStatus(STREAM_CONNECTED)
@objc.python_method
def updateAudioStatusWithSessionState(self, text, error=False):
if not error and self.zrtp_show_verify_phrase:
return
if error:
self.audioStatus.setTextColor_(NSColor.redColor())
else:
self.audioStatus.setTextColor_(NSColor.blackColor())
self.audioStatus.setStringValue_(text)
self.audioStatus.sizeToFit()
self.audioStatus.display()
@objc.python_method
def updateAudioStatusWithCodecInformation(self):
if self.zrtp_show_verify_phrase:
return
if self.show_zrtp_ok_status_countdown > 0:
self.audioStatus.setTextColor_(NSColor.colorWithDeviceRed_green_blue_alpha_(53/256.0, 100/256.0, 204/256.0, 1.0))
self.audioStatus.setStringValue_(NSLocalizedString("Encrypted using ZRTP", "Audio status label"))
self.show_zrtp_ok_status_countdown -= 1
self.audioStatus.sizeToFit()
return
if self.transfer_in_progress or self.transferred:
return
if self.holdByLocal and not self.answeringMachine:
self.audioStatus.setTextColor_(NSColor.colorWithDeviceRed_green_blue_alpha_(53/256.0, 100/256.0, 204/256.0, 1.0))
self.audioStatus.setStringValue_(NSLocalizedString("On Hold", "Audio status label"))
elif self.holdByRemote and not self.answeringMachine:
self.audioStatus.setTextColor_(NSColor.colorWithDeviceRed_green_blue_alpha_(53/256.0, 100/256.0, 204/256.0, 1.0))
self.audioStatus.setStringValue_(NSLocalizedString("Hold by Remote", "Audio status label"))
else:
if self.answeringMachine:
self.audioStatus.setStringValue_(NSLocalizedString("Answering machine active", "Audio status label"))
elif self.stream.sample_rate and self.stream.codec:
sample_rate = self.stream.sample_rate/1000
codec = beautify_audio_codec(self.stream.codec)
if self.stream.sample_rate and self.stream.sample_rate >= 16000:
self.audioStatus.setTextColor_(NSColor.colorWithDeviceRed_green_blue_alpha_(53/256.0, 100/256.0, 204/256.0, 1.0))
hd_label = NSLocalizedString("Wideband", "Label")
else:
self.audioStatus.setTextColor_(NSColor.blackColor())
hd_label = NSLocalizedString("Narrowband", "Label")
#self.audioStatus.setStringValue_(u"%s (%s %0.fkHz)" % (hd_label, codec, sample_rate))
self.audioStatus.setStringValue_("%s (%s)" % (hd_label, codec))
self.audioStatus.sizeToFit()
@objc.python_method
def updateLabelColor(self):
if self.isConferencing:
if self.view.selected:
self.label.setTextColor_(NSColor.blackColor())
else:
self.label.setTextColor_(NSColor.grayColor())
else:
if self.holdByLocal or self.holdByRemote:
self.label.setTextColor_(NSColor.grayColor())
else:
self.label.setTextColor_(NSColor.blackColor())
@objc.python_method
def updateTLSIcon(self):
if self.session and self.session.transport == "tls":
frame = self.label.frame()
frame.origin.x = NSMaxX(self.tlsIcon.frame())
self.label.setFrame_(frame)
self.tlsIcon.setHidden_(False)
else:
frame = self.label.frame()
frame.origin.x = NSMinX(self.tlsIcon.frame())
self.label.setFrame_(frame)
self.tlsIcon.setHidden_(True)
@objc.python_method
def changeStatus(self, new_status, fail_reason=None):
self.sessionController.log_debug('changeStatus %s from %s to %s' % (self, self.status, new_status))
if not NSThread.isMainThread():
raise Exception("called from non-main thread")
oldstatus = self.status
if self.status == new_status:
return
self.status = new_status
status = self.status
if status == STREAM_WAITING_DNS_LOOKUP:
self.updateAudioStatusWithSessionState(NSLocalizedString("Finding Destination...", "Audio status label"))
elif status == STREAM_RINGING:
self.updateAudioStatusWithSessionState(NSLocalizedString("Ringing...", "Audio status label"))
elif status == STREAM_CONNECTING:
self.updateTLSIcon()
self.updateAudioStatusWithSessionState(NSLocalizedString("Connecting...", "Audio status label"))
elif status == STREAM_PROPOSING:
self.updateTLSIcon()
self.updateAudioStatusWithSessionState(NSLocalizedString("Adding Audio...", "Audio status label"))
elif status == STREAM_CONNECTED:
if not self.answeringMachine:
if self.holdByLocal:
self.segmentedButtons.setSelected_forSegment_(True, self.hold_segment)
self.segmentedButtons.setImage_forSegment_(NSImage.imageNamed_("paused"), self.hold_segment)
self.segmentedConferenceButtons.setSelected_forSegment_(True, self.conference_hold_segment)
self.segmentedConferenceButtons.setImage_forSegment_(NSImage.imageNamed_("paused"), self.conference_hold_segment)
else:
self.segmentedButtons.setSelected_forSegment_(False, self.hold_segment)
self.segmentedButtons.setImage_forSegment_(NSImage.imageNamed_("pause"), self.hold_segment)
self.segmentedConferenceButtons.setSelected_forSegment_(False, self.conference_hold_segment)
self.segmentedConferenceButtons.setImage_forSegment_(NSImage.imageNamed_("pause"), self.conference_hold_segment)
else:
self.segmentedButtons.setSelected_forSegment_(self.recordingEnabled, self.record_segment)
self.segmentedButtons.setImage_forSegment_(NSImage.imageNamed_("recording1"), self.record_segment)
self.updateAudioStatusWithCodecInformation()
self.updateLabelColor()
self.updateTLSIcon()
self.update_encryption_icon()
NSApp.delegate().contactsWindowController.updateAudioButtons()
elif status == STREAM_DISCONNECTING:
if len(self.sessionController.streamHandlers) > 1:
self.hangup_reason = NSLocalizedString("Audio Removed", "Audio status label")
self.updateAudioStatusWithSessionState(NSLocalizedString("Audio Removed", "Audio status label"))
elif oldstatus == STREAM_WAITING_DNS_LOOKUP:
self.updateAudioStatusWithSessionState(NSLocalizedString("Session Cancelled", "Audio status label"))
else:
self.hangup_reason = NSLocalizedString("Session Ended", "Audio status label")
self.updateAudioStatusWithSessionState(NSLocalizedString("Session Ended", "Audio status label"))
elif status == STREAM_CANCELLING:
self.updateAudioStatusWithSessionState(NSLocalizedString("Cancelling Request...", "Audio status label"))
elif status == STREAM_INCOMING:
self.updateTLSIcon()
self.updateAudioStatusWithSessionState(NSLocalizedString("Accepting Session...", "Audio status label"))
elif status == STREAM_IDLE:
if self.user_hanged_up:
self.updateAudioStatusWithSessionState(NSLocalizedString("Session Ended", "Audio status label"))
elif oldstatus in (STREAM_CONNECTING, STREAM_PROPOSING, STREAM_WAITING_DNS_LOOKUP, STREAM_IDLE):
self.updateAudioStatusWithSessionState(NSLocalizedString("Session Cancelled", "Audio status label"))
elif not self.transferred:
if fail_reason == "remote":
self.updateAudioStatusWithSessionState(NSLocalizedString("Session Ended by Remote", "Audio status label"))
elif fail_reason == "local":
status = self.hangup_reason if self.hangup_reason else NSLocalizedString("Session Ended", "Audio status label")
self.updateAudioStatusWithSessionState(status)
else:
self.updateAudioStatusWithSessionState(NSLocalizedString("Session Cancelled", "Audio status label"))
self.audioStatus.sizeToFit()
elif status == STREAM_FAILED:
self.audioEndTime = time.time()
if self.user_hanged_up and oldstatus in (STREAM_CONNECTING, STREAM_PROPOSING):
self.updateAudioStatusWithSessionState(NSLocalizedString("Session Cancelled", "Audio status label"))
elif oldstatus == STREAM_CANCELLING:
self.updateAudioStatusWithSessionState(NSLocalizedString("Request Cancelled", "Audio status label"), True)
elif oldstatus != STREAM_FAILED:
self.updateAudioStatusWithSessionState(fail_reason[0:32].title() if fail_reason else NSLocalizedString("Error", "Audio status label"), True)
if status == STREAM_CONNECTED:
self.segmentedButtons.setEnabled_forSegment_(True, self.encryption_segment)
self.segmentedButtons.setEnabled_forSegment_(self.transferEnabled, self.transfer_segment)
self.segmentedButtons.setEnabled_forSegment_(True, self.hold_segment)
self.segmentedButtons.setEnabled_forSegment_(self.recordingEnabled, self.record_segment)
self.segmentedButtons.setEnabled_forSegment_(True, self.hangup_segment)
self.segmentedConferenceButtons.setEnabled_forSegment_(True, self.conference_mute_segment)
self.segmentedConferenceButtons.setEnabled_forSegment_(True, self.conference_hold_segment)
self.segmentedConferenceButtons.setEnabled_forSegment_(self.recordingEnabled, self.conference_record_segment)
self.segmentedConferenceButtons.setEnabled_forSegment_(True, self.conference_hangup_segment)
elif status in (STREAM_CONNECTING, STREAM_PROPOSING, STREAM_INCOMING, STREAM_WAITING_DNS_LOOKUP, STREAM_RINGING):
for i in range(len(self.normal_segments)):
self.segmentedButtons.setEnabled_forSegment_(False, i)
self.segmentedButtons.setEnabled_forSegment_(True, self.hangup_segment)
for i in range(len(self.conference_segments)):
self.segmentedConferenceButtons.setEnabled_forSegment_(False, i)
self.segmentedConferenceButtons.setEnabled_forSegment_(True, self.conference_hangup_segment)
elif status == STREAM_FAILED:
for i in range(len(self.normal_segments)):
self.segmentedButtons.setEnabled_forSegment_(False, i)
for i in range(len(self.conference_segments)):
self.segmentedConferenceButtons.setEnabled_forSegment_(False, i)
else:
for i in range(len(self.normal_segments)):
self.segmentedButtons.setEnabled_forSegment_(False, i)
for i in range(len(self.conference_segments)):
self.segmentedConferenceButtons.setEnabled_forSegment_(False, i)
if status in (STREAM_IDLE, STREAM_FAILED):
self.view.setDelegate_(None)
MediaStream.changeStatus(self, oldstatus, new_status, fail_reason)
@objc.python_method
def updateStatistics(self):
if not self.stream:
return
stats = self.stream.statistics
if stats is not None and self.last_stats is not None:
jitter = stats['rx']['jitter']['last'] / 1000.0 + stats['tx']['jitter']['last'] / 1000.0
rtt = stats['rtt']['last'] / 1000 / 2
rx_packets = stats['rx']['packets'] - self.last_stats['rx']['packets']
rx_lost_packets = stats['rx']['packets_lost'] - self.last_stats['rx']['packets_lost']
loss_rx = 100.0 * rx_lost_packets / rx_packets if rx_packets else 0
tx_packets = stats['tx']['packets'] - self.last_stats['tx']['packets']
tx_lost_packets = stats['tx']['packets_lost'] - self.last_stats['tx']['packets_lost']
loss_tx = 100.0 * tx_lost_packets / tx_packets if tx_packets else 0
self.statistics['loss_rx'] = loss_rx
self.statistics['loss_tx'] = loss_tx
self.statistics['jitter'] = jitter
self.statistics['rtt'] = rtt
rx_overhead = (stats['rx']['packets'] - self.previous_rx_packets) * RTP_PACKET_OVERHEAD
tx_overhead = (stats['tx']['packets'] - self.previous_tx_packets) * RTP_PACKET_OVERHEAD
if self.previous_rx_packets:
self.statistics['rx_bytes'] = stats['rx']['bytes']/STATISTICS_INTERVAL - self.previous_rx_bytes + rx_overhead
if self.previous_tx_packets:
self.statistics['tx_bytes'] = stats['tx']['bytes']/STATISTICS_INTERVAL - self.previous_tx_bytes + tx_overhead
if self.statistics['rx_bytes'] < 0:
self.statistics['rx_bytes'] = 0
if self.statistics['tx_bytes'] < 0:
self.statistics['tx_bytes'] = 0
self.previous_rx_bytes = stats['rx']['bytes'] if stats['rx']['bytes'] >=0 else 0
self.previous_tx_bytes = stats['tx']['bytes'] if stats['tx']['bytes'] >=0 else 0
self.previous_rx_packets = stats['rx']['packets']
self.previous_tx_packets = stats['tx']['packets']
self.last_stats = stats
@objc.python_method
def updateDuration(self):
if not self.session:
return
if self.zrtp_show_verify_phrase:
self.elapsed.setStringValue_(NSLocalizedString("Authentication String:", "Label"))
return
if self.session.end_time:
now = self.session.end_time
else:
now = ISOTimestamp.now()
if self.session.start_time and now >= self.session.start_time:
elapsed = now - self.session.start_time
self.duration = elapsed.seconds
h = elapsed.seconds / (60*60)
m = (elapsed.seconds / 60) % 60
s = elapsed.seconds % 60
text = "%02i:%02i:%02i" % (h,m,s)
#speed = self.statistics['rx_bytes']
#speed_text = ' %s/s' % format_size(speed, bits=True) if speed else ''
#text = text + speed_text
self.elapsed.setStringValue_(text)
else:
if self.status == STREAM_CONNECTING and self.sessionController.routes:
if time.time() - self.timestamp < 2.1:
# for the first two seconds display the selected account
label = self.sessionController.account.gui.account_label or self.sessionController.account.id if self.sessionController.account is not BonjourAccount() else "Bonjour"
self.elapsed.setStringValue_(label)
else:
route = self.sessionController.routes[0]
dest = "%s:%s" % (route.uri.transport.decode().upper(), route.uri.host.decode())
self.elapsed.setStringValue_(dest)
elif self.status == STREAM_RINGING:
self.updateAudioStatusWithSessionState(NSLocalizedString("Ringing...", "Audio status label"))
else:
label = self.sessionController.account.gui.account_label or self.sessionController.account.id if self.sessionController.account is not BonjourAccount() else "Bonjour"
self.elapsed.setStringValue_(label)
@objc.python_method
def updateTileStatistics(self):
if not self.session:
return
self.updateDuration()
if self.stream:
settings = SIPSimpleSettings()
jitter = self.statistics['jitter']
rtt = self.statistics['rtt']
loss_rx = self.statistics['loss_rx']
loss_tx = self.statistics['loss_tx']
if self.jitter_history is not None:
self.jitter_history.append(jitter)
if self.rtt_history is not None:
self.rtt_history.append(rtt)
if self.loss_rx_history is not None:
self.loss_rx_history.append(loss_rx)
if self.loss_tx_history is not None:
self.loss_tx_history.append(loss_tx)
if self.rx_speed_history is not None:
self.rx_speed_history.append(self.statistics['rx_bytes'] * 8)
if self.tx_speed_history is not None:
self.tx_speed_history.append(self.statistics['tx_bytes'] * 8)
text = ""
qos_data = NotificationData()
qos_data.latency = '0ms'
qos_data.packet_loss_rx = '0%'
send_qos_notify = False
if rtt > settings.gui.rtt_threshold:
if rtt > 1000:
latency = '%.1f' % (float(rtt)/1000.0)
text += NSLocalizedString("%ss Latency", "Label") % latency
send_qos_notify = True
qos_data.latency = '%ss' % latency
else:
text += NSLocalizedString("%dms Latency", "Label") % rtt
send_qos_notify = True
qos_data.latency = '%sms' % rtt
if loss_rx > 3:
text += " " + NSLocalizedString("%d%% Loss", "Label") % loss_rx + ' RX'
qos_data.packet_loss_rx = '%d%%' % loss_rx
send_qos_notify = True
if send_qos_notify:
self.info.setStringValue_(text)
if not self.audio_has_quality_issues:
self.notification_center.post_notification("AudioSessionHasQualityIssues", sender=self, data=qos_data)
self.audio_has_quality_issues = True
else:
if self.audio_has_quality_issues:
self.notification_center.post_notification("AudioSessionQualityRestored", sender=self, data=qos_data)
self.audio_has_quality_issues = False
self.info.setStringValue_("")
else:
self.info.setStringValue_("")
def menuWillOpen_(self, menu):
if menu == self.encryptionMenu:
# sded encrypted
item = menu.itemWithTag_(11)
item.setHidden_(self.zrtp_active or not self.encryption_active)
# not encrypted
item = menu.itemWithTag_(31)
item.setHidden_(self.encryption_active)
item.setEnabled_(False)
elif menu == self.transferMenu:
while menu.numberOfItems() > 1:
menu.removeItemAtIndex_(1)
for session_controller in (s for s in self.sessionControllersManager.sessionControllers if s is not self.sessionController and type(self.sessionController.account) == type(s.account) and s.hasStreamOfType("audio") and s.streamHandlerOfType("audio").canTransfer):
item = menu.addItemWithTitle_action_keyEquivalent_(session_controller.titleLong, "userClickedTransferMenuItem:", "")
item.setIndentationLevel_(1)
item.setTarget_(self)
item.setRepresentedObject_(session_controller)
item = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("A contact by dragging this audio call over it", "Menu item"), "", "")
item.setIndentationLevel_(1)
item.setEnabled_(False)
# use typed search text as blind transfer destination
target = NSApp.delegate().contactsWindowController.searchBox.stringValue()
if target:
parsed_target = normalize_sip_uri_for_outgoing_session(target, self.sessionController.account)
if parsed_target:
item = menu.addItemWithTitle_action_keyEquivalent_(format_identity_to_string(parsed_target), "userClickedBlindTransferMenuItem:", "")
item.setIndentationLevel_(1)
item.setTarget_(self)
item.setRepresentedObject_(parsed_target)
else:
aor_supports_chat = True
aor_supports_screen_sharing_server = True