negotiator.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. /**
  12. * Manages all negotiations between Peers.
  13. */
  14. export class Negotiator<
  15. Events extends BaseConnectionEvents<ErrorType>,
  16. ErrorType extends string,
  17. ConnectionType extends BaseConnection<
  18. any,
  19. Events | BaseConnectionEvents,
  20. ErrorType
  21. >,
  22. > {
  23. constructor(readonly connection: ConnectionType) {}
  24. /** Returns a PeerConnection object set up correctly (for data, media). */
  25. startConnection(options: any) {
  26. const peerConnection = this._startPeerConnection();
  27. // Set the connection's PC.
  28. this.connection.peerConnection = peerConnection;
  29. if (this.connection.type === ConnectionType.Media && options._stream) {
  30. this._addTracksToConnection(options._stream, peerConnection);
  31. }
  32. // What do we need to do now?
  33. if (options.originator) {
  34. const dataConnection = this.connection;
  35. const config: RTCDataChannelInit = { ordered: !!options.reliable };
  36. const dataChannel = peerConnection.createDataChannel(
  37. dataConnection.label,
  38. config,
  39. );
  40. dataConnection._initializeDataChannel(dataChannel);
  41. void this._makeOffer();
  42. } else {
  43. void this.handleSDP("OFFER", options.sdp);
  44. }
  45. }
  46. /** Start a PC. */
  47. private _startPeerConnection(): RTCPeerConnection {
  48. logger.log("Creating RTCPeerConnection.");
  49. const peerConnection = new RTCPeerConnection(
  50. this.connection.provider.options.config,
  51. );
  52. this._setupListeners(peerConnection);
  53. return peerConnection;
  54. }
  55. /** Set up various WebRTC listeners. */
  56. private _setupListeners(peerConnection: RTCPeerConnection) {
  57. const peerId = this.connection.peer;
  58. const connectionId = this.connection.connectionId;
  59. const connectionType = this.connection.type;
  60. const provider = this.connection.provider;
  61. // ICE CANDIDATES.
  62. logger.log("Listening for ICE candidates.");
  63. peerConnection.onicecandidate = (evt) => {
  64. if (!evt.candidate || !evt.candidate.candidate) return;
  65. logger.log(`Received ICE candidates for ${peerId}:`, evt.candidate);
  66. provider.socket.send({
  67. type: ServerMessageType.Candidate,
  68. payload: {
  69. candidate: evt.candidate,
  70. type: connectionType,
  71. connectionId: connectionId,
  72. },
  73. dst: peerId,
  74. });
  75. };
  76. peerConnection.oniceconnectionstatechange = () => {
  77. switch (peerConnection.iceConnectionState) {
  78. case "failed":
  79. logger.log(
  80. "iceConnectionState is failed, closing connections to " + peerId,
  81. );
  82. this.connection.emitError(
  83. BaseConnectionErrorType.NegotiationFailed,
  84. "Negotiation of connection to " + peerId + " failed.",
  85. );
  86. this.connection.close();
  87. break;
  88. case "closed":
  89. logger.log(
  90. "iceConnectionState is closed, closing connections to " + peerId,
  91. );
  92. this.connection.emitError(
  93. BaseConnectionErrorType.ConnectionClosed,
  94. "Connection to " + peerId + " closed.",
  95. );
  96. this.connection.close();
  97. break;
  98. case "disconnected":
  99. logger.log(
  100. "iceConnectionState changed to disconnected on the connection with " +
  101. peerId,
  102. );
  103. break;
  104. case "completed":
  105. peerConnection.onicecandidate = () => {};
  106. break;
  107. }
  108. this.connection.emit(
  109. "iceStateChanged",
  110. peerConnection.iceConnectionState,
  111. );
  112. };
  113. // DATACONNECTION.
  114. logger.log("Listening for data channel");
  115. // Fired between offer and answer, so options should already be saved
  116. // in the options hash.
  117. peerConnection.ondatachannel = (evt) => {
  118. logger.log("Received data channel");
  119. const dataChannel = evt.channel;
  120. const connection = <DataConnection>(
  121. provider.getConnection(peerId, connectionId)
  122. );
  123. connection._initializeDataChannel(dataChannel);
  124. };
  125. // MEDIACONNECTION.
  126. logger.log("Listening for remote stream");
  127. peerConnection.ontrack = (evt) => {
  128. logger.log("Received remote stream");
  129. const stream = evt.streams[0];
  130. const connection = provider.getConnection(peerId, connectionId);
  131. if (connection.type === ConnectionType.Media) {
  132. const mediaConnection = <MediaConnection>connection;
  133. this._addStreamToMediaConnection(stream, mediaConnection);
  134. }
  135. };
  136. }
  137. cleanup(): void {
  138. logger.log("Cleaning up PeerConnection to " + this.connection.peer);
  139. const peerConnection = this.connection.peerConnection;
  140. if (!peerConnection) {
  141. return;
  142. }
  143. this.connection.peerConnection = null;
  144. //unsubscribe from all PeerConnection's events
  145. peerConnection.onicecandidate =
  146. peerConnection.oniceconnectionstatechange =
  147. peerConnection.ondatachannel =
  148. peerConnection.ontrack =
  149. () => {};
  150. const peerConnectionNotClosed = peerConnection.signalingState !== "closed";
  151. let dataChannelNotClosed = false;
  152. const dataChannel = this.connection.dataChannel;
  153. if (dataChannel) {
  154. dataChannelNotClosed =
  155. !!dataChannel.readyState && dataChannel.readyState !== "closed";
  156. }
  157. if (peerConnectionNotClosed || dataChannelNotClosed) {
  158. peerConnection.close();
  159. }
  160. }
  161. private async _makeOffer(): Promise<void> {
  162. const peerConnection = this.connection.peerConnection;
  163. const provider = this.connection.provider;
  164. try {
  165. const offer = await peerConnection.createOffer(
  166. this.connection.options.constraints,
  167. );
  168. logger.log("Created offer.");
  169. if (
  170. this.connection.options.sdpTransform &&
  171. typeof this.connection.options.sdpTransform === "function"
  172. ) {
  173. offer.sdp =
  174. this.connection.options.sdpTransform(offer.sdp) || offer.sdp;
  175. }
  176. try {
  177. await peerConnection.setLocalDescription(offer);
  178. logger.log(
  179. "Set localDescription:",
  180. offer,
  181. `for:${this.connection.peer}`,
  182. );
  183. let payload: any = {
  184. sdp: offer,
  185. type: this.connection.type,
  186. connectionId: this.connection.connectionId,
  187. metadata: this.connection.metadata,
  188. };
  189. if (this.connection.type === ConnectionType.Data) {
  190. const dataConnection = <DataConnection>(<unknown>this.connection);
  191. payload = {
  192. ...payload,
  193. label: dataConnection.label,
  194. reliable: dataConnection.reliable,
  195. serialization: dataConnection.serialization,
  196. };
  197. }
  198. provider.socket.send({
  199. type: ServerMessageType.Offer,
  200. payload,
  201. dst: this.connection.peer,
  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. }