negotiator.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /**
  2. * Manages all negotiations between Peers.
  3. */
  4. // TODO: LOCKS.
  5. // TODO: FIREFOX new PC after offer made for DC.
  6. var Negotiator = {
  7. pcs: {
  8. data: {},
  9. media: {}
  10. }, // type => {peerId: {pc_id: pc}}.
  11. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  12. queue: [] // connections that are delayed due to a PC being in use.
  13. }
  14. Negotiator._idPrefix = 'pc_';
  15. /** Returns a PeerConnection object set up correctly (for data, media). */
  16. // Options preceeded with _ are ones we add artificially.
  17. Negotiator.startConnection = function(connection, options) {
  18. //Negotiator._addProvider(provider);
  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 = pc;
  26. // What do we need to do now?
  27. if (options.originator) {
  28. if (connection.type === 'data') {
  29. // Create the datachannel.
  30. var dc = pc.createDataChannel(connection.label, {reliable: options.reliable});
  31. connection.initialize(dc);
  32. }
  33. if (!util.supports.onnegotiationneeded) {
  34. Negotiator._makeOffer(connection);
  35. }
  36. } else {
  37. Negotiator.handleSDP('OFFER', connection, options.sdp);
  38. }
  39. }
  40. Negotiator._getPeerConnection = function(connection, options) {
  41. if (!Negotiator.pcs[connection.type]) {
  42. util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
  43. }
  44. if (!Negotiator.pcs[connection.type][connection.peer]) {
  45. Negotiator.pcs[connection.type][connection.peer] = {};
  46. }
  47. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  48. var pc;
  49. if (options.multiplex) {
  50. // TODO: this doesn't work right now because we don't have PC ids.
  51. // Find an existing PC to use.
  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 if (options.pc) { // Simplest case: PC id already provided for us.
  60. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  61. }
  62. if (!pc || pc.signalingState !== 'stable') {
  63. pc = Negotiator._startPeerConnection(connection);
  64. }
  65. return pc;
  66. }
  67. /*
  68. Negotiator._addProvider = function(provider) {
  69. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  70. // Wait for provider to obtain an ID.
  71. provider.on('open', function(id) {
  72. Negotiator._addProvider(provider);
  73. });
  74. } else {
  75. Negotiator.providers[provider.id] = provider;
  76. }
  77. }*/
  78. /** Start a PC. */
  79. Negotiator._startPeerConnection = function(connection) {
  80. util.log('Creating RTCPeerConnection.');
  81. var id = Negotiator._idPrefix + util.randomToken();
  82. pc = new RTCPeerConnection(connection.provider.options.config, {optional: [{RtpDataChannels: true}]});
  83. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  84. Negotiator._setupListeners(connection, pc, id);
  85. return pc;
  86. }
  87. /** Set up various WebRTC listeners. */
  88. Negotiator._setupListeners = function(connection, pc, pc_id) {
  89. var peerId = connection.peer;
  90. var connectionId = connection.id;
  91. var provider = connection.provider;
  92. // ICE CANDIDATES.
  93. util.log('Listening for ICE candidates.');
  94. pc.onicecandidate = function(evt) {
  95. if (evt.candidate) {
  96. util.log('Received ICE candidates for:', connection.peer);
  97. provider.socket.send({
  98. type: 'CANDIDATE',
  99. payload: {
  100. candidate: evt.candidate,
  101. type: connection.type,
  102. connectionId: connection.id
  103. },
  104. dst: peerId,
  105. });
  106. }
  107. };
  108. pc.oniceconnectionstatechange = function() {
  109. switch (pc.iceConnectionState) {
  110. case 'failed':
  111. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  112. Negotiator.cleanup(connection);
  113. break;
  114. case 'completed':
  115. pc.onicecandidate = util.noop;
  116. break;
  117. }
  118. };
  119. // Fallback for older Chrome impls.
  120. pc.onicechange = pc.oniceconnectionstatechange;
  121. // ONNEGOTIATIONNEEDED (Chrome)
  122. util.log('Listening for `negotiationneeded`');
  123. pc.onnegotiationneeded = function() {
  124. util.log('`negotiationneeded` triggered');
  125. Negotiator._makeOffer(connection);
  126. };
  127. // DATACONNECTION.
  128. util.log('Listening for data channel');
  129. // Fired between offer and answer, so options should already be saved
  130. // in the options hash.
  131. pc.ondatachannel = function(evt) {
  132. util.log('Received data channel');
  133. var dc = evt.channel;
  134. var connection = provider.getConnection(peerId, connectionId);
  135. connection.initialize(dc);
  136. };
  137. // MEDIACONNECTION.
  138. util.log('Listening for remote stream');
  139. pc.onaddstream = function(evt) {
  140. util.log('Received remote stream');
  141. var stream = evt.stream;
  142. provider.getConnection(peerId, id).receiveStream(stream);
  143. };
  144. }
  145. Negotiator.cleanup = function(connection) {
  146. connection.close(); // Will fail safely if connection is already closed.
  147. // TODO: close PeerConnection when all connections are closed.
  148. util.log('Cleanup PeerConnection for ' + connection.peer);
  149. /*if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
  150. this.pc.close();
  151. this.pc = null;
  152. }*/
  153. connection.provider.socket.send({
  154. type: 'LEAVE',
  155. dst: connection.peer
  156. });
  157. }
  158. Negotiator._makeOffer = function(connection) {
  159. var pc = connection.pc;
  160. pc.createOffer(function(offer) {
  161. util.log('Created offer.');
  162. if (!util.supports.reliable && connection.type === 'data') {
  163. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  164. }
  165. pc.setLocalDescription(offer, function() {
  166. util.log('Set localDescription: offer', 'for:', connection.peer);
  167. connection.provider.socket.send({
  168. type: 'OFFER',
  169. payload: {
  170. sdp: offer,
  171. type: connection.type,
  172. label: connection.label,
  173. reliable: connection.reliable,
  174. serialization: connection.serialization,
  175. metadata: connection.metadata,
  176. connectionId: connection.id
  177. },
  178. dst: connection.peer,
  179. });
  180. }, function(err) {
  181. connection.provider.emit('error', err);
  182. util.log('Failed to setLocalDescription, ', err);
  183. });
  184. }, function(err) {
  185. connection.provider.emit('error', err);
  186. util.log('Failed to createOffer, ', err);
  187. });
  188. }
  189. Negotiator._makeAnswer = function(connection) {
  190. var pc = connection.pc;
  191. pc.createAnswer(function(answer) {
  192. util.log('Created answer.');
  193. if (!util.supports.reliable && connection.type === 'data') {
  194. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  195. }
  196. pc.setLocalDescription(answer, function() {
  197. util.log('Set localDescription: answer', 'for:', connection.peer);
  198. connection.provider.socket.send({
  199. type: 'ANSWER',
  200. payload: {
  201. sdp: answer,
  202. type: connection.type,
  203. connectionId: connection.id
  204. },
  205. dst: connection.peer
  206. });
  207. }, function(err) {
  208. connection.provider.emit('error', err);
  209. util.log('Failed to setLocalDescription, ', err);
  210. });
  211. }, function(err) {
  212. connection.provider.emit('error', err);
  213. util.log('Failed to create answer, ', err);
  214. });
  215. }
  216. /** Handle an SDP. */
  217. Negotiator.handleSDP = function(type, connection, sdp) {
  218. sdp = new RTCSessionDescription(sdp);
  219. var pc = connection.pc;
  220. util.log('Setting remote description', sdp);
  221. pc.setRemoteDescription(sdp, function() {
  222. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  223. if (type === 'OFFER') {
  224. if (connection.type === 'media') {
  225. if (connection.localStream) {
  226. // Add local stream (from answer).
  227. pc.addStream(connection.localStream);
  228. }
  229. util.setZeroTimeout(function(){
  230. // Add remote streams
  231. connection.addStream(pc.getRemoteStreams()[0]);
  232. });
  233. }
  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, candidate) {
  243. var candidate = new RTCIceCandidate(candidate);
  244. connection.pc.addIceCandidate(candidate);
  245. util.log('Added ICE candidate for:', connection.peer);
  246. }