negotiator.js 8.4 KB

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