connectionmanager.js 11 KB

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