-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
603 lines (550 loc) · 17.5 KB
/
index.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
var Emitter = require('emitter')
, WebSocketSignal = require('./signal/web-socket')
, BridgeSignal = require('./signal/bridge')
, AppChannelSignal = require('./signal/app-channel')
, debug = { connection: require('debug')('rtc:connection'),
channel: require('debug')('rtc:channel') };
// Fallbacks for vendor-specific variables until the spec is finalized.
var PeerConnection = window.webkitRTCPeerConnection
|| window.mozRTCPeerConnection
|| window.RTCPeerConnection;
exports.sdpConstraints = {'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true }};
exports.servers = { iceServers: [
{url: 'stun:stun.l.google.com:19302'}
]}
exports.available = (function(){
if( typeof PeerConnection == 'function'
&& PeerConnection.prototype // stupid mozilla
&& typeof PeerConnection.prototype.createDataChannel == 'function' ){
try {
var pc = new PeerConnection(null,{optional: [{RtpDataChannels: true}]});
pc.createDataChannel('feat',{reliable:false}).close()
return true;
} catch(e){
return false;
}
} else {
return false;
}
})();
exports.connect = function(opts){
opts = opts || {};
opts.dataChannels = opts.dataChannels || false;
opts.connectionTimeout = opts.connectionTimeout || 30000;
opts.turnConfigURL = opts.turnConfigURL || '';
opts.autoNegotiate = typeof opts.autoNegotiate == 'boolean' ? opts.autoNegotiate : true;
opts.signal = opts.signal || (typeof goog != undefined ? 'appchan' : 'ws');
var rtc = Emitter({})
, channels = rtc.channels = {}
, connection
, signal
, timeout
, challenge = Date.now() + Math.random()
, challenged = rtc.challenged = false
, challenger = rtc.challenger = false
, connected = rtc.connected = false
, initiator = rtc.initiator = null
, negotiationneeded = false
, streams = []
, open = rtc.open = false;
// create a signal
if( opts.signal == 'ws' ){
signal = rtc.signal = new WebSocketSignal(opts)
} else if( opts.signal == 'bridge' ){
signal = rtc.signal = new BridgeSignal(opts)
} else if( opts.signal == 'appchan' ){
signal = rtc.signal = new AppChannelSignal(opts)
}
signal.on('open',function(){
if( connection ){ rtc.close() }
connection = createConnection();
createDataChannels();
addMissingStreams(connection);
})
signal.on('offer',function(desc){
if( !connection ){ return; }
debug.connection('remote offer',connection.signalingState,[desc])
if( connection.signalingState == 'stable' ){
connection.setRemoteDescription(rewriteSDP(desc),function(){
debug.connection('create answer')
connection.createAnswer(onLocalDescriptionAndSend,null,exports.sdpConstraints);
},onDescError('remote offer'));
} else {
debug.connection('received remote "offer" bit expected an "answer"')
}
})
signal.on('answer',function(desc){
if( !connection ){ return; }
debug.connection('remote answer',connection.signalingState,[desc])
if( connection.signalingState != 'stable' ){
connection.setRemoteDescription(rewriteSDP(desc),function(){},onDescError('remote answer'));
} else {
debug.connection('received "answer" but expected an "offer"')
}
})
signal.on('candidate',function(candidate){
if( !connection ){ return; }
// skip while disconnected
if( connection.iceConnectionState == 'disconnected' ){
return;
}
try {
debug.connection('signal icecandidate',arguments)
connection.addIceCandidate(candidate);
} catch(e){
console.warn('failed to add ice candidate. was it received from a previous connection?',e)
}
})
signal.on('request-for-offer',function(e){
debug.connection('signal request-for-offer')
sendOffer()
})
signal.on('challenge',function(e){
// a request-for-challenge
if( e.challenge === null ){
debug.connection('request-for-challenge',challenge)
sendChallenge()
return;
}
// in case a challenge was received without
// having sent one we send it now.
if( !challenger ){
sendChallenge()
}
// the one with the lowest challenge
// (and thus the first one to arrive)
// is the initiator.
// and the initiator will "start" the
// rtc connection by sending the initial
// offer. the rest of the handshake will
// be dealt with by the library.
debug.connection('challenge',challenge,e.challenge)
if( e.challenge > challenge ){
rtc.initiator = initiator = true;
sendOffer();
} else {
rtc.initiator = initiator = false;
}
// mark this connection as challenged
// (a requirement to be considered "open")
rtc.challenged = challenged = true;
if( !connected ){
rtc.connected = connected = true;
rtc.emit('connected')
}
})
signal.on('connected',function(){
debug.connection('signal connected')
// instead of letting a server decide
// which peer should send the initial
// offer (aka "initiator") we request
// the peer to send us a challenge
requestChallenge()
})
signal.on('disconnected',function(){
debug.connection('signal disconnected')
if( connected ){
rtc.emit('disconnected')
rtc.connected = connected = false;
}
rtc.reconnect()
})
signal.on('event',function(evt){
var type = evt.type;
delete evt.type;
rtc.emit(type,evt);
})
signal.on('error',function(evt){
rtc.emit('error',evt)
})
function createConnection(){
debug.connection('create')
// clear any previous timeouts
stopTimeout('create');
var config = {optional: [{RtpDataChannels: !!opts.dataChannels}]};
var connection = new PeerConnection(exports.servers,config);
connection.onconnecting = function(e){
debug.connection('connecting',arguments)
rtc.emit('connecting',e)
}
connection.onclose = function(e){
debug.connection('close',arguments)
rtc.emit('close',e)
stopTimeout('onclose');
checkOpen()
}
connection.onaddstream = function(e){
debug.connection('addstream',arguments)
rtc.emit('addstream',e)
}
connection.onremovestream = function(e){
debug.connection('removestream',arguments)
rtc.emit('removestream',e)
}
connection.ondatachannel = function(e){
debug.connection('datachannel',arguments)
channels[e.channel.label] = initDataChannel(e.channel);
rtc.emit('datachannel',e)
}
connection.ongatheringchange = function(e){
debug.connection('gatheringchange -> %s',connection.iceGatheringState,arguments)
rtc.emit('gatheringchange',e)
checkOpen()
}
connection.onicecandidate = function(e){
if( e.candidate ){
// debug.connection('icecandidate %s',opts.bufferCandidates ? '(buffered)' : '',arguments)
signal.send(e.candidate)
} else {
debug.connection('icecandidate end %s',opts.bufferCandidates ? '(buffered)' : '')
signal.send({candidate:null})
}
rtc.emit('icecandidate',e)
checkOpen()
}
connection.oniceconnectionstatechange =
connection.onicechange = function(e){
debug.connection('icechange -> %s',connection.iceConnectionState,arguments)
rtc.emit('icechange',e)
checkOpen()
}
connection.onnegotiationneeded = function(e){
debug.connection('negotiationneeded',arguments)
rtc.emit('negotiationneeded',e)
if( opts.autoNegotiate ){
if( open ){
rtc.offer()
} else {
negotiationneeded = true;
}
}
}
connection.onsignalingstatechange =
connection.onstatechange = function(e){
debug.connection('statechange -> %s',connection.signalingState,arguments)
rtc.emit('statechange',e)
checkOpen()
}
rtc.connection = connection;
return connection;
}
function checkOpen(){
var isOpen = connection && challenged && challenger &&
initiator !== null &&
connection.signalingState == 'stable' &&
connection.iceConnectionState != 'disconnected' &&
(connection.iceConnectionState == 'connected' ||
connection.iceGatheringState == 'complete');
// closed -> open
if( !open && isOpen ){
debug.connection('CLOSED -> OPEN')
stopTimeout('isopen');
rtc.open = open = true;
rtc.emit('open')
addMissingStreams(connection);
if( negotiationneeded ){
debug.connection('negotiationneeded on open')
rtc.offer()
}
// closed -> closed
} else if( !open && !isOpen ){
debug.connection('CLOSED -> CLOSED')
startTimeout('isopen')
// open -> closed
} else if( open && !isOpen ){
debug.connection('OPEN -> CLOSED')
rtc.open = open = false;
stopTimeout('isopen');
rtc.emit('close')
// open -> open
} else {
debug.connection('OPEN -> OPEN')
}
}
function createDataChannels() {
if( opts.dataChannels ){
var labels = typeof opts.dataChannels == 'string' ?
[opts.dataChannels] :
opts.dataChannels;
for(var i=0; i<labels.length; i++){
createDataChannel(labels[i]);
}
}
}
function createDataChannel(label){
debug.channel('create',label);
var channel;
try {
// Reliable Data Channels not yet supported in Chrome
// Data Channel api supported from Chrome M25.
// You need to start chrome with --enable-data-channels flag.
channel = connection.createDataChannel(label,{reliable: false});
} catch (e) {
console.error('Create Data channel failed with exception: ' + e.message);
return null;
}
channels[label] = initDataChannel(channel);
return channel;
}
function addMissingStreams(connection){
// re-add any missing streams
// [stream,constraints...]
for(var i=0; i<streams.length; i+=2){
var stream = streams[i];
if( !getStreamById(connection,stream.id) ){
debug.connection('re-added missing stream',stream.id)
connection.addStream(stream);
}
}
}
// a fallback version of connection.getStreamById
function getStreamById(connection,id){
if( typeof connection.getStreamById == 'function' ){
return connection.getStreamById(id);
} else {
var streams = connection.localStreams || connection.getLocalStreams();
for(var i=0; i<streams.length; i++){
if( streams[i].id === id ){
return streams[i];
}
}
return null;
}
}
function closeDataChannel(label){
var channel = channels[label];
if( channel ){
if( channel.readyState != 'closed' ){
channel.close();
}
channel.onmessage = null;
channel.onopen = null;
channel.onclose = null;
channel.onerror = null;
delete channels[label];
}
}
function closeConnection(){
if( connection ){
stopTimeout('close')
if( connection.signalingState != 'closed' ){
connection.close()
}
connection.onconnecting = null;
connection.onopen = null;
connection.onclose = null;
connection.onaddstream = null;
connection.onremovestream = null;
connection.ondatachannel = null;
connection.ongatheringchange = null;
connection.onicecandidate = null;
connection.onicechange = null;
connection.onidentityresult = null;
connection.onnegotiationneeded = null;
connection.oniceconnectionstatechange = null;
connection.onsignalingstatechange = null;
connection.onstatechange = null;
connection = null;
}
rtc.connection = null;
}
function initDataChannel(channel){
if( channel ){
debug.channel('adding listeners',channel.label)
channel.onmessage = function(e){
debug.channel('message %s',channel.label,e)
rtc.emit('channel '+channel.label+' message',e)
rtc.emit('channel message',e)
}
channel.onopen = function(e){
debug.channel('open %s',channel.label)
rtc.emit('channel '+channel.label+' open',e)
rtc.emit('channel open',e)
}
channel.onclose = function(e){
debug.channel('close %s',channel.label)
rtc.emit('channel '+channel.label+' close',e)
rtc.emit('channel close',e)
}
channel.onerror = function(e){
debug.channel('error %s',channel.label,e)
rtc.emit('channel '+channel.label+' error',e)
rtc.emit('channel error',e)
rtc.emit('error',e)
}
}
return channel;
}
var startTimeout = function(from){
debug.connection('timeout started',from)
clearTimeout(timeout);
timeout = setTimeout(function(){
rtc.emit('timeout');
},opts.connectionTimeout)
}
var stopTimeout = function(from){
if( timeout ){
debug.connection('timeout stopped',from)
clearTimeout(timeout);
timeout = null;
}
}
var sendOffer = function(){
if( connection ){
debug.connection('send offer',connection.signalingState)
if( connection.signalingState != 'have-remote-offer' ){
connection.createOffer(onLocalDescriptionAndSend,null,exports.sdpConstraints);
} else {
debug.connection('offer not sent because of signalingState',connection.signalingState)
}
negotiationneeded = false;
}
}
var sendChallenge = function(){
debug.connection('send challenge',challenge)
signal.send({challenge:challenge})
rtc.challenger = challenger = true;
}
var requestOffer = function(){
if( connection ){
debug.connection('request offer')
signal.send({type:'request-for-offer'})
negotiationneeded = false;
}
}
var requestChallenge = function(){
debug.connection('request challenge')
signal.send({challenge:null})
}
var onDescError = function(src){
return function(err){
if( connection ){
console.log('signalingState',connection.signalingState)
console.log('iceConnectionState',connection.iceConnectionState)
console.log('iceGatheringState',connection.iceGatheringState)
}
console.warn('could not set %s description',src,err)
}
}
var onLocalDescriptionAndSend = function(desc){
debug.connection('local description',desc)
if( connection ){
connection.setLocalDescription(desc,function(){},onDescError('local '+desc.type))
signal.send(desc)
}
}
rtc.offer = function(){
if( initiator === true ){
sendOffer()
} else if( initiator === false ){
requestOffer()
} else {
console.warn('attempting to offer before open')
}
}
rtc.addStream = function(stream,constraints){
debug.connection('adding local stream')
try {
connection && connection.addStream(stream,constraints);
streams.push(stream,constraints);
} catch(e){}
return this;
}
rtc.removeStream = function(stream){
debug.connection('removing local stream')
var i = streams.indexOf(stream);
~i && streams.splice(i,2);
connection && connection.removeStream(stream);
return this;
}
rtc.reconnect = function(){
debug.connection('reconnect')
if( connection ) {
rtc.close(true)
}
connection = createConnection();
createDataChannels();
requestChallenge();
rtc.emit('reconnect')
return this;
}
rtc.close = function(keepSignal){
debug.connection('close')
var labels = Object.keys(channels);
labels.forEach(closeDataChannel)
closeConnection()
rtc.challenged = challenged = false;
rtc.challenger = challenger = false;
rtc.initiator = initiator = null;
checkOpen()
keepSignal || signal.send('close')
}
rtc.send = function(label,data){
debug.channel('send',label,data)
var channel = channels[label];
if( channel ){
if( channel.readyState == 'open' ){
channel.send(data);
} else {
console.warn('tried to send data on a not open channel %s',label)
}
} else {
console.error('tried to send to non-existing channel %s',label);
}
}
// ensure we close properly before
// unload. (hoping this will lessen
// the "Aw snap" errors)
try {
var _before = window.onbeforeunload;
window.onbeforeunload = function() {
stopTimeout('unload');
rtc.close();
// chain in case there's other listeners
if( typeof _before == 'function' ){
_before.apply(window,arguments);
}
}
} catch(e){
// wrapped in try/catch in case onbeforeunload
// is not available (such as in a packaged app)
}
// request optional turn configuration
if( opts.turnConfigURL ){
requestTURNConfiguration(opts.turnConfigURL,rtc);
}
return rtc;
}
function rewriteSDP(desc){
// adjust the bandwidth to 64kbps instead of default 30kbps
desc.sdp = desc.sdp.replace('b=AS:30','b=AS:64')
return desc;
}
// 'http://computeengineondemand.appspot.com/turn?username=apa&key=1329412323'
function requestTURNConfiguration(url,rtc){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if( xhr.readyState == 4 && xhr.status == 200 ){
var data;
try {
data = JSON.parse(xhr.responseText);
} catch(e) {
return debug.connection('got bad data from turn ajax service.',xhr.responseText);
}
if( data.uris && data.uris[0] && data.username && data.password ){
for (var i = 0; i < data.uris.length; i++) {
exports.servers.iceServers.push({
url: data.uris[i].replace(':', ':' + data.username + '@'),
credential: data.password
})
}
// attempt a reconnect using the new configuration
rtc && rtc.reconnect()
}
}
}
xhr.open('GET', url, true);
xhr.send();
}