provider.js 11 KB

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