connectionmanager.js 11 KB

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