negotiator.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. // Set the connection's PC.
  21. connection.pc = connection.peerConnection = pc;
  22. if (connection.type === "media" && options._stream) {
  23. // Add the stream.
  24. pc.addStream(options._stream);
  25. }
  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. Negotiator._makeOffer(connection);
  45. } else {
  46. Negotiator.handleSDP("OFFER", connection, options.sdp);
  47. }
  48. };
  49. Negotiator._getPeerConnection = function(connection, options) {
  50. if (!Negotiator.pcs[connection.type]) {
  51. util.error(
  52. connection.type +
  53. " is not a valid connection type. Maybe you overrode the `type` property somewhere."
  54. );
  55. }
  56. if (!Negotiator.pcs[connection.type][connection.peer]) {
  57. Negotiator.pcs[connection.type][connection.peer] = {};
  58. }
  59. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  60. var pc;
  61. // Not multiplexing while FF and Chrome have not-great support for it.
  62. /*if (options.multiplex) {
  63. ids = Object.keys(peerConnections);
  64. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  65. pc = peerConnections[ids[i]];
  66. if (pc.signalingState === 'stable') {
  67. break; // We can go ahead and use this PC.
  68. }
  69. }
  70. } else */
  71. if (options.pc) {
  72. // Simplest case: PC id already provided for us.
  73. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  74. }
  75. if (!pc || pc.signalingState !== "stable") {
  76. pc = Negotiator._startPeerConnection(connection);
  77. }
  78. return pc;
  79. };
  80. /*
  81. Negotiator._addProvider = function(provider) {
  82. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  83. // Wait for provider to obtain an ID.
  84. provider.on('open', function(id) {
  85. Negotiator._addProvider(provider);
  86. });
  87. } else {
  88. Negotiator.providers[provider.id] = provider;
  89. }
  90. }*/
  91. /** Start a PC. */
  92. Negotiator._startPeerConnection = function(connection) {
  93. util.log("Creating RTCPeerConnection.");
  94. var id = Negotiator._idPrefix + util.randomToken();
  95. var optional = {};
  96. if (connection.type === "data" && !util.supports.sctp) {
  97. optional = { optional: [{ RtpDataChannels: true }] };
  98. } else if (connection.type === "media") {
  99. // Interop req for chrome.
  100. optional = { optional: [{ DtlsSrtpKeyAgreement: true }] };
  101. }
  102. var pc = new RTCPeerConnection(connection.provider.options.config, optional);
  103. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  104. Negotiator._setupListeners(connection, pc, id);
  105. return pc;
  106. };
  107. /** Set up various WebRTC listeners. */
  108. Negotiator._setupListeners = function(connection, pc, pc_id) {
  109. var peerId = connection.peer;
  110. var connectionId = connection.id;
  111. var provider = connection.provider;
  112. // ICE CANDIDATES.
  113. util.log("Listening for ICE candidates.");
  114. pc.onicecandidate = function(evt) {
  115. if (evt.candidate) {
  116. util.log("Received ICE candidates for:", connection.peer);
  117. provider.socket.send({
  118. type: "CANDIDATE",
  119. payload: {
  120. candidate: evt.candidate,
  121. type: connection.type,
  122. connectionId: connection.id
  123. },
  124. dst: peerId
  125. });
  126. }
  127. };
  128. pc.oniceconnectionstatechange = function() {
  129. switch (pc.iceConnectionState) {
  130. case "failed":
  131. util.log(
  132. "iceConnectionState is disconnected, closing connections to " + peerId
  133. );
  134. connection.emit(
  135. "error",
  136. new Error("Negotiation of connection to " + peerId + " failed.")
  137. );
  138. connection.close();
  139. break;
  140. case "disconnected":
  141. util.log(
  142. "iceConnectionState is disconnected, closing connections to " + peerId
  143. );
  144. connection.close();
  145. break;
  146. case "completed":
  147. pc.onicecandidate = util.noop;
  148. break;
  149. }
  150. };
  151. // Fallback for older Chrome impls.
  152. pc.onicechange = pc.oniceconnectionstatechange;
  153. // DATACONNECTION.
  154. util.log("Listening for data channel");
  155. // Fired between offer and answer, so options should already be saved
  156. // in the options hash.
  157. pc.ondatachannel = function(evt) {
  158. util.log("Received data channel");
  159. var dc = evt.channel;
  160. var connection = provider.getConnection(peerId, connectionId);
  161. connection.initialize(dc);
  162. };
  163. // MEDIACONNECTION.
  164. util.log("Listening for remote stream");
  165. pc.onaddstream = function(evt) {
  166. util.log("Received remote stream");
  167. var stream = evt.stream;
  168. var connection = provider.getConnection(peerId, connectionId);
  169. // 10/10/2014: looks like in Chrome 38, onaddstream is triggered after
  170. // setting the remote description. Our connection object in these cases
  171. // is actually a DATA connection, so addStream fails.
  172. // TODO: This is hopefully just a temporary fix. We should try to
  173. // understand why this is happening.
  174. if (connection.type === "media") {
  175. connection.addStream(stream);
  176. }
  177. };
  178. };
  179. Negotiator.cleanup = function(connection) {
  180. util.log("Cleaning up PeerConnection to " + connection.peer);
  181. var pc = connection.pc;
  182. if (
  183. !!pc &&
  184. ((pc.readyState && pc.readyState !== "closed") ||
  185. pc.signalingState !== "closed")
  186. ) {
  187. pc.close();
  188. connection.pc = null;
  189. }
  190. };
  191. Negotiator._makeOffer = function(connection) {
  192. var pc = connection.pc;
  193. pc.createOffer(
  194. function(offer) {
  195. util.log("Created offer.");
  196. if (
  197. !util.supports.sctp &&
  198. connection.type === "data" &&
  199. connection.reliable
  200. ) {
  201. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  202. }
  203. pc.setLocalDescription(
  204. offer,
  205. function() {
  206. util.log("Set localDescription: offer", "for:", connection.peer);
  207. connection.provider.socket.send({
  208. type: "OFFER",
  209. payload: {
  210. sdp: offer,
  211. type: connection.type,
  212. label: connection.label,
  213. connectionId: connection.id,
  214. reliable: connection.reliable,
  215. serialization: connection.serialization,
  216. metadata: connection.metadata,
  217. browser: util.browser
  218. },
  219. dst: connection.peer
  220. });
  221. },
  222. function(err) {
  223. // TODO: investigate why _makeOffer is being called from the answer
  224. if (
  225. err !=
  226. "OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"
  227. ) {
  228. connection.provider.emitError("webrtc", err);
  229. util.log("Failed to setLocalDescription, ", err);
  230. }
  231. }
  232. );
  233. },
  234. function(err) {
  235. connection.provider.emitError("webrtc", err);
  236. util.log("Failed to createOffer, ", err);
  237. },
  238. connection.options.constraints
  239. );
  240. };
  241. Negotiator._makeAnswer = function(connection) {
  242. var pc = connection.pc;
  243. pc.createAnswer(
  244. function(answer) {
  245. util.log("Created answer.");
  246. if (
  247. !util.supports.sctp &&
  248. connection.type === "data" &&
  249. connection.reliable
  250. ) {
  251. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  252. }
  253. pc.setLocalDescription(
  254. answer,
  255. function() {
  256. util.log("Set localDescription: answer", "for:", connection.peer);
  257. connection.provider.socket.send({
  258. type: "ANSWER",
  259. payload: {
  260. sdp: answer,
  261. type: connection.type,
  262. connectionId: connection.id,
  263. browser: util.browser
  264. },
  265. dst: connection.peer
  266. });
  267. },
  268. function(err) {
  269. connection.provider.emitError("webrtc", err);
  270. util.log("Failed to setLocalDescription, ", err);
  271. }
  272. );
  273. },
  274. function(err) {
  275. connection.provider.emitError("webrtc", err);
  276. util.log("Failed to create answer, ", err);
  277. }
  278. );
  279. };
  280. /** Handle an SDP. */
  281. Negotiator.handleSDP = function(type, connection, sdp) {
  282. sdp = new RTCSessionDescription(sdp);
  283. var pc = connection.pc;
  284. util.log("Setting remote description", sdp);
  285. pc.setRemoteDescription(
  286. sdp,
  287. function() {
  288. util.log("Set remoteDescription:", type, "for:", connection.peer);
  289. if (type === "OFFER") {
  290. Negotiator._makeAnswer(connection);
  291. }
  292. },
  293. function(err) {
  294. connection.provider.emitError("webrtc", err);
  295. util.log("Failed to setRemoteDescription, ", err);
  296. }
  297. );
  298. };
  299. /** Handle a candidate. */
  300. Negotiator.handleCandidate = function(connection, ice) {
  301. var candidate = ice.candidate;
  302. var sdpMLineIndex = ice.sdpMLineIndex;
  303. connection.pc.addIceCandidate(
  304. new RTCIceCandidate({
  305. sdpMLineIndex: sdpMLineIndex,
  306. candidate: candidate
  307. })
  308. );
  309. util.log("Added ICE candidate for:", connection.peer);
  310. };
  311. module.exports = Negotiator;