negotiator.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 'disconnected':
  129. case 'failed':
  130. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  131. connection.close();
  132. break;
  133. case 'completed':
  134. pc.onicecandidate = util.noop;
  135. break;
  136. }
  137. };
  138. // Fallback for older Chrome impls.
  139. pc.onicechange = pc.oniceconnectionstatechange;
  140. // ONNEGOTIATIONNEEDED (Chrome)
  141. util.log('Listening for `negotiationneeded`');
  142. pc.onnegotiationneeded = function() {
  143. util.log('`negotiationneeded` triggered');
  144. if (pc.signalingState == 'stable') {
  145. Negotiator._makeOffer(connection);
  146. } else {
  147. util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
  148. }
  149. };
  150. // DATACONNECTION.
  151. util.log('Listening for data channel');
  152. // Fired between offer and answer, so options should already be saved
  153. // in the options hash.
  154. pc.ondatachannel = function(evt) {
  155. util.log('Received data channel');
  156. var dc = evt.channel;
  157. var connection = provider.getConnection(peerId, connectionId);
  158. connection.initialize(dc);
  159. };
  160. // MEDIACONNECTION.
  161. util.log('Listening for remote stream');
  162. pc.onaddstream = function(evt) {
  163. util.log('Received remote stream');
  164. var stream = evt.stream;
  165. var connection = provider.getConnection(peerId, connectionId);
  166. // 10/10/2014: looks like in Chrome 38, onaddstream is triggered after
  167. // setting the remote description. Our connection object in these cases
  168. // is actually a DATA connection, so addStream fails.
  169. // TODO: This is hopefully just a temporary fix. We should try to
  170. // understand why this is happening.
  171. if (connection.type === 'media') {
  172. connection.addStream(stream);
  173. }
  174. };
  175. }
  176. Negotiator.cleanup = function(connection) {
  177. util.log('Cleaning up PeerConnection to ' + connection.peer);
  178. var pc = connection.pc;
  179. if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
  180. pc.close();
  181. connection.pc = null;
  182. }
  183. }
  184. Negotiator._makeOffer = function(connection) {
  185. var pc = connection.pc;
  186. pc.createOffer(function(offer) {
  187. util.log('Created offer.');
  188. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  189. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  190. }
  191. pc.setLocalDescription(offer, function() {
  192. util.log('Set localDescription: offer', 'for:', connection.peer);
  193. connection.provider.socket.send({
  194. type: 'OFFER',
  195. payload: {
  196. sdp: offer,
  197. type: connection.type,
  198. label: connection.label,
  199. connectionId: connection.id,
  200. reliable: connection.reliable,
  201. serialization: connection.serialization,
  202. metadata: connection.metadata,
  203. browser: util.browser
  204. },
  205. dst: connection.peer
  206. });
  207. }, function(err) {
  208. connection.provider.emitError('webrtc', err);
  209. util.log('Failed to setLocalDescription, ', err);
  210. });
  211. }, function(err) {
  212. connection.provider.emitError('webrtc', err);
  213. util.log('Failed to createOffer, ', err);
  214. }, connection.options.constraints);
  215. }
  216. Negotiator._makeAnswer = function(connection) {
  217. var pc = connection.pc;
  218. pc.createAnswer(function(answer) {
  219. util.log('Created answer.');
  220. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  221. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  222. }
  223. pc.setLocalDescription(answer, function() {
  224. util.log('Set localDescription: answer', 'for:', connection.peer);
  225. connection.provider.socket.send({
  226. type: 'ANSWER',
  227. payload: {
  228. sdp: answer,
  229. type: connection.type,
  230. connectionId: connection.id,
  231. browser: util.browser
  232. },
  233. dst: connection.peer
  234. });
  235. }, function(err) {
  236. connection.provider.emitError('webrtc', err);
  237. util.log('Failed to setLocalDescription, ', err);
  238. });
  239. }, function(err) {
  240. connection.provider.emitError('webrtc', err);
  241. util.log('Failed to create answer, ', err);
  242. });
  243. }
  244. /** Handle an SDP. */
  245. Negotiator.handleSDP = function(type, connection, sdp) {
  246. sdp = new RTCSessionDescription(sdp);
  247. var pc = connection.pc;
  248. util.log('Setting remote description', sdp);
  249. pc.setRemoteDescription(sdp, function() {
  250. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  251. if (type === 'OFFER') {
  252. Negotiator._makeAnswer(connection);
  253. }
  254. }, function(err) {
  255. connection.provider.emitError('webrtc', err);
  256. util.log('Failed to setRemoteDescription, ', err);
  257. });
  258. }
  259. /** Handle a candidate. */
  260. Negotiator.handleCandidate = function(connection, ice) {
  261. var candidate = ice.candidate;
  262. var sdpMLineIndex = ice.sdpMLineIndex;
  263. connection.pc.addIceCandidate(new RTCIceCandidate({
  264. sdpMLineIndex: sdpMLineIndex,
  265. candidate: candidate
  266. }));
  267. util.log('Added ICE candidate for:', connection.peer);
  268. }
  269. module.exports = Negotiator;