-
Notifications
You must be signed in to change notification settings - Fork 0
/
phone.js
1659 lines (1508 loc) · 68.4 KB
/
phone.js
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) 2011-2012, Intencity Cloud Technologies
// Copyright (c) 2011-2012, Kundan Singh
// This software is licensed under LGPL.
// See README and http://code.google.com/p/sip-js for details.
function getFlashMovie(name) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[name] : document[name];
}
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
return (qs == null ? default_ : qs[1]);
}
function cleanHTML(value) {
return ("" + value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
function Phone() {
// properties in config
this.displayname = 'First Last';
this.username = 'myname';
this.domain = 'localhost';
this.authname = 'myname';
this.password = '';
this.transport = 'udp';
// properties in register
this.outbound = 'proxy';
this.outbound_proxy_address ='127.0.0.1:5060';
this.register_interval = 180;
this.rport = true;
this.sipoutbound = false;
this.local_aor = '"' + this.displayname + '" <sip:' + this.username + '@' + this.domain + '>';
this.sock_state = "idle";
this.register_state = "not registered";
this.register_button = 'Register';
// properties in call
this.call_state = "idle";
// possible state values:
// idle - not in a call (may not have socket)
// outbound call:
// waiting - want to initiate a call, and waiting for socket connection
// inviting - sending outbound INVITE, may be waiting for media
// ringback - received 18x response for outbound INVITE
// accepted - received 2xx response for outbound INVITE
// active - sent ACK for outbound INVITE
// incoming call:
// incoming - received incoming INVITE
// accepting - accepted an incoming INVITE, waiting for media
// failure, termination
// failed - outbound/inbound call failed due to some reason
// closed - call is closed by remote party
this.target_scheme = "sip";
this.target_value = "yourname@localhost";
this.target_aor = this.target_scheme + ":" + this.target_value;
this.has_audio = true;
this.has_tones = false;
this.has_video = true;
this.has_text = false;
this.has_location = false;
this.location = null;
// properties in network
this.network_status = null;
//properties in program log
this.log_scroll = true;
// private attributes
this._handlers = {};
this.network_type = "Flash";
this.listen_ip = null;
this._listen_port = null;
this._stack = null;
this._sock = null;
this._next_message = null;
// SIP headers
this.user_agent = "sip-js/1.0";
this.server = this.user_agent;
// media context
this._local_sdp = null;
this._remote_sdp = null;
this._rtp = []; // RealTimeSocket instances
this._gw = null;
// HTML5
this.has_html5_websocket = false;
this.has_html5_video = false;
this.has_html5_webrtc = false;
this.websocket_path = "/sip";
this._webrtc_local_stream = null;
this._webrtc_peer_connection = null;
this.enable_sound_alert = false;
this.webrtc_servers = "stun://stun.l.google.com:19302"; // comma separated list, each item is either "url" or "url|credential"
this._sdp_timeout = 500; // 0.5s after calling createOffer or createAnswer, use the SDP
// SIP requirements for websocket
this._instance_id = "";
this._gruu = "";
};
Phone.prototype.populate = function() {
for (var attr in this) {
var def = this[attr];
if ((typeof def != "function") && attr.charAt(0) != "_") {
var param = getQuerystring(attr, def);
if (typeof this[attr] == "number")
param = (typeof param == "number" ? param : parseInt(param));
else if (typeof this[attr] == "boolean")
param = (typeof param == "boolean" ? param : (param != "false" ? true : false));
else
param = unescape(param);
if (def == param)
this.dispatchEvent({"type": "propertyChange", "property": attr, "newValue": param});
else
this.setProperty(attr, param);
}
}
};
Phone.prototype.detectHTML5 = function() {
this.setProperty("has_html5_websocket", typeof WebSocket != "undefined");
this.setProperty("has_html5_video", !!document.createElement('video').canPlayType);
this.setProperty("has_html5_webrtc", typeof navigator.webkitGetUserMedia != "undefined" && typeof webkitRTCPeerConnection != "undefined");
log("detecting HTML support websocket=" + this.has_html5_websocket + " video=" + this.has_html5_video + " webrtc=" + this.has_html5_webrtc);
if (!this.has_html5_websocket || !this.has_html5_video || !this.has_html5_webrtc) {
$("webrtc-network").innerHTML += '<font color="red">Some HTML5 features are missing in your browser</font>';
}
if (this.has_html5_websocket) {
// SIP over websocket works
this.setProperty("network_status", "available");
this.enableButtons(true);
this.enableBox('config', true);
$("websocket_path").value = this.websocket_path;
$("webrtc_servers").value = this.webrtc_servers;
$("listen_ip").style.visibility = "hidden";
this.listen_ip = 'r' + Math.floor(Math.random() * 10000000000) + ".invalid";
this._listen_port = 0;
if (this.outbound_proxy_address == "127.0.0.1:5060") {
var outbound_proxy_address = "127.0.0.1:5080";
if (window.location.href) {
var uri = sip.parse_uri(window.location.href);
outbound_proxy_address = uri.host + ":5080";
}
this.setProperty("outbound_proxy", true);
this.setProperty("outbound_proxy_address", outbound_proxy_address);
}
}
if (this.has_html5_video) {
// add <video> to local and remote video boxes
var local = document.createElement("video");
local.id = "html5-local-video";
local.style.width = "240";
local.style.height = "168";
// local.style.backgroundColor = "#000000";
local.autoplay = "autoplay";
$('local-video').appendChild(local);
var remote = document.createElement("video");
remote.id = "html5-remote-video";
remote.style.width = "240";
remote.style.height = "168";
// remote.style.backgroundColor = "#000000";
remote.autoplay = "autoplay";
$('remote-video').appendChild(remote);
var audio = document.createElement("audio");
audio.id = "html5-audio";
audio.autoplay = "autoplay";
$("webrtc-network").appendChild(audio);
}
};
Phone.prototype.addEventListener = function(type, handler) {
if (this._handlers[type] === undefined)
this._handlers[type] = [];
this._handlers[type].push(handler);
};
Phone.prototype.dispatchEvent = function(event) {
// log("dispatchEvent(" + event.type + ", " + event.property + ", " + event.newValue + ")");
if (this._handlers[event.type] !== undefined) {
var handlers = this._handlers[event.type];
for (var i=0; i<handlers.length; ++i) {
var handler = handlers[i];
handler(event);
}
}
};
Phone.prototype.setProperty = function(name, value) {
if (this[name] !== undefined) {
var oldValue = this[name];
if (oldValue != value) {
this[name] = value;
this.dispatchEvent({"type": "propertyChange", "property": name, "newValue": value, "oldValue": oldValue});
}
if (name == "username" || name == "domain" || name == "displayname") {
this.setProperty("local_aor", '"' + this.displayname + '" <sip:' + this.username + '@' + this.domain + '>');
}
else if (name == "target_scheme") {
log("target_scheme=" + value);
var target_value = {"sip": "yourname@" + this.domain, "tel" : "+12125551234", "urn": "service:sos"}[value];
this.setProperty("target_value", target_value);
this.setProperty("target_aor", this.target_scheme + ":" + this.target_value);
}
else if (name == "target_value") {
this.setProperty("target_aor", this.target_scheme + ":" + this.target_value);
}
else if (name == "network_type") {
if (value == "Flash" && this.transport == "ws") {
this.setProperty("transport", "udp");
}
else if (value == "WebRTC" && this.transport != "ws") {
this.setProperty("transport", "ws");
}
}
}
else {
this.dispatchEvent({"type": "propertyChange", "property": name, "newValue": value});
}
};
Phone.prototype.enableButtons = function(enable) {
var inputs = ["register_button", "call_button", "target_type", "target_scheme", "target_value"];
for (var i=0; i<inputs.length; ++i) {
this.enable(inputs[i], enable);
}
};
Phone.prototype.statusChanged = function(value) {
this.setProperty("network_status", value);
var enable = (value == "connected");
this.enableButtons(enable);
if (enable) {
// enable config edit only
this.enableBox("config", true);
}
else {
// disable all edits and reset
this.enableBox("config", false);
this.enableBox("register", false);
this.enableBox("call", false);
this.enableBox("network", false);
this.setProperty("sock_state", "idle");
this.setProperty("register_state", "not registered");
this.setProperty("call_state", "idle");
this._listen_port = null;
this._stack = null;
this._sock = null;
this._local_sdp = null;
this._remote_sdp = null;
this._rtp = []; // RealTimeSocket instances
this._gw = null;
}
};
Phone.prototype.enable = function(name, enable) {
this.dispatchEvent({"type": "propertyChange", "property": name + ".disabled", "newValue": enable ? false : "disabled"});
};
Phone.prototype.enableBox = function(name, enable) {
$('edit_' + name).style.visibility = (enable ? "hidden" : "visible");
$('save_' + name).style.visibility = (enable ? "visible" : "hidden");
var inputs = [];
if (name == 'config')
inputs = ["displayname", "username", "domain", "authname", "password"];
//inputs = ["displayname", "username", "domain", "authname", "password", "transport_udp", "transport_tcp", "transport_ws"];
else if (name == 'register')
inputs = ["outbound_target", "outbound_proxy", "outbound_proxy_address", "register_interval", "local_aor"];
//inputs = ["outbound_domain", "outbound_target", "outbound_proxy", "outbound_proxy_address", "register_interval", "rport", "sipoutbound", "local_aor"];
else if (name == 'network')
inputs = ["listen_ip", "network_type", "websocket_path", "enable_sound_alert", "webrtc_servers"];
else if (name == 'call')
inputs = ['has_audio', 'has_video', 'has_location'];
// inputs = ['has_audio', 'has_tones', 'has_video', 'has_text', 'has_location']; // TODO: eventually use this
for (var i=0; i<inputs.length; ++i) {
this.enable(inputs[i], enable);
}
if (enable) {
var boxes = ["config", "register", "call", "network"];
for (var i=0; i<boxes.length; ++i) {
if (boxes[i] != name) {
this.enableBox(boxes[i], false);
}
}
}
return false;
};
Phone.prototype.networkChanged = function() {
for (var i=0; i<network.interfaces.length; ++i) {
var intf = network.interfaces[i];
if (intf.active) {
for (var j=0; j<intf.addresses.length; ++j) {
var addr = intf.addresses[j];
if (addr.ipVersion == "IPv4") {
this.setProperty("listen_ip", addr.address);
break;
}
}
}
if (this.listen_ip)
break;
}
};
Phone.prototype.register = function() {
log("register() " + this.local_aor);
if (this.sock_state == "idle") {
this.setProperty("sock_state", "creating");
this.setProperty("register_state", "waiting");
this.setProperty("register_button", "Unregister");
this.setProperty("register_button.disabled", true);
this.createSocket();
}
else if (this.sock_state == "bound" || this.sock_state == "connected") {
if (this._reg && this.register_state != "not registered") {
this.setProperty("register_state", "unregistering");
this.setProperty("register_button.disabled", true);
this.sendUnregister();
}
else if (this.register_state == "not registered") {
this.setProperty("register_state", "registering");
this.setProperty("register_button.disabled", true);
this.sendRegister();
}
else {
log("ignoring register in state " + this.register_state + " " + this._reg);
}
}
};
Phone.prototype.changeNetworkType = function() {
var current = this.network_type;
var other = (current == 'Flash' ? 'WebRTC' : 'Flash');
var result = confirm('Using the ' + current + ' network. Would you like to relaunch with the ' + other + ' network');
if (result) {
window.location = 'phone.html?network_type=' + other;
}
return false;
};
Phone.prototype.call = function() {
log("call() " + this.target_aor);
if (this.sock_state == "idle") {
this.setProperty("sock_state", "creating");
this.setProperty("call_state", "waiting");
this.setProperty("call_button.disabled", true);
this.setProperty("end_button.disabled", false);
this.createSocket();
}
else if (this.sock_state == "bound" || this.sock_state == "connected") {
if (this.call_state == "idle") {
this.setProperty("call_state", "inviting");
this.setProperty("call_button.disabled", true);
this.setProperty("end_button.disabled", false);
this.sendInvite();
}
else if (this.call_state == "incoming") {
this.setProperty("call_button.disabled", true);
this.setProperty("end_button.disabled", false);
this.sendInviteResponse(200, 'OK');
}
else {
this.dispatchMessage("End the existing call first");
}
}
};
Phone.prototype.end = function() {
log("end()");
if (this.call_state != "idle") {
if (this.call_state == "inviting" || this.call_state == "ringback") {
this.sendCancel();
}
else if (this.call_state == "incoming") {
this.sendInviteResponse(603, 'Decline');
}
else if (this.call_state == "active" || this.call_state == "accepted" || this.call_state == "accepting") {
this.sendBye();
}
else {
if (this.call_state != "failed" && this.call_state != "closed") {
log("ignoring end in " + this.call_state + " state");
}
this.hungup();
}
this.setProperty("call_button.disabled", false);
this.setProperty("end_button.disabled", true);
this.setProperty("call_state", "idle");
}
};
Phone.prototype.createUUID4 = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
Phone.prototype.createInstanceId = function() {
if (!this._instance_id && typeof localStorage != "undefined") {
this._instance_id = localStorage.getItem("instance_id");
if (!this._instance_id) {
this._instance_id = "<urn:uuid:" + this.createUUID4() + ">";
localStorage.setItem("instance_id", this._instance_id);
}
}
};
Phone.prototype.createSocket = function() {
log("createSocket() transport=" + this.transport);
if (this.transport == "udp") {
this._sock = new network.DatagramSocket();
var parent = this;
this._sock.addEventListener("propertyChange", function(event) { parent.onSockPropertyChange(event); });
this._sock.addEventListener("data", function(event) { parent.onSockData(event); });
this._sock.addEventListener("ioError", function(event) { parent.onSockError(event); });
this._sock.bind(0, "0.0.0.0");
this._sock.receive();
}
else if (this.transport == "ws") {
log(" connecting to " + this.outbound_proxy_address);
try {
this._sock = new WebSocket('ws://' + this.outbound_proxy_address + this.websocket_path, ["sip"]);
var parent = this;
this._sock.onopen = function() { parent.onWebSocketOpen(); };
this._sock.onclose = function() { parent.onWebSocketClose(); };
this._sock.onerror = function(error) { parent.onWebSocketError(error); };
this._sock.onmessage = function(msg) { parent.onWebSocketMessage(msg); };
} catch (error) {
log("error in websocket: " + error, "error");
}
}
else {
log(this.transport + " transport is not yet implemented", "error");
this.setProperty("sock_state", "idle");
if (this.register_state == "waiting") {
this.setProperty("register_state", "not registered");
this.setProperty("register_button", "Register");
this.setProperty("register_button.disabled", false);
}
if (this.call_state == "waiting") {
this.setProperty("call_state", "idle");
this.setProperty("call_button.disabled", false);
this.setProperty("end_button.disabled", true);
}
}
};
Phone.prototype.onSockPropertyChange = function(event) {
if (event.property == "bound") {
if (event.newValue) {
// this._listen_port = sock.localPort;
// log("listen_port=" + this._listen_port);
}
else {
listen_port = null;
this.resetSockState();
}
}
else if (event.property == "localPort") {
if (event.newValue) {
this._listen_port = this._sock.localPort;
log("listen_port=" + this._listen_port);
this.setProperty("sock_state", "bound");
this.createStack();
}
}
else if (event.property == "connected") {
// TCP or WS socket
log("socket connected=" + event.newValue);
if (event.newValue) {
this.setProperty("sock_state", "connected");
this.createStack();
}
else {
this.resetSockState();
}
}
};
Phone.prototype.resetSockState = function() {
this.setProperty("sock_state", "idle");
if (this.register_state == "waiting" || this.register_state == "registered") {
this.setProperty("register_state", "not registered");
this.setProperty("register_button", "Register");
this.setProperty("register_button.disabled", false);
this._reg = null;
}
if (this.call_state == "waiting") {
this.setProperty("call_state", "idle");
this.setProperty("call_button.disabled", false);
this.setProperty("end_button.disabled", true);
}
};
Phone.prototype.createStack = function() {
var transport = new sip.TransportInfo(this.listen_ip, this._listen_port, this.transport, this.transport == "tls", this.transport != "udp", this.transport != "udp");
this._stack = new sip.Stack(this, transport);
if (this.register_state == "waiting") {
this.setProperty("register_state", "registering");
this.sendRegister();
}
if (this.call_state == "waiting") {
this.setProperty("call_state", "inviting");
this.sendInvite();
}
if (this._next_message != null) {
this.sendMessage(this._next_message);
this._next_message = null;
}
};
Phone.prototype.sendRegister = function() {
if (this._reg == null) {
this._reg = new sip.UserAgent(this._stack);
this._reg.remoteParty = new sip.Address(this.local_aor);
this._reg.localParty = new sip.Address(this.local_aor);
if (this.outbound == "proxy") {
var outbound_proxy = this.getRouteHeader();
if (this.transport != "udp")
outbound_proxy.value.uri.param['transport'] = this.transport;
this._reg.routeSet = [outbound_proxy];
// For REGISTER should we change uri instead of routeSet?
// this._reg.remoteTarget = new sip.URI("sip:" + this.username + "@" + this.outbound_proxy_address);
}
}
var m = this.createRegister();
m.setItem('Expires', new sip.Header("" + this.register_interval, 'Expires'))
this._reg.sendRequest(m);
};
Phone.prototype.createRegister = function() {
var m = this._reg.createRequest('REGISTER');
var c = new sip.Header(this._stack.uri.toString(), 'Contact');
c.value.uri.user = this.username;
if (this.transport == "ws" || this.transport == "wss") {
this.createInstanceId();
c.setItem('reg-id', '1');
c.setItem('+sip.instance', this._instance_id);
m.setItem('Supported', new sip.Header('path, outbound, gruu', 'Supported'));
}
m.setItem('Contact', c);
return m;
};
Phone.prototype.sendUnregister = function() {
var m = this.createRegister();
m.setItem('Expires', new sip.Header("0", 'Expires'))
this._reg.sendRequest(m);
};
Phone.prototype.receivedRegisterResponse = function(ua, response) {
if (response.isfinal()) {
if (this.register_state == "registering") {
if (response.is2xx()) {
this.setProperty("register_state", "registered");
this.setProperty("register_button", "Unregister");
this.setProperty("register_button.disabled", false);
}
else {
this.setProperty("register_state", "not registered");
this.setProperty("register_button", "Register");
this.setProperty("register_button.disabled", false);
this._reg = null;
}
}
else if (this.register_state == "unregistering") {
this.setProperty("register_state", "not registered");
this.setProperty("register_button", "Register");
this.setProperty("register_button.disabled", false);
this._reg = null;
}
}
};
Phone.prototype.sendInvite = function() {
if (this._call == null) {
this._call = new sip.UserAgent(this._stack);
this._call.remoteParty = new sip.Address(this.target_aor);
this._call.localParty = new sip.Address(this.local_aor);
if (this.outbound == "proxy") {
this._call.routeSet = [this.getRouteHeader(this._call.remoteParty.uri.user)];
}
}
this.dispatchMessage("Inviting " + this._call.remoteParty.toString() + " ...");
if (this.network_type == "WebRTC") {
this.createWebRtcConnection();
}
else {
this.createMediaSockets();
}
};
Phone.prototype.setVideoProperty = function(videoname, attr, value) {
if (this.network_type == "WebRTC") {
log("set " + videoname + "." + attr + " = " + value);
var obj = $("html5-" + videoname);
if (obj) {
if (attr == "controls") {
obj.controls = value;
}
else if (attr == "live" && this.has_html5_webrtc) {
if (value) {
log("local-stream=" + (this._webrtc_local_stream === null));
if (this._webrtc_local_stream == null) {
var phone = this;
try {
navigator.webkitGetUserMedia({"video": true, "audio": true},
function(stream) { phone.onUserMediaSuccess(stream); },
function(error) { phone.onUserMediaError(error); });
}
catch (e) {
// try older style
navigator.webkitGetUserMedia("video,audio",
function(stream) { phone.onUserMediaSuccess(stream); },
function(error) { phone.onUserMediaError(error); });
}
}
else {
this.onUserMediaSuccess(this._webrtc_local_stream);
}
}
else {
obj.setAttribute('src', '');
}
}
else {
log("ignoring set property '" + attr + "' on '" + videoname + '"');
}
}
else {
log("cannot get video object of id 'html5-" + videoname + "' to set property '" + attr + "'");
}
}
else {
var obj = getFlashMovie(videoname);
if (obj) {
obj.setProperty(attr, value);
}
else {
log("cannot get video object of name '" + videoname + "' to set property '" + attr + "'");
}
}
};
Phone.prototype.getVideoProperty = function(videoname, attr) {
var result = undefined;
if (this.network_type == "WebRTC") {
var obj = $("html5-" + videoname);
if (obj) {
if (attr == "controls") {
result = obj.controls;
}
else {
log("ignoring get property '" + attr + "' on '" + videoname + '"');
}
}
else {
log("cannot get video object of id 'html5-" + videoname + "' to get property '" + attr + "'");
}
log("get " + videoname + "." + attr + " = " + result);
}
else {
var obj = getFlashMovie(videoname);
if (obj) {
result = obj.getProperty(attr);
}
else {
log("cannot get video object of name '" + videoname + "' to get property '" + attr + "'");
}
}
return result;
};
Phone.prototype.onUserMediaSuccess = function(stream) {
log("webrtc - accessing user media successfully");
if (stream !== this._webrtc_local_stream) {
this._webrtc_local_stream = stream;
if (this.call_state == "inviting" || this.call_state == "accepting") {
// need to start peer-connection also
this.createdWebRtcLocalStream();
}
}
var video = $("html5-local-video");
if (video) {
var url = webkitURL.createObjectURL(stream);
log('webrtc - local-video.src="' + url + '"');
video.setAttribute('src', url);
}
};
Phone.prototype.onUserMediaError = function(error) {
log("webrtc - failed to get access to local media: " + error.code);
var obj = $("local-video-on");
if (obj) {
obj.checked = false;
}
if (this.call_state == "inviting" || this.call_state == "accepting") {
if (this.call_state == "accepting") {
ua.sendResponse(ua.createResponse(603, 'Declined Media Devices'));
}
this.setProperty("call_state", "failed");
this.setProperty("call_button.disabled", true);
this.setProperty("end_button.disabled", false);
this.dispatchMessage('Failed: cannot access user media devices');
this.hungup();
}
};
Phone.prototype.createMediaSockets = function() {
var this_ = this;
var handler = function(event) {
if (event.property == "bound")
this_.createdMediaSockets();
};
this._gw = new network.RealTimeGateway();
this._gw.addEventListener("propertyChange", function(event) {
if (event.property == "publishurl")
getFlashMovie('local-video').setProperty('src', event.newValue);
else if (event.property == "playurl")
getFlashMovie('remote-video').setProperty('src', event.newValue);
});
if (this.has_audio || this.has_tones) {
var as = new network.RealTimeSocket();
this._rtp.push(as);
as.addEventListener("propertyChange", handler);
as.bind();
}
if (this.has_video) {
var vs = new network.RealTimeSocket();
this._rtp.push(vs);
vs.addEventListener("propertyChange", handler);
vs.bind();
}
if (this.has_text) {
var ts = new network.RealTimeSocket();
this._rtp.push(ts);
ts.addEventListener("propertyChange", handler);
ts.bind();
}
};
Phone.prototype.createdMediaSockets = function() {
var all = true;
var streams = [];
for (var i=0; i<this._rtp.length; ++i) {
if (this._rtp[i].bound == false) {
all = false;
break;
}
}
if (all) {
var rtp = this._rtp.slice();
if (this.has_audio || this.has_tones) {
var fmt = [];
if (this.has_audio) {
fmt.push({pt: 0, name: "pcmu", rate: 8000});
//fmt.push({pt: 8, name: "pcma", rate: 8000});
//fmt.push({pt: 96, name: "speex", rate: 8000});
//fmt.push({pt: 97, name: "speex", rate: 16000});
}
if (this.has_tones) {
fmt.push({pt: 101, name: "telephone-event", rate: 8000});
}
var audio = new sip.SDP.media({media: "audio", port: rtp.shift().localPort, proto: "RTP/AVP", fmt: fmt});
streams.push(audio);
}
if (this.has_video) {
var fmt = [{pt: 100, name: "h264", rate: 90000}];
var video = new sip.SDP.media({media: "video", port: rtp.shift().localPort, proto: "RTP/AVP", fmt: fmt});
video['a'] = ['fmtp:100 profile-level-id=42801f;packetization-mode=1'];
streams.push(video);
}
if (this.has_text) {
var fmt = [{pt: 98, name: "t140", rate: 1000}, {pt: 99, name: "red", rate: 1000}];
var text = new sip.SDP.media({media: "text", port: rtp.shift().localPort, proto: "RTP/AVP", fmt: fmt});
text['a'] = ['fmtp:99 98/98/98/98'];
streams.push(text);
}
if (this.call_state == "inviting") {
this._local_sdp = sip.createOffer(streams);
this._local_sdp['o'].address = this.listen_ip;
this._local_sdp['c'] = new sip.SDP.connection({address: this.listen_ip});
var m = this._call.createRequest('INVITE');
var c = new sip.Header(this._stack.uri.toString(), 'Contact');
c.value.uri.user = this.username;
m.setItem('Contact', c);
if (this.user_agent)
m.setItem('User-Agent', new sip.Header(this.user_agent, 'User-Agent'));
if (this.has_location && this.location) {
var xml = this.locationToXML(this.location, this.target_value);
var multipart = this.createMultipartBody('application/sdp', this._local_sdp.toString(), 'application/pidf+xml', xml);
m.setItem('Content-Type', new sip.Header('multipart/mixed; boundary="' + multipart[0] + '"', 'Content-Type'));
m.setBody(multipart[1]);
}
else {
m.setItem('Content-Type', new sip.Header('application/sdp', 'Content-Type'));
m.setBody(this._local_sdp.toString());
}
this._call.sendRequest(m);
}
else if (this.call_state == "accepting") {
var offer = null
var ua = this._call;
if (ua.request.hasItem('Content-Type') && ua.request.first('Content-Type').value.toLowerCase() == 'application/sdp') {
try {
offer = new sip.SDP(this._call.request.body);
} catch (ex) {
log("Failed to create SDP: " + ex);
}
}
this._remote_sdp = offer;
this._local_sdp = sip.createAnswer(streams, offer);
if (this._local_sdp == null) {
this.dispatchMessage('Incompatible session description');
ua.sendResponse(ua.createResponse(488, 'Incompatible Session Description'));
this.setProperty('call_state', 'idle');
this.hungup();
}
else {
this._local_sdp['o'].address = this.listen_ip;
this._local_sdp['c'] = new sip.SDP.connection({address: this.listen_ip});
this.createMediaConnections();
this.setProperty('call_state', 'active');
var m = this._call.createResponse(200, 'OK');
var c = new sip.Header(this._stack.uri.toString(), 'Contact');
c.value.uri.user = this.username;
m.setItem('Contact', c);
if (this.server)
m.setItem('Server', new sip.Header(this.server, 'Server'));
m.setItem('Content-Type', new sip.Header('application/sdp', 'Content-Type'));
m.setBody(this._local_sdp.toString());
this._call.sendResponse(m);
}
}
else {
log('invalid call state in createdMediaSockets: ' + this.call_state);
}
}
};
Phone.prototype.createWebRtcConnection = function() {
try {
if ((this.has_audio || this.has_video) && !this.has_html5_webrtc) {
throw new String("missing WebRTC, cannot use audio or video")
}
if (this._webrtc_local_stream == null) {
this.setVideoProperty("local-video", "live", true);
}
else {
this.createdWebRtcLocalStream();
}
}
catch (e) {
if (this.call_state == "accepting") {
ua.sendResponse(ua.createResponse(500, 'Error in getting user media'));
}
this.setProperty("call_state", "failed");
this.setProperty("call_button.disabled", true);
this.setProperty("end_button.disabled", false);
this.dispatchMessage('Failed: "' + e + '"');
this.hungup();
}
};
Phone.prototype.getIceServers = function() {
var parts = this.webrtc_servers.split(","); // comma separated list
var result = [];
for (var i=0; i<parts.length; ++i) {
var part = parts[i];
if (part) {
var index = part.indexOf("|");
if (index < 0)
result.push({url: part});
else
result.push({url: part.substr(0, index), credential: part.substr(index+1)});
}
}
return result;
};
// extract SDP from the SIP message
Phone.prototype.getSDP = function(message) {
var type = message.hasItem("Content-Type") ? message.first("Content-Type").value : null;
return (type == "application/sdp" || message.body) ? message.body : null;
};
Phone.prototype.createdWebRtcLocalStream = function() {
var phone = this;
this._webrtc_peer_connection = new webkitRTCPeerConnection({iceServers: this.getIceServers()}, null);
this._webrtc_peer_connection.onconnecting = function(message) { phone.onWebRtcConnecting(message); };
this._webrtc_peer_connection.onopen = function(message) { phone.onWebRtcOpen(message) };
this._webrtc_peer_connection.onaddstream = function(event) { phone.onWebRtcAddStream(event.stream); };
this._webrtc_peer_connection.onremovestream = function(event) { phone.onWebRtcRemoveStream(); };
//we use timeout instead of onicecandidate event handler
//this._webrtc_peer_connection.onicecandidate = function(event) { console.log(event.candidate);};
if (this.call_state == "accepting" && this._call != null && this._call.request != null) {
var result = this.getSDP(this._call.request);
if (result) {
this._webrtc_peer_connection.setRemoteDescription(new RTCSessionDescription({type: "offer", sdp: result}));
}
}
if (this._webrtc_local_stream != null) {
this._webrtc_peer_connection.addStream(this._webrtc_local_stream);
}
if (this.call_state == "inviting") {
this._webrtc_peer_connection.createOffer(function(offer) {
phone._webrtc_peer_connection.setLocalDescription(offer);
setTimeout(function() {
phone.onWebRtcSendMessage();
}, phone._sdp_timeout);
});
}
else if (this.call_state == "accepting") {
this._webrtc_peer_connection.createAnswer(function(offer) {
phone._webrtc_peer_connection.setLocalDescription(offer);
setTimeout(function() {
phone.onWebRtcSendMessage();
}, phone._sdp_timeout);
});
}
};
Phone.prototype.onWebRtcSendMessage = function() {
if (this.call_state == "inviting") {
this._local_sdp = this._webrtc_peer_connection.localDescription.sdp;
var m = this._call.createRequest('INVITE');
//var c = new sip.Header(this._stack.uri.toString(), 'Contact');
//c.value.uri.user = this.username;
var c = new sip.Header((new sip.Address(this.local_aor)).uri.toString(), 'Contact');
m.setItem('Contact', c);
if (this.user_agent)
m.setItem('User-Agent', new sip.Header(this.user_agent, 'User-Agent'));
m.setItem('Content-Type', new sip.Header("application/sdp", 'Content-Type'));
m.setBody(this._local_sdp);
this._call.sendRequest(m);
}
else if (this.call_state == "accepting") {
this._local_sdp = this._webrtc_peer_connection.localDescription.sdp;
var ua = this._call;
this.setProperty('call_state', 'active');
this.dispatchMessage('Connected');
var m = this._call.createResponse(200, 'OK');
//var c = new sip.Header(this._stack.uri.toString(), 'Contact');
//c.value.uri.user = this.username;
var c = new sip.Header((new sip.Address(this.local_aor)).uri.toString(), 'Contact');
m.setItem('Contact', c);