-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwraprtc.js
379 lines (352 loc) · 14.5 KB
/
wraprtc.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
/* JR 5/2013 - parts of code borrowed heavily from other projects - see README */
(function(window) {
var supported = null
, version = null
, getUserMedia = null
, _stopUserMedia = null /* BR: our non-standard addition */
, attachMediaStream = null
, sdpConstraints = {'mandatory': {
'OfferToReceiveAudio':true,
'OfferToReceiveVideo':true }}
;
/* --- */
function init() {
if (navigator.mozGetUserMedia) {
supported = "firefox";
RTCPeerConnection = function(){return mozRTCPeerConnection(/* note no arguments */);}
RTCSessionDescription = mozRTCSessionDescription;
RTCIceCandidate = mozRTCIceCandidate;
getUserMedia = navigator.mozGetUserMedia.bind(navigator);
_stopUserMedia = function(element, stream) {
element.pause();
element.mozSrcObject = null;
};
attachMediaStream = function(element, stream) {
element.mozSrcObject = stream;
element.play();
};
/* reattachMediaStream = function(to, from) {
// console.log("Reattaching media stream");
to.mozSrcObject = from.mozSrcObject;
to.play();
}; */
MediaStream.prototype.getVideoTracks = function() { return []; }
MediaStream.prototype.getAudioTracks = function() { return []; }
}
else if (navigator.webkitGetUserMedia) {
supported = "chrome";
version = parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]);
getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
_stopUserMedia = function(element, stream) {
element.pause();
element.src = "";
if (typeof(stream.stop)!=='undefined')
stream.stop(); /* this works for chrome Mac/25.0.1364.160 */
};
RTCPeerConnection = webkitRTCPeerConnection;
attachMediaStream = function(element, stream) {
element.src = webkitURL.createObjectURL(stream);
};
/* reattachMediaStream = function(to, from) {
to.src = from.src;
}; */
// The representation of tracks in a stream is changed in M26.
// Unify them for earlier Chrome versions in the coexisting period.
if (!webkitMediaStream.prototype.getVideoTracks) {
webkitMediaStream.prototype.getVideoTracks = function() {
return this.videoTracks;
};
webkitMediaStream.prototype.getAudioTracks = function() {
return this.audioTracks;
};
}
/* these methods are currently unused -- therefore commented out
// New syntax of getXXXStreams method in M26.
if (!webkitRTCPeerConnection.prototype.getLocalStreams) {
webkitRTCPeerConnection.prototype.getLocalStreams = function() {
return this.localStreams;
};
webkitRTCPeerConnection.prototype.getRemoteStreams = function() {
return this.remoteStreams;
};
}
*/
/* -- not looking into opera further for the present, seems to be a lack of documentation and/or features
else if (navigator.getUserMedia) {
supported = "opera??";
getUserMedia = navigator.getUserMedia.bind(navigator);
/*Opera 12: http://stackoverflow.com/questions/11642926/stop-close-webcam-which-is-opened-by-navigator-getusermedia
element.pause();
element.src = null; *./
*/
}
}
function fireOnce(en, pc, opts) {
var fn = opts[en];
if (typeof(fn)==='undefined') return false;
var fl = "_br_"+en;
if (pc[fl]) return false;
fn.call(opts);
pc[fl] = true;
}
function createPeerConnection(opts) {
/* https://groups.google.com/forum/#!topic/discuss-webrtc/b-5alYpbxXw
http://code.google.com/p/natvpn/source/browse/trunk/stun_server_list */
var pc_config = {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]};
var pc_constraints = {"optional": [{"DtlsSrtpKeyAgreement": true}]};
var pc = null;
/*
RTCPeerConection() for mozilla actually currently ignores arguments
if (supported === "firefox") {
pc_config = {"iceServers":[{"url":"stun:173.194.79.127"/* IP of stun.l.google.com, orig=stun:23.21.150.121*./}]};
};
*/
try {
pc = new RTCPeerConnection(pc_config, pc_constraints);
// opts.setPC && opts.setPC(pc); -- depreciate
/*
-- this just for testing / dev ...
var fne = function(event,marker){console.log(marker,event); return true;}
pc.onsignalingstatechange = function(e){fne(e,7);}
pc.onstatechange = function(e){fne(e,8);}
pc.onopen = function(e){fne(e,9);}
pc.ondatachannel = fne;
pc.onidentityresult = fne;
pc.onnegotiationneeded = fne;
*/
pc.oniceconnectionstatechange = function(event){
/* apparently not fired in google chrome - 25.0.1364.160 */
/* fires with XP / Chrome = 27.0.1453.116 m */
/* fires with XP / Nightly (mozilla) 24.0a1 */
if (pc.iceConnectionState==='connected') fireOnce('connected', pc, opts);
if (pc.iceConnectionState==='disconnected') fireOnce('disconnected', pc, opts);
}
pc.onicecandidate = function(event) {
if (!event.candidate) {
opts.signalOut && opts.signalOut(undefined);
if (/* yuck */ supported==='chrome' && version<27)
fireOnce('connected', pc, opts);
return;
}
opts.signalOut && opts.signalOut({type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate});
}
} catch (e) {
opts.onSupportFailure && opts.onSupportFailure(e.message);
return;
}
if (opts.element) {
pc.onaddstream = /*onRemoteStreamAdded*/ function(event) {
attachMediaStream(opts.element, event.stream);
opts.setStream && opts.setStream(event.stream);
};
}
pc.onremovestream = function(event) { /*fne(event,222); console.log("onRemoteStreamRemoved;"); example also doesn't do anything here ... */
};
return pc;
}
function setStatus(state) {
// __elem__.innerHTML = state; -- reference
}
function mergeConstraints(cons1, cons2) {
var merged = cons1;
for (var name in cons2.mandatory) {
merged.mandatory[name] = cons2.mandatory[name];
}
merged.optional.concat(cons2.optional);
return merged;
}
function setLocalAndSendMessage(how, pc, sessionDescription) {
// Set Opus as the preferred codec in SDP if Opus is present.
sessionDescription.sdp = preferOpus(sessionDescription.sdp);
pc.setLocalDescription(sessionDescription);
how.signalOut && how.signalOut(sessionDescription);
}
/* --- */
function openWebcam(opts) {
try {
getUserMedia(
{"audio": true, "video": {"mandatory": {}, "optional": []}},
function(stream) /* success */ {
opts.element && attachMediaStream(opts.element, stream);
opts.setStream && opts.setStream(stream);
},
function(error) /* failure */ {
/* called with error.code==1 if user denies permission (on chrome ) */
opts.onError && opts.onError(error.code);
});
}
catch (e) {
opts.onSupportFailure && opts.onSupportFailure(e.message);
}
}
/* --- */
function callPeer(stream, opts) {
var pc = createPeerConnection(opts);
if (stream)
pc.addStream(stream);
var constraints = {"optional": [], "mandatory": {"MozDontOfferDataChannel": true}};
// temporary measure to remove Moz* constraints in Chrome
if (supported !== "firefox") {
for (prop in constraints.mandatory) {
if (prop.indexOf("Moz") != -1) {
delete constraints.mandatory[prop];
}
}
}
constraints = mergeConstraints(constraints, sdpConstraints);
pc.createOffer(function(sdp){setLocalAndSendMessage(opts, pc, sdp);}, opts.onError, constraints);
opts.setPC && opts.setPC(pc);
}
function answer(msg, stream, opts) {
var pc = createPeerConnection(opts);
if (stream)
pc.addStream(stream);
var rtcsd = new RTCSessionDescription(msg);
pc.setRemoteDescription(rtcsd);
pc.createAnswer(function(sdp){setLocalAndSendMessage(opts, pc, sdp);}, opts.onError, sdpConstraints);
opts.setPC && opts.setPC(pc);
}
function setRemoteDescription(pc, msg) {
pc.setRemoteDescription(new RTCSessionDescription(msg));
}
function candidate(pc, msg) {
var candy = new RTCIceCandidate({sdpMLineIndex:msg.label, candidate: msg.candidate});
pc.addIceCandidate(candy);
}
function stop(element, stream) { _stopUserMedia(element, stream); }
function stopConnection(pc) {
try {
pc.close(); /* this is throwing DOM exception 11 on chrome */
}
catch(e) {
console.log && console.log('Exception in RTCPeerConnection.close()', pc, e);
}
pc = null;
}
function mediaChannelAction(stream, action) {
var tracks, endis;
switch(action) {
case 'mute': tracks=stream.getAudioTracks(); endis = false; break;
case 'unmute': tracks=stream.getAudioTracks(); endis = true; break;
case 'video_off': tracks=stream.getVideoTracks(); endis = false; break;
case 'video_on': tracks=stream.getVideoTracks(); endis = true; break;
default:
return false;
}
for(var i=0; i<tracks.length; i++) {
tracks[i].enabled = endis;
}
return true;
}
/* === SDP manipulation utils === */
// Set Opus as the default audio codec if it's present.
function preferOpus(sdp) {
var sdpLines = sdp.split('\r\n');
// Search for m line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('m=audio') !== -1) {
var mLineIndex = i;
break;
}
}
if (mLineIndex === null)
return sdp;
// If Opus is available, set it as the default in m line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('opus/48000') !== -1) {
var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
if (opusPayload)
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
break;
}
}
// Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
return sdp;
}
// Set Opus in stereo if stereo is enabled.
function addStereoToSDP(msg) {
if (!msg.sdp)
return;
var sdpLines = msg.sdp.split('\r\n');
var fmtpLineIndex = null;
// Find opus payload.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('opus/48000') !== -1) {
var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
break;
}
}
// Find the payload in fmtp line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('a=fmtp') !== -1) {
var payload = extractSdp(sdpLines[i], /a=fmtp:(\d+)/ );
if (payload === opusPayload) {
fmtpLineIndex = i;
break;
}
}
}
// No fmtp line found.
if (fmtpLineIndex === null)
return ;
// Append stereo=1 to fmtp line.
sdpLines[fmtpLineIndex] = sdpLines[fmtpLineIndex].concat(' stereo=1');
msg.sdp = sdpLines.join('\r\n');
}
function extractSdp(sdpLine, pattern) {
var result = sdpLine.match(pattern);
return (result && result.length == 2)? result[1]: null;
}
// Set the selected codec to the first in m line.
function setDefaultCodec(mLine, payload) {
var elements = mLine.split(' ');
var newLine = new Array();
var index = 0;
for (var i = 0; i < elements.length; i++) {
if (index === 3) // Format of media starts from the fourth.
newLine[index++] = payload; // Put target payload to the first.
if (elements[i] !== payload)
newLine[index++] = elements[i];
}
return newLine.join(' ');
}
// Strip CN from sdp before CN constraints is ready.
function removeCN(sdpLines, mLineIndex) {
var mLineElements = sdpLines[mLineIndex].split(' ');
// Scan from end for the convenience of removing an item.
for (var i = sdpLines.length-1; i >= 0; i--) {
var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
if (payload) {
var cnPos = mLineElements.indexOf(payload);
if (cnPos !== -1) {
// Remove CN payload from m line.
mLineElements.splice(cnPos, 1);
}
// Remove CN line in sdp
sdpLines.splice(i, 1);
}
}
sdpLines[mLineIndex] = mLineElements.join(' ');
return sdpLines;
}
/* === */
/* --- */
init();
window.wrapRTC = {
supported: supported,
openWebcam: openWebcam,
stop: stop,
stopConnection: stopConnection,
callPeer: callPeer,
answer: answer,
setRemoteDescription: setRemoteDescription,
candidate: candidate,
mediaChannelAction: mediaChannelAction,
addStereoToSDP: addStereoToSDP
}
})(window);