forked from BenJaziaSadok/janus-gateway-php
-
Notifications
You must be signed in to change notification settings - Fork 1
/
janus.js
1550 lines (1503 loc) · 53.4 KB
/
janus.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
// List of sessions
Janus.sessions = {};
// Screensharing Chrome Extension ID
Janus.extensionId = "hapfgfdkleiggjjpfpenajgdnfckjpaj";
Janus.isExtensionEnabled = function() {
if(window.navigator.userAgent.match('Chrome')) {
var chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
var maxver = 33;
if(window.navigator.userAgent.match('Linux'))
maxver = 35; // "known" crash in chrome 34 and 35 on linux
if(chromever >= 26 && chromever <= maxver) {
// Older versions of Chrome don't support this extension-based approach, so lie
return true;
}
return ($('#janus-extension-installed').length > 0);
} else {
// Firefox of others, no need for the extension (but this doesn't mean it will work)
return true;
}
};
Janus.noop = function() {};
// Initialization
Janus.init = function(options) {
options = options || {};
options.callback = (typeof options.callback == "function") ? options.callback : Janus.noop;
if(Janus.initDone === true) {
// Already initialized
options.callback();
} else {
if(typeof console == "undefined" || typeof console.log == "undefined")
console = { log: function() {} };
// Console log (debugging disabled by default)
Janus.log = (options.debug === true) ? console.log.bind(console) : Janus.noop;
Janus.log("Initializing library");
Janus.initDone = true;
// Detect tab close
window.onbeforeunload = function() {
Janus.log("Closing window");
for(var s in Janus.sessions) {
Janus.log("Destroying session " + s);
Janus.sessions[s].destroy();
}
}
// Helper to add external JavaScript sources
function addJs(src) {
if(src === 'jquery.min.js') {
if(window.jQuery) {
// Already loaded
options.callback();
return;
}
}
var oHead = document.getElementsByTagName('head').item(0);
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.src = src;
oScript.onload = function() {
Janus.log("Library " + src + " loaded");
if(src === 'jquery.min.js') {
options.callback();
}
}
oHead.appendChild(oScript);
};
//addJs('adapter.js');
addJs('jquery.min.js');
}
};
// Helper method to check whether WebRTC is supported by this browser
Janus.isWebrtcSupported = function() {
if(RTCPeerConnection === null || getUserMedia === null) {
return false;
}
return true;
};
function Janus(gatewayCallbacks) {
if(Janus.initDone === undefined) {
gatewayCallbacks.error("Library not initialized");
return {};
}
if(!Janus.isWebrtcSupported()) {
gatewayCallbacks.error("WebRTC not supported by this browser");
return {};
}
Janus.log("Library initialized: " + Janus.initDone);
gatewayCallbacks = gatewayCallbacks || {};
gatewayCallbacks.success = (typeof gatewayCallbacks.success == "function") ? gatewayCallbacks.success : jQuery.noop;
gatewayCallbacks.error = (typeof gatewayCallbacks.error == "function") ? gatewayCallbacks.error : jQuery.noop;
gatewayCallbacks.destroyed = (typeof gatewayCallbacks.destroyed == "function") ? gatewayCallbacks.destroyed : jQuery.noop;
if(gatewayCallbacks.server === null || gatewayCallbacks.server === undefined) {
gatewayCallbacks.error("Invalid gateway url");
return {};
}
var websockets = false;
var ws = null;
var servers = null, serversIndex = 0;
var server = gatewayCallbacks.server;
if($.isArray(server)) {
Janus.log("Multiple servers provided (" + server.length + "), will use the first that works");
server = null;
servers = gatewayCallbacks.server;
Janus.log(servers);
} else {
if(server.indexOf("ws") === 0) {
websockets = true;
Janus.log("Using WebSockets to contact Janus");
} else {
websockets = false;
Janus.log("Using REST API to contact Janus");
}
Janus.log(server);
}
var iceServers = gatewayCallbacks.iceServers;
if(iceServers === undefined || iceServers === null)
iceServers = [{"url": "stun:stun.l.google.com:19302"}];
var ipv6Support = gatewayCallbacks.ipv6;
if(ipv6Support === undefined || ipv6Support === null)
ipv6Support = false;
var maxev = null;
if(gatewayCallbacks.max_poll_events !== undefined && gatewayCallbacks.max_poll_events !== null)
maxev = gatewayCallbacks.max_poll_events;
if(maxev < 1)
maxev = 1;
var connected = false;
var sessionId = null;
var pluginHandles = {};
var that = this;
var retries = 0;
var transactions = {};
createSession(gatewayCallbacks);
// Public methods
this.getServer = function() { return server; };
this.isConnected = function() { return connected; };
this.getSessionId = function() { return sessionId; };
this.destroy = function(callbacks) { destroySession(callbacks); };
this.attach = function(callbacks) { createHandle(callbacks); };
// Private method to create random identifiers (e.g., transaction)
function randomString(len) {
charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
}
function eventHandler() {
if(sessionId == null)
return;
Janus.log('Long poll...');
if(!connected) {
Janus.log("Is the gateway down? (connected=false)");
return;
}
//Refresh
$.ajax({
type: 'POST',
url: 'janus.php',
cache: false,
async:true,
timeout: 60000,
data:{action:'Refresh',sessionId:sessionId},
success: handleEvent,
error: function(XMLHttpRequest, textStatus, errorThrown) {
Janus.log(textStatus + ": " + errorThrown);
//~ clearTimeout(timeoutTimer);
retries++;
if(retries > 20) {
// Did we just lose the gateway? :-(
connected = false;
gatewayCallbacks.error("Lost connection to the gateway (is it down?)");
return;
}
eventHandler();
},
dataType: "json"
});
}
// Private event handler: this will trigger plugin callbacks, if set
function handleEvent(json) {
retries = 0;
if(!websockets && sessionId !== undefined && sessionId !== null)
setTimeout(eventHandler, 200);
Janus.log("Got event on session " + sessionId);
Janus.log(json);
if(!websockets && $.isArray(json)) {
// We got an array: it means we passed a maxev > 1, iterate on all objects
for(var i=0; i<json.length; i++) {
handleEvent(json[i]);
}
return;
}
if(json["janus"] === "keepalive") {
// Nothing happened
return;
} else if(json["janus"] === "ack") {
// Just an ack, we can probably ignore
var transaction = json["transaction"];
if(transaction !== null && transaction !== undefined) {
var reportSuccess = transactions[transaction];
if(reportSuccess !== null && reportSuccess !== undefined) {
reportSuccess(json);
}
delete transactions[transaction];
}
return;
} else if(json["janus"] === "success") {
// Success!
var transaction = json["transaction"];
if(transaction !== null && transaction !== undefined) {
var reportSuccess = transactions[transaction];
if(reportSuccess !== null && reportSuccess !== undefined) {
reportSuccess(json);
}
delete transactions[transaction];
}
return;
} else if(json["janus"] === "webrtcup") {
// The PeerConnection with the gateway is up! FIXME Should we notify this?
return;
} else if(json["janus"] === "hangup") {
// A plugin asked the core to hangup a PeerConnection on one of our handles
var sender = json["sender"];
if(sender === undefined || sender === null) {
Janus.log("Missing sender...");
return;
}
var pluginHandle = pluginHandles[sender];
if(pluginHandle === undefined || pluginHandle === null) {
Janus.log("This handle is not attached to this session");
return;
}
pluginHandle.hangup();
} else if(json["janus"] === "detached") {
// A plugin asked the core to detach one of our handles
var sender = json["sender"];
if(sender === undefined || sender === null) {
Janus.log("Missing sender...");
return;
}
var pluginHandle = pluginHandles[sender];
if(pluginHandle === undefined || pluginHandle === null) {
Janus.log("This handle is not attached to this session");
return;
}
pluginHandle.ondetached();
pluginHandle.detach();
} else if(json["janus"] === "error") {
// Oops, something wrong happened
Janus.log("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
var transaction = json["transaction"];
if(transaction !== null && transaction !== undefined) {
var reportSuccess = transactions[transaction];
if(reportSuccess !== null && reportSuccess !== undefined) {
reportSuccess(json);
}
delete transactions[transaction];
}
return;
} else if(json["janus"] === "event") {
var sender = json["sender"];
if(sender === undefined || sender === null) {
Janus.log("Missing sender...");
return;
}
var plugindata = json["plugindata"];
if(plugindata === undefined || plugindata === null) {
Janus.log("Missing plugindata...");
return;
}
Janus.log(" -- Event is coming from " + sender + " (" + plugindata["plugin"] + ")");
var data = plugindata["data"];
Janus.log(data);
var pluginHandle = pluginHandles[sender];
if(pluginHandle === undefined || pluginHandle === null) {
Janus.log("This handle is not attached to this session");
return;
}
var jsep = json["jsep"];
if(jsep !== undefined && jsep !== null) {
Janus.log("Handling SDP as well...");
Janus.log(jsep);
}
var callback = pluginHandle.onmessage;
if(callback !== null && callback !== undefined) {
Janus.log("Notifying application...");
// Send to callback specified when attaching plugin handle
callback(data, jsep);
} else {
// Send to generic callback (?)
Janus.log("No provided notification callback");
}
} else {
Janus.log("Unknown message '" + json["janus"] + "'");
}
}
// Private method to create a session
function createSession(callbacks) {
if(server === null && $.isArray(servers)) {
// We still need to find a working server from the list we were given
server = servers[serversIndex];
if(server.indexOf("ws") === 0) {
websockets = true;
Janus.log("Server #" + (serversIndex+1) + ": trying WebSockets to contact Janus");
} else {
websockets = false;
Janus.log("Server #" + (serversIndex+1) + ": trying REST API to contact Janus");
}
Janus.log(server);
}
$.ajax({
type: 'POST',
url: 'janus.php',
cache: false,
async:true,
data: {action:'CreateSession'},
success: function(json) {
console.log(json);
//var json = $.parseJSON(json);
console.log(json);
Janus.log("Create session:");
Janus.log(json);
if(json["janus"] !== "success") {
Janus.log("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
callbacks.error(json["error"].reason);
return;
}
connected = true;
sessionId = json.data["id"];
Janus.log("Created session: " + sessionId);
Janus.sessions[sessionId] = that;
eventHandler();
callbacks.success();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
Janus.log(textStatus + ": " + errorThrown); // FIXME
if($.isArray(servers)) {
serversIndex++;
if(serversIndex == servers.length) {
// We tried all the servers the user gave us and they all failed
callbacks.error("Error connecting to any of the provided Janus servers: Is the gateway down?");
return;
}
// Let's try the next server
server = null;
setTimeout(function() { createSession(callbacks); }, 200);
return;
}
if(errorThrown === "")
callbacks.error(textStatus + ": Is the gateway down?");
else
callbacks.error(textStatus + ": " + errorThrown);
},
dataType: "json"
});
}
// Private method to destroy a session
function destroySession(callbacks, syncRequest) {
syncRequest = (syncRequest === true);
Janus.log("Destroying session " + sessionId + " (sync=" + syncRequest + ")");
callbacks = callbacks || {};
// FIXME This method triggers a success even when we fail
callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
if(!connected) {
Janus.log("Is the gateway down? (connected=false)");
callbacks.success();
return;
}
if(sessionId === undefined || sessionId === null) {
Janus.log("No session to destroy");
callbacks.success();
gatewayCallbacks.destroyed();
return;
}
delete Janus.sessions[sessionId];
// Destroy all handles first
for(ph in pluginHandles) {
var phv = pluginHandles[ph];
Janus.log("Destroying handle " + phv.id + " (" + phv.plugin + ")");
destroyHandle(phv.id, null, syncRequest);
}
$.ajax({
type: 'POST',
url: 'janus.php',
cache: false,
data: {action:'destroySession',sessionId:sessionId},
async: true, // Sometimes we need false here, or destroying in onbeforeunload won't work
success: function(json) {
//var json = $.parseJSON(json);
Janus.log("Destroyed session:");
Janus.log(json);
sessionId = null;
connected = false;
if(json["janus"] !== "success") {
Janus.log("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
}
callbacks.success();
gatewayCallbacks.destroyed();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
Janus.log(textStatus + ": " + errorThrown); // FIXME
// Reset everything anyway
sessionId = null;
connected = false;
callbacks.success();
gatewayCallbacks.destroyed();
},
dataType: "json"
});
}
// Private method to create a plugin handle
function createHandle(callbacks) {
callbacks = callbacks || {};
callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
callbacks.consentDialog = (typeof callbacks.consentDialog == "function") ? callbacks.consentDialog : jQuery.noop;
callbacks.onmessage = (typeof callbacks.onmessage == "function") ? callbacks.onmessage : jQuery.noop;
callbacks.onlocalstream = (typeof callbacks.onlocalstream == "function") ? callbacks.onlocalstream : jQuery.noop;
callbacks.onremotestream = (typeof callbacks.onremotestream == "function") ? callbacks.onremotestream : jQuery.noop;
callbacks.ondata = (typeof callbacks.ondata == "function") ? callbacks.ondata : jQuery.noop;
callbacks.ondataopen = (typeof callbacks.ondataopen == "function") ? callbacks.ondataopen : jQuery.noop;
callbacks.oncleanup = (typeof callbacks.oncleanup == "function") ? callbacks.oncleanup : jQuery.noop;
callbacks.ondetached = (typeof callbacks.ondetached == "function") ? callbacks.ondetached : jQuery.noop;
if(!connected) {
Janus.log("Is the gateway down? (connected=false)");
callbacks.error("Is the gateway down? (connected=false)");
return;
}
var plugin = callbacks.plugin;
if(plugin === undefined || plugin === null) {
Janus.log("Invalid plugin");
callbacks.error("Invalid plugin");
return;
}
//alert(sessionId);alert(plugin);
$.ajax({
type: 'POST',
url: 'janus.php',
async:true,
cache: false,
data: {action:'createHandle',sessionId:sessionId,plugin:plugin},
success: function(json) {
//var json = $.parseJSON(json);
Janus.log("Create handle:");
Janus.log(json);
var handleId = json.data["id"];
if(json["janus"] !== "success") {
Janus.log("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
callbacks.error("Ooops: " + json["error"].code + " " + json["error"].reason);
return;
}
var handleId = json.data["id"];
Janus.log("Created handle: " + handleId);
var pluginHandle =
{
session : that,
plugin : plugin,
id : handleId,
webrtcStuff : {
started : false,
myStream : null,
remoteStream : null,
mySdp : null,
pc : null,
dataChannel : null,
dtmfSender : null,
trickle : true,
iceDone : false,
sdpSent : false,
volume : {
value : null,
timer : null
},
bitrate : {
value : null,
bsnow : null,
bsbefore : null,
tsnow : null,
tsbefore : null,
timer : null
}
},
getId : function() { return handleId; },
getPlugin : function() { return plugin; },
getVolume : function() { return getVolume(handleId); },
getBitrate : function() { return getBitrate(handleId); },
send : function(callbacks) { sendMessage(handleId, callbacks); },
data : function(callbacks) { sendData(handleId, callbacks); },
dtmf : function(callbacks) { sendDtmf(handleId, callbacks); },
consentDialog : callbacks.consentDialog,
onmessage : callbacks.onmessage,
createOffer : function(callbacks) { prepareWebrtc(handleId, callbacks); },
createAnswer : function(callbacks) { prepareWebrtc(handleId, callbacks); },
handleRemoteJsep : function(callbacks) { prepareWebrtcPeer(handleId, callbacks); },
onlocalstream : callbacks.onlocalstream,
onremotestream : callbacks.onremotestream,
ondata : callbacks.ondata,
ondataopen : callbacks.ondataopen,
oncleanup : callbacks.oncleanup,
ondetached : callbacks.ondetached,
hangup : function() { cleanupWebrtc(handleId); },
detach : function(callbacks) { destroyHandle(handleId, callbacks); }
}
pluginHandles[handleId] = pluginHandle;
callbacks.success(pluginHandle);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
Janus.log(textStatus + ": " + errorThrown); // FIXME
},
dataType: "json"
});
}
// Private method to send a message
function sendMessage(handleId, callbacks) {
callbacks = callbacks || {};
callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
if(!connected) {
Janus.log("Is the gateway down? (connected=false)");
callbacks.error("Is the gateway down? (connected=false)");
return;
}
var message = callbacks.message;
var jsep = callbacks.jsep;
Janus.log("Sending message to plugin (handle=" + handleId + "):");
//Janus.log(request);
//alert(JSON.stringify(jsep));
$.ajax({
type: 'POST',
url: 'janus.php',
async:true,
cache: false,
data: {action:'sendMessage',jsep:JSON.stringify(jsep),sessionId:sessionId,handleId:handleId,message:JSON.stringify(message)},
success: function(json) {
//var json = $.parseJSON(json);
Janus.log(json);
Janus.log("Message sent!");
if(json["janus"] === "success") {
// We got a success, must have been a synchronous transaction
var plugindata = json["plugindata"];
if(plugindata === undefined || plugindata === null) {
Janus.log("Request succeeded, but missing plugindata...");
callbacks.success();
return;
}
Janus.log("Synchronous transaction successful (" + plugindata["plugin"] + ")");
var data = plugindata["data"];
Janus.log(data);
callbacks.success(data);
return;
} else if(json["janus"] !== "ack") {
// Not a success and not an ack, must be an error
if(json["error"] !== undefined && json["error"] !== null) {
Janus.log("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
callbacks.error(json["error"].code + " " + json["error"].reason);
} else {
Janus.log("Unknown error"); // FIXME
callbacks.error("Unknown error");
}
return;
}
// If we got here, the plugin decided to handle the request asynchronously
callbacks.success();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
Janus.log(textStatus + ": " + errorThrown); // FIXME
callbacks.error(textStatus + ": " + errorThrown);
},
dataType: "json"
});
}
// Private method to send a trickle candidate
function sendTrickleCandidate(handleId, candidate) {
if(!connected) {
Janus.log("Is the gateway down? (connected=false)");
return;
}
Janus.log("Sending trickle candidate (handle=" + handleId + "):");
$.ajax({
type: 'POST',
url: 'janus.php',
async:true,
cache: false,
data: {action:'sendTrickleCandidate',sessionId:sessionId,handleId:handleId,candidate:JSON.stringify(candidate)},
success: function(json) {
console.log(JSON.stringify(candidate));
//var json = $.parseJSON(json);
Janus.log(json);
Janus.log("Candidate sent!");
if(json["janus"] !== "ack") {
Janus.log("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
return;
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
Janus.log(textStatus + ": " + errorThrown); // FIXME
},
dataType: "json"
});
}
// Private method to send a data channel message
function sendData(handleId, callbacks) {
callbacks = callbacks || {};
callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
var pluginHandle = pluginHandles[handleId];
if(pluginHandle === null || pluginHandle === undefined ||
pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
Janus.log("Invalid handle");
callbacks.error("Invalid handle");
return;
}
var config = pluginHandle.webrtcStuff;
var text = callbacks.text;
if(text === null || text === undefined) {
Janus.log("Invalid text");
callbacks.error("Invalid text");
return;
}
Janus.log("Sending string on data channel: " + text);
config.dataChannel.send(text);
callbacks.success();
}
// Private method to send a DTMF tone
function sendDtmf(handleId, callbacks) {
callbacks = callbacks || {};
callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
var pluginHandle = pluginHandles[handleId];
if(pluginHandle === null || pluginHandle === undefined ||
pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
Janus.log("Invalid handle");
callbacks.error("Invalid handle");
return;
}
var config = pluginHandle.webrtcStuff;
if(config.dtmfSender === null || config.dtmfSender === undefined) {
// Create the DTMF sender, if possible
if(config.myStream !== undefined && config.myStream !== null) {
var tracks = config.myStream.getAudioTracks();
if(tracks !== null && tracks !== undefined && tracks.length > 0) {
var local_audio_track = tracks[0];
config.dtmfSender = config.pc.createDTMFSender(local_audio_track);
Janus.log("Created DTMF Sender");
config.dtmfSender.ontonechange = function(tone) { Janus.log("Sent DTMF tone: " + tone.tone); };
}
}
if(config.dtmfSender === null || config.dtmfSender === undefined) {
Janus.log("Invalid DTMF configuration");
callbacks.error("Invalid DTMF configuration");
return;
}
}
var dtmf = callbacks.dtmf;
if(dtmf === null || dtmf === undefined) {
Janus.log("Invalid DTMF parameters");
callbacks.error("Invalid DTMF parameters");
return;
}
var tones = dtmf.tones;
if(tones === null || tones === undefined) {
Janus.log("Invalid DTMF string");
callbacks.error("Invalid DTMF string");
return;
}
var duration = dtmf.duration;
if(duration === null || duration === undefined)
duration = 500; // We choose 500ms as the default duration for a tone
var gap = dtmf.gap;
if(gap === null || gap === undefined)
gap = 50; // We choose 50ms as the default gap between tones
Janus.log("Sending DTMF string " + tones + " (duration " + duration + "ms, gap " + gap + "ms");
config.dtmfSender.insertDTMF(tones, duration, gap);
}
// Private method to destroy a plugin handle
function destroyHandle(handleId, callbacks, syncRequest) {
syncRequest = (syncRequest === true);
Janus.log("Destroying handle " + handleId + " (sync=" + syncRequest + ")");
callbacks = callbacks || {};
callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
cleanupWebrtc(handleId);
if(!connected) {
Janus.log("Is the gateway down? (connected=false)");
callbacks.error("Is the gateway down? (connected=false)");
return;
}
$.ajax({
type: 'POST',
url: 'janus.php',
async:true,
cache: false,
data: {action:'destroyHandle',sessionId:sessionId,handleId:handleId},
success: function(json) {
//var json = $.parseJSON(json);
Janus.log("Destroyed handle:");
Janus.log(json);
if(json["janus"] !== "success") {
Janus.log("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
}
delete pluginHandles[handleId];
callbacks.success();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
Janus.log(textStatus + ": " + errorThrown); // FIXME
// We cleanup anyway
delete pluginHandles[handleId];
callbacks.success();
},
dataType: "json"
});
}
// WebRTC stuff
function streamsDone(handleId, jsep, media, callbacks, stream) {
var pluginHandle = pluginHandles[handleId];
if(pluginHandle === null || pluginHandle === undefined ||
pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
Janus.log("Invalid handle");
callbacks.error("Invalid handle");
return;
}
var config = pluginHandle.webrtcStuff;
if(stream !== null && stream !== undefined)
Janus.log(stream);
config.myStream = stream;
Janus.log("streamsDone:");
if(stream !== null && stream !== undefined)
Janus.log(stream);
var pc_config = {"iceServers": iceServers};
//~ var pc_constraints = {'mandatory': {'MozDontOfferDataChannel':true}};
var pc_constraints = {
"optional": [{"DtlsSrtpKeyAgreement": true}]
};
if(ipv6Support === true) {
// FIXME This is only supported in Chrome right now
// For support in Firefox track this: https://bugzilla.mozilla.org/show_bug.cgi?id=797262
pc_constraints.optional.push({"googIPv6":true});
}
Janus.log("Creating PeerConnection:");
Janus.log(pc_constraints);
config.pc = new RTCPeerConnection(pc_config, pc_constraints);
Janus.log(config.pc);
if(config.pc.getStats) { // FIXME
config.volume.value = 0;
config.bitrate.value = "0 kbits/sec";
}
Janus.log("Preparing local SDP and gathering candidates (trickle=" + config.trickle + ")");
config.pc.onicecandidate = function(event) {
if (event.candidate == null) {
Janus.log("End of candidates.");
config.iceDone = true;
if(config.trickle === true) {
// Notify end of candidates
sendTrickleCandidate(handleId, {"completed": true});
} else {
// No trickle, time to send the complete SDP (including all candidates)
sendSDP(handleId, callbacks);
}
} else {
// JSON.stringify doesn't work on some WebRTC objects anymore
// See https://code.google.com/p/chromium/issues/detail?id=467366
var candidate = {
"candidate": event.candidate.candidate,
"sdpMid": event.candidate.sdpMid,
"sdpMLineIndex": event.candidate.sdpMLineIndex
};
Janus.log("candidates: " + JSON.stringify(candidate));
if(config.trickle === true) {
// Send candidate
sendTrickleCandidate(handleId, candidate);
}
}
};
if(stream !== null && stream !== undefined) {
Janus.log('Adding local stream');
config.pc.addStream(stream);
pluginHandle.onlocalstream(stream);
}
config.pc.onaddstream = function(remoteStream) {
Janus.log("Handling Remote Stream:");
Janus.log(remoteStream);
config.remoteStream = remoteStream;
pluginHandle.onremotestream(remoteStream.stream);
};
// Any data channel to create?
if(isDataEnabled(media)) {
Janus.log("Creating data channel");
var onDataChannelMessage = function(event) {
Janus.log('Received message on data channel: ' + event.data);
pluginHandle.ondata(event.data); // FIXME
}
var onDataChannelStateChange = function() {
var dcState = config.dataChannel !== null ? config.dataChannel.readyState : "null";
Janus.log('State change on data channel: ' + dcState);
if(dcState === 'open') {
pluginHandle.ondataopen(); // FIXME
}
}
var onDataChannelError = function(error) {
Janus.log('Got error on data channel:');
Janus.log(error);
// TODO
}
// Until we implement the proxying of open requests within the Janus core, we open a channel ourselves whatever the case
config.dataChannel = config.pc.createDataChannel("JanusDataChannel", {ordered:false}); // FIXME Add options (ordered, maxRetransmits, etc.)
config.dataChannel.onmessage = onDataChannelMessage;
config.dataChannel.onopen = onDataChannelStateChange;
config.dataChannel.onclose = onDataChannelStateChange;
config.dataChannel.onerror = onDataChannelError;
}
// Create offer/answer now
if(jsep === null || jsep === undefined) {
createOffer(handleId, media, callbacks);
} else {
config.pc.setRemoteDescription(
new RTCSessionDescription(jsep),
function() {
Janus.log("Remote description accepted!");
createAnswer(handleId, media, callbacks);
}, callbacks.error);
}
}
function prepareWebrtc(handleId, callbacks) {
callbacks = callbacks || {};
callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : webrtcError;
var jsep = callbacks.jsep;
var media = callbacks.media;
var pluginHandle = pluginHandles[handleId];
if(pluginHandle === null || pluginHandle === undefined ||
pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
Janus.log("Invalid handle");
callbacks.error("Invalid handle");
return;
}
var config = pluginHandle.webrtcStuff;
// Are we updating a session?
if(config.pc !== undefined && config.pc !== null) {
Janus.log("Updating existing media session");
// Create offer/answer now
if(jsep === null || jsep === undefined) {
createOffer(handleId, media, callbacks);
} else {
config.pc.setRemoteDescription(
new RTCSessionDescription(jsep),
function() {
Janus.log("Remote description accepted!");
createAnswer(handleId, media, callbacks);
}, callbacks.error);
}
return;
}
config.trickle = isTrickleEnabled(callbacks.trickle);
if(isAudioSendEnabled(media) || isVideoSendEnabled(media)) {
var constraints = { mandatory: {}, optional: []};
pluginHandle.consentDialog(true);
var videoSupport = isVideoSendEnabled(media);
if(videoSupport === true && media != undefined && media != null) {
if(media.video && media.video != 'screen') {
var width = 0;
var height = 0, maxHeight = 0;
if(media.video === 'lowres') {
// Small resolution, 4:3
height = 240;
maxHeight = 240;
width = 320;
} else if(media.video === 'lowres-16:9') {
// Small resolution, 16:9
height = 180;
maxHeight = 180;
width = 320;
} else if(media.video === 'hires' || media.video === 'hires-16:9' ) {
// High resolution is only 16:9
height = 720;
maxHeight = 720;
width = 1280;
if(navigator.mozGetUserMedia) {
var firefoxVer = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
if(firefoxVer < 38) {
// Unless this is and old Firefox, which doesn't support it
Janus.log(media.video + " unsupported, falling back to stdres (old Firefox)");
height = 480;
maxHeight = 480;
width = 640;
}
}
} else if(media.video === 'stdres') {
// Normal resolution, 4:3
height = 480;
maxHeight = 480;
width = 640;
} else if(media.video === 'stdres-16:9') {
// Normal resolution, 16:9
height = 360;
maxHeight = 360;
width = 640;
} else {
Janus.log("Default video setting (" + media.video + ") is stdres 4:3");
height = 480;
maxHeight = 480;
width = 640;
}
Janus.log("Adding media constraint " + media.video);
if(navigator.mozGetUserMedia) {
var firefoxVer = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
if(firefoxVer < 38) {
videoSupport = {
'require': ['height', 'width'],
'height': {'max': maxHeight, 'min': height},
'width': {'max': width, 'min': width}
};
} else {
// http://stackoverflow.com/questions/28282385/webrtc-firefox-constraints/28911694#28911694
// https://github.com/meetecho/janus-gateway/pull/246
videoSupport = {
'height': {'ideal': height},
'width': {'ideal': width}
};
}
} else {
videoSupport = {
'mandatory': {
'maxHeight': maxHeight,
'minHeight': height,
'maxWidth': width,
'minWidth': width
},
'optional': []
};
}
Janus.log(videoSupport);
} else if(media.video === 'screen') {
// Not a webcam, but screen capture
if(window.location.protocol !== 'https:') {
// Screen sharing mandates HTTPS
Janus.log("Screen sharing only works on HTTPS, try the https:// version of this page");
pluginHandle.consentDialog(false);
callbacks.error("Screen sharing only works on HTTPS, try the https:// version of this page");
return;
}
// We're going to try and use the extension for Chrome 34+, the old approach
// for older versions of Chrome, or the experimental support in Firefox 33+
var cache = {};
function callbackUserMedia (error, stream) {
pluginHandle.consentDialog(false);
if(error) {
callbacks.error(error);
} else {
streamsDone(handleId, jsep, media, callbacks, stream);
}
};
function getScreenMedia(constraints, gsmCallback) {
Janus.log("Adding media constraint (screen capture)");
Janus.log(constraints);
getUserMedia(constraints,
function(stream) {
gsmCallback(null, stream);
},
function(error) {
pluginHandle.consentDialog(false);
gsmCallback(error);
}
);
};
if(window.navigator.userAgent.match('Chrome')) {
var chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
var maxver = 33;
if(window.navigator.userAgent.match('Linux'))
maxver = 35; // "known" crash in chrome 34 and 35 on linux
if(chromever >= 26 && chromever <= maxver) {
// Chrome 26->33 requires some awkward chrome://flags manipulation
constraints = {