Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ProxyConnectionPC.js 12KB

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