connectionmanager.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /**
  2. * Manages DataConnections between its peer and one other peer.
  3. * Internally, manages PeerConnection.
  4. */
  5. function ConnectionManager(id, peer, socket, options) {
  6. if (!(this instanceof ConnectionManager)) return new ConnectionManager(id, peer, socket, options);
  7. EventEmitter.call(this);
  8. options = util.extend({
  9. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  10. }, options);
  11. this._options = options;
  12. // PeerConnection is not yet dead.
  13. this.open = true;
  14. this.id = id;
  15. this.peer = peer;
  16. this.pc = null;
  17. // Mapping labels to metadata and serialization.
  18. // label => { metadata: ..., serialization: ..., reliable: ...}
  19. this.labels = {};
  20. // A default label in the event that none are passed in.
  21. this._default = 0;
  22. // DataConnections on this PC.
  23. this.connections = {};
  24. this._queued = [];
  25. this._socket = socket;
  26. if (!!this.id) {
  27. this.initialize();
  28. }
  29. };
  30. util.inherits(ConnectionManager, EventEmitter);
  31. ConnectionManager.prototype.initialize = function(id, socket) {
  32. if (!!id) {
  33. this.id = id;
  34. }
  35. if (!!socket) {
  36. this._socket = socket;
  37. }
  38. // Set up PeerConnection.
  39. this._startPeerConnection();
  40. // Process queued DCs.
  41. this._processQueue();
  42. // Listen for ICE candidates.
  43. this._setupIce();
  44. // Listen for negotiation needed.
  45. // Chrome only **
  46. this._setupNegotiationHandler();
  47. // Listen for data channel.
  48. this._setupDataChannel();
  49. // Listen for remote streams.
  50. this._setupStreamListener();
  51. this.initialize = function() { };
  52. };
  53. /** Start a PC. */
  54. ConnectionManager.prototype._startPeerConnection = function() {
  55. util.log('Creating RTCPeerConnection');
  56. this.pc = new RTCPeerConnection(this._options.config, { optional: [ { RtpDataChannels: true } ]});
  57. };
  58. /** Add DataChannels to all queued DataConnections. */
  59. ConnectionManager.prototype._processQueue = function() {
  60. console.log(this._queued);
  61. for (var i = 0; i < this._queued.length; i++) {
  62. var conn = this._queued[i];
  63. if (conn.constructor == MediaConnection) {
  64. console.log('adding', conn.localStream);
  65. this.pc.addStream(conn.localStream);
  66. } else if (conn.constructor = DataConnection) {
  67. var reliable = util.browserisms === 'Firefox' ? conn.reliable : false;
  68. conn.addDC(this.pc.createDataChannel(conn.label, { reliable: reliable }));
  69. }
  70. }
  71. if (util.browserisms === 'Firefox' && this._queued.length > 0) {
  72. this._makeOffer();
  73. }
  74. this._queued = [];
  75. };
  76. /** Set up ICE candidate handlers. */
  77. ConnectionManager.prototype._setupIce = function() {
  78. util.log('Listening for ICE candidates.');
  79. var self = this;
  80. this.pc.onicecandidate = function(evt) {
  81. if (evt.candidate) {
  82. util.log('Received ICE candidates.');
  83. self._socket.send({
  84. type: 'CANDIDATE',
  85. payload: {
  86. candidate: evt.candidate
  87. },
  88. dst: self.peer
  89. });
  90. }
  91. };
  92. this.pc.oniceconnectionstatechange = function() {
  93. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  94. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  95. self.close();
  96. }
  97. };
  98. // Fallback for older Chrome impls.
  99. this.pc.onicechange = function() {
  100. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  101. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  102. self.close();
  103. }
  104. };
  105. };
  106. /** Set up onnegotiationneeded. */
  107. ConnectionManager.prototype._setupNegotiationHandler = function() {
  108. var self = this;
  109. util.log('Listening for `negotiationneeded`');
  110. this.pc.onnegotiationneeded = function() {
  111. util.log('`negotiationneeded` triggered');
  112. self._makeOffer();
  113. };
  114. };
  115. /** Set up Data Channel listener. */
  116. ConnectionManager.prototype._setupDataChannel = function() {
  117. var self = this;
  118. util.log('Listening for data channel');
  119. this.pc.ondatachannel = function(evt) {
  120. util.log('Received data channel');
  121. var dc = evt.channel;
  122. var label = dc.label;
  123. // This should not be empty.
  124. var options = self.labels[label] || {};
  125. var connection = new DataConnection(self.peer, dc, options);
  126. self._attachConnectionListeners(connection);
  127. self.connections[label] = connection;
  128. self.emit('connection', connection);
  129. };
  130. };
  131. /** Set up remote stream listener. */
  132. ConnectionManager.prototype._setupStreamListener = function() {
  133. var self = this;
  134. util.log('Listening for remote stream');
  135. this.pc.onaddstream = function(evt) {
  136. util.log('Received remote stream');
  137. var stream = evt.stream;
  138. if (!!self._call) {
  139. self._call.receiveStream(stream);
  140. }
  141. };
  142. };
  143. /** Send an offer. */
  144. ConnectionManager.prototype._makeOffer = function() {
  145. var self = this;
  146. this.pc.createOffer(function(offer) {
  147. util.log('Created offer.');
  148. // Firefox currently does not support multiplexing once an offer is made.
  149. self.firefoxSingular = true;
  150. if (util.browserisms === 'Webkit') {
  151. //offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  152. }
  153. self.pc.setLocalDescription(offer, function() {
  154. util.log('Set localDescription to offer');
  155. self._socket.send({
  156. type: 'OFFER',
  157. payload: {
  158. sdp: offer,
  159. config: self._options.config,
  160. labels: self.labels,
  161. call: !!self._call
  162. },
  163. dst: self.peer
  164. });
  165. // We can now reset labels because all info has been communicated.
  166. self.labels = {};
  167. }, function(err) {
  168. self.emit('error', err);
  169. util.log('Failed to setLocalDescription, ', err);
  170. });
  171. });
  172. };
  173. /** Create an answer for PC. */
  174. ConnectionManager.prototype._makeAnswer = function() {
  175. var self = this;
  176. this.pc.createAnswer(function(answer) {
  177. util.log('Created answer.');
  178. if (util.browserisms === 'Webkit') {
  179. //answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  180. }
  181. self.pc.setLocalDescription(answer, function() {
  182. util.log('Set localDescription to answer.');
  183. self._socket.send({
  184. type: 'ANSWER',
  185. payload: {
  186. sdp: answer
  187. },
  188. dst: self.peer
  189. });
  190. }, function(err) {
  191. self.emit('error', err);
  192. util.log('Failed to setLocalDescription, ', err);
  193. });
  194. }, function(err) {
  195. self.emit('error', err);
  196. util.log('Failed to create answer, ', err);
  197. });
  198. };
  199. /** Clean up PC, close related DCs. */
  200. ConnectionManager.prototype._cleanup = function() {
  201. util.log('Cleanup ConnectionManager for ' + this.peer);
  202. if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
  203. this.pc.close();
  204. this.pc = null;
  205. }
  206. var self = this;
  207. this._socket.send({
  208. type: 'LEAVE',
  209. dst: self.peer
  210. });
  211. this.open = false;
  212. this.emit('close');
  213. };
  214. /** Attach connection listeners. */
  215. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  216. var self = this;
  217. connection.on('close', function() {
  218. if (!!self.connections[connection.label]) {
  219. delete self.connections[connection.label];
  220. }
  221. if (!Object.keys(self.connections).length) {
  222. self._cleanup();
  223. }
  224. });
  225. connection.on('open', function() {
  226. self._lock = false;
  227. self._processQueue();
  228. });
  229. };
  230. /** Handle an SDP. */
  231. ConnectionManager.prototype.handleSDP = function(sdp, type, call) {
  232. sdp = new RTCSessionDescription(sdp);
  233. var self = this;
  234. this.pc.setRemoteDescription(sdp, function() {
  235. util.log('Set remoteDescription: ' + type);
  236. if (type === 'OFFER') {
  237. if (call && !self._call) {
  238. self._call = new MediaConnection(self.peer);
  239. self._call.on('answer', function(stream){
  240. if (stream) {
  241. self.pc.addStream(stream);
  242. }
  243. self._makeAnswer();
  244. util.setZeroTimeout(function(){
  245. // Add remote streams
  246. self._call.receiveStream(self.pc.getRemoteStreams()[0]);
  247. });
  248. });
  249. self.emit('call', self._call);
  250. } else {
  251. self._makeAnswer();
  252. }
  253. } else {
  254. // Got answer from remote
  255. self._lock = false;
  256. }
  257. }, function(err) {
  258. self.emit('error', err);
  259. util.log('Failed to setRemoteDescription, ', err);
  260. });
  261. };
  262. /** Handle a candidate. */
  263. ConnectionManager.prototype.handleCandidate = function(message) {
  264. var candidate = new RTCIceCandidate(message.candidate);
  265. this.pc.addIceCandidate(candidate);
  266. util.log('Added ICE candidate.');
  267. };
  268. /** Handle peer leaving. */
  269. ConnectionManager.prototype.handleLeave = function() {
  270. util.log('Peer ' + this.peer + ' disconnected.');
  271. this.close();
  272. };
  273. /** Closes manager and all related connections. */
  274. ConnectionManager.prototype.close = function() {
  275. if (!this.open) {
  276. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  277. return;
  278. }
  279. var labels = Object.keys(this.connections);
  280. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  281. var label = labels[i];
  282. var connection = this.connections[label];
  283. connection.close();
  284. }
  285. this.connections = null;
  286. this._cleanup();
  287. };
  288. /** Create and returns a DataConnection with the peer with the given label. */
  289. ConnectionManager.prototype.connect = function(options) {
  290. if (!this.open) {
  291. return;
  292. }
  293. console.log('trying to connect');
  294. options = util.extend({
  295. label: 'peerjs',
  296. reliable: (util.browserisms === 'Firefox')
  297. }, options);
  298. // Check if label is taken...if so, generate a new label randomly.
  299. while (!!this.connections[options.label]) {
  300. options.label = 'peerjs' + this._default;
  301. this._default += 1;
  302. }
  303. this.labels[options.label] = options;
  304. var dc;
  305. if (!!this.pc && !this._lock) {
  306. var reliable = util.browserisms === 'Firefox' ? options.reliable : false;
  307. dc = this.pc.createDataChannel(options.label, { reliable: reliable });
  308. if (util.browserisms === 'Firefox') {
  309. this._makeOffer();
  310. }
  311. }
  312. var connection = new DataConnection(this.peer, dc, options);
  313. this._attachConnectionListeners(connection);
  314. this.connections[options.label] = connection;
  315. if (!this.pc || this._lock) {
  316. console.log('qing', this._lock);
  317. this._queued.push(connection);
  318. }
  319. this._lock = true
  320. return connection;
  321. };
  322. ConnectionManager.prototype.call = function(stream, options) {
  323. if (!this.open) {
  324. return;
  325. }
  326. options = util.extend({
  327. }, options);
  328. if (!!this.pc && !this._lock) {
  329. this.pc.addStream(stream);
  330. if (util.browserisms === 'Firefox') {
  331. this._makeOffer();
  332. }
  333. }
  334. var connection = new MediaConnection(this.peer, stream, options);
  335. this._call = connection;
  336. if (!this.pc || this._lock) {
  337. this._queued.push(connection);
  338. }
  339. this._lock = true;
  340. return connection;
  341. };
  342. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  343. ConnectionManager.prototype.update = function(updates) {
  344. var labels = Object.keys(updates);
  345. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  346. var label = labels[i];
  347. this.labels[label] = updates[label];
  348. }
  349. };