You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ProxyConnectionPC.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import { getLogger } from '@jitsi/logger';
  2. import RTCEvents from '../../service/RTC/RTCEvents';
  3. import { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  4. import RTC from '../RTC/RTC';
  5. import JingleSessionPC from '../xmpp/JingleSessionPC';
  6. import { DEFAULT_STUN_SERVERS } from '../xmpp/xmpp';
  7. import CustomSignalingLayer from './CustomSignalingLayer';
  8. import { ACTIONS } from './constants';
  9. const logger = getLogger(__filename);
  10. /**
  11. * An adapter around {@code JingleSessionPC} so its logic can be re-used without
  12. * an XMPP connection. It is being re-used for consistency with the rest of the
  13. * codebase and to leverage existing peer connection event handling. Also
  14. * this class provides a facade to hide most of the API for
  15. * {@code JingleSessionPC}.
  16. */
  17. export default class ProxyConnectionPC {
  18. /**
  19. * Initializes a new {@code ProxyConnectionPC} instance.
  20. *
  21. * @param {Object} options - Values to initialize the instance with.
  22. * @param {Object} [options.pcConfig] - The {@code RTCConfiguration} to use for the WebRTC peer connection.
  23. * @param {boolean} [options.isInitiator] - If true, the local client should send offers. If false, the local
  24. * client should send answers. Defaults to false.
  25. * @param {Function} options.onRemoteStream - Callback to invoke when a remote media stream has been received
  26. * through the peer connection.
  27. * @param {string} options.peerJid - The jid of the remote client with which the peer connection is being establish
  28. * and which should receive direct messages regarding peer connection updates.
  29. * @param {boolean} [options.receiveVideo] - Whether or not the peer connection should accept incoming video
  30. * streams. Defaults to false.
  31. * @param {Function} options.onSendMessage - Callback to invoke when a message has to be sent (signaled) out.
  32. */
  33. constructor(options = {}) {
  34. this._options = {
  35. pcConfig: {},
  36. isInitiator: false,
  37. receiveAudio: false,
  38. receiveVideo: false,
  39. ...options
  40. };
  41. /**
  42. * Instances of {@code JitsiTrack} associated with this instance of
  43. * {@code ProxyConnectionPC}.
  44. *
  45. * @type {Array<JitsiTrack>}
  46. */
  47. this._tracks = [];
  48. /**
  49. * The active instance of {@code JingleSessionPC}.
  50. *
  51. * @type {JingleSessionPC|null}
  52. */
  53. this._peerConnection = null;
  54. // Bind event handlers so they are only bound once for every instance.
  55. this._onError = this._onError.bind(this);
  56. this._onRemoteStream = this._onRemoteStream.bind(this);
  57. this._onSendMessage = this._onSendMessage.bind(this);
  58. }
  59. /**
  60. * Returns the jid of the remote peer with which this peer connection should
  61. * be established with.
  62. *
  63. * @returns {string}
  64. */
  65. getPeerJid() {
  66. return this._options.peerJid;
  67. }
  68. /**
  69. * Updates the peer connection based on the passed in jingle.
  70. *
  71. * @param {Object} $jingle - An XML jingle element, wrapped in query,
  72. * describing how the peer connection should be updated.
  73. * @returns {void}
  74. */
  75. processMessage($jingle) {
  76. switch ($jingle.attr('action')) {
  77. case ACTIONS.ACCEPT:
  78. this._onSessionAccept($jingle);
  79. break;
  80. case ACTIONS.INITIATE:
  81. this._onSessionInitiate($jingle);
  82. break;
  83. case ACTIONS.TERMINATE:
  84. this._onSessionTerminate($jingle);
  85. break;
  86. case ACTIONS.TRANSPORT_INFO:
  87. this._onTransportInfo($jingle);
  88. break;
  89. }
  90. }
  91. /**
  92. * Instantiates a peer connection and starts the offer/answer cycle to
  93. * establish a connection with a remote peer.
  94. *
  95. * @param {Array<JitsiLocalTrack>} localTracks - Initial local tracks to add
  96. * to add to the peer connection.
  97. * @returns {void}
  98. */
  99. start(localTracks = []) {
  100. if (this._peerConnection) {
  101. return;
  102. }
  103. this._tracks = this._tracks.concat(localTracks);
  104. this._peerConnection = this._createPeerConnection();
  105. this._peerConnection.invite(localTracks);
  106. }
  107. /**
  108. * Begins the process of disconnecting from a remote peer and cleaning up
  109. * the peer connection.
  110. *
  111. * @returns {void}
  112. */
  113. stop() {
  114. if (this._peerConnection) {
  115. this._peerConnection.terminate();
  116. }
  117. this._onSessionTerminate();
  118. }
  119. /**
  120. * Instantiates a new {@code JingleSessionPC} by stubbing out the various
  121. * dependencies of {@code JingleSessionPC}.
  122. *
  123. * @private
  124. * @returns {JingleSessionPC}
  125. */
  126. _createPeerConnection() {
  127. /**
  128. * {@code JingleSessionPC} takes in the entire jitsi-meet config.js
  129. * object, which may not be accessible from the caller.
  130. *
  131. * @type {Object}
  132. */
  133. const configStub = {};
  134. /**
  135. * {@code JingleSessionPC} assumes an XMPP/Strophe connection object is
  136. * passed through, which also has the jingle plugin initialized on it.
  137. * This connection object is used to signal out peer connection updates
  138. * via iqs, and those updates need to be piped back out to the remote
  139. * peer.
  140. *
  141. * @type {Object}
  142. */
  143. const connectionStub = {
  144. // At the time this is used for Spot and it's okay to say the connection is always connected, because if
  145. // spot has no signalling it will not be in a meeting where this is used.
  146. connected: true,
  147. jingle: {
  148. terminate: () => { /** no-op */ }
  149. },
  150. sendIQ: this._onSendMessage,
  151. // Returns empty function, because it does not add any listeners for real.
  152. // eslint-disable-next-line no-empty-function
  153. addEventListener: () => () => { },
  154. // eslint-disable-next-line no-empty-function
  155. addCancellableListener: () => () => { }
  156. };
  157. /**
  158. * {@code JingleSessionPC} can take in a custom ice configuration,
  159. * depending on the peer connection type, peer-to-peer or other.
  160. * However, {@code ProxyConnectionPC} always assume a peer-to-peer
  161. * connection so the ice configuration is hard-coded with defaults.
  162. *
  163. * @type {Object}
  164. */
  165. const pcConfigStub = {
  166. iceServers: DEFAULT_STUN_SERVERS,
  167. ...this._options.pcConfig
  168. };
  169. /**
  170. * {@code JingleSessionPC} expects an instance of
  171. * {@code JitsiConference}, which has an event emitter that is used
  172. * to signal various connection updates that the local client should
  173. * act upon. The conference instance is not a dependency of a proxy
  174. * connection, but the emitted events can be relevant to the proxy
  175. * connection so the event emitter is stubbed.
  176. *
  177. * @param {string} event - The constant for the event type.
  178. * @type {Function}
  179. * @returns {void}
  180. */
  181. const emitter = event => {
  182. switch (event) {
  183. case XMPPEvents.CONNECTION_ICE_FAILED:
  184. case XMPPEvents.CONNECTION_FAILED:
  185. this._onError(ACTIONS.CONNECTION_ERROR, event);
  186. break;
  187. }
  188. };
  189. /**
  190. * {@link JingleSessionPC} expects an instance of
  191. * {@link ChatRoom} to be passed in. {@link ProxyConnectionPC}
  192. * is instantiated outside of the {@code JitsiConference}, so it must be
  193. * stubbed to prevent errors.
  194. *
  195. * @type {Object}
  196. */
  197. const roomStub = {
  198. addEventListener: () => { /* no op */ },
  199. addPresenceListener: () => { /* no-op */ },
  200. connectionTimes: [],
  201. eventEmitter: { emit: emitter },
  202. removeEventListener: () => { /* no op */ },
  203. removePresenceListener: () => { /* no-op */ }
  204. };
  205. /**
  206. * A {@code JitsiConference} stub passed to the {@link RTC} module.
  207. * @type {Object}
  208. */
  209. const conferenceStub = {
  210. myUserId: () => ''
  211. };
  212. /**
  213. * Create an instance of {@code RTC} as it is required for peer
  214. * connection creation by {@code JingleSessionPC}. An existing instance
  215. * of {@code RTC} from elsewhere should not be re-used because it is
  216. * a stateful grouping of utilities.
  217. */
  218. this._rtc = new RTC(conferenceStub, {});
  219. /**
  220. * Add the remote track listener here as {@code JingleSessionPC} has
  221. * {@code TraceablePeerConnection} which uses {@code RTC}'s event
  222. * emitter.
  223. */
  224. this._rtc.addListener(
  225. RTCEvents.REMOTE_TRACK_ADDED,
  226. this._onRemoteStream
  227. );
  228. const peerConnection = new JingleSessionPC(
  229. undefined, // sid
  230. undefined, // localJid
  231. this._options.peerJid, // remoteJid
  232. connectionStub, // connection
  233. {
  234. offerToReceiveAudio: this._options.receiveAudio,
  235. offerToReceiveVideo: this._options.receiveVideo
  236. }, // mediaConstraints
  237. pcConfigStub, // pcConfig
  238. true, // isP2P
  239. this._options.isInitiator // isInitiator
  240. );
  241. const signalingLayer = new CustomSignalingLayer();
  242. signalingLayer.setChatRoom(roomStub);
  243. /**
  244. * An additional initialize call is necessary to properly set instance
  245. * variable for calling.
  246. */
  247. peerConnection.initialize(roomStub, this._rtc, signalingLayer, configStub);
  248. return peerConnection;
  249. }
  250. /**
  251. * Invoked when a connection related issue has been encountered.
  252. *
  253. * @param {string} errorType - The constant indicating the type of the error
  254. * that occurred.
  255. * @param {string} details - Optional additional data about the error.
  256. * @private
  257. * @returns {void}
  258. */
  259. _onError(errorType, details = '') {
  260. this._options.onError(this._options.peerJid, errorType, details);
  261. }
  262. /**
  263. * Callback invoked when the peer connection has received a remote media
  264. * stream.
  265. *
  266. * @param {JitsiRemoteTrack} jitsiRemoteTrack - The remote media stream
  267. * wrapped in {@code JitsiRemoteTrack}.
  268. * @private
  269. * @returns {void}
  270. */
  271. _onRemoteStream(jitsiRemoteTrack) {
  272. this._tracks.push(jitsiRemoteTrack);
  273. this._options.onRemoteStream(jitsiRemoteTrack);
  274. }
  275. /**
  276. * Callback invoked when {@code JingleSessionPC} needs to signal a message
  277. * out to the remote peer.
  278. *
  279. * @param {XML} iq - The message to signal out.
  280. * @param {Function} callback - Callback when the IQ was acknowledged.
  281. * @private
  282. * @returns {void}
  283. */
  284. _onSendMessage(iq, callback) {
  285. this._options.onSendMessage(this._options.peerJid, iq);
  286. if (callback) {
  287. // Fake some time to receive the acknowledge.
  288. setTimeout(callback, 250);
  289. }
  290. }
  291. /**
  292. * Callback invoked in response to an agreement to start a proxy connection.
  293. * The passed in jingle element should contain an SDP answer to a previously
  294. * sent SDP offer.
  295. *
  296. * @param {Object} $jingle - The jingle element wrapped in jQuery.
  297. * @private
  298. * @returns {void}
  299. */
  300. _onSessionAccept($jingle) {
  301. if (!this._peerConnection) {
  302. logger.error('Received an answer when no peer connection exists.');
  303. return;
  304. }
  305. this._peerConnection.setAnswer($jingle);
  306. }
  307. /**
  308. * Callback invoked in response to a request to start a proxy connection.
  309. * The passed in jingle element should contain an SDP offer.
  310. *
  311. * @param {Object} $jingle - The jingle element wrapped in jQuery.
  312. * @private
  313. * @returns {void}
  314. */
  315. _onSessionInitiate($jingle) {
  316. if (this._peerConnection) {
  317. logger.error('Received an offer when an offer was already sent.');
  318. return;
  319. }
  320. this._peerConnection = this._createPeerConnection();
  321. this._peerConnection.acceptOffer(
  322. $jingle,
  323. () => { /** no-op */ },
  324. () => this._onError(
  325. this._options.peerJid,
  326. ACTIONS.CONNECTION_ERROR,
  327. 'session initiate error'
  328. ),
  329. []
  330. );
  331. }
  332. /**
  333. * Callback invoked in response to a request to disconnect an active proxy
  334. * connection. Cleans up tracks and the peer connection.
  335. *
  336. * @private
  337. * @returns {void}
  338. */
  339. _onSessionTerminate() {
  340. this._tracks.forEach(track => track.dispose());
  341. this._tracks = [];
  342. if (this._peerConnection) {
  343. this._peerConnection.onTerminated();
  344. }
  345. if (this._rtc) {
  346. this._rtc.removeListener(
  347. RTCEvents.REMOTE_TRACK_ADDED,
  348. this._onRemoteStream
  349. );
  350. this._rtc.destroy();
  351. }
  352. }
  353. /**
  354. * Callback invoked in response to ICE candidates from the remote peer.
  355. * The passed in jingle element should contain an ICE candidate.
  356. *
  357. * @param {Object} $jingle - The jingle element wrapped in jQuery.
  358. * @private
  359. * @returns {void}
  360. */
  361. _onTransportInfo($jingle) {
  362. this._peerConnection.addIceCandidates($jingle);
  363. }
  364. }