forked from MrSwitch/peer.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tb.js
376 lines (281 loc) · 7.54 KB
/
tb.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
//
//
// TB.Lite
// @Author Andrew Dodson (@mr_swtich)
//
(function(){
// Does this browser support WebRTC?
navigator.getUserMedia || (navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
// URL?
window.URL || (window.URL = window.webkitURL);
// This is the massive Nut that holds it together
// But because its so ugly we are hiding it out of our code.
// This creates instances of a new PeerConnection
function PeerConnection(callback){
var peerConn;
try {
peerConn = new webkitDeprecatedPeerConnection("STUN stun.l.google.com:19302", callback);
} catch (e) {
try {
peerConn = new webkitPeerConnection("STUN stun.l.google.com:19302", callback);
} catch (e) {
console.log("Failed to create PeerConnection, exception: " + e.message);
}
}
return peerConn;
}
// EVENTS
// Extend the function we do have.
var Events = function(){
this._listeners = {};
// Return
this.on = function(name, callback){
if(typeof(name)==='object'){
for(var x in name){
this.on(x, name[x]);
}
return this;
}
console.log('ATTACHED: ' + name);
if(callback){
// Set the listeners if its undefined
this._listeners[name] || (this._listeners[name] = []);
// Append the new callback to the listeners
this._listeners[name].push(callback);
}
return this;
};
// Trigger Events defined on the publisher widget
this.trigger = function(name,evt){
console.log('Triggered: ' + name);
if(this._listeners[name]){
this._listeners[name].forEach(function(o,i){
o(evt);
});
}
return this;
};
};
TB = {};
TB.peerConn = {};
TB.rcvConn = {};
TB.initPublisher = function( rplElm ){
if(!(this instanceof TB.initPublisher)){
return new TB.initPublisher(rplElm);
}
Events.apply(this, arguments);
var self = this;
// Search for the element to replace
if(typeof rplElm === 'string'){
var el = document.getElementById(rplElm);
if(!el){
el = document.querySelector(rplElm);
}
rplElm = el;
}
// Is the item in a video element?
if(rplElm.tagName.toLowerCase() !== 'video'){
this.el = document.createElement('video');
rplElm.appendChild(this.el);
}
else{
this.el = rplElm;
}
// Set AutoPlay
this.el.autoplay = true;
// Create a success callback
// Fired when the users camera is attached
var _success = function(stream){
// Attach the stream to the UI
self.el.src = URL ? URL.createObjectURL(stream) : stream;
// Save stream to element
self.stream = stream;
// Add an error event
self.el.onerror = function(event) {
stream.stop();
self.trigger('failure', event);
};
// Trigger any success listeners.
self.el.onload = function(){
self.trigger('success', event);
};
// Vid onload doesn't seem to fire
self.trigger('started', stream);
};
// Trigger a failure
var _failure = function(event){
self.trigger('failure', event);
};
// Call it?
try{
navigator.getUserMedia({audio:true,video:true}, _success, _failure);
}
catch(e){
try{
navigator.getUserMedia('audio,video', _success, _failure);
}
catch(e){
_failure();
}
}
return this;
};
// initSession
// Create a New Peer Session
TB.initSession = function(sessionId, apiKey, token){
// Lets force a new instance
if(!(this instanceof TB.initSession)){
return new TB.initSession(sessionId, apiKey, token);
}
// Apply on,trigger
Events.apply(this, arguments);
var socket,
localStream;
// We dont need to make these publicly avaliable
// but what the heck, maybe its useful
this.streams = {
in : {},
out : {}
};
var self = this;
// Add listeners for new messages
this.connect = function(video){
// Given a video tag
// Broadcast to all parties the new stream
socket = io.connect('ws://'+window.location.host );
// Define an onload handler
socket.on('message', function(data){
console.info("WebSocket Message " + data);
data = JSON.parse(data);
self.trigger(data.type,data);
});
};
// Publish a new LocalMedia object
this.publish = function(camera){
// Given a video tag
// Lets pass in the SDP over
var action = function(){
localStream = camera.stream;
// Socket
self.send({
type : 'streamAvailable'
});
};
// LocalStream
if(camera.stream){
action();
}
else{
camera.on('started', action);
}
};
// Send message
this.send = function(o){
socket.send(JSON.stringify(o));
};
// Bind events
// When your client first connects you recieve a sessionConnected Event
this.on('sessionConnected', function(){
});
// When someone disconnects you get this fired
this.on('connectionDestroyed', function(){
});
//
// 1. connectionCreated
//
// When someone else connects you need to send them a streamCreated event
this.on('connectionCreated', function(data){
// If we have a localStream defined lets tell the end user that a stream is available
if(localStream){
self.send({
type : 'streamAvailable',
to : data.from
});
}
});
//
// 2. streamAvailable
//
// When another client starts publishing they send a streamAvailable event.
// This client then responds requesting an OFFER
this.on('streamAvailable', function(data){
// Received a connectionCreated event
// Get their stream?
self.send({
type : 'requestOffer',
to : data.from
});
});
//
// 3. requestOffer
//
// A client has sent a directMessage to connect to this client
// We obtain an OFFER from the STUN server
// And post it back to the other client
this.on('requestOffer', function(data){
if(!localStream){
console.error('Something went wrong you dont have a local Media');
}
var pc = PeerConnection(function(message){
// IF THIS IS CALLED IN STEP 3: Reponse to an ANSWER
// THEN IT WONT CONTAIN AN OFFER
if(message.indexOf('OFFER')===-1){
// Occasionally if something went very wrong and we crossed streams.
// Then the STUN server returns a NOMATCH
if(message.indexOf('NOMATCH')>-1){
console.error('NO MATCH ERROR');
console.error(message);
}
return;
}
// DISPATCH OFFER
self.send({
type : 'processOffer',
to : data.from,
payload : message
});
});
pc.addStream(localStream);
self.streams.out[data.from] = pc;
});
//
// 4. processAnswer
//
// Once we sent back an answer we should
this.on('processOffer', function(data){
var pc = PeerConnection(function(message){
self.send({
type : 'processAnswer',
to : data.from,
payload : message
});
});
// PeerConn
pc.addEventListener("addstream", function(event){
self.trigger('streamCreated', event);
}, false);
pc.addEventListener("removestream", function(event){
self.trigger('streamDestroyed', event);
}, false);
pc.addEventListener("message", function(event){
self.trigger('message', event);
}, false);
pc.processSignalingMessage(data.payload);
// Assign it to be collected by other things
self.streams.in[data.from] = pc;
});
//
// 5. processAnswer
//
// Once we sent back an answer we should
this.on('processAnswer', function(data){
console.debug("Signal");
self.streams.out[data.from].addStream(localStream);
self.streams.out[data.from].addEventListener("message", function(event){
self.trigger('message', event);
}, false);
self.streams.out[data.from].processSignalingMessage(data.payload);
});
return this;
};
})();