negotiator.ts 9.9 KB

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