negotiator.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /**
  2. * Manages all negotiations between Peers.
  3. */
  4. var Negotiator = {
  5. pcs: {
  6. data: {},
  7. media: {}
  8. }, // type => {peerId: {pc_id: pc}}.
  9. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  10. queue: [] // connections that are delayed due to a PC being in use.
  11. }
  12. Negotiator._idPrefix = 'pc_';
  13. /** Returns a PeerConnection object set up correctly (for data, media). */
  14. Negotiator.startConnection = function(connection, options) {
  15. var pc = Negotiator._getPeerConnection(connection, options);
  16. if (connection.type === 'media' && options._stream) {
  17. // Add the stream.
  18. pc.addStream(options._stream);
  19. }
  20. // Set the connection's PC.
  21. connection.pc = pc;
  22. // What do we need to do now?
  23. if (options.originator) {
  24. if (connection.type === 'data') {
  25. // Create the datachannel.
  26. var config = {};
  27. // Dropping reliable:false support, since it seems to be crashing
  28. // Chrome.
  29. /*if (util.supports.sctp && !options.reliable) {
  30. // If we have canonical reliable support...
  31. config = {maxRetransmits: 0};
  32. }*/
  33. // Fallback to ensure older browsers don't crash.
  34. if (!util.supports.sctp) {
  35. config = {reliable: options.reliable};
  36. }
  37. var dc = pc.createDataChannel(connection.label, config);
  38. connection.initialize(dc);
  39. }
  40. if (!util.supports.onnegotiationneeded) {
  41. Negotiator._makeOffer(connection);
  42. }
  43. } else {
  44. Negotiator.handleSDP('OFFER', connection, options.sdp);
  45. }
  46. }
  47. Negotiator._getPeerConnection = function(connection, options) {
  48. if (!Negotiator.pcs[connection.type]) {
  49. util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
  50. }
  51. if (!Negotiator.pcs[connection.type][connection.peer]) {
  52. Negotiator.pcs[connection.type][connection.peer] = {};
  53. }
  54. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  55. var pc;
  56. // Not multiplexing while FF and Chrome have not-great support for it.
  57. /*if (options.multiplex) {
  58. ids = Object.keys(peerConnections);
  59. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  60. pc = peerConnections[ids[i]];
  61. if (pc.signalingState === 'stable') {
  62. break; // We can go ahead and use this PC.
  63. }
  64. }
  65. } else */
  66. if (options.pc) { // Simplest case: PC id already provided for us.
  67. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  68. }
  69. if (!pc || pc.signalingState !== 'stable') {
  70. pc = Negotiator._startPeerConnection(connection);
  71. }
  72. return pc;
  73. }
  74. /*
  75. Negotiator._addProvider = function(provider) {
  76. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  77. // Wait for provider to obtain an ID.
  78. provider.on('open', function(id) {
  79. Negotiator._addProvider(provider);
  80. });
  81. } else {
  82. Negotiator.providers[provider.id] = provider;
  83. }
  84. }*/
  85. /** Start a PC. */
  86. Negotiator._startPeerConnection = function(connection) {
  87. util.log('Creating RTCPeerConnection.');
  88. var id = Negotiator._idPrefix + util.randomToken();
  89. var optional = {};
  90. if (connection.type === 'data' && !util.supports.sctp) {
  91. optional = {optional: [{RtpDataChannels: true}]};
  92. } else if (connection.type === 'media') {
  93. // Interop req for chrome.
  94. optional = {optional: [{DtlsSrtpKeyAgreement: true}]};
  95. }
  96. var pc = new RTCPeerConnection(connection.provider.options.config, optional);
  97. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  98. Negotiator._setupListeners(connection, pc, id);
  99. return pc;
  100. }
  101. /** Set up various WebRTC listeners. */
  102. Negotiator._setupListeners = function(connection, pc, pc_id) {
  103. var peerId = connection.peer;
  104. var connectionId = connection.id;
  105. var provider = connection.provider;
  106. // ICE CANDIDATES.
  107. util.log('Listening for ICE candidates.');
  108. pc.onicecandidate = function(evt) {
  109. if (evt.candidate) {
  110. util.log('Received ICE candidates for:', connection.peer);
  111. provider.socket.send({
  112. type: 'CANDIDATE',
  113. payload: {
  114. candidate: evt.candidate,
  115. type: connection.type,
  116. connectionId: connection.id
  117. },
  118. dst: peerId
  119. });
  120. }
  121. };
  122. pc.oniceconnectionstatechange = function() {
  123. switch (pc.iceConnectionState) {
  124. case 'disconnected':
  125. case 'failed':
  126. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  127. connection.close();
  128. break;
  129. case 'completed':
  130. pc.onicecandidate = util.noop;
  131. break;
  132. }
  133. };
  134. // Fallback for older Chrome impls.
  135. pc.onicechange = pc.oniceconnectionstatechange;
  136. // ONNEGOTIATIONNEEDED (Chrome)
  137. util.log('Listening for `negotiationneeded`');
  138. pc.onnegotiationneeded = function() {
  139. util.log('`negotiationneeded` triggered');
  140. if (pc.signalingState == 'stable') {
  141. Negotiator._makeOffer(connection);
  142. } else {
  143. util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
  144. }
  145. };
  146. // DATACONNECTION.
  147. util.log('Listening for data channel');
  148. // Fired between offer and answer, so options should already be saved
  149. // in the options hash.
  150. pc.ondatachannel = function(evt) {
  151. util.log('Received data channel');
  152. var dc = evt.channel;
  153. var connection = provider.getConnection(peerId, connectionId);
  154. connection.initialize(dc);
  155. };
  156. // MEDIACONNECTION.
  157. util.log('Listening for remote stream');
  158. pc.onaddstream = function(evt) {
  159. util.log('Received remote stream');
  160. var stream = evt.stream;
  161. provider.getConnection(peerId, connectionId).addStream(stream);
  162. };
  163. }
  164. Negotiator.cleanup = function(connection) {
  165. util.log('Cleaning up PeerConnection to ' + connection.peer);
  166. var pc = connection.pc;
  167. if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
  168. pc.close();
  169. connection.pc = null;
  170. }
  171. }
  172. Negotiator._makeOffer = function(connection) {
  173. var pc = connection.pc;
  174. pc.createOffer(function(offer) {
  175. util.log('Created offer.');
  176. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  177. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  178. }
  179. pc.setLocalDescription(offer, function() {
  180. util.log('Set localDescription: offer', 'for:', connection.peer);
  181. connection.provider.socket.send({
  182. type: 'OFFER',
  183. payload: {
  184. sdp: offer,
  185. type: connection.type,
  186. label: connection.label,
  187. connectionId: connection.id,
  188. reliable: connection.reliable,
  189. serialization: connection.serialization,
  190. metadata: connection.metadata,
  191. browser: util.browser
  192. },
  193. dst: connection.peer
  194. });
  195. }, function(err) {
  196. connection.provider.emit('error', err);
  197. util.log('Failed to setLocalDescription, ', err);
  198. });
  199. }, function(err) {
  200. connection.provider.emit('error', err);
  201. util.log('Failed to createOffer, ', err);
  202. }, connection.options.constraints);
  203. }
  204. Negotiator._makeAnswer = function(connection) {
  205. var pc = connection.pc;
  206. pc.createAnswer(function(answer) {
  207. util.log('Created answer.');
  208. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  209. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  210. }
  211. pc.setLocalDescription(answer, function() {
  212. util.log('Set localDescription: answer', 'for:', connection.peer);
  213. connection.provider.socket.send({
  214. type: 'ANSWER',
  215. payload: {
  216. sdp: answer,
  217. type: connection.type,
  218. connectionId: connection.id,
  219. browser: util.browser
  220. },
  221. dst: connection.peer
  222. });
  223. }, function(err) {
  224. connection.provider.emit('error', err);
  225. util.log('Failed to setLocalDescription, ', err);
  226. });
  227. }, function(err) {
  228. connection.provider.emit('error', err);
  229. util.log('Failed to create answer, ', err);
  230. });
  231. }
  232. /** Handle an SDP. */
  233. Negotiator.handleSDP = function(type, connection, sdp) {
  234. sdp = new RTCSessionDescription(sdp);
  235. var pc = connection.pc;
  236. util.log('Setting remote description', sdp);
  237. pc.setRemoteDescription(sdp, function() {
  238. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  239. if (type === 'OFFER') {
  240. Negotiator._makeAnswer(connection);
  241. }
  242. }, function(err) {
  243. connection.provider.emit('error', err);
  244. util.log('Failed to setRemoteDescription, ', err);
  245. });
  246. }
  247. /** Handle a candidate. */
  248. Negotiator.handleCandidate = function(connection, ice) {
  249. var candidate = ice.candidate;
  250. var sdpMLineIndex = ice.sdpMLineIndex;
  251. connection.pc.addIceCandidate(new RTCIceCandidate({
  252. sdpMLineIndex: sdpMLineIndex,
  253. candidate: candidate
  254. }));
  255. util.log('Added ICE candidate for:', connection.peer);
  256. }