connectionmanager.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. });
  174. };
  175. /** Create an answer for PC. */
  176. ConnectionManager.prototype._makeAnswer = function() {
  177. var self = this;
  178. this.pc.createAnswer(function(answer) {
  179. util.log('Created answer.');
  180. if (util.browserisms === 'Webkit') {
  181. //answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  182. }
  183. self.pc.setLocalDescription(answer, function() {
  184. util.log('Set localDescription to answer.');
  185. self._socket.send({
  186. type: 'ANSWER',
  187. payload: {
  188. sdp: answer
  189. },
  190. dst: self.peer,
  191. manager: self._managerId
  192. });
  193. }, function(err) {
  194. self.emit('error', err);
  195. util.log('Failed to setLocalDescription, ', err);
  196. });
  197. }, function(err) {
  198. self.emit('error', err);
  199. util.log('Failed to create answer, ', err);
  200. });
  201. };
  202. /** Clean up PC, close related DCs. */
  203. ConnectionManager.prototype._cleanup = function() {
  204. util.log('Cleanup ConnectionManager for ' + this.peer);
  205. if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
  206. this.pc.close();
  207. this.pc = null;
  208. }
  209. var self = this;
  210. this._socket.send({
  211. type: 'LEAVE',
  212. dst: self.peer
  213. });
  214. this.destroyed = true;
  215. this.emit('close');
  216. };
  217. /** Attach connection listeners. */
  218. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  219. var self = this;
  220. connection.on('close', function() {
  221. if (!!self.connections[connection.label]) {
  222. delete self.connections[connection.label];
  223. }
  224. if (!Object.keys(self.connections).length) {
  225. self._cleanup();
  226. }
  227. });
  228. connection.on('open', function() {
  229. self._lock = false;
  230. self._processQueue();
  231. });
  232. };
  233. /** Handle an SDP. */
  234. ConnectionManager.prototype.handleSDP = function(sdp, type, call) {
  235. sdp = new RTCSessionDescription(sdp);
  236. var self = this;
  237. this.pc.setRemoteDescription(sdp, function() {
  238. util.log('Set remoteDescription: ' + type);
  239. if (type === 'OFFER') {
  240. if (call && !self._call) {
  241. self._call = new MediaConnection(self.peer);
  242. self._call.on('answer', function(stream){
  243. if (stream) {
  244. self.pc.addStream(stream);
  245. }
  246. self._makeAnswer();
  247. util.setZeroTimeout(function(){
  248. // Add remote streams
  249. self._call.receiveStream(self.pc.getRemoteStreams()[0]);
  250. });
  251. });
  252. self.emit('call', self._call);
  253. } else {
  254. self._makeAnswer();
  255. }
  256. } else {
  257. // Got answer from remote
  258. self._lock = false;
  259. }
  260. }, function(err) {
  261. self.emit('error', err);
  262. util.log('Failed to setRemoteDescription, ', err);
  263. });
  264. };
  265. /** Handle a candidate. */
  266. ConnectionManager.prototype.handleCandidate = function(message) {
  267. var candidate = new RTCIceCandidate(message.candidate);
  268. this.pc.addIceCandidate(candidate);
  269. util.log('Added ICE candidate.');
  270. };
  271. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  272. ConnectionManager.prototype.handleUpdate = function(updates) {
  273. var labels = Object.keys(updates);
  274. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  275. var label = labels[i];
  276. this.labels[label] = updates[label];
  277. }
  278. };
  279. /** Handle peer leaving. */
  280. ConnectionManager.prototype.handleLeave = function() {
  281. util.log('Peer ' + this.peer + ' disconnected.');
  282. this.close();
  283. };
  284. /** Closes manager and all related connections. */
  285. ConnectionManager.prototype.close = function() {
  286. if (this.destroyed) {
  287. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  288. return;
  289. }
  290. var labels = Object.keys(this.connections);
  291. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  292. var label = labels[i];
  293. var connection = this.connections[label];
  294. connection.close();
  295. }
  296. // TODO: close the call
  297. this.connections = null;
  298. this._cleanup();
  299. };
  300. /** Create and returns a DataConnection with the peer with the given label. */
  301. ConnectionManager.prototype.connect = function(options) {
  302. if (this.destroyed) {
  303. return;
  304. }
  305. console.log('trying to connect');
  306. options = util.extend({
  307. label: 'peerjs',
  308. reliable: (util.browserisms === 'Firefox')
  309. }, options);
  310. // Check if label is taken...if so, generate a new label randomly.
  311. while (!!this.connections[options.label]) {
  312. options.label = 'peerjs' + this._default;
  313. this._default += 1;
  314. }
  315. this.labels[options.label] = options;
  316. var dc;
  317. if (!!this.pc && !this._lock) {
  318. var reliable = util.browserisms === 'Firefox' ? options.reliable : false;
  319. dc = this.pc.createDataChannel(options.label, { reliable: reliable });
  320. if (util.browserisms === 'Firefox') {
  321. this._makeOffer();
  322. }
  323. }
  324. var connection = new DataConnection(this.peer, dc, options);
  325. this._attachConnectionListeners(connection);
  326. this.connections[options.label] = connection;
  327. if (!this.pc || this._lock) {
  328. console.log('qing', this._lock);
  329. this._queued.push(connection);
  330. }
  331. this._lock = true
  332. return connection;
  333. };
  334. ConnectionManager.prototype.call = function(stream, options) {
  335. if (this.destroyed) {
  336. return;
  337. }
  338. options = util.extend({
  339. }, options);
  340. if (!!this.pc && !this._lock) {
  341. this.pc.addStream(stream);
  342. if (util.browserisms === 'Firefox') {
  343. this._makeOffer();
  344. }
  345. }
  346. var connection = new MediaConnection(this.peer, stream, options);
  347. this._call = connection;
  348. if (!this.pc || this._lock) {
  349. this._queued.push(connection);
  350. }
  351. this._lock = true;
  352. return connection;
  353. };