negotiator.js 8.1 KB

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