negotiator.js 9.5 KB

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