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