forked from muaz-khan/WebRTC-Experiment
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmeeting.js
451 lines (377 loc) · 14.9 KB
/
meeting.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
// 2013, @muazkh - https://github.com/muaz-khan
// MIT License - https://www.webrtc-experiment.com/licence/
// Documentation - https://github.com/muaz-khan/WebRTC-Experiment/tree/master/audio-broadcast
(function() {
// a middle-agent between public API and the Signaler object
window.Meeting = function(channel) {
var signaler, self = this;
this.channel = channel;
// get alerted for each new meeting
this.onmeeting = function(room) {
if (self.detectedRoom) return;
self.detectedRoom = true;
self.meet(room);
};
function initSignaler() {
signaler = new Signaler(self);
}
function captureUserMedia(callback) {
var constraints = {
audio: true,
video: false
};
navigator.getUserMedia(constraints, onstream, onerror);
function onstream(stream) {
self.stream = stream;
callback(stream);
var audio = document.createElement('audio');
audio.id = 'self';
audio[isFirefox ? 'mozSrcObject' : 'src'] = isFirefox ? stream : window.URL.createObjectURL(stream);
audio.autoplay = true;
audio.controls = true;
audio.play();
self.onaddstream({
audio: audio,
stream: stream,
userid: 'self',
type: 'local'
});
}
function onerror(e) {
console.error(e);
}
}
// setup new meeting room
this.setup = function(roomid) {
captureUserMedia(function() {
!signaler && initSignaler();
signaler.broadcast({
roomid: roomid || self.channel
});
});
};
// join pre-created meeting room
this.meet = function(room) {
captureUserMedia(function() {
!signaler && initSignaler();
signaler.join({
to: room.userid,
roomid: room.roomid
});
});
};
// check pre-created meeting rooms
this.check = initSignaler;
};
// it is a backbone object
function Signaler(root) {
// unique session-id
var channel = root.channel;
// signalling implementation
// if no custom signalling channel is provided; use Firebase
if (!root.openSignalingChannel) {
if (!window.Firebase) throw 'You must link <https://cdn.firebase.com/v0/firebase.js> file.';
// Firebase is capable to store data in JSON format
// root.transmitOnce = true;
var socket = new window.Firebase('https://' + (root.firebase || 'signaling') + '.firebaseIO.com/' + channel);
socket.on('child_added', function(snap) {
var data = snap.val();
if (data.userid != userid) {
if (data.leaving && root.onuserleft) root.onuserleft(data.userid);
else signaler.onmessage(data);
}
// we want socket.io behavior;
// that's why data is removed from firebase servers
// as soon as it is received
// data.userid != userid &&
if (data.userid != userid) snap.ref().remove();
});
// method to signal the data
this.signal = function(data) {
data.userid = userid;
socket.push(data);
};
} else {
// custom signalling implementations
// e.g. WebSocket, Socket.io, SignalR, WebSycn, XMLHttpRequest, Long-Polling etc.
var socket = root.openSignalingChannel(function(message) {
message = JSON.parse(message);
if (message.userid != userid) {
if (message.leaving && root.onuserleft) root.onuserleft(message.userid);
else signaler.onmessage(message);
}
});
// method to signal the data
this.signal = function(data) {
data.userid = userid;
socket.send(JSON.stringify(data));
};
}
// unique identifier for the current user
var userid = root.userid || getToken();
// self instance
var signaler = this;
// object to store all connected peers
var peers = { };
// object to store ICE candidates for answerer
var candidates = { };
// it is called when your signalling implementation fires "onmessage"
this.onmessage = function(message) {
// if new room detected
if (message.roomid && message.broadcasting && !signaler.sentParticipationRequest)
root.onmeeting(message);
else
// for pretty logging
console.debug(JSON.stringify(message, function(key, value) {
if (value.sdp) {
console.log(value.sdp.type, '————', value.sdp.sdp);
return '';
} else return value;
}, '————'));
// if someone shared SDP
if (message.sdp && message.to == userid)
this.onsdp(message);
// if someone shared ICE
if (message.candidate && message.to == userid)
this.onice(message);
// if someone sent participation request
if (message.participationRequest && message.to == userid) {
var _options = options;
_options.to = message.userid;
_options.stream = root.stream;
peers[message.userid] = Offer.createOffer(_options);
}
};
// if someone shared SDP
this.onsdp = function(message) {
var sdp = message.sdp;
if (sdp.type == 'offer') {
var _options = options;
_options.stream = root.stream;
_options.sdp = sdp;
_options.to = message.userid;
peers[message.userid] = Answer.createAnswer(_options);
}
if (sdp.type == 'answer') {
peers[message.userid].setRemoteDescription(sdp);
}
};
// if someone shared ICE
this.onice = function(message) {
var peer = peers[message.userid];
if (!peer) {
var candidate = candidates[message.userid];
if (candidate) candidates[message.userid][candidate.length] = message.candidate;
else candidates[message.userid] = [message.candidate];
} else {
peer.addIceCandidate(message.candidate);
var _candidates = candidates[message.userid] || [];
if (_candidates.length) {
for (var i = 0; i < _candidates.length; i++) {
peer.addIceCandidate(_candidates[i]);
}
candidates[message.userid] = [];
}
}
};
// it is passed over Offer/Answer objects for reusability
var options = {
onsdp: function(sdp, to) {
signaler.signal({
sdp: sdp,
to: to
});
},
onicecandidate: function(candidate, to) {
signaler.signal({
candidate: candidate,
to: to
});
},
onaddstream: function(stream, _userid) {
console.debug('onaddstream', '>>>>>>', stream);
var audio = document.createElement('audio');
audio.id = _userid;
audio[isFirefox ? 'mozSrcObject' : 'src'] = isFirefox ? stream : window.URL.createObjectURL(stream);
audio.autoplay = true;
audio.controls = true;
audio.addEventListener('play', function() {
setTimeout(function() {
audio.muted = false;
audio.volume = 1;
afterRemoteStreamStartedFlowing();
}, 3000);
}, false);
audio.play();
function afterRemoteStreamStartedFlowing() {
if (!root.onaddstream) return;
root.onaddstream({
audio: audio,
stream: stream,
userid: _userid,
type: 'remote'
});
}
}
};
// call only for session initiator
this.broadcast = function(_config) {
signaler.roomid = _config.roomid || getToken();
signaler.isbroadcaster = true;
(function transmit() {
signaler.signal({
roomid: signaler.roomid,
broadcasting: true
});
!root.transmitOnce && setTimeout(transmit, 3000);
})();
// if broadcaster leaves; clear all JSON files from Firebase servers
if (socket.onDisconnect) socket.onDisconnect().remove();
};
// called for each new participant
this.join = function(_config) {
signaler.roomid = _config.roomid;
this.signal({
participationRequest: true,
to: _config.to
});
signaler.sentParticipationRequest = true;
};
unloadHandler(userid, signaler);
}
// IceServersHandler.js
var IceServersHandler = (function() {
function getIceServers(connection) {
// resiprocate: 3344+4433
// pions: 7575
var iceServers = [{
'urls': [
'stun:stun.l.google.com:19302',
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
'stun:stun.l.google.com:19302?transport=udp',
]
}];
return iceServers;
}
return {
getIceServers: getIceServers
};
})();
// reusable stuff
var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription;
var RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate;
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
window.URL = window.URL || window.webkitURL;
var isFirefox = !!navigator.mozGetUserMedia;
var isChrome = !!navigator.webkitGetUserMedia;
var iceServers = {
iceServers: IceServersHandler.getIceServers()
};
var optionalArgument = {
optional: [{
DtlsSrtpKeyAgreement: true
}]
};
var offerAnswerConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
}
};
function getToken() {
return (Math.random() * new Date().getTime()).toString(36).replace( /\./g , '');
}
function onSdpSuccess() {}
function onSdpError(e) {
console.error('sdp error:', e.name, e.message);
}
// var offer = Offer.createOffer(config);
// offer.setRemoteDescription(sdp);
// offer.addIceCandidate(candidate);
var Offer = {
createOffer: function(config) {
var peer = new RTCPeerConnection(iceServers, optionalArgument);
if (config.stream) peer.addStream(config.stream);
if (config.onaddstream)
peer.onaddstream = function(event) {
config.onaddstream(event.stream, config.to);
};
if (config.onicecandidate)
peer.onicecandidate = function(event) {
if (event.candidate) config.onicecandidate(event.candidate, config.to);
};
peer.createOffer(function(sdp) {
peer.setLocalDescription(sdp);
if (config.onsdp) config.onsdp(sdp, config.to);
}, onSdpError, offerAnswerConstraints);
this.peer = peer;
return this;
},
setRemoteDescription: function(sdp) {
this.peer.setRemoteDescription(new RTCSessionDescription(sdp), onSdpSuccess, onSdpError);
},
addIceCandidate: function(candidate) {
this.peer.addIceCandidate(new RTCIceCandidate({
sdpMLineIndex: candidate.sdpMLineIndex,
candidate: candidate.candidate
}));
}
};
// var answer = Answer.createAnswer(config);
// answer.setRemoteDescription(sdp);
//answer.addIceCandidate(candidate);
var Answer = {
createAnswer: function(config) {
var peer = new RTCPeerConnection(iceServers, optionalArgument);
if (config.stream) peer.addStream(config.stream);
if (config.onaddstream)
peer.onaddstream = function(event) {
config.onaddstream(event.stream, config.to);
};
if (config.onicecandidate)
peer.onicecandidate = function(event) {
if (event.candidate) config.onicecandidate(event.candidate, config.to);
};
peer.setRemoteDescription(new RTCSessionDescription(config.sdp), onSdpSuccess, onSdpError);
peer.createAnswer(function(sdp) {
peer.setLocalDescription(sdp);
if (config.onsdp) config.onsdp(sdp, config.to);
}, onSdpError, offerAnswerConstraints);
this.peer = peer;
return this;
},
addIceCandidate: function(candidate) {
this.peer.addIceCandidate(new RTCIceCandidate({
sdpMLineIndex: candidate.sdpMLineIndex,
candidate: candidate.candidate
}));
}
};
function unloadHandler(userid, signaler) {
window.onbeforeunload = function() {
leaveRoom();
// return 'You\'re leaving the session.';
};
window.onkeyup = function(e) {
if (e.keyCode == 116)
leaveRoom();
};
var anchors = document.querySelectorAll('a'),
length = anchors.length;
for (var i = 0; i < length; i++) {
var a = anchors[i];
if (a.href.indexOf('#') !== 0 && a.getAttribute('target') != '_blank')
a.onclick = function() {
leaveRoom();
};
}
function leaveRoom() {
signaler.signal({
leaving: true
});
}
}
})();