negotiator.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import logger from "./logger";
  2. import type { MediaConnection } from "./mediaconnection";
  3. import type { DataConnection } from "./dataconnection/DataConnection";
  4. import {
  5. BaseConnectionErrorType,
  6. ConnectionType,
  7. PeerErrorType,
  8. ServerMessageType,
  9. } from "./enums";
  10. import { BaseConnection } from "./baseconnection";
  11. /**
  12. * Manages all negotiations between Peers.
  13. */
  14. export class Negotiator {
  15. constructor(readonly connection: DataConnection | MediaConnection) {}
  16. /** Returns a PeerConnection object set up correctly (for data, media). */
  17. startConnection(options: any) {
  18. const peerConnection = this._startPeerConnection();
  19. // Set the connection's PC.
  20. this.connection.peerConnection = peerConnection;
  21. if (this.connection.type === ConnectionType.Media && options._stream) {
  22. this._addTracksToConnection(options._stream, peerConnection);
  23. }
  24. // What do we need to do now?
  25. if (options.originator) {
  26. const dataConnection = this.connection;
  27. const config: RTCDataChannelInit = { ordered: !!options.reliable };
  28. const dataChannel = peerConnection.createDataChannel(
  29. dataConnection.label,
  30. config,
  31. );
  32. dataConnection._initializeDataChannel(dataChannel);
  33. void this._makeOffer();
  34. } else {
  35. void this.handleSDP("OFFER", options.sdp);
  36. }
  37. }
  38. /** Start a PC. */
  39. private _startPeerConnection(): RTCPeerConnection {
  40. logger.log("Creating RTCPeerConnection.");
  41. const peerConnection = new RTCPeerConnection(
  42. this.connection.provider.options.config,
  43. );
  44. this._setupListeners(peerConnection);
  45. return peerConnection;
  46. }
  47. /** Set up various WebRTC listeners. */
  48. private _setupListeners(peerConnection: RTCPeerConnection) {
  49. const peerId = this.connection.peer;
  50. const connectionId = this.connection.connectionId;
  51. const connectionType = this.connection.type;
  52. const provider = this.connection.provider;
  53. // ICE CANDIDATES.
  54. logger.log("Listening for ICE candidates.");
  55. peerConnection.onicecandidate = (evt) => {
  56. if (!evt.candidate || !evt.candidate.candidate) return;
  57. logger.log(`Received ICE candidates for ${peerId}:`, evt.candidate);
  58. provider.socket.send({
  59. type: ServerMessageType.Candidate,
  60. payload: {
  61. candidate: evt.candidate,
  62. type: connectionType,
  63. connectionId: connectionId,
  64. },
  65. dst: peerId,
  66. });
  67. };
  68. peerConnection.oniceconnectionstatechange = () => {
  69. switch (peerConnection.iceConnectionState) {
  70. case "failed":
  71. logger.log(
  72. "iceConnectionState is failed, closing connections to " + peerId,
  73. );
  74. this.connection.emitError(
  75. BaseConnectionErrorType.NegotiationFailed,
  76. "Negotiation of connection to " + peerId + " failed.",
  77. );
  78. this.connection.close();
  79. break;
  80. case "closed":
  81. logger.log(
  82. "iceConnectionState is closed, closing connections to " + peerId,
  83. );
  84. this.connection.emitError(
  85. BaseConnectionErrorType.ConnectionClosed,
  86. "Connection to " + peerId + " closed.",
  87. );
  88. this.connection.close();
  89. break;
  90. case "disconnected":
  91. logger.log(
  92. "iceConnectionState changed to disconnected on the connection with " +
  93. peerId,
  94. );
  95. break;
  96. case "completed":
  97. peerConnection.onicecandidate = () => {};
  98. break;
  99. }
  100. (this.connection as BaseConnection<{}>).emit(
  101. "iceStateChanged",
  102. peerConnection.iceConnectionState,
  103. );
  104. };
  105. // DATACONNECTION.
  106. logger.log("Listening for data channel");
  107. // Fired between offer and answer, so options should already be saved
  108. // in the options hash.
  109. peerConnection.ondatachannel = (evt) => {
  110. logger.log("Received data channel");
  111. const dataChannel = evt.channel;
  112. const connection = <DataConnection>(
  113. provider.getConnection(peerId, connectionId)
  114. );
  115. connection._initializeDataChannel(dataChannel);
  116. };
  117. // MEDIACONNECTION.
  118. logger.log("Listening for remote stream");
  119. peerConnection.ontrack = (evt) => {
  120. logger.log("Received remote stream");
  121. const stream = evt.streams[0];
  122. const connection = provider.getConnection(peerId, connectionId);
  123. if (connection.type === ConnectionType.Media) {
  124. const mediaConnection = <MediaConnection>connection;
  125. this._addStreamToMediaConnection(stream, mediaConnection);
  126. }
  127. };
  128. }
  129. cleanup(): void {
  130. logger.log("Cleaning up PeerConnection to " + this.connection.peer);
  131. const peerConnection = this.connection.peerConnection;
  132. if (!peerConnection) {
  133. return;
  134. }
  135. this.connection.peerConnection = null;
  136. //unsubscribe from all PeerConnection's events
  137. peerConnection.onicecandidate =
  138. peerConnection.oniceconnectionstatechange =
  139. peerConnection.ondatachannel =
  140. peerConnection.ontrack =
  141. () => {};
  142. const peerConnectionNotClosed = peerConnection.signalingState !== "closed";
  143. let dataChannelNotClosed = false;
  144. const dataChannel = this.connection.dataChannel;
  145. if (dataChannel) {
  146. dataChannelNotClosed =
  147. !!dataChannel.readyState && dataChannel.readyState !== "closed";
  148. }
  149. if (peerConnectionNotClosed || dataChannelNotClosed) {
  150. peerConnection.close();
  151. }
  152. }
  153. private async _makeOffer(): Promise<void> {
  154. const peerConnection = this.connection.peerConnection;
  155. const provider = this.connection.provider;
  156. try {
  157. const offer = await peerConnection.createOffer(
  158. this.connection.options.constraints,
  159. );
  160. logger.log("Created offer.");
  161. if (
  162. this.connection.options.sdpTransform &&
  163. typeof this.connection.options.sdpTransform === "function"
  164. ) {
  165. offer.sdp =
  166. this.connection.options.sdpTransform(offer.sdp) || offer.sdp;
  167. }
  168. try {
  169. await peerConnection.setLocalDescription(offer);
  170. logger.log(
  171. "Set localDescription:",
  172. offer,
  173. `for:${this.connection.peer}`,
  174. );
  175. if (this.connection.type === ConnectionType.Media) {
  176. const payload = {
  177. sdp: offer,
  178. type: this.connection.type,
  179. connectionId: this.connection.connectionId,
  180. metadata: this.connection.metadata,
  181. };
  182. provider.socket.send({
  183. type: ServerMessageType.Offer,
  184. dst: this.connection.peer,
  185. payload,
  186. });
  187. } else {
  188. const payload = {
  189. sdp: offer,
  190. type: this.connection.type,
  191. connectionId: this.connection.connectionId,
  192. metadata: this.connection.metadata,
  193. label: this.connection.label,
  194. reliable: this.connection.reliable,
  195. serialization: this.connection.serialization,
  196. };
  197. provider.socket.send({
  198. type: ServerMessageType.Offer,
  199. dst: this.connection.peer,
  200. payload,
  201. });
  202. }
  203. } catch (err) {
  204. // TODO: investigate why _makeOffer is being called from the answer
  205. if (
  206. err !=
  207. "OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"
  208. ) {
  209. provider.emitError(PeerErrorType.WebRTC, err);
  210. logger.log("Failed to setLocalDescription, ", err);
  211. }
  212. }
  213. } catch (err_1) {
  214. provider.emitError(PeerErrorType.WebRTC, err_1);
  215. logger.log("Failed to createOffer, ", err_1);
  216. }
  217. }
  218. private async _makeAnswer(): Promise<void> {
  219. const peerConnection = this.connection.peerConnection;
  220. const provider = this.connection.provider;
  221. try {
  222. const answer = await peerConnection.createAnswer();
  223. logger.log("Created answer.");
  224. if (
  225. this.connection.options.sdpTransform &&
  226. typeof this.connection.options.sdpTransform === "function"
  227. ) {
  228. answer.sdp =
  229. this.connection.options.sdpTransform(answer.sdp) || answer.sdp;
  230. }
  231. try {
  232. await peerConnection.setLocalDescription(answer);
  233. logger.log(
  234. `Set localDescription:`,
  235. answer,
  236. `for:${this.connection.peer}`,
  237. );
  238. provider.socket.send({
  239. type: ServerMessageType.Answer,
  240. payload: {
  241. sdp: answer,
  242. type: this.connection.type,
  243. connectionId: this.connection.connectionId,
  244. },
  245. dst: this.connection.peer,
  246. });
  247. } catch (err) {
  248. provider.emitError(PeerErrorType.WebRTC, err);
  249. logger.log("Failed to setLocalDescription, ", err);
  250. }
  251. } catch (err_1) {
  252. provider.emitError(PeerErrorType.WebRTC, err_1);
  253. logger.log("Failed to create answer, ", err_1);
  254. }
  255. }
  256. /** Handle an SDP. */
  257. async handleSDP(type: string, sdp: any): Promise<void> {
  258. sdp = new RTCSessionDescription(sdp);
  259. const peerConnection = this.connection.peerConnection;
  260. const provider = this.connection.provider;
  261. logger.log("Setting remote description", sdp);
  262. const self = this;
  263. try {
  264. await peerConnection.setRemoteDescription(sdp);
  265. logger.log(`Set remoteDescription:${type} for:${this.connection.peer}`);
  266. if (type === "OFFER") {
  267. await self._makeAnswer();
  268. }
  269. } catch (err) {
  270. provider.emitError(PeerErrorType.WebRTC, err);
  271. logger.log("Failed to setRemoteDescription, ", err);
  272. }
  273. }
  274. /** Handle a candidate. */
  275. async handleCandidate(ice: RTCIceCandidate) {
  276. logger.log(`handleCandidate:`, ice);
  277. try {
  278. await this.connection.peerConnection.addIceCandidate(ice);
  279. logger.log(`Added ICE candidate for:${this.connection.peer}`);
  280. } catch (err) {
  281. this.connection.provider.emitError(PeerErrorType.WebRTC, err);
  282. logger.log("Failed to handleCandidate, ", err);
  283. }
  284. }
  285. private _addTracksToConnection(
  286. stream: MediaStream,
  287. peerConnection: RTCPeerConnection,
  288. ): void {
  289. logger.log(`add tracks from stream ${stream.id} to peer connection`);
  290. if (!peerConnection.addTrack) {
  291. return logger.error(
  292. `Your browser does't support RTCPeerConnection#addTrack. Ignored.`,
  293. );
  294. }
  295. stream.getTracks().forEach((track) => {
  296. peerConnection.addTrack(track, stream);
  297. });
  298. }
  299. private _addStreamToMediaConnection(
  300. stream: MediaStream,
  301. mediaConnection: MediaConnection,
  302. ): void {
  303. logger.log(
  304. `add stream ${stream.id} to media connection ${mediaConnection.connectionId}`,
  305. );
  306. mediaConnection.addStream(stream);
  307. }
  308. }