webrtc.io.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. //CLIENT
  2. // Fallbacks for vendor-specific variables until the spec is finalized.
  3. var PeerConnection = (window.PeerConnection || window.webkitPeerConnection00 || window.webkitRTCPeerConnection || window.mozRTCPeerConnection);
  4. var URL = (window.URL || window.webkitURL || window.msURL || window.oURL);
  5. var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
  6. var nativeRTCIceCandidate = (window.mozRTCIceCandidate || window.RTCIceCandidate);
  7. var nativeRTCSessionDescription = (window.mozRTCSessionDescription || window.RTCSessionDescription); // order is very important: "RTCSessionDescription" defined in Nighly but useless
  8. var sdpConstraints = {
  9. 'mandatory': {
  10. 'OfferToReceiveAudio': true,
  11. 'OfferToReceiveVideo': true
  12. }
  13. };
  14. if (navigator.webkitGetUserMedia) {
  15. if (!webkitMediaStream.prototype.getVideoTracks) {
  16. webkitMediaStream.prototype.getVideoTracks = function() {
  17. return this.videoTracks;
  18. };
  19. webkitMediaStream.prototype.getAudioTracks = function() {
  20. return this.audioTracks;
  21. };
  22. }
  23. // New syntax of getXXXStreams method in M26.
  24. if (!webkitRTCPeerConnection.prototype.getLocalStreams) {
  25. webkitRTCPeerConnection.prototype.getLocalStreams = function() {
  26. return this.localStreams;
  27. };
  28. webkitRTCPeerConnection.prototype.getRemoteStreams = function() {
  29. return this.remoteStreams;
  30. };
  31. }
  32. }
  33. (function() {
  34. var rtc;
  35. if ('undefined' === typeof module) {
  36. rtc = this.rtc = {};
  37. } else {
  38. rtc = module.exports = {};
  39. }
  40. // Holds a connection to the server.
  41. rtc._socket = null;
  42. // Holds identity for the client
  43. rtc._me = null;
  44. // Holds callbacks for certain events.
  45. rtc._events = {};
  46. rtc.on = function(eventName, callback) {
  47. rtc._events[eventName] = rtc._events[eventName] || [];
  48. rtc._events[eventName].push(callback);
  49. };
  50. rtc.fire = function(eventName, _) {
  51. var events = rtc._events[eventName];
  52. var args = Array.prototype.slice.call(arguments, 1);
  53. if (!events) {
  54. return;
  55. }
  56. for (var i = 0, len = events.length; i < len; i++) {
  57. events[i].apply(null, args);
  58. }
  59. };
  60. // Holds the STUN/ICE server to use for PeerConnections.
  61. rtc.SERVER = function() {
  62. if (navigator.mozGetUserMedia) {
  63. return {
  64. "iceServers": [{
  65. "url": "stun:23.21.150.121"
  66. }]
  67. };
  68. }
  69. return {
  70. "iceServers": [{
  71. "url": "stun:stun.l.google.com:19302"
  72. }]
  73. };
  74. };
  75. // Reference to the lone PeerConnection instance.
  76. rtc.peerConnections = {};
  77. // Array of known peer socket ids
  78. rtc.connections = [];
  79. // Stream-related variables.
  80. rtc.streams = [];
  81. rtc.numStreams = 0;
  82. rtc.initializedStreams = 0;
  83. // Reference to the data channels
  84. rtc.dataChannels = {};
  85. // PeerConnection datachannel configuration
  86. rtc.dataChannelConfig = {
  87. "optional": [{
  88. "RtpDataChannels": true
  89. }, {
  90. "DtlsSrtpKeyAgreement": true
  91. }]
  92. };
  93. rtc.pc_constraints = {
  94. "optional": [{
  95. "DtlsSrtpKeyAgreement": true
  96. }]
  97. };
  98. // check whether data channel is supported.
  99. rtc.checkDataChannelSupport = function() {
  100. try {
  101. // raises exception if createDataChannel is not supported
  102. var pc = new PeerConnection(rtc.SERVER(), rtc.dataChannelConfig);
  103. var channel = pc.createDataChannel('supportCheck', {
  104. reliable: false
  105. });
  106. channel.close();
  107. return true;
  108. } catch (e) {
  109. return false;
  110. }
  111. };
  112. rtc.dataChannelSupport = rtc.checkDataChannelSupport();
  113. /**
  114. * Connects to the websocket server.
  115. */
  116. rtc.connect = function(server, room) {
  117. room = room || ""; // by default, join a room called the blank string
  118. rtc._socket = new WebSocket(server);
  119. rtc._socket.onopen = function() {
  120. rtc._socket.send(JSON.stringify({
  121. "eventName": "join_room",
  122. "data": {
  123. "room": room
  124. }
  125. }));
  126. rtc._socket.onmessage = function(msg) {
  127. var json = JSON.parse(msg.data);
  128. rtc.fire(json.eventName, json.data);
  129. };
  130. rtc._socket.onerror = function(err) {
  131. console.error('onerror');
  132. console.error(err);
  133. };
  134. rtc._socket.onclose = function(data) {
  135. rtc.fire('disconnect stream', rtc._socket.id);
  136. delete rtc.peerConnections[rtc._socket.id];
  137. };
  138. rtc.on('get_peers', function(data) {
  139. rtc.connections = data.connections;
  140. rtc._me = data.you;
  141. // fire connections event and pass peers
  142. rtc.fire('connections', rtc.connections);
  143. });
  144. rtc.on('receive_ice_candidate', function(data) {
  145. var candidate = new nativeRTCIceCandidate(data);
  146. rtc.peerConnections[data.socketId].addIceCandidate(candidate);
  147. rtc.fire('receive ice candidate', candidate);
  148. });
  149. rtc.on('new_peer_connected', function(data) {
  150. rtc.connections.push(data.socketId);
  151. var pc = rtc.createPeerConnection(data.socketId);
  152. for (var i = 0; i < rtc.streams.length; i++) {
  153. var stream = rtc.streams[i];
  154. pc.addStream(stream);
  155. }
  156. });
  157. rtc.on('remove_peer_connected', function(data) {
  158. rtc.fire('disconnect stream', data.socketId);
  159. delete rtc.peerConnections[data.socketId];
  160. });
  161. rtc.on('receive_offer', function(data) {
  162. rtc.receiveOffer(data.socketId, data.sdp);
  163. rtc.fire('receive offer', data);
  164. });
  165. rtc.on('receive_answer', function(data) {
  166. rtc.receiveAnswer(data.socketId, data.sdp);
  167. rtc.fire('receive answer', data);
  168. });
  169. rtc.fire('connect');
  170. };
  171. };
  172. rtc.sendOffers = function() {
  173. for (var i = 0, len = rtc.connections.length; i < len; i++) {
  174. var socketId = rtc.connections[i];
  175. rtc.sendOffer(socketId);
  176. }
  177. };
  178. rtc.onClose = function(data) {
  179. rtc.on('close_stream', function() {
  180. rtc.fire('close_stream', data);
  181. });
  182. };
  183. rtc.createPeerConnections = function() {
  184. for (var i = 0; i < rtc.connections.length; i++) {
  185. rtc.createPeerConnection(rtc.connections[i]);
  186. }
  187. };
  188. rtc.createPeerConnection = function(id) {
  189. var config = rtc.pc_constraints;
  190. if (rtc.dataChannelSupport) config = rtc.dataChannelConfig;
  191. var pc = rtc.peerConnections[id] = new PeerConnection(rtc.SERVER(), config);
  192. pc.onicecandidate = function(event) {
  193. if (event.candidate) {
  194. rtc._socket.send(JSON.stringify({
  195. "eventName": "send_ice_candidate",
  196. "data": {
  197. "label": event.candidate.sdpMLineIndex,
  198. "candidate": event.candidate.candidate,
  199. "socketId": id
  200. }
  201. }));
  202. }
  203. rtc.fire('ice candidate', event.candidate);
  204. };
  205. pc.onopen = function() {
  206. // TODO: Finalize this API
  207. rtc.fire('peer connection opened');
  208. };
  209. pc.onaddstream = function(event) {
  210. // TODO: Finalize this API
  211. rtc.fire('add remote stream', event.stream, id);
  212. };
  213. if (rtc.dataChannelSupport) {
  214. pc.ondatachannel = function(evt) {
  215. console.log('data channel connecting ' + id);
  216. rtc.addDataChannel(id, evt.channel);
  217. };
  218. }
  219. return pc;
  220. };
  221. rtc.sendOffer = function(socketId) {
  222. var pc = rtc.peerConnections[socketId];
  223. var constraints = {
  224. "optional": [],
  225. "mandatory": {
  226. "MozDontOfferDataChannel": true
  227. }
  228. };
  229. // temporary measure to remove Moz* constraints in Chrome
  230. if (navigator.webkitGetUserMedia) {
  231. for (var prop in constraints.mandatory) {
  232. if (prop.indexOf("Moz") != -1) {
  233. delete constraints.mandatory[prop];
  234. }
  235. }
  236. }
  237. constraints = mergeConstraints(constraints, sdpConstraints);
  238. pc.createOffer(function(session_description) {
  239. session_description.sdp = preferOpus(session_description.sdp);
  240. pc.setLocalDescription(session_description);
  241. rtc._socket.send(JSON.stringify({
  242. "eventName": "send_offer",
  243. "data": {
  244. "socketId": socketId,
  245. "sdp": session_description
  246. }
  247. }));
  248. }, null, sdpConstraints);
  249. };
  250. rtc.receiveOffer = function(socketId, sdp) {
  251. var pc = rtc.peerConnections[socketId];
  252. rtc.sendAnswer(socketId, sdp);
  253. };
  254. rtc.sendAnswer = function(socketId, sdp) {
  255. var pc = rtc.peerConnections[socketId];
  256. pc.setRemoteDescription(new nativeRTCSessionDescription(sdp));
  257. pc.createAnswer(function(session_description) {
  258. pc.setLocalDescription(session_description);
  259. rtc._socket.send(JSON.stringify({
  260. "eventName": "send_answer",
  261. "data": {
  262. "socketId": socketId,
  263. "sdp": session_description
  264. }
  265. }));
  266. //TODO Unused variable!?
  267. var offer = pc.remoteDescription;
  268. }, null, sdpConstraints);
  269. };
  270. rtc.receiveAnswer = function(socketId, sdp) {
  271. var pc = rtc.peerConnections[socketId];
  272. pc.setRemoteDescription(new nativeRTCSessionDescription(sdp));
  273. };
  274. rtc.createStream = function(opt, onSuccess, onFail) {
  275. var options;
  276. onSuccess = onSuccess || function() {};
  277. onFail = onFail || function() {};
  278. options = {
  279. video: !! opt.video,
  280. audio: !! opt.audio
  281. };
  282. if (getUserMedia) {
  283. rtc.numStreams++;
  284. getUserMedia.call(navigator, options, function(stream) {
  285. rtc.streams.push(stream);
  286. rtc.initializedStreams++;
  287. onSuccess(stream);
  288. if (rtc.initializedStreams === rtc.numStreams) {
  289. rtc.fire('ready');
  290. }
  291. }, function() {
  292. alert("Could not connect stream.");
  293. onFail();
  294. });
  295. } else {
  296. alert('Your Browser does not support WebRTC (Video Chat). Try Firefox, Chrome, or Opera');
  297. }
  298. };
  299. rtc.addStreams = function() {
  300. for (var i = 0; i < rtc.streams.length; i++) {
  301. var stream = rtc.streams[i];
  302. for (var connection in rtc.peerConnections) {
  303. rtc.peerConnections[connection].addStream(stream);
  304. }
  305. }
  306. };
  307. rtc.attachStream = function(stream, domId) {
  308. var element = document.getElementById(domId);
  309. if (navigator.mozGetUserMedia) {
  310. console.log("Attaching media stream");
  311. element.mozSrcObject = stream;
  312. element.play();
  313. } else {
  314. element.src = webkitURL.createObjectURL(stream);
  315. }
  316. };
  317. rtc.createDataChannel = function(pcOrId, label) {
  318. if (!rtc.dataChannelSupport) {
  319. //TODO this should be an exception
  320. alert('webRTC data channel is not yet supported in this browser,' +
  321. ' or you must turn on experimental flags');
  322. return;
  323. }
  324. var id, pc;
  325. if (typeof(pcOrId) === 'string') {
  326. id = pcOrId;
  327. pc = rtc.peerConnections[pcOrId];
  328. } else {
  329. pc = pcOrId;
  330. id = undefined;
  331. for (var key in rtc.peerConnections) {
  332. if (rtc.peerConnections[key] === pc) id = key;
  333. }
  334. }
  335. if (!id) throw new Error('attempt to createDataChannel with unknown id');
  336. if (!pc || !(pc instanceof PeerConnection)) throw new Error('attempt to createDataChannel without peerConnection');
  337. // need a label
  338. label = label || 'fileTransfer' || String(id);
  339. // chrome only supports reliable false atm.
  340. var options = {
  341. reliable: false
  342. };
  343. var channel;
  344. try {
  345. console.log('createDataChannel ' + id);
  346. channel = pc.createDataChannel(label, options);
  347. } catch (error) {
  348. console.log('seems that DataChannel is NOT actually supported!');
  349. throw error;
  350. }
  351. return rtc.addDataChannel(id, channel);
  352. };
  353. rtc.addDataChannel = function(id, channel) {
  354. channel.onopen = function() {
  355. console.log('data stream open ' + id);
  356. rtc.fire('data stream open', channel);
  357. };
  358. channel.onclose = function(event) {
  359. delete rtc.dataChannels[id];
  360. console.log('data stream close ' + id);
  361. rtc.fire('data stream close', channel);
  362. };
  363. channel.onmessage = function(message) {
  364. console.log('data stream message ' + id);
  365. console.log(message);
  366. rtc.fire('data stream data', channel, message.data);
  367. };
  368. channel.onerror = function(err) {
  369. console.log('data stream error ' + id + ': ' + err);
  370. rtc.fire('data stream error', channel, err);
  371. };
  372. // track dataChannel
  373. rtc.dataChannels[id] = channel;
  374. return channel;
  375. };
  376. rtc.addDataChannels = function() {
  377. if (!rtc.dataChannelSupport) return;
  378. for (var connection in rtc.peerConnections)
  379. rtc.createDataChannel(connection);
  380. };
  381. rtc.on('ready', function() {
  382. rtc.createPeerConnections();
  383. rtc.addStreams();
  384. rtc.addDataChannels();
  385. rtc.sendOffers();
  386. });
  387. }).call(this);
  388. function preferOpus(sdp) {
  389. var sdpLines = sdp.split('\r\n');
  390. var mLineIndex = null;
  391. // Search for m line.
  392. for (var i = 0; i < sdpLines.length; i++) {
  393. if (sdpLines[i].search('m=audio') !== -1) {
  394. mLineIndex = i;
  395. break;
  396. }
  397. }
  398. if (mLineIndex === null) return sdp;
  399. // If Opus is available, set it as the default in m line.
  400. for (var j = 0; j < sdpLines.length; j++) {
  401. if (sdpLines[j].search('opus/48000') !== -1) {
  402. var opusPayload = extractSdp(sdpLines[j], /:(\d+) opus\/48000/i);
  403. if (opusPayload) sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
  404. break;
  405. }
  406. }
  407. // Remove CN in m line and sdp.
  408. sdpLines = removeCN(sdpLines, mLineIndex);
  409. sdp = sdpLines.join('\r\n');
  410. return sdp;
  411. }
  412. function extractSdp(sdpLine, pattern) {
  413. var result = sdpLine.match(pattern);
  414. return (result && result.length == 2) ? result[1] : null;
  415. }
  416. function setDefaultCodec(mLine, payload) {
  417. var elements = mLine.split(' ');
  418. var newLine = [];
  419. var index = 0;
  420. for (var i = 0; i < elements.length; i++) {
  421. if (index === 3) // Format of media starts from the fourth.
  422. newLine[index++] = payload; // Put target payload to the first.
  423. if (elements[i] !== payload) newLine[index++] = elements[i];
  424. }
  425. return newLine.join(' ');
  426. }
  427. function removeCN(sdpLines, mLineIndex) {
  428. var mLineElements = sdpLines[mLineIndex].split(' ');
  429. // Scan from end for the convenience of removing an item.
  430. for (var i = sdpLines.length - 1; i >= 0; i--) {
  431. var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
  432. if (payload) {
  433. var cnPos = mLineElements.indexOf(payload);
  434. if (cnPos !== -1) {
  435. // Remove CN payload from m line.
  436. mLineElements.splice(cnPos, 1);
  437. }
  438. // Remove CN line in sdp
  439. sdpLines.splice(i, 1);
  440. }
  441. }
  442. sdpLines[mLineIndex] = mLineElements.join(' ');
  443. return sdpLines;
  444. }
  445. function mergeConstraints(cons1, cons2) {
  446. var merged = cons1;
  447. for (var name in cons2.mandatory) {
  448. merged.mandatory[name] = cons2.mandatory[name];
  449. }
  450. merged.optional.concat(cons2.optional);
  451. return merged;
  452. }