negotiator.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. 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. this._makeOffer();
  34. } else {
  35. 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.emit(
  75. "error",
  76. new Error("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.emit(
  85. "error",
  86. new Error("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 = util.noop;
  98. break;
  99. }
  100. this.connection.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. let payload: any = {
  176. sdp: offer,
  177. type: this.connection.type,
  178. connectionId: this.connection.connectionId,
  179. metadata: this.connection.metadata,
  180. browser: util.browser,
  181. };
  182. if (this.connection.type === ConnectionType.Data) {
  183. const dataConnection = <DataConnection>(<unknown>this.connection);
  184. payload = {
  185. ...payload,
  186. label: dataConnection.label,
  187. reliable: dataConnection.reliable,
  188. serialization: dataConnection.serialization,
  189. };
  190. }
  191. provider.socket.send({
  192. type: ServerMessageType.Offer,
  193. payload,
  194. dst: this.connection.peer,
  195. });
  196. } catch (err) {
  197. // TODO: investigate why _makeOffer is being called from the answer
  198. if (
  199. err !=
  200. "OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"
  201. ) {
  202. provider.emitError(PeerErrorType.WebRTC, err);
  203. logger.log("Failed to setLocalDescription, ", err);
  204. }
  205. }
  206. } catch (err_1) {
  207. provider.emitError(PeerErrorType.WebRTC, err_1);
  208. logger.log("Failed to createOffer, ", err_1);
  209. }
  210. }
  211. private async _makeAnswer(): Promise<void> {
  212. const peerConnection = this.connection.peerConnection;
  213. const provider = this.connection.provider;
  214. try {
  215. const answer = await peerConnection.createAnswer();
  216. logger.log("Created answer.");
  217. if (
  218. this.connection.options.sdpTransform &&
  219. typeof this.connection.options.sdpTransform === "function"
  220. ) {
  221. answer.sdp =
  222. this.connection.options.sdpTransform(answer.sdp) || answer.sdp;
  223. }
  224. try {
  225. await peerConnection.setLocalDescription(answer);
  226. logger.log(
  227. `Set localDescription:`,
  228. answer,
  229. `for:${this.connection.peer}`,
  230. );
  231. provider.socket.send({
  232. type: ServerMessageType.Answer,
  233. payload: {
  234. sdp: answer,
  235. type: this.connection.type,
  236. connectionId: this.connection.connectionId,
  237. browser: util.browser,
  238. },
  239. dst: this.connection.peer,
  240. });
  241. } catch (err) {
  242. provider.emitError(PeerErrorType.WebRTC, err);
  243. logger.log("Failed to setLocalDescription, ", err);
  244. }
  245. } catch (err_1) {
  246. provider.emitError(PeerErrorType.WebRTC, err_1);
  247. logger.log("Failed to create answer, ", err_1);
  248. }
  249. }
  250. /** Handle an SDP. */
  251. async handleSDP(type: string, sdp: any): Promise<void> {
  252. sdp = new RTCSessionDescription(sdp);
  253. const peerConnection = this.connection.peerConnection;
  254. const provider = this.connection.provider;
  255. logger.log("Setting remote description", sdp);
  256. const self = this;
  257. try {
  258. await peerConnection.setRemoteDescription(sdp);
  259. logger.log(`Set remoteDescription:${type} for:${this.connection.peer}`);
  260. if (type === "OFFER") {
  261. await self._makeAnswer();
  262. }
  263. } catch (err) {
  264. provider.emitError(PeerErrorType.WebRTC, err);
  265. logger.log("Failed to setRemoteDescription, ", err);
  266. }
  267. }
  268. /** Handle a candidate. */
  269. async handleCandidate(ice: any): Promise<void> {
  270. logger.log(`handleCandidate:`, ice);
  271. const candidate = ice.candidate;
  272. const sdpMLineIndex = ice.sdpMLineIndex;
  273. const sdpMid = ice.sdpMid;
  274. const peerConnection = this.connection.peerConnection;
  275. const provider = this.connection.provider;
  276. try {
  277. await peerConnection.addIceCandidate(
  278. new RTCIceCandidate({
  279. sdpMid: sdpMid,
  280. sdpMLineIndex: sdpMLineIndex,
  281. candidate: candidate,
  282. }),
  283. );
  284. logger.log(`Added ICE candidate for:${this.connection.peer}`);
  285. } catch (err) {
  286. provider.emitError(PeerErrorType.WebRTC, err);
  287. logger.log("Failed to handleCandidate, ", err);
  288. }
  289. }
  290. private _addTracksToConnection(
  291. stream: MediaStream,
  292. peerConnection: RTCPeerConnection,
  293. ): void {
  294. logger.log(`add tracks from stream ${stream.id} to peer connection`);
  295. if (!peerConnection.addTrack) {
  296. return logger.error(
  297. `Your browser does't support RTCPeerConnection#addTrack. Ignored.`,
  298. );
  299. }
  300. stream.getTracks().forEach((track) => {
  301. peerConnection.addTrack(track, stream);
  302. });
  303. }
  304. private _addStreamToMediaConnection(
  305. stream: MediaStream,
  306. mediaConnection: MediaConnection,
  307. ): void {
  308. logger.log(
  309. `add stream ${stream.id} to media connection ${mediaConnection.connectionId}`,
  310. );
  311. mediaConnection.addStream(stream);
  312. }
  313. }