webrtc.io.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. //CLIENT
  2. // Fallbacks for vendor-specific variables until the spec is finalized.
  3. var PeerConnection = window.PeerConnection || window.webkitPeerConnection00 || window.webkitRTCPeerConnection;
  4. var URL = window.URL || window.webkitURL || window.msURL || window.oURL;
  5. var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  6. (function() {
  7. var rtc;
  8. if ('undefined' === typeof module) {
  9. rtc = this.rtc = {};
  10. } else {
  11. rtc = module.exports = {};
  12. }
  13. // Holds a connection to the server.
  14. rtc._socket = null;
  15. // Holds identity for the client
  16. rtc._me = null;
  17. // Holds callbacks for certain events.
  18. rtc._events = {};
  19. rtc.on = function(eventName, callback) {
  20. rtc._events[eventName] = rtc._events[eventName] || [];
  21. rtc._events[eventName].push(callback);
  22. };
  23. rtc.fire = function(eventName, _) {
  24. var events = rtc._events[eventName];
  25. var args = Array.prototype.slice.call(arguments, 1);
  26. if (!events) {
  27. return;
  28. }
  29. for (var i = 0, len = events.length; i < len; i++) {
  30. events[i].apply(null, args);
  31. }
  32. };
  33. // Holds the STUN/ICE server to use for PeerConnections.
  34. rtc.SERVER = {iceServers:[{url:"stun:stun.l.google.com:19302"}]};
  35. // Reference to the lone PeerConnection instance.
  36. rtc.peerConnections = {};
  37. // Array of known peer socket ids
  38. rtc.connections = [];
  39. // Stream-related variables.
  40. rtc.streams = [];
  41. rtc.numStreams = 0;
  42. rtc.initializedStreams = 0;
  43. // Reference to the data channels
  44. rtc.dataChannels = {};
  45. // PeerConnection datachannel configuration
  46. rtc.dataChannelConfig = {optional: [ {RtpDataChannels: true} ] };
  47. // check whether data channel is supported.
  48. rtc.checkDataChannelSupport = function() {
  49. try {
  50. // raises exception if createDataChannel is not supported
  51. var pc = new PeerConnection(rtc.SERVER, rtc.dataChannelConfig);
  52. channel = pc.createDataChannel('supportCheck', {reliable: false});
  53. channel.close();
  54. return true;
  55. } catch(e) {
  56. return false;
  57. }
  58. };
  59. rtc.dataChannelSupport = rtc.checkDataChannelSupport();
  60. /**
  61. * Connects to the websocket server.
  62. */
  63. rtc.connect = function(server, room) {
  64. room = room || ""; // by default, join a room called the blank string
  65. rtc._socket = new WebSocket(server);
  66. rtc._socket.onopen = function() {
  67. rtc._socket.send(JSON.stringify({
  68. "eventName": "join_room",
  69. "data":{
  70. "room": room
  71. }
  72. }));
  73. rtc._socket.onmessage = function(msg) {
  74. var json = JSON.parse(msg.data);
  75. rtc.fire(json.eventName, json.data);
  76. };
  77. rtc._socket.onerror = function(err) {
  78. console.error('onerror');
  79. console.error(err);
  80. };
  81. rtc._socket.onclose = function(data) {
  82. rtc.fire('disconnect stream', rtc._socket.id);
  83. delete rtc.peerConnections[rtc._socket.id];
  84. };
  85. rtc.on('get_peers', function(data) {
  86. rtc.connections = data.connections;
  87. rtc._me = data.you;
  88. // fire connections event and pass peers
  89. rtc.fire('connections', rtc.connections);
  90. });
  91. rtc.on('receive_ice_candidate', function(data) {
  92. var candidate = new RTCIceCandidate(data);
  93. rtc.peerConnections[data.socketId].addIceCandidate(candidate);
  94. rtc.fire('receive ice candidate', candidate);
  95. });
  96. rtc.on('new_peer_connected', function(data) {
  97. rtc.connections.push(data.socketId);
  98. var pc = rtc.createPeerConnection(data.socketId);
  99. for (var i = 0; i < rtc.streams.length; i++) {
  100. var stream = rtc.streams[i];
  101. pc.addStream(stream);
  102. }
  103. });
  104. rtc.on('remove_peer_connected', function(data) {
  105. rtc.fire('disconnect stream', data.socketId);
  106. delete rtc.peerConnections[data.socketId];
  107. });
  108. rtc.on('receive_offer', function(data) {
  109. rtc.receiveOffer(data.socketId, data.sdp);
  110. rtc.fire('receive offer', data);
  111. });
  112. rtc.on('receive_answer', function(data) {
  113. rtc.receiveAnswer(data.socketId, data.sdp);
  114. rtc.fire('receive answer', data);
  115. });
  116. rtc.fire('connect');
  117. };
  118. };
  119. rtc.sendOffers = function() {
  120. for (var i = 0, len = rtc.connections.length; i < len; i++) {
  121. var socketId = rtc.connections[i];
  122. rtc.sendOffer(socketId);
  123. }
  124. };
  125. rtc.onClose = function(data) {
  126. rtc.on('close_stream', function() {
  127. rtc.fire('close_stream', data);
  128. });
  129. };
  130. rtc.createPeerConnections = function() {
  131. for (var i = 0; i < rtc.connections.length; i++) {
  132. rtc.createPeerConnection(rtc.connections[i]);
  133. }
  134. };
  135. rtc.createPeerConnection = function(id) {
  136. var config;
  137. if (rtc.dataChannelSupport)
  138. config = rtc.dataChannelConfig;
  139. var pc = rtc.peerConnections[id] = new PeerConnection(rtc.SERVER, config);
  140. pc.onicecandidate = function(event) {
  141. if (event.candidate) {
  142. rtc._socket.send(JSON.stringify({
  143. "eventName": "send_ice_candidate",
  144. "data": {
  145. "label": event.candidate.label,
  146. "candidate": event.candidate.candidate,
  147. "socketId": id
  148. }
  149. }));
  150. }
  151. rtc.fire('ice candidate', event.candidate);
  152. };
  153. pc.onopen = function() {
  154. // TODO: Finalize this API
  155. rtc.fire('peer connection opened');
  156. };
  157. pc.onaddstream = function(event) {
  158. // TODO: Finalize this API
  159. rtc.fire('add remote stream', event.stream, id);
  160. };
  161. if (rtc.dataChannelSupport) {
  162. pc.ondatachannel = function (evt) {
  163. console.log('data channel connecting ' + id);
  164. rtc.addDataChannel(id, evt.channel);
  165. };
  166. }
  167. return pc;
  168. };
  169. rtc.sendOffer = function(socketId) {
  170. var pc = rtc.peerConnections[socketId];
  171. pc.createOffer( function(session_description) {
  172. pc.setLocalDescription(session_description);
  173. rtc._socket.send(JSON.stringify({
  174. "eventName": "send_offer",
  175. "data":{
  176. "socketId": socketId,
  177. "sdp": session_description
  178. }
  179. }));
  180. });
  181. };
  182. rtc.receiveOffer = function(socketId, sdp) {
  183. var pc = rtc.peerConnections[socketId];
  184. pc.setRemoteDescription(new RTCSessionDescription(sdp));
  185. rtc.sendAnswer(socketId);
  186. };
  187. rtc.sendAnswer = function(socketId) {
  188. var pc = rtc.peerConnections[socketId];
  189. pc.createAnswer( function(session_description) {
  190. pc.setLocalDescription(session_description);
  191. rtc._socket.send(JSON.stringify({
  192. "eventName": "send_answer",
  193. "data":{
  194. "socketId": socketId,
  195. "sdp": session_description
  196. }
  197. }));
  198. var offer = pc.remoteDescription;
  199. });
  200. };
  201. rtc.receiveAnswer = function(socketId, sdp) {
  202. var pc = rtc.peerConnections[socketId];
  203. pc.setRemoteDescription(new RTCSessionDescription(sdp));
  204. };
  205. rtc.createStream = function(opt, onSuccess, onFail) {
  206. var options;
  207. onSuccess = onSuccess ||
  208. function() {};
  209. onFail = onFail ||
  210. function() {};
  211. options = {
  212. video: !!opt.video,
  213. audio: !!opt.audio
  214. };
  215. if (getUserMedia) {
  216. rtc.numStreams++;
  217. getUserMedia.call(navigator, options, function(stream) {
  218. rtc.streams.push(stream);
  219. rtc.initializedStreams++;
  220. onSuccess(stream);
  221. if (rtc.initializedStreams === rtc.numStreams) {
  222. rtc.fire('ready');
  223. }
  224. }, function() {
  225. alert("Could not connect stream.");
  226. onFail();
  227. });
  228. } else {
  229. alert('webRTC is not yet supported in this browser.');
  230. }
  231. };
  232. rtc.addStreams = function() {
  233. for (var i = 0; i < rtc.streams.length; i++) {
  234. var stream = rtc.streams[i];
  235. for (var connection in rtc.peerConnections) {
  236. rtc.peerConnections[connection].addStream(stream);
  237. }
  238. }
  239. };
  240. rtc.attachStream = function(stream, domId) {
  241. document.getElementById(domId).src = URL.createObjectURL(stream);
  242. };
  243. rtc.createDataChannel = function(pcOrId, label) {
  244. if (!rtc.dataChannelSupport) {
  245. alert('webRTC data channel is not yet supported in this browser,' +
  246. ' or you must turn on experimental flags');
  247. return;
  248. }
  249. if (typeof(pcOrId) === 'string') {
  250. id = pcOrId;
  251. pc = rtc.peerConnections[pcOrId];
  252. } else {
  253. pc = pcOrId;
  254. id = undefined;
  255. for (var key in rtc.peerConnections) {
  256. if (rtc.peerConnections[key] === pc)
  257. id = key;
  258. }
  259. }
  260. if (!id)
  261. throw new Error ('attempt to createDataChannel with unknown id');
  262. if (!pc || !(pc instanceof PeerConnection))
  263. throw new Error ('attempt to createDataChannel without peerConnection');
  264. // need a label
  265. label = label || 'fileTransfer' || String(id);
  266. // chrome only supports reliable false atm.
  267. options = {reliable: false};
  268. try {
  269. console.log('createDataChannel ' + id);
  270. channel = pc.createDataChannel(label, options);
  271. } catch (error) {
  272. console.log('seems that DataChannel is NOT actually supported!');
  273. throw error;
  274. }
  275. return rtc.addDataChannel(id, channel);
  276. };
  277. rtc.addDataChannel = function(id, channel) {
  278. channel.onopen = function() {
  279. console.log('data stream open ' + id);
  280. rtc.fire('data stream open', channel);
  281. };
  282. channel.onclose = function(event) {
  283. delete rtc.dataChannels[id];
  284. console.log('data stream close ' + id);
  285. rtc.fire('data stream close', channel);
  286. };
  287. channel.onmessage = function(message) {
  288. console.log('data stream message ' + id);
  289. console.log(message);
  290. rtc.fire('data stream data', channel, message.data);
  291. };
  292. channel.onerror = function(err) {
  293. console.log('data stream error ' + id + ': ' + err);
  294. rtc.fire('data stream error', channel, err);
  295. };
  296. // track dataChannel
  297. rtc.dataChannels[id] = channel;
  298. return channel;
  299. };
  300. rtc.addDataChannels = function() {
  301. if (!rtc.dataChannelSupport)
  302. return;
  303. for (var connection in rtc.peerConnections)
  304. rtc.createDataChannel(connection);
  305. };
  306. rtc.on('ready', function() {
  307. rtc.createPeerConnections();
  308. rtc.addStreams();
  309. rtc.addDataChannels();
  310. rtc.sendOffers();
  311. });
  312. }).call(this);