negotiator.js 8.3 KB

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