Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ProxyConnectionPC.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. jvb: { iceServers: [] },
  162. p2p: {
  163. iceServers: DEFAULT_STUN_SERVERS,
  164. ...this._options.iceConfig
  165. }
  166. };
  167. /**
  168. * {@code JingleSessionPC} expects an instance of
  169. * {@code JitsiConference}, which has an event emitter that is used
  170. * to signal various connection updates that the local client should
  171. * act upon. The conference instance is not a dependency of a proxy
  172. * connection, but the emitted events can be relevant to the proxy
  173. * connection so the event emitter is stubbed.
  174. *
  175. * @param {string} event - The constant for the event type.
  176. * @type {Function}
  177. * @returns {void}
  178. */
  179. const emitter = event => {
  180. switch (event) {
  181. case XMPPEvents.CONNECTION_ICE_FAILED:
  182. case XMPPEvents.CONNECTION_FAILED:
  183. this._onError(ACTIONS.CONNECTION_ERROR, event);
  184. break;
  185. }
  186. };
  187. /**
  188. * {@code JingleSessionPC} expects an instance of
  189. * {@code JitsiConference} to be passed in. {@code ProxyConnectionPC}
  190. * is instantiated outside of the {@code JitsiConference}, so it must be
  191. * stubbed to prevent errors.
  192. *
  193. * @type {Object}
  194. */
  195. const roomStub = {
  196. addPresenceListener: () => { /** no-op */ },
  197. connectionTimes: [],
  198. eventEmitter: { emit: emitter },
  199. getMediaPresenceInfo: () => {
  200. // Errors occur if this function does not return an object
  201. return {};
  202. },
  203. removePresenceListener: () => { /** no-op */ }
  204. };
  205. /**
  206. * Create an instance of {@code RTC} as it is required for peer
  207. * connection creation by {@code JingleSessionPC}. An existing instance
  208. * of {@code RTC} from elsewhere should not be re-used because it is
  209. * a stateful grouping of utilities.
  210. */
  211. const rtc = new RTC(this, {});
  212. /**
  213. * Add the remote track listener here as {@code JingleSessionPC} has
  214. * {@code TraceablePeerConnection} which uses {@code RTC}'s event
  215. * emitter.
  216. */
  217. rtc.addListener(
  218. RTCEvents.REMOTE_TRACK_ADDED,
  219. this._onRemoteStream
  220. );
  221. const peerConnection = new JingleSessionPC(
  222. undefined, // sid
  223. undefined, // localJid
  224. this._options.peerJid, // remoteJid
  225. connectionStub, // connection
  226. {
  227. offerToReceiveAudio: this._options.receiveAudio,
  228. offerToReceiveVideo: this._options.receiveVideo
  229. }, // mediaConstraints
  230. iceConfigStub, // iceConfig
  231. true, // isP2P
  232. this._options.isInitiator // isInitiator
  233. );
  234. /**
  235. * An additional initialize call is necessary to properly set instance
  236. * variable for calling.
  237. */
  238. peerConnection.initialize(roomStub, rtc, configStub);
  239. return peerConnection;
  240. }
  241. /**
  242. * Invoked when a connection related issue has been encountered.
  243. *
  244. * @param {string} errorType - The constant indicating the type of the error
  245. * that occured.
  246. * @param {string} details - Optional additional data about the error.
  247. * @private
  248. * @returns {void}
  249. */
  250. _onError(errorType, details = '') {
  251. this._options.onError(this._options.peerJid, errorType, details);
  252. }
  253. /**
  254. * Callback invoked when the peer connection has received a remote media
  255. * stream.
  256. *
  257. * @param {JitsiRemoteTrack} jitsiRemoteTrack - The remote media stream
  258. * wrapped in {@code JitsiRemoteTrack}.
  259. * @private
  260. * @returns {void}
  261. */
  262. _onRemoteStream(jitsiRemoteTrack) {
  263. this._tracks.push(jitsiRemoteTrack);
  264. this._options.onRemoteStream(jitsiRemoteTrack);
  265. }
  266. /**
  267. * Callback invoked when {@code JingleSessionPC} needs to signal a message
  268. * out to the remote peer.
  269. *
  270. * @param {XML} iq - The message to signal out.
  271. * @private
  272. * @returns {void}
  273. */
  274. _onSendMessage(iq) {
  275. this._options.onSendMessage(this._options.peerJid, iq);
  276. }
  277. /**
  278. * Callback invoked in response to an agreement to start a proxy connection.
  279. * The passed in jingle element should contain an SDP answer to a previously
  280. * sent SDP offer.
  281. *
  282. * @param {Object} $jingle - The jingle element wrapped in jQuery.
  283. * @private
  284. * @returns {void}
  285. */
  286. _onSessionAccept($jingle) {
  287. if (!this._peerConnection) {
  288. logger.error('Received an answer when no peer connection exists.');
  289. return;
  290. }
  291. this._peerConnection.setAnswer($jingle);
  292. }
  293. /**
  294. * Callback invoked in response to a request to start a proxy connection.
  295. * The passed in jingle element should contain an SDP offer.
  296. *
  297. * @param {Object} $jingle - The jingle element wrapped in jQuery.
  298. * @private
  299. * @returns {void}
  300. */
  301. _onSessionInitiate($jingle) {
  302. if (this._peerConnection) {
  303. logger.error('Received an offer when an offer was already sent.');
  304. return;
  305. }
  306. this._peerConnection = this._createPeerConnection();
  307. this._peerConnection.acceptOffer(
  308. $jingle,
  309. () => { /** no-op */ },
  310. () => this._onError(
  311. this._options.peerJid,
  312. ACTIONS.CONNECTION_ERROR,
  313. 'session initiate error'
  314. )
  315. );
  316. }
  317. /**
  318. * Callback invoked in response to a request to disconnect an active proxy
  319. * connection. Cleans up tracks and the peer connection.
  320. *
  321. * @private
  322. * @returns {void}
  323. */
  324. _onSessionTerminate() {
  325. this._tracks.forEach(track => track.dispose());
  326. this._tracks = [];
  327. if (!this._peerConnection) {
  328. return;
  329. }
  330. this._peerConnection.onTerminated();
  331. }
  332. /**
  333. * Callback invoked in response to ICE candidates from the remote peer.
  334. * The passed in jingle element should contain an ICE candidate.
  335. *
  336. * @param {Object} $jingle - The jingle element wrapped in jQuery.
  337. * @private
  338. * @returns {void}
  339. */
  340. _onTransportInfo($jingle) {
  341. this._peerConnection.addIceCandidates($jingle);
  342. }
  343. }