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.

JingleSessionPC.js 95KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import { isEqual } from 'lodash-es';
  4. import { $build, $iq, Strophe } from 'strophe.js';
  5. import { JitsiTrackEvents } from '../../JitsiTrackEvents';
  6. import { CodecMimeType } from '../../service/RTC/CodecMimeType';
  7. import { MediaDirection } from '../../service/RTC/MediaDirection';
  8. import { MediaType } from '../../service/RTC/MediaType';
  9. import { SSRC_GROUP_SEMANTICS } from '../../service/RTC/StandardVideoQualitySettings';
  10. import { VideoType } from '../../service/RTC/VideoType';
  11. import {
  12. ICE_DURATION,
  13. ICE_STATE_CHANGED,
  14. VIDEO_CODEC_CHANGED
  15. } from '../../service/statistics/AnalyticsEvents';
  16. import { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  17. import { XEP } from '../../service/xmpp/XMPPExtensioProtocols';
  18. import { SS_DEFAULT_FRAME_RATE } from '../RTC/ScreenObtainer';
  19. import FeatureFlags from '../flags/FeatureFlags';
  20. import SDP from '../sdp/SDP';
  21. import { SDPDiffer } from '../sdp/SDPDiffer';
  22. import SDPUtil from '../sdp/SDPUtil';
  23. import Statistics from '../statistics/statistics';
  24. import AsyncQueue, { ClearedQueueError } from '../util/AsyncQueue';
  25. import browser from './../browser';
  26. import JingleSession from './JingleSession';
  27. import * as JingleSessionState from './JingleSessionState';
  28. import MediaSessionEvents from './MediaSessionEvents';
  29. import XmppConnection from './XmppConnection';
  30. const logger = getLogger('modules/xmpp/JingleSessionPC');
  31. /**
  32. * Constant tells how long we're going to wait for IQ response, before timeout
  33. * error is triggered.
  34. * @type {number}
  35. */
  36. const IQ_TIMEOUT = 10000;
  37. /*
  38. * The default number of samples (per stat) to keep when webrtc stats gathering
  39. * is enabled in TraceablePeerConnection.
  40. */
  41. const DEFAULT_MAX_STATS = 300;
  42. /**
  43. * The time duration for which the client keeps gathering ICE candidates to be sent out in a single IQ.
  44. * @type {number} timeout in ms.
  45. */
  46. const ICE_CAND_GATHERING_TIMEOUT = 150;
  47. /**
  48. * Reads the endpoint ID given a string which represents either the endpoint's full JID, or the endpoint ID itself.
  49. * @param {String} jidOrEndpointId A string which is either the full JID of a participant, or the ID of an
  50. * endpoint/participant.
  51. * @returns The endpoint ID associated with 'jidOrEndpointId'.
  52. */
  53. function getEndpointId(jidOrEndpointId) {
  54. return Strophe.getResourceFromJid(jidOrEndpointId) || jidOrEndpointId;
  55. }
  56. /**
  57. * Add "source" element as a child of "description" element.
  58. * @param {Object} description The "description" element to add to.
  59. * @param {Object} s Contains properties of the source being added.
  60. * @param {Number} ssrc_ The SSRC.
  61. * @param {String} msid The "msid" attribute.
  62. */
  63. function _addSourceElement(description, s, ssrc_, msid) {
  64. description.c('source', {
  65. xmlns: XEP.SOURCE_ATTRIBUTES,
  66. ssrc: ssrc_,
  67. name: s.source,
  68. videoType: s.videoType?.toLowerCase()
  69. })
  70. .c('parameter', {
  71. name: 'msid',
  72. value: msid
  73. })
  74. .up()
  75. .c('ssrc-info', {
  76. xmlns: 'http://jitsi.org/jitmeet',
  77. owner: s.owner
  78. })
  79. .up()
  80. .up();
  81. }
  82. /**
  83. * @typedef {Object} JingleSessionPCOptions
  84. * video test ?(ask George).
  85. * @property {boolean} disableRtx - Described in the config.js[1].
  86. * @property {boolean} disableSimulcast - Described in the config.js[1].
  87. * @property {boolean} enableInsertableStreams - Set to true when the insertable streams constraints is to be enabled
  88. * on the PeerConnection.
  89. * @property {boolean} failICE - it's an option used in the tests. Set to
  90. * <tt>true</tt> to block any real candidates and make the ICE fail.
  91. * @property {boolean} gatherStats - Described in the config.js[1].
  92. * @property {object} p2p - Peer to peer related options (FIXME those could be
  93. * fetched from config.p2p on the upper level).
  94. * @property {Object} testing - Testing and/or experimental options.
  95. * @property {boolean} webrtcIceUdpDisable - Described in the config.js[1].
  96. * @property {boolean} webrtcIceTcpDisable - Described in the config.js[1].
  97. *
  98. * [1]: https://github.com/jitsi/jitsi-meet/blob/master/config.js
  99. */
  100. /**
  101. *
  102. */
  103. export default class JingleSessionPC extends JingleSession {
  104. /**
  105. * Parses 'senders' attribute of the video content.
  106. * @param {jQuery} jingleContents
  107. * @return {string|null} one of the values of content "senders" attribute
  108. * defined by Jingle. If there is no "senders" attribute or if the value is
  109. * invalid then <tt>null</tt> will be returned.
  110. * @private
  111. */
  112. static parseVideoSenders(jingleContents) {
  113. const videoContents = jingleContents.find('>content[name="video"]');
  114. if (videoContents.length) {
  115. const senders = videoContents[0].getAttribute('senders');
  116. if (senders === 'both'
  117. || senders === 'initiator'
  118. || senders === 'responder'
  119. || senders === 'none') {
  120. return senders;
  121. }
  122. }
  123. return null;
  124. }
  125. /**
  126. * Parses the source-name and max frame height value of the 'content-modify' IQ when source-name signaling
  127. * is enabled.
  128. *
  129. * @param {jQuery} jingleContents - A jQuery selector pointing to the '>jingle' element.
  130. * @returns {Object|null}
  131. */
  132. static parseSourceMaxFrameHeight(jingleContents) {
  133. const receiverConstraints = [];
  134. const sourceFrameHeightSel = jingleContents.find('>content[name="video"]>source-frame-height');
  135. let maxHeight, sourceName;
  136. if (sourceFrameHeightSel.length) {
  137. sourceFrameHeightSel.each((_, source) => {
  138. sourceName = source.getAttribute('sourceName');
  139. maxHeight = source.getAttribute('maxHeight');
  140. receiverConstraints.push({
  141. maxHeight,
  142. sourceName
  143. });
  144. });
  145. return receiverConstraints;
  146. }
  147. return null;
  148. }
  149. /* eslint-disable max-params */
  150. /**
  151. * Creates new <tt>JingleSessionPC</tt>
  152. * @param {string} sid the Jingle Session ID - random string which identifies the session
  153. * @param {string} localJid our JID
  154. * @param {string} remoteJid remote peer JID
  155. * @param {XmppConnection} connection - The XMPP connection instance.
  156. * @param mediaConstraints the media constraints object passed to createOffer/Answer, as defined
  157. * by the WebRTC standard
  158. * @param pcConfig The {@code RTCConfiguration} to use for the WebRTC peer connection.
  159. * @param {boolean} isP2P indicates whether this instance is meant to be used in a direct, peer to
  160. * peer connection or <tt>false</tt> if it's a JVB connection.
  161. * @param {boolean} isInitiator indicates if it will be the side which initiates the session.
  162. * @constructor
  163. *
  164. * @implements {SignalingLayer}
  165. */
  166. constructor(
  167. sid,
  168. localJid,
  169. remoteJid,
  170. connection,
  171. mediaConstraints,
  172. pcConfig,
  173. isP2P,
  174. isInitiator) {
  175. super(
  176. sid,
  177. localJid,
  178. remoteJid, connection, mediaConstraints, pcConfig, isInitiator);
  179. /**
  180. * The bridge session's identifier. One Jingle session can during
  181. * it's lifetime participate in multiple bridge sessions managed by
  182. * Jicofo. A new bridge session is started whenever Jicofo sends
  183. * 'session-initiate'.
  184. *
  185. * @type {?string}
  186. * @private
  187. */
  188. this._bridgeSessionId = null;
  189. /**
  190. * The oldest SDP passed to {@link notifyMySSRCUpdate} while the XMPP connection was offline that will be
  191. * used to update Jicofo once the XMPP connection goes back online.
  192. * @type {SDP|undefined}
  193. * @private
  194. */
  195. this._cachedOldLocalSdp = undefined;
  196. /**
  197. * The latest SDP passed to {@link notifyMySSRCUpdate} while the XMPP connection was offline that will be
  198. * used to update Jicofo once the XMPP connection goes back online.
  199. * @type {SDP|undefined}
  200. * @private
  201. */
  202. this._cachedNewLocalSdp = undefined;
  203. /**
  204. * Stores result of {@link window.performance.now()} at the time when
  205. * ICE enters 'checking' state.
  206. * @type {number|null} null if no value has been stored yet
  207. * @private
  208. */
  209. this._iceCheckingStartedTimestamp = null;
  210. /**
  211. * Stores result of {@link window.performance.now()} at the time when
  212. * first ICE candidate is spawned by the peerconnection to mark when
  213. * ICE gathering started. That's, because ICE gathering state changed
  214. * events are not supported by most of the browsers, so we try something
  215. * that will work everywhere. It may not be as accurate, but given that
  216. * 'host' candidate usually comes first, the delay should be minimal.
  217. * @type {number|null} null if no value has been stored yet
  218. * @private
  219. */
  220. this._gatheringStartedTimestamp = null;
  221. /**
  222. * Receiver constraints (max height) set by the application per remote source. Will be used for p2p connection.
  223. *
  224. * @type {Map<string, number>}
  225. */
  226. this._sourceReceiverConstraints = undefined;
  227. /**
  228. * Indicates whether or not this session is willing to send/receive
  229. * video media. When set to <tt>false</tt> the underlying peer
  230. * connection will disable local video transfer and the remote peer will
  231. * be will be asked to stop sending video via 'content-modify' IQ
  232. * (the senders attribute of video contents will be adjusted
  233. * accordingly). Note that this notification is sent only in P2P
  234. * session, because Jicofo does not support it yet. Obviously when
  235. * the value is changed from <tt>false</tt> to <tt>true</tt> another
  236. * notification will be sent to resume video transfer on the remote
  237. * side.
  238. * @type {boolean}
  239. * @private
  240. */
  241. this._localSendReceiveVideoActive = true;
  242. /**
  243. * Indicates whether or not the remote peer has video transfer active.
  244. * When set to <tt>true</tt> it means that remote peer is neither
  245. * sending nor willing to receive video. In such case we'll ask
  246. * our peerconnection to stop sending video by calling
  247. * {@link TraceablePeerConnection.setVideoTransferActive} with
  248. * <tt>false</tt>.
  249. * @type {boolean}
  250. * @private
  251. */
  252. this._remoteSendReceiveVideoActive = true;
  253. /**
  254. * Marks that ICE gathering duration has been reported already. That
  255. * prevents reporting it again.
  256. * @type {boolean}
  257. * @private
  258. */
  259. this._gatheringReported = false;
  260. this.lasticecandidate = false;
  261. this.closed = false;
  262. /**
  263. * Indicates whether or not this <tt>JingleSessionPC</tt> is used in
  264. * a peer to peer type of session.
  265. * @type {boolean} <tt>true</tt> if it's a peer to peer
  266. * session or <tt>false</tt> if it's a JVB session
  267. */
  268. this.isP2P = isP2P;
  269. /**
  270. * Remote preference for the receive video max frame height.
  271. *
  272. * @type {Number|undefined}
  273. */
  274. this.remoteRecvMaxFrameHeight = undefined;
  275. /**
  276. * Number of remote video sources, in SSRC rewriting mode.
  277. * Used to generate next unique msid attribute.
  278. *
  279. * @type {Number}
  280. */
  281. this.numRemoteVideoSources = 0;
  282. /**
  283. * Number of remote audio sources, in SSRC rewriting mode.
  284. * Used to generate next unique msid attribute.
  285. *
  286. * @type {Number}
  287. */
  288. this.numRemoteAudioSources = 0;
  289. /**
  290. * Remote preference for the receive video max frame heights when source-name signaling is enabled.
  291. *
  292. * @type {Map<string, number>|undefined}
  293. */
  294. this.remoteSourceMaxFrameHeights = undefined;
  295. /**
  296. * The queue used to serialize operations done on the peerconnection after the session is established.
  297. * The queue is paused until the first offer/answer cycle is complete. Only track or codec related
  298. * operations which necessitate a renegotiation cycle need to be pushed to the modification queue.
  299. * These tasks will be executed after the session has been established.
  300. *
  301. * @type {AsyncQueue}
  302. */
  303. this.modificationQueue = new AsyncQueue();
  304. this.modificationQueue.pause();
  305. /**
  306. * Flag used to guarantee that the connection established event is
  307. * triggered just once.
  308. * @type {boolean}
  309. */
  310. this.wasConnected = false;
  311. /**
  312. * Keeps track of how long (in ms) it took from ICE start to ICE
  313. * connect.
  314. *
  315. * @type {number}
  316. */
  317. this.establishmentDuration = undefined;
  318. this._xmppListeners = [];
  319. this._xmppListeners.push(
  320. connection.addCancellableListener(
  321. XmppConnection.Events.CONN_STATUS_CHANGED,
  322. this.onXmppStatusChanged.bind(this))
  323. );
  324. this._removeSenderVideoConstraintsChangeListener = undefined;
  325. }
  326. /**
  327. * Handles either Jingle 'source-add' or 'source-remove' message for this Jingle session.
  328. *
  329. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt> otherwise.
  330. * @param {Array<Element>} elem an array of Jingle "content" elements.
  331. * @returns {Promise} resolved when the operation is done or rejected with an error.
  332. * @private
  333. */
  334. _addOrRemoveRemoteStream(isAdd, elem) {
  335. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  336. const workFunction = finishedCallback => {
  337. if (!this.peerconnection.remoteDescription?.sdp) {
  338. const errMsg = `${logPrefix} - received before remoteDescription is set, ignoring!!`;
  339. logger.error(errMsg);
  340. finishedCallback(errMsg);
  341. return;
  342. }
  343. logger.log(`${this} Processing ${logPrefix}`);
  344. const currentRemoteSdp = new SDP(this.peerconnection.remoteDescription.sdp, this.isP2P);
  345. const sourceDescription = this._processSourceMapFromJingle(elem, isAdd);
  346. if (!sourceDescription.size) {
  347. logger.debug(`${this} ${logPrefix} - no sources to ${isAdd ? 'add' : 'remove'}`);
  348. finishedCallback();
  349. }
  350. logger.debug(`${isAdd ? 'adding' : 'removing'} sources=${Array.from(sourceDescription.keys())}`);
  351. // Update the remote description.
  352. const modifiedMids = currentRemoteSdp.updateRemoteSources(sourceDescription, isAdd);
  353. for (const mid of modifiedMids) {
  354. if (this.isP2P) {
  355. const { media } = SDPUtil.parseMLine(currentRemoteSdp.media[mid].split('\r\n')[0]);
  356. const desiredDirection = this.peerconnection.getDesiredMediaDirection(media, isAdd);
  357. const currentDirections = isAdd ? [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ]
  358. : [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ];
  359. currentDirections.forEach(direction => {
  360. currentRemoteSdp.media[mid] = currentRemoteSdp.media[mid]
  361. .replace(`a=${direction}`, `a=${desiredDirection}`);
  362. });
  363. currentRemoteSdp.raw = currentRemoteSdp.session + currentRemoteSdp.media.join('');
  364. }
  365. }
  366. this._renegotiate(currentRemoteSdp.raw).then(() => {
  367. logger.log(`${this} ${logPrefix} - OK`);
  368. finishedCallback();
  369. }, error => {
  370. logger.error(`${this} ${logPrefix} failed:`, error);
  371. finishedCallback(error);
  372. });
  373. };
  374. logger.debug(`${this} Queued ${logPrefix} task`);
  375. // Queue and execute
  376. this.modificationQueue.push(workFunction);
  377. }
  378. /**
  379. * See {@link addTrackToPc} and {@link removeTrackFromPc}.
  380. *
  381. * @param {boolean} isRemove <tt>true</tt> for "remove" operation or <tt>false</tt> for "add" operation.
  382. * @param {JitsiLocalTrack} track the track that will be added/removed.
  383. * @returns {Promise} resolved when the operation is done or rejected with an error.
  384. * @private
  385. */
  386. _addRemoveTrack(isRemove, track) {
  387. if (!track) {
  388. return Promise.reject('invalid "track" argument value');
  389. }
  390. const operationName = isRemove ? 'removeTrack' : 'addTrack';
  391. const workFunction = finishedCallback => {
  392. const tpc = this.peerconnection;
  393. if (!tpc) {
  394. finishedCallback(`Error: tried ${operationName} track with no active peer connection`);
  395. return;
  396. }
  397. const operationPromise
  398. = isRemove
  399. ? tpc.removeTrackFromPc(track)
  400. : tpc.addTrackToPc(track);
  401. operationPromise
  402. .then(shouldRenegotiate => {
  403. if (shouldRenegotiate) {
  404. this._renegotiate().then(finishedCallback);
  405. } else {
  406. finishedCallback();
  407. }
  408. },
  409. finishedCallback /* will be called with an error */);
  410. };
  411. logger.debug(`${this} Queued ${operationName} task`);
  412. return new Promise((resolve, reject) => {
  413. this.modificationQueue.push(
  414. workFunction,
  415. error => {
  416. if (error) {
  417. if (error instanceof ClearedQueueError) {
  418. // The session might have been terminated before the task was executed, making it obsolete.
  419. logger.debug(`${this} ${operationName} aborted: session terminated`);
  420. resolve();
  421. return;
  422. }
  423. logger.error(`${this} ${operationName} failed`);
  424. reject(error);
  425. } else {
  426. logger.debug(`${this} ${operationName} done`);
  427. resolve();
  428. }
  429. });
  430. });
  431. }
  432. /**
  433. * Checks whether or not this session instance is still operational.
  434. *
  435. * @returns {boolean} {@code true} if operation or {@code false} otherwise.
  436. * @private
  437. */
  438. _assertNotEnded() {
  439. return this.state !== JingleSessionState.ENDED;
  440. }
  441. /**
  442. * Takes in a jingle offer iq, returns the new sdp offer that can be set as remote description in the
  443. * peerconnection.
  444. *
  445. * @param {jquery xml element} offerIq the incoming offer.
  446. * @returns {SDP object} the jingle offer translated to SDP.
  447. * @private
  448. */
  449. _processNewJingleOfferIq(offerIq) {
  450. const remoteSdp = new SDP('', this.isP2P);
  451. if (this.webrtcIceTcpDisable) {
  452. remoteSdp.removeTcpCandidates = true;
  453. }
  454. if (this.webrtcIceUdpDisable) {
  455. remoteSdp.removeUdpCandidates = true;
  456. }
  457. if (this.failICE) {
  458. remoteSdp.failICE = true;
  459. }
  460. remoteSdp.fromJingle(offerIq);
  461. this._processSourceMapFromJingle($(offerIq).find('>content'));
  462. return remoteSdp;
  463. }
  464. /**
  465. * Parses the SSRC information from the source-add/source-remove element passed and updates the SSRC owners.
  466. *
  467. * @param {jquery xml element} sourceElement the source-add/source-remove element from jingle.
  468. * @param {boolean} isAdd true if the sources are being added, false if they are to be removed.
  469. * @returns {Map<string, Object>} - The map of source name to ssrcs, msid and groups.
  470. */
  471. _processSourceMapFromJingle(sourceElement, isAdd = true) {
  472. /**
  473. * Map of source name to ssrcs, mediaType, msid and groups.
  474. * @type {Map<string,
  475. * {
  476. * mediaType: string,
  477. * msid: string,
  478. * ssrcList: Array<number>,
  479. * groups: {semantics: string, ssrcs: Array<number>}
  480. * }>}
  481. */
  482. const sourceDescription = new Map();
  483. const sourceElementArray = Array.isArray(sourceElement) ? sourceElement : [ sourceElement ];
  484. for (const content of sourceElementArray) {
  485. const descriptionsWithSources = $(content).find('>description')
  486. .filter((_, el) => $(el).find('>source').length);
  487. for (const description of descriptionsWithSources) {
  488. const mediaType = $(description).attr('media');
  489. if (mediaType === MediaType.AUDIO && this.options.startSilent) {
  490. // eslint-disable-next-line no-continue
  491. continue;
  492. }
  493. const sources = $(description).find('>source');
  494. const removeSsrcs = [];
  495. for (const source of sources) {
  496. const ssrc = $(source).attr('ssrc');
  497. const sourceName = $(source).attr('name');
  498. const msid = $(source)
  499. .find('>parameter[name="msid"]')
  500. .attr('value');
  501. let videoType = $(source).attr('videoType');
  502. // If the videoType is DESKTOP_HIGH_FPS for remote tracks, we should treat it as DESKTOP.
  503. if (videoType === VideoType.DESKTOP_HIGH_FPS) {
  504. videoType = VideoType.DESKTOP;
  505. }
  506. if (sourceDescription.has(sourceName)) {
  507. sourceDescription.get(sourceName).ssrcList?.push(ssrc);
  508. } else {
  509. sourceDescription.set(sourceName, {
  510. groups: [],
  511. mediaType,
  512. msid,
  513. ssrcList: [ ssrc ],
  514. videoType
  515. });
  516. }
  517. // Update the source owner and source name.
  518. const owner = $(source)
  519. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  520. .attr('owner');
  521. if (owner && isAdd) {
  522. // JVB source-add.
  523. this._signalingLayer.setSSRCOwner(Number(ssrc), getEndpointId(owner), sourceName);
  524. } else if (isAdd) {
  525. // P2P source-add.
  526. this._signalingLayer.setSSRCOwner(Number(ssrc),
  527. Strophe.getResourceFromJid(this.remoteJid), sourceName);
  528. } else {
  529. removeSsrcs.push(Number(ssrc));
  530. }
  531. }
  532. // 'source-remove' from remote peer.
  533. removeSsrcs.length && this._signalingLayer.removeSSRCOwners(removeSsrcs);
  534. const groups = $(description).find('>ssrc-group');
  535. if (!groups.length) {
  536. continue; // eslint-disable-line no-continue
  537. }
  538. for (const group of groups) {
  539. const semantics = $(group).attr('semantics');
  540. const groupSsrcs = [];
  541. for (const source of $(group).find('>source')) {
  542. groupSsrcs.push($(source).attr('ssrc'));
  543. }
  544. for (const [ sourceName, { ssrcList } ] of sourceDescription) {
  545. if (isEqual(ssrcList.slice().sort(), groupSsrcs.slice().sort())) {
  546. sourceDescription.get(sourceName).groups.push({
  547. semantics,
  548. ssrcs: groupSsrcs
  549. });
  550. }
  551. }
  552. }
  553. }
  554. }
  555. sourceDescription.size && this.peerconnection.updateRemoteSources(sourceDescription, isAdd);
  556. return sourceDescription;
  557. }
  558. /**
  559. * Does a new offer/answer flow using the existing remote description (if not provided) and signals any new sources
  560. * to Jicofo or the remote peer.
  561. *
  562. * @param {string} [optionalRemoteSdp] optional, raw remote sdp to use. If not provided, the remote sdp from the
  563. * peerconnection will be used.
  564. * @returns {Promise} promise which resolves when the o/a flow is complete with no arguments or rejects with an
  565. * error {string}
  566. * @private
  567. */
  568. _renegotiate(optionalRemoteSdp) {
  569. if (this.peerconnection.signalingState === 'closed') {
  570. const error = new Error('Attempted to renegotiate in state closed');
  571. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  572. return Promise.reject(error);
  573. }
  574. const remoteSdp = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  575. if (!remoteSdp) {
  576. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  577. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  578. return Promise.reject(error);
  579. }
  580. const remoteDescription = {
  581. type: 'offer',
  582. sdp: remoteSdp
  583. };
  584. const oldLocalSDP = this.peerconnection.localDescription.sdp;
  585. logger.debug(`${this} Renegotiate: setting remote description`);
  586. return this.peerconnection.setRemoteDescription(remoteDescription)
  587. .then(() => {
  588. logger.debug(`${this} Renegotiate: creating answer`);
  589. return this.peerconnection.createAnswer(this.mediaConstraints);
  590. })
  591. .then(answer => {
  592. logger.debug(`${this} Renegotiate: setting local description`);
  593. return this.peerconnection.setLocalDescription(answer);
  594. })
  595. .then(() => {
  596. if (oldLocalSDP) {
  597. // Send the source updates after every renegotiation cycle.
  598. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(this.peerconnection.localDescription.sdp));
  599. }
  600. });
  601. }
  602. /**
  603. * Sends 'content-modify' IQ in order to ask the remote peer to either stop or resume sending video media or to
  604. * adjust sender's video constraints.
  605. *
  606. * @returns {void}
  607. * @private
  608. */
  609. _sendContentModify() {
  610. const senders = this._localSendReceiveVideoActive ? 'both' : 'none';
  611. const sessionModify
  612. = $iq({
  613. to: this.remoteJid,
  614. type: 'set'
  615. })
  616. .c('jingle', {
  617. xmlns: 'urn:xmpp:jingle:1',
  618. action: 'content-modify',
  619. initiator: this.initiatorJid,
  620. sid: this.sid
  621. })
  622. .c('content', {
  623. name: MediaType.VIDEO,
  624. senders
  625. });
  626. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  627. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  628. sessionModify
  629. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  630. .attrs({
  631. sourceName,
  632. maxHeight
  633. });
  634. sessionModify.up();
  635. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  636. });
  637. }
  638. logger.debug(sessionModify.tree());
  639. this.connection.sendIQ(
  640. sessionModify,
  641. null,
  642. this.newJingleErrorHandler(sessionModify),
  643. IQ_TIMEOUT);
  644. }
  645. /**
  646. * Sends given candidate in Jingle 'transport-info' message.
  647. *
  648. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  649. * @returns {void}
  650. * @private
  651. */
  652. _sendIceCandidate(candidate) {
  653. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  654. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  655. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  656. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  657. if (!(ice && jcand)) {
  658. logger.error('failed to get ice && jcand');
  659. return;
  660. }
  661. ice.xmlns = XEP.ICE_UDP_TRANSPORT;
  662. if (this.usedrip) {
  663. if (this.dripContainer.length === 0) {
  664. setTimeout(() => {
  665. if (this.dripContainer.length === 0) {
  666. return;
  667. }
  668. this._sendIceCandidates(this.dripContainer);
  669. this.dripContainer = [];
  670. }, ICE_CAND_GATHERING_TIMEOUT);
  671. }
  672. this.dripContainer.push(candidate);
  673. } else {
  674. this._sendIceCandidates([ candidate ]);
  675. }
  676. } else {
  677. logger.log(`${this} _sendIceCandidate: last candidate`);
  678. // FIXME: remember to re-think in ICE-restart
  679. this.lasticecandidate = true;
  680. }
  681. }
  682. /**
  683. * Sends given candidates in Jingle 'transport-info' message.
  684. *
  685. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE candidate instances.
  686. * @returns {void}
  687. * @private
  688. */
  689. _sendIceCandidates(candidates) {
  690. if (!this._assertNotEnded('_sendIceCandidates')) {
  691. return;
  692. }
  693. logger.log(`${this} _sendIceCandidates ${JSON.stringify(candidates)}`);
  694. const cand = $iq({ to: this.remoteJid,
  695. type: 'set' })
  696. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  697. action: 'transport-info',
  698. initiator: this.initiatorJid,
  699. sid: this.sid });
  700. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  701. for (let mid = 0; mid < localSDP.media.length; mid++) {
  702. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  703. const mline
  704. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  705. if (cands.length > 0) {
  706. const ice
  707. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  708. ice.xmlns = XEP.ICE_UDP_TRANSPORT;
  709. cand.c('content', {
  710. creator: this.initiatorJid === this.localJid
  711. ? 'initiator' : 'responder',
  712. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  713. }).c('transport', ice);
  714. for (let i = 0; i < cands.length; i++) {
  715. const candidate
  716. = SDPUtil.candidateToJingle(cands[i].candidate);
  717. // Mangle ICE candidate if 'failICE' test option is enabled
  718. if (this.failICE) {
  719. candidate.ip = '1.1.1.1';
  720. }
  721. cand.c('candidate', candidate).up();
  722. }
  723. // add fingerprint
  724. const fingerprintLine
  725. = SDPUtil.findLine(
  726. localSDP.media[mid],
  727. 'a=fingerprint:', localSDP.session);
  728. if (fingerprintLine) {
  729. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  730. tmp.required = true;
  731. cand.c(
  732. 'fingerprint',
  733. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  734. .t(tmp.fingerprint);
  735. delete tmp.fingerprint;
  736. cand.attrs(tmp);
  737. cand.up();
  738. }
  739. cand.up(); // transport
  740. cand.up(); // content
  741. }
  742. }
  743. // might merge last-candidate notification into this, but it is called
  744. // a lot later. See webrtc issue #2340
  745. // logger.log('was this the last candidate', this.lasticecandidate);
  746. this.connection.sendIQ(
  747. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  748. }
  749. /**
  750. * Sends Jingle 'session-accept' message.
  751. *
  752. * @param {function()} success callback called when we receive 'RESULT' packet for the 'session-accept'.
  753. * @param {function(error)} failure called when we receive an error response or when the request has timed out.
  754. * @returns {void}
  755. * @private
  756. */
  757. _sendSessionAccept(success, failure) {
  758. // NOTE: since we're just reading from it, we don't need to be within
  759. // the modification queue to access the local description
  760. const localSDP = new SDP(this.peerconnection.localDescription.sdp, this.isP2P);
  761. const accept = $iq({ to: this.remoteJid,
  762. type: 'set' })
  763. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  764. action: 'session-accept',
  765. initiator: this.initiatorJid,
  766. responder: this.responderJid,
  767. sid: this.sid });
  768. if (this.webrtcIceTcpDisable) {
  769. localSDP.removeTcpCandidates = true;
  770. }
  771. if (this.webrtcIceUdpDisable) {
  772. localSDP.removeUdpCandidates = true;
  773. }
  774. if (this.failICE) {
  775. localSDP.failICE = true;
  776. }
  777. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  778. localSDP.initialLastN = this.options.channelLastN;
  779. }
  780. localSDP.toJingle(
  781. accept,
  782. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  783. logger.info(`${this} Sending session-accept`);
  784. logger.debug(accept.tree());
  785. this.connection.sendIQ(accept,
  786. success,
  787. this.newJingleErrorHandler(accept, error => {
  788. failure(error);
  789. // 'session-accept' is a critical timeout and we'll
  790. // have to restart
  791. this.room.eventEmitter.emit(
  792. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  793. }),
  794. IQ_TIMEOUT);
  795. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  796. // fingerprint and setup) ASAP in order to start the connection
  797. // establishment.
  798. //
  799. // FIXME Flushing the connection at this point triggers an issue with
  800. // BOSH request handling in Prosody on slow connections.
  801. //
  802. // The problem is that this request will be quite large and it may take
  803. // time before it reaches Prosody. In the meantime Strophe may decide
  804. // to send the next one. And it was observed that a small request with
  805. // 'transport-info' usually follows this one. It does reach Prosody
  806. // before the previous one was completely received. 'rid' on the server
  807. // is increased and Prosody ignores the request with 'session-accept'.
  808. // It will never reach Jicofo and everything in the request table is
  809. // lost. Removing the flush does not guarantee it will never happen, but
  810. // makes it much less likely('transport-info' is bundled with
  811. // 'session-accept' and any immediate requests).
  812. //
  813. // this.connection.flush();
  814. }
  815. /**
  816. * Sends 'session-initiate' to the remote peer.
  817. *
  818. * NOTE this method is synchronous and we're not waiting for the RESULT
  819. * response which would delay the startup process.
  820. *
  821. * @param {string} offerSdp - The local session description which will be used to generate an offer.
  822. * @returns {void}
  823. * @private
  824. */
  825. _sendSessionInitiate(offerSdp) {
  826. let init = $iq({
  827. to: this.remoteJid,
  828. type: 'set'
  829. }).c('jingle', {
  830. xmlns: 'urn:xmpp:jingle:1',
  831. action: 'session-initiate',
  832. initiator: this.initiatorJid,
  833. sid: this.sid
  834. });
  835. new SDP(offerSdp, this.isP2P).toJingle(
  836. init,
  837. this.isInitiator ? 'initiator' : 'responder');
  838. init = init.tree();
  839. logger.debug(`${this} Session-initiate: `, init);
  840. this.connection.sendIQ(init,
  841. () => {
  842. logger.info(`${this} Got RESULT for "session-initiate"`);
  843. },
  844. error => {
  845. logger.error(`${this} "session-initiate" error`, error);
  846. },
  847. IQ_TIMEOUT);
  848. }
  849. /**
  850. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  851. *
  852. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  853. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  854. * 'session-accept' sent.
  855. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  856. * can be used to log some details about the error.
  857. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  858. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  859. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  860. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  861. * assumption that the initial offer/answer cycle has been executed already.
  862. */
  863. acceptOffer(jingleOffer, success, failure, localTracks = []) {
  864. this.setOfferAnswerCycle(
  865. jingleOffer,
  866. () => {
  867. // FIXME we may not care about RESULT packet for session-accept
  868. // then we should either call 'success' here immediately or
  869. // modify sendSessionAccept method to do that
  870. this._sendSessionAccept(() => {
  871. // Start processing tasks on the modification queue.
  872. logger.debug(`${this} Resuming the modification queue after session is established!`);
  873. this.modificationQueue.resume();
  874. success();
  875. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  876. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  877. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  878. // This will happen when someone shares a secondary source to a two people call, the other user
  879. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  880. // point, there are 2 video tracks which need to be signaled to the remote peer.
  881. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  882. videoTracks.length && videoTracks.splice(0, 1);
  883. videoTracks.length && this.addTracks(videoTracks);
  884. },
  885. error => {
  886. failure(error);
  887. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  888. });
  889. },
  890. failure,
  891. localTracks);
  892. }
  893. /**
  894. * {@inheritDoc}
  895. */
  896. addIceCandidates(elem) {
  897. if (this.peerconnection.signalingState === 'closed') {
  898. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  899. return;
  900. }
  901. const iceCandidates = [];
  902. elem.find('>content>transport>candidate')
  903. .each((idx, candidate) => {
  904. let line = SDPUtil.candidateFromJingle(candidate);
  905. line = line.replace('\r\n', '').replace('a=', '');
  906. // FIXME this code does not care to handle
  907. // non-bundle transport
  908. const rtcCandidate = new RTCIceCandidate({
  909. sdpMLineIndex: 0,
  910. // FF comes up with more complex names like audio-23423,
  911. // Given that it works on both Chrome and FF without
  912. // providing it, let's leave it like this for the time
  913. // being...
  914. // sdpMid: 'audio',
  915. sdpMid: '',
  916. candidate: line
  917. });
  918. iceCandidates.push(rtcCandidate);
  919. });
  920. if (!iceCandidates.length) {
  921. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  922. return;
  923. }
  924. // We want to have this task queued, so that we know it is executed,
  925. // after the initial sRD/sLD offer/answer cycle was done (based on
  926. // the assumption that candidates are spawned after the offer/answer
  927. // and XMPP preserves order).
  928. const workFunction = finishedCallback => {
  929. for (const iceCandidate of iceCandidates) {
  930. this.peerconnection.addIceCandidate(iceCandidate)
  931. .then(
  932. () => logger.debug(`${this} addIceCandidate ok!`),
  933. err => logger.error(`${this} addIceCandidate failed!`, err));
  934. }
  935. finishedCallback();
  936. logger.debug(`${this} ICE candidates task finished`);
  937. };
  938. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  939. this.modificationQueue.push(workFunction);
  940. }
  941. /**
  942. * Handles a Jingle source-add message for this Jingle session.
  943. *
  944. * @param {Array<Element>} elem an array of Jingle "content" elements.
  945. * @returns {Promise} resolved when the operation is done or rejected with an error.
  946. */
  947. addRemoteStream(elem) {
  948. this._addOrRemoveRemoteStream(true /* add */, elem);
  949. }
  950. /**
  951. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  952. * being added to the peerconnection for the first time.
  953. *
  954. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  955. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  956. * otherwise.
  957. */
  958. addTracks(localTracks = null) {
  959. if (!localTracks?.length) {
  960. Promise.reject(new Error('No tracks passed'));
  961. }
  962. const replaceTracks = [];
  963. const workFunction = finishedCallback => {
  964. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp, this.isP2P);
  965. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  966. .find(t => t.receiver.track.kind === MediaType.VIDEO
  967. && t.direction === MediaDirection.RECVONLY
  968. && t.currentDirection === MediaDirection.RECVONLY);
  969. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  970. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  971. // existing one in that case.
  972. for (const track of localTracks) {
  973. if (!this.isP2P || !recvOnlyTransceiver) {
  974. remoteSdp.addMlineForNewSource(track.getType());
  975. }
  976. }
  977. this._renegotiate(remoteSdp.raw)
  978. .then(() => {
  979. // Replace the tracks on the newly generated transceivers.
  980. for (const track of localTracks) {
  981. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  982. }
  983. return Promise.all(replaceTracks);
  984. })
  985. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  986. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  987. .then(() => this._renegotiate())
  988. .then(() => finishedCallback(), error => finishedCallback(error));
  989. };
  990. return new Promise((resolve, reject) => {
  991. logger.debug(`${this} Queued renegotiation after addTrack`);
  992. this.modificationQueue.push(
  993. workFunction,
  994. error => {
  995. if (error) {
  996. if (error instanceof ClearedQueueError) {
  997. // The session might have been terminated before the task was executed, making it obsolete.
  998. logger.debug(`${this} renegotiation after addTrack aborted: session terminated`);
  999. resolve();
  1000. return;
  1001. }
  1002. logger.error(`${this} renegotiation after addTrack error`, error);
  1003. reject(error);
  1004. } else {
  1005. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1006. resolve();
  1007. }
  1008. });
  1009. });
  1010. }
  1011. /**
  1012. * Adds local track back to the peerconnection associated with this session.
  1013. *
  1014. * @param {JitsiLocalTrack} track - the local track to be added back to the peerconnection.
  1015. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  1016. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  1017. * details in case something goes wrong.
  1018. * @returns {Promise<void>}
  1019. */
  1020. addTrackToPc(track) {
  1021. return this._addRemoveTrack(false /* add */, track)
  1022. .then(() => {
  1023. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  1024. // unmutes it the first time, all the parameters need to be configured.
  1025. if (track.isVideoTrack()) {
  1026. return this.peerconnection.configureVideoSenderEncodings(track);
  1027. }
  1028. });
  1029. }
  1030. /**
  1031. * Closes the underlying peerconnection and shuts down the modification queue.
  1032. *
  1033. * @returns {void}
  1034. */
  1035. close() {
  1036. this.state = JingleSessionState.ENDED;
  1037. this.establishmentDuration = undefined;
  1038. if (this.peerconnection) {
  1039. this.peerconnection.onicecandidate = null;
  1040. this.peerconnection.oniceconnectionstatechange = null;
  1041. this.peerconnection.onnegotiationneeded = null;
  1042. this.peerconnection.onsignalingstatechange = null;
  1043. }
  1044. logger.debug(`${this} Clearing modificationQueue`);
  1045. // Remove any pending tasks from the queue
  1046. this.modificationQueue.clear();
  1047. logger.debug(`${this} Queued PC close task`);
  1048. this.modificationQueue.push(finishCallback => {
  1049. // do not try to close if already closed.
  1050. this.peerconnection && this.peerconnection.close();
  1051. finishCallback();
  1052. logger.debug(`${this} PC close task done!`);
  1053. });
  1054. logger.debug(`${this} Shutdown modificationQueue!`);
  1055. // No more tasks can go in after the close task
  1056. this.modificationQueue.shutdown();
  1057. }
  1058. /**
  1059. * @inheritDoc
  1060. * @param {JingleSessionPCOptions} options - a set of config options.
  1061. * @returns {void}
  1062. */
  1063. doInitialize(options) {
  1064. this.failICE = Boolean(options.testing?.failICE);
  1065. this.lasticecandidate = false;
  1066. this.options = options;
  1067. /**
  1068. * {@code true} if reconnect is in progress.
  1069. * @type {boolean}
  1070. */
  1071. this.isReconnect = false;
  1072. /**
  1073. * Set to {@code true} if the connection was ever stable
  1074. * @type {boolean}
  1075. */
  1076. this.wasstable = false;
  1077. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  1078. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  1079. const pcOptions = { disableRtx: options.disableRtx };
  1080. if (options.gatherStats) {
  1081. pcOptions.maxstats = DEFAULT_MAX_STATS;
  1082. }
  1083. pcOptions.capScreenshareBitrate = false;
  1084. pcOptions.codecSettings = options.codecSettings;
  1085. pcOptions.enableInsertableStreams = options.enableInsertableStreams;
  1086. pcOptions.usesCodecSelectionAPI = this.usesCodecSelectionAPI
  1087. = browser.supportsCodecSelectionAPI()
  1088. && (options.testing?.enableCodecSelectionAPI ?? true)
  1089. && !this.isP2P;
  1090. if (options.videoQuality) {
  1091. const settings = Object.entries(options.videoQuality)
  1092. .map(entry => {
  1093. entry[0] = entry[0].toLowerCase();
  1094. return entry;
  1095. });
  1096. pcOptions.videoQuality = Object.fromEntries(settings);
  1097. }
  1098. pcOptions.forceTurnRelay = options.forceTurnRelay;
  1099. pcOptions.audioQuality = options.audioQuality;
  1100. pcOptions.disableSimulcast = this.isP2P ? true : options.disableSimulcast;
  1101. if (!this.isP2P) {
  1102. // Do not send lower spatial layers for low fps screenshare and enable them only for high fps screenshare.
  1103. pcOptions.capScreenshareBitrate = !(options.desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE);
  1104. }
  1105. if (options.startSilent) {
  1106. pcOptions.startSilent = true;
  1107. }
  1108. this.peerconnection
  1109. = this.rtc.createPeerConnection(
  1110. this._signalingLayer,
  1111. this.pcConfig,
  1112. this.isP2P,
  1113. pcOptions);
  1114. this.peerconnection.onicecandidate = ev => {
  1115. if (!ev) {
  1116. // There was an incomplete check for ev before which left
  1117. // the last line of the function unprotected from a potential
  1118. // throw of an exception. Consequently, it may be argued that
  1119. // the check is unnecessary. Anyway, I'm leaving it and making
  1120. // the check complete.
  1121. return;
  1122. }
  1123. // XXX this is broken, candidate is not parsed.
  1124. const candidate = ev.candidate;
  1125. const now = window.performance.now();
  1126. if (candidate) {
  1127. if (this._gatheringStartedTimestamp === null) {
  1128. this._gatheringStartedTimestamp = now;
  1129. }
  1130. // Discard candidates of disabled protocols.
  1131. let protocol = candidate.protocol;
  1132. if (typeof protocol === 'string') {
  1133. protocol = protocol.toLowerCase();
  1134. if (protocol === 'tcp' || protocol === 'ssltcp') {
  1135. if (this.webrtcIceTcpDisable) {
  1136. return;
  1137. }
  1138. } else if (protocol === 'udp') {
  1139. if (this.webrtcIceUdpDisable) {
  1140. return;
  1141. }
  1142. }
  1143. }
  1144. } else if (!this._gatheringReported) {
  1145. // End of gathering
  1146. Statistics.sendAnalytics(
  1147. ICE_DURATION,
  1148. {
  1149. phase: 'gathering',
  1150. value: now - this._gatheringStartedTimestamp,
  1151. p2p: this.isP2P,
  1152. initiator: this.isInitiator
  1153. });
  1154. this._gatheringReported = true;
  1155. }
  1156. if (this.isP2P) {
  1157. this._sendIceCandidate(candidate);
  1158. }
  1159. };
  1160. // Note there is a change in the spec about closed:
  1161. // This value moved into the RTCPeerConnectionState enum in
  1162. // the May 13, 2016 draft of the specification, as it reflects the state
  1163. // of the RTCPeerConnection, not the signaling connection. You now
  1164. // detect a closed connection by checking for connectionState to be
  1165. // "closed" instead.
  1166. // I suppose at some point this will be moved to onconnectionstatechange
  1167. this.peerconnection.onsignalingstatechange = () => {
  1168. if (this.peerconnection.signalingState === 'stable') {
  1169. this.wasstable = true;
  1170. } else if (this.peerconnection.signalingState === 'closed'
  1171. || this.peerconnection.connectionState === 'closed') {
  1172. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  1173. }
  1174. };
  1175. /**
  1176. * The oniceconnectionstatechange event handler contains the code to
  1177. * execute when the iceconnectionstatechange event, of type Event,
  1178. * is received by this RTCPeerConnection. Such an event is sent when
  1179. * the value of RTCPeerConnection.iceConnectionState changes.
  1180. */
  1181. this.peerconnection.oniceconnectionstatechange = () => {
  1182. const now = window.performance.now();
  1183. let isStable = false;
  1184. if (!this.isP2P) {
  1185. this.room.connectionTimes[
  1186. `ice.state.${this.peerconnection.iceConnectionState}`]
  1187. = now;
  1188. }
  1189. logger.log(`(TIME) ICE ${this.peerconnection.iceConnectionState} ${this.isP2P ? 'P2P' : 'JVB'}:\t`, now);
  1190. Statistics.sendAnalytics(
  1191. ICE_STATE_CHANGED,
  1192. {
  1193. p2p: this.isP2P,
  1194. state: this.peerconnection.iceConnectionState,
  1195. 'signaling_state': this.peerconnection.signalingState,
  1196. reconnect: this.isReconnect,
  1197. value: now
  1198. });
  1199. this.room.eventEmitter.emit(
  1200. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  1201. this,
  1202. this.peerconnection.iceConnectionState);
  1203. switch (this.peerconnection.iceConnectionState) {
  1204. case 'checking':
  1205. this._iceCheckingStartedTimestamp = now;
  1206. break;
  1207. case 'connected':
  1208. case 'completed':
  1209. // Informs interested parties that the connection has been restored. This includes the case when
  1210. // media connection to the bridge has been restored after an ICE failure by using session-terminate.
  1211. if (this.peerconnection.signalingState === 'stable') {
  1212. isStable = true;
  1213. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED, this);
  1214. }
  1215. // Add a workaround for an issue on chrome in Unified plan when the local endpoint is the offerer.
  1216. // The 'signalingstatechange' event for 'stable' is handled after the 'iceconnectionstatechange' event
  1217. // for 'completed' is handled by the client. This prevents the client from firing a
  1218. // CONNECTION_ESTABLISHED event for the p2p session. As a result, the offerer continues to stay on the
  1219. // jvb connection while the remote peer switches to the p2p connection breaking the media flow between
  1220. // the endpoints.
  1221. // TODO - file a chromium bug and add the information here.
  1222. if (!this.wasConnected
  1223. && (this.wasstable
  1224. || isStable
  1225. || (this.isInitiator && (browser.isChromiumBased() || browser.isReactNative())))) {
  1226. Statistics.sendAnalytics(
  1227. ICE_DURATION,
  1228. {
  1229. phase: 'checking',
  1230. value: now - this._iceCheckingStartedTimestamp,
  1231. p2p: this.isP2P,
  1232. initiator: this.isInitiator
  1233. });
  1234. // Switch between ICE gathering and ICE checking whichever
  1235. // started first (scenarios are different for initiator
  1236. // vs responder)
  1237. const iceStarted
  1238. = Math.min(
  1239. this._iceCheckingStartedTimestamp,
  1240. this._gatheringStartedTimestamp);
  1241. this.establishmentDuration = now - iceStarted;
  1242. Statistics.sendAnalytics(
  1243. ICE_DURATION,
  1244. {
  1245. phase: 'establishment',
  1246. value: this.establishmentDuration,
  1247. p2p: this.isP2P,
  1248. initiator: this.isInitiator
  1249. });
  1250. this.wasConnected = true;
  1251. this.room.eventEmitter.emit(
  1252. XMPPEvents.CONNECTION_ESTABLISHED, this);
  1253. }
  1254. this.isReconnect = false;
  1255. break;
  1256. case 'disconnected':
  1257. this.isReconnect = true;
  1258. // Informs interested parties that the connection has been
  1259. // interrupted.
  1260. if (this.wasstable) {
  1261. this.room.eventEmitter.emit(
  1262. XMPPEvents.CONNECTION_INTERRUPTED, this);
  1263. }
  1264. break;
  1265. case 'failed':
  1266. this.room.eventEmitter.emit(
  1267. XMPPEvents.CONNECTION_ICE_FAILED, this);
  1268. break;
  1269. }
  1270. };
  1271. /**
  1272. * The connection state event is fired whenever the aggregate of underlying
  1273. * transports change their state.
  1274. */
  1275. this.peerconnection.onconnectionstatechange = () => {
  1276. const icestate = this.peerconnection.iceConnectionState;
  1277. logger.log(`(TIME) ${this.isP2P ? 'P2P' : 'JVB'} PC state is now ${this.peerconnection.connectionState} `
  1278. + `(ICE state ${this.peerconnection.iceConnectionState}):\t`, window.performance.now());
  1279. switch (this.peerconnection.connectionState) {
  1280. case 'failed':
  1281. // Since version 76 Chrome no longer switches ICE connection
  1282. // state to failed (see
  1283. // https://bugs.chromium.org/p/chromium/issues/detail?id=982793
  1284. // for details) we use this workaround to recover from lost connections
  1285. if (icestate === 'disconnected') {
  1286. this.room.eventEmitter.emit(
  1287. XMPPEvents.CONNECTION_ICE_FAILED, this);
  1288. }
  1289. break;
  1290. }
  1291. };
  1292. /**
  1293. * The negotiationneeded event is fired whenever we shake the media on the
  1294. * RTCPeerConnection object.
  1295. */
  1296. this.peerconnection.onnegotiationneeded = () => {
  1297. const state = this.peerconnection.signalingState;
  1298. const remoteDescription = this.peerconnection.remoteDescription;
  1299. if (!this.isP2P
  1300. && state === 'stable'
  1301. && remoteDescription
  1302. && typeof remoteDescription.sdp === 'string') {
  1303. logger.info(`${this} onnegotiationneeded fired on ${this.peerconnection}`);
  1304. const workFunction = finishedCallback => {
  1305. this._renegotiate()
  1306. .then(() => this.peerconnection.configureAudioSenderEncodings())
  1307. .then(() => finishedCallback(), error => finishedCallback(error));
  1308. };
  1309. this.modificationQueue.push(
  1310. workFunction,
  1311. error => {
  1312. if (error) {
  1313. logger.error(`${this} onnegotiationneeded error`, error);
  1314. } else {
  1315. logger.debug(`${this} onnegotiationneeded executed - OK`);
  1316. }
  1317. });
  1318. }
  1319. };
  1320. }
  1321. /**
  1322. * Returns the ice connection state for the peer connection.
  1323. *
  1324. * @returns the ice connection state for the peer connection.
  1325. */
  1326. getIceConnectionState() {
  1327. return this.peerconnection.getConnectionState();
  1328. }
  1329. /**
  1330. * Returns the preference for max frame height for the remote video sources.
  1331. *
  1332. * @returns {Map<string, number>|undefined}
  1333. */
  1334. getRemoteSourcesRecvMaxFrameHeight() {
  1335. if (this.isP2P) {
  1336. return this.remoteSourceMaxFrameHeights;
  1337. }
  1338. return undefined;
  1339. }
  1340. /**
  1341. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  1342. *
  1343. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  1344. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  1345. * @returns {void}
  1346. */
  1347. invite(localTracks = []) {
  1348. if (!this.isInitiator) {
  1349. throw new Error('Trying to invite from the responder session');
  1350. }
  1351. logger.debug(`${this} Executing invite task`);
  1352. const addTracks = [];
  1353. for (const track of localTracks) {
  1354. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1355. }
  1356. Promise.all(addTracks)
  1357. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  1358. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  1359. .then(() => {
  1360. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  1361. this._sendSessionInitiate(this.peerconnection.localDescription.sdp);
  1362. })
  1363. .then(() => {
  1364. logger.debug(`${this} invite executed - OK`);
  1365. })
  1366. .catch(error => {
  1367. logger.error(`${this} invite error`, error);
  1368. });
  1369. }
  1370. /**
  1371. * Enables/disables local video based on 'senders' attribute of the video conent in 'content-modify' IQ sent by the
  1372. * remote peer. Also, checks if the sourceMaxFrameHeight (as requested by the p2p peer) or the senders attribute of
  1373. * the video content has changed and modifies the local video resolution accordingly.
  1374. *
  1375. * @param {Element} jingleContents - The content of the 'content-modify' IQ sent by the remote peer.
  1376. * @returns {void}
  1377. */
  1378. modifyContents(jingleContents) {
  1379. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  1380. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  1381. if (sourceMaxFrameHeights) {
  1382. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  1383. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  1384. }
  1385. if (newVideoSenders === null) {
  1386. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  1387. return;
  1388. }
  1389. if (!this._assertNotEnded()) {
  1390. return;
  1391. }
  1392. const isRemoteVideoActive
  1393. = newVideoSenders === 'both'
  1394. || (newVideoSenders === 'initiator' && this.isInitiator)
  1395. || (newVideoSenders === 'responder' && !this.isInitiator);
  1396. if (isRemoteVideoActive !== this._remoteSendReceiveVideoActive) {
  1397. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  1398. this._remoteSendReceiveVideoActive = isRemoteVideoActive;
  1399. this.peerconnection
  1400. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  1401. }
  1402. }
  1403. /**
  1404. * Method returns function(errorResponse) which is a callback to be passed to Strophe connection.sendIQ method. An
  1405. * 'error' structure is created that is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1406. * structure is as follows:
  1407. * {
  1408. * code: {XMPP error response code}
  1409. * reason: {the name of XMPP error reason element or 'timeout' if the
  1410. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1411. * source: {request.tree() that provides original request}
  1412. * session: {this JingleSessionPC.toString()}
  1413. * }
  1414. * @param request Strophe IQ instance which is the request to be dumped into the error structure.
  1415. * @param failureCb function(error) called when error response was returned or when a timeout has occurred.
  1416. * @returns {function(this:JingleSessionPC)}
  1417. */
  1418. newJingleErrorHandler(request, failureCb) {
  1419. return errResponse => {
  1420. const error = {};
  1421. // Get XMPP error code and condition(reason)
  1422. const errorElSel = $(errResponse).find('error');
  1423. if (errorElSel.length) {
  1424. error.code = errorElSel.attr('code');
  1425. const errorReasonSel = $(errResponse).find('error :first');
  1426. if (errorReasonSel.length) {
  1427. error.reason = errorReasonSel[0].tagName;
  1428. }
  1429. const errorMsgSel = errorElSel.find('>text');
  1430. if (errorMsgSel.length) {
  1431. error.msg = errorMsgSel.text();
  1432. }
  1433. }
  1434. if (!errResponse) {
  1435. error.reason = 'timeout';
  1436. }
  1437. error.session = this.toString();
  1438. if (failureCb) {
  1439. failureCb(error);
  1440. } else if (this.state === JingleSessionState.ENDED
  1441. && error.reason === 'item-not-found') {
  1442. // When remote peer decides to terminate the session, but it
  1443. // still have few messages on the queue for processing,
  1444. // it will first send us 'session-terminate' (we enter ENDED)
  1445. // and then follow with 'item-not-found' for the queued requests
  1446. // We don't want to have that logged on error level.
  1447. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  1448. } else {
  1449. logger.error(`Jingle error: ${JSON.stringify(error)}`);
  1450. }
  1451. };
  1452. }
  1453. /**
  1454. * Figures out added/removed ssrcs and sends updated IQs to the remote peer or Jicofo.
  1455. *
  1456. * @param oldSDP SDP object for old description.
  1457. * @param newSDP SDP object for new description.
  1458. * @returns {void}
  1459. */
  1460. notifyMySSRCUpdate(oldSDP, newSDP) {
  1461. if (this.state !== JingleSessionState.ACTIVE) {
  1462. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  1463. return;
  1464. }
  1465. if (!this.connection.connected) {
  1466. // The goal is to compare the oldest SDP with the latest one upon reconnect
  1467. if (!this._cachedOldLocalSdp) {
  1468. this._cachedOldLocalSdp = oldSDP;
  1469. }
  1470. this._cachedNewLocalSdp = newSDP;
  1471. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  1472. return;
  1473. }
  1474. this._cachedOldLocalSdp = undefined;
  1475. this._cachedNewLocalSdp = undefined;
  1476. const getSignaledSourceInfo = sdpDiffer => {
  1477. const newMedia = sdpDiffer.getNewMedia();
  1478. let ssrcs = [];
  1479. let mediaType = null;
  1480. // It is assumed that sources are signaled one at a time.
  1481. Object.keys(newMedia).forEach(mediaIndex => {
  1482. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  1483. mediaType = newMedia[mediaIndex].mediaType;
  1484. if (signaledSsrcs?.length) {
  1485. ssrcs = ssrcs.concat(signaledSsrcs);
  1486. }
  1487. });
  1488. return {
  1489. mediaType,
  1490. ssrcs
  1491. };
  1492. };
  1493. // send source-remove IQ.
  1494. let sdpDiffer = new SDPDiffer(newSDP, oldSDP, this.isP2P);
  1495. const remove = $iq({ to: this.remoteJid,
  1496. type: 'set' })
  1497. .c('jingle', {
  1498. xmlns: 'urn:xmpp:jingle:1',
  1499. action: 'source-remove',
  1500. initiator: this.initiatorJid,
  1501. sid: this.sid
  1502. }
  1503. );
  1504. sdpDiffer.toJingle(remove);
  1505. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  1506. // need to
  1507. const ctx = {};
  1508. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  1509. if (removedSsrcInfo.ssrcs.length) {
  1510. // Log only the SSRCs instead of the full IQ.
  1511. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  1512. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  1513. this.connection.sendIQ(
  1514. remove,
  1515. () => {
  1516. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  1517. },
  1518. this.newJingleErrorHandler(remove, error => {
  1519. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  1520. }),
  1521. IQ_TIMEOUT);
  1522. }
  1523. // send source-add IQ.
  1524. sdpDiffer = new SDPDiffer(oldSDP, newSDP, this.isP2P);
  1525. const add = $iq({ to: this.remoteJid,
  1526. type: 'set' })
  1527. .c('jingle', {
  1528. xmlns: 'urn:xmpp:jingle:1',
  1529. action: 'source-add',
  1530. initiator: this.initiatorJid,
  1531. sid: this.sid
  1532. }
  1533. );
  1534. sdpDiffer.toJingle(add);
  1535. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  1536. if (addedSsrcInfo.ssrcs.length) {
  1537. // Log only the SSRCs instead of the full IQ.
  1538. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  1539. this.connection.sendIQ(
  1540. add,
  1541. () => {
  1542. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  1543. },
  1544. this.newJingleErrorHandler(add, error => {
  1545. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  1546. }),
  1547. IQ_TIMEOUT);
  1548. }
  1549. }
  1550. /**
  1551. * Handles the termination of the session.
  1552. *
  1553. * @param {string} reasonCondition - The XMPP Jingle reason condition.
  1554. * @param {string} reasonText - The XMPP Jingle reason text.
  1555. * @returns {void}
  1556. */
  1557. onTerminated(reasonCondition, reasonText) {
  1558. // Do something with reason and reasonCondition when we start to care
  1559. // this.reasonCondition = reasonCondition;
  1560. // this.reasonText = reasonText;
  1561. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1562. this._xmppListeners.forEach(removeListener => removeListener());
  1563. this._xmppListeners = [];
  1564. if (this._removeSenderVideoConstraintsChangeListener) {
  1565. this._removeSenderVideoConstraintsChangeListener();
  1566. }
  1567. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1568. this.peerconnection.getRemoteTracks().forEach(track => {
  1569. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1570. });
  1571. }
  1572. this.close();
  1573. }
  1574. /**
  1575. * Handles XMPP connection state changes. Resends any session updates that were cached while the XMPP connection
  1576. * was down.
  1577. *
  1578. * @param {XmppConnection.Status} status - The new status.
  1579. * @returns {void}
  1580. */
  1581. onXmppStatusChanged(status) {
  1582. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1583. logger.info(`${this} Sending SSRC update on reconnect`);
  1584. this.notifyMySSRCUpdate(
  1585. this._cachedOldLocalSdp,
  1586. this._cachedNewLocalSdp);
  1587. }
  1588. }
  1589. /**
  1590. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1591. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1592. *
  1593. * @param {Object} message - The source map message.
  1594. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1595. * @returns {void}
  1596. */
  1597. processSourceMap(message, mediaType) {
  1598. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1599. return;
  1600. }
  1601. if (mediaType === MediaType.AUDIO && this.options.startSilent) {
  1602. return;
  1603. }
  1604. const newSsrcs = [];
  1605. for (const src of message.mappedSources) {
  1606. const { owner, source, ssrc } = src;
  1607. const isNewSsrc = this.peerconnection.addRemoteSsrc(ssrc, source);
  1608. if (isNewSsrc) {
  1609. newSsrcs.push(src);
  1610. logger.debug(`New SSRC signaled ${ssrc}: owner=${owner}, source-name=${source}`);
  1611. // Check if there is an old mapping for the given source and clear the owner on the associated track.
  1612. const oldSsrc = this.peerconnection.remoteSources.get(source);
  1613. if (oldSsrc) {
  1614. this._signalingLayer.removeSSRCOwners([ oldSsrc ]);
  1615. const track = this.peerconnection.getTrackBySSRC(oldSsrc);
  1616. if (track) {
  1617. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_SET, track);
  1618. }
  1619. }
  1620. } else {
  1621. const track = this.peerconnection.getTrackBySSRC(ssrc);
  1622. if (!track || (track.getParticipantId() === owner && track.getSourceName() === source)) {
  1623. !track && logger.warn(`Remote track for SSRC=${ssrc} hasn't been created yet,`
  1624. + 'not processing the source map');
  1625. continue; // eslint-disable-line no-continue
  1626. }
  1627. logger.debug(`Existing SSRC re-mapped ${ssrc}: new owner=${owner}, source-name=${source}`);
  1628. this._signalingLayer.setSSRCOwner(ssrc, owner, source);
  1629. const oldSourceName = track.getSourceName();
  1630. const sourceInfo = this.peerconnection.getRemoteSourceInfoBySourceName(oldSourceName);
  1631. // Update the SSRC map on the peerconnection.
  1632. if (sourceInfo) {
  1633. this.peerconnection.updateRemoteSources(new Map([ [ oldSourceName, sourceInfo ] ]), false);
  1634. this.peerconnection.updateRemoteSources(new Map([ [ source, sourceInfo ] ]), true /* isAdd */);
  1635. }
  1636. // Update the muted state and the video type on the track since the presence for this track could have
  1637. // been received before the updated source map is received on the bridge channel.
  1638. const { muted, videoType } = this._signalingLayer.getPeerMediaInfo(owner, mediaType, source);
  1639. muted && this.peerconnection._sourceMutedChanged(source, muted);
  1640. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_SET, track, owner, source, videoType);
  1641. }
  1642. }
  1643. // Add the new SSRCs to the remote description by generating a source message.
  1644. if (newSsrcs.length) {
  1645. let node = $build('content', {
  1646. xmlns: 'urn:xmpp:jingle:1',
  1647. name: mediaType
  1648. }).c('description', {
  1649. xmlns: XEP.RTP_MEDIA,
  1650. media: mediaType
  1651. });
  1652. for (const src of newSsrcs) {
  1653. const { rtx, ssrc, source } = src;
  1654. let msid;
  1655. if (mediaType === MediaType.VIDEO) {
  1656. const idx = ++this.numRemoteVideoSources;
  1657. msid = `remote-video-${idx} remote-video-${idx}`;
  1658. if (rtx !== '-1') {
  1659. _addSourceElement(node, src, rtx, msid);
  1660. node.c('ssrc-group', {
  1661. xmlns: XEP.SOURCE_ATTRIBUTES,
  1662. semantics: SSRC_GROUP_SEMANTICS.FID
  1663. })
  1664. .c('source', {
  1665. xmlns: XEP.SOURCE_ATTRIBUTES,
  1666. ssrc
  1667. })
  1668. .up()
  1669. .c('source', {
  1670. xmlns: XEP.SOURCE_ATTRIBUTES,
  1671. ssrc: rtx
  1672. })
  1673. .up()
  1674. .up();
  1675. }
  1676. } else {
  1677. const idx = ++this.numRemoteAudioSources;
  1678. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1679. }
  1680. _addSourceElement(node, src, ssrc, msid);
  1681. this.peerconnection.remoteSources.set(source, ssrc);
  1682. }
  1683. node = node.up();
  1684. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1685. }
  1686. }
  1687. /**
  1688. * Handles a Jingle source-remove message for this Jingle session.
  1689. *
  1690. * @param {Array<Element>} contents - An array of content elements from the source-remove message.
  1691. * @returns {void}
  1692. */
  1693. removeRemoteStream(elem) {
  1694. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1695. }
  1696. /**
  1697. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1698. *
  1699. * @param {string} id Endpoint id of the participant that has left the call.
  1700. * @returns {void}
  1701. */
  1702. removeRemoteStreamsOnLeave(id) {
  1703. const workFunction = finishCallback => {
  1704. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1705. if (removeSsrcInfo.size) {
  1706. logger.debug(`${this} Removing SSRCs for user ${id}, sources=${Array.from(removeSsrcInfo.keys())}`);
  1707. const newRemoteSdp = new SDP(this.peerconnection.remoteDescription.sdp, this.isP2P);
  1708. newRemoteSdp.updateRemoteSources(removeSsrcInfo, false /* isAdd */);
  1709. this.peerconnection.updateRemoteSources(removeSsrcInfo, false /* isAdd */);
  1710. this._renegotiate(newRemoteSdp.raw)
  1711. .then(() => finishCallback(), error => finishCallback(error));
  1712. } else {
  1713. finishCallback();
  1714. }
  1715. };
  1716. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1717. this.modificationQueue.push(
  1718. workFunction,
  1719. error => {
  1720. if (error) {
  1721. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1722. } else {
  1723. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1724. }
  1725. });
  1726. }
  1727. /**
  1728. * Removes local track from the peerconnection as part of the mute operation.
  1729. *
  1730. * @param {JitsiLocalTrack} track the local track to be removed.
  1731. * @return {Promise} a promise which will be resolved once the local track is removed from this session or rejected
  1732. * with a <tt>string</tt> that the describes the error if anything goes wrong.
  1733. */
  1734. removeTrackFromPc(track) {
  1735. return this._addRemoveTrack(true /* remove */, track);
  1736. }
  1737. /**
  1738. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single offer/answer cycle (if needed) after
  1739. * both operations are done.
  1740. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid <tt>oldTrack</tt> with a null
  1741. * <tt>newTrack</tt> effectively just removes <tt>oldTrack</tt>.
  1742. *
  1743. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be replaced.
  1744. * @param {JitsiLocalTrack|null} newTrack the new track to use.
  1745. * @returns {Promise} which resolves once the replacement is complete with no arguments or rejects with an error.
  1746. */
  1747. replaceTrack(oldTrack, newTrack) {
  1748. const workFunction = finishedCallback => {
  1749. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  1750. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1751. .then(shouldRenegotiate => {
  1752. let promise = Promise.resolve();
  1753. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  1754. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  1755. if (shouldRenegotiate && (oldTrack || newTrack) && this.state === JingleSessionState.ACTIVE) {
  1756. promise = this._renegotiate();
  1757. }
  1758. return promise.then(() => {
  1759. // Set the source name of the new track.
  1760. if (oldTrack && newTrack && oldTrack.isVideoTrack()) {
  1761. newTrack.setSourceName(oldTrack.getSourceName());
  1762. }
  1763. });
  1764. })
  1765. .then(() => finishedCallback(), error => finishedCallback(error));
  1766. };
  1767. return new Promise((resolve, reject) => {
  1768. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  1769. this.modificationQueue.push(
  1770. workFunction,
  1771. error => {
  1772. if (error) {
  1773. if (error instanceof ClearedQueueError) {
  1774. // The session might have been terminated before the task was executed, making it obsolete.
  1775. logger.debug('Replace track aborted: session terminated');
  1776. resolve();
  1777. return;
  1778. }
  1779. logger.error(`${this} Replace track error:`, error);
  1780. reject(error);
  1781. } else {
  1782. logger.info(`${this} Replace track done!`);
  1783. resolve();
  1784. }
  1785. });
  1786. });
  1787. }
  1788. /**
  1789. * Sets the answer received from the remote peer as the remote description.
  1790. *
  1791. * @param {Element} jingleAnswer - The jingle answer element.
  1792. * @returns {void}
  1793. * @throws {Error} if the method is called on a responder session.
  1794. */
  1795. setAnswer(jingleAnswer) {
  1796. if (!this.isInitiator) {
  1797. throw new Error('Trying to set an answer on the responder session');
  1798. }
  1799. logger.debug(`${this} Executing setAnswer task`);
  1800. const newRemoteSdp = this._processNewJingleOfferIq(jingleAnswer);
  1801. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1802. const remoteDescription = {
  1803. type: 'answer',
  1804. sdp: newRemoteSdp.raw
  1805. };
  1806. this.peerconnection.setRemoteDescription(remoteDescription)
  1807. .then(() => {
  1808. if (this.state === JingleSessionState.PENDING) {
  1809. this.state = JingleSessionState.ACTIVE;
  1810. // Start processing tasks on the modification queue.
  1811. logger.debug(`${this} Resuming the modification queue after session is established!`);
  1812. this.modificationQueue.resume();
  1813. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1814. this._sendContentModify();
  1815. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1816. }
  1817. })
  1818. .then(() => {
  1819. logger.debug(`${this} setAnswer task done`);
  1820. })
  1821. .catch(error => {
  1822. logger.error(`${this} setAnswer task failed: ${error}`);
  1823. });
  1824. }
  1825. /**
  1826. * Resumes or suspends media transfer over the underlying peer connection.
  1827. *
  1828. * @param {boolean} active - <tt>true</tt> to enable media transfer or <tt>false</tt> to suspend media transmission.
  1829. * @returns {Promise}
  1830. */
  1831. setMediaTransferActive(active) {
  1832. const changed = this.peerconnection.audioTransferActive !== active
  1833. || this.peerconnection.videoTransferActive !== active;
  1834. if (!changed) {
  1835. return Promise.resolve();
  1836. }
  1837. return this.peerconnection.setMediaTransferActive(active)
  1838. .then(() => {
  1839. this.peerconnection.audioTransferActive = active;
  1840. this.peerconnection.videoTransferActive = active;
  1841. // Reconfigure the audio and video tracks so that only the correct encodings are active.
  1842. const promises = [];
  1843. promises.push(this.peerconnection.configureVideoSenderEncodings());
  1844. promises.push(this.peerconnection.configureAudioSenderEncodings());
  1845. return Promise.allSettled(promises);
  1846. });
  1847. }
  1848. /**
  1849. * This is a setRemoteDescription/setLocalDescription cycle which starts at converting Strophe Jingle IQ into
  1850. * remote offer SDP. Once converted, setRemoteDescription, createAnswer and setLocalDescription calls follow.
  1851. *
  1852. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element of the offer (or answer) IQ
  1853. * @param success callback called when sRD/sLD cycle finishes successfully.
  1854. * @param failure callback called with an error object as an argument if we fail at any point during setRD,
  1855. * createAnswer, setLD.
  1856. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  1857. * the offer/answer cycle executes (for the local track addition to be an atomic operation together with the
  1858. * offer/answer).
  1859. * @returns {void}
  1860. */
  1861. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  1862. logger.debug(`${this} Executing setOfferAnswerCycle task`);
  1863. const addTracks = [];
  1864. const audioTracks = localTracks.filter(track => track.getType() === MediaType.AUDIO);
  1865. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  1866. let tracks = localTracks;
  1867. // Add only 1 video track at a time. Adding 2 or more video tracks to the peerconnection at the same time
  1868. // makes the browser go into a renegotiation loop by firing 'negotiationneeded' event after every
  1869. // renegotiation.
  1870. if (videoTracks.length > 1) {
  1871. tracks = [ ...audioTracks, videoTracks[0] ];
  1872. }
  1873. for (const track of tracks) {
  1874. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1875. }
  1876. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  1877. const bridgeSession = $(jingleOfferAnswerIq).find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]');
  1878. const bridgeSessionId = bridgeSession.attr('id');
  1879. if (bridgeSessionId !== this._bridgeSessionId) {
  1880. this._bridgeSessionId = bridgeSessionId;
  1881. }
  1882. Promise.all(addTracks)
  1883. .then(() => this._renegotiate(newRemoteSdp.raw))
  1884. .then(() => {
  1885. this.peerconnection.processLocalSdpForTransceiverInfo(tracks);
  1886. if (this.state === JingleSessionState.PENDING) {
  1887. this.state = JingleSessionState.ACTIVE;
  1888. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1889. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1890. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1891. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1892. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1893. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1894. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1895. if (this.isP2P && (!this._localSendReceiveVideoActive || this._sourceReceiverConstraints)) {
  1896. this._sendContentModify();
  1897. }
  1898. }
  1899. })
  1900. .then(() => {
  1901. logger.debug(`${this} setOfferAnswerCycle task done`);
  1902. success();
  1903. })
  1904. .catch(error => {
  1905. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1906. failure(error);
  1907. });
  1908. }
  1909. /**
  1910. * Resumes or suspends video media transfer over the p2p peer connection.
  1911. *
  1912. * @param {boolean} videoActive <tt>true</tt> to enable video media transfer or <tt>false</tt> to suspend video
  1913. * media transmission.
  1914. * @return {Promise} a <tt>Promise</tt> which will resolve once the operation is done. It will be rejected with
  1915. * an error description as a string in case anything goes wrong.
  1916. */
  1917. setP2pVideoTransferActive(videoActive) {
  1918. if (!this.peerconnection) {
  1919. return Promise.reject('Can not modify video transfer active state,'
  1920. + ' before "initialize" is called');
  1921. }
  1922. if (this._localSendReceiveVideoActive !== videoActive) {
  1923. this._localSendReceiveVideoActive = videoActive;
  1924. if (this.isP2P && this.state === JingleSessionState.ACTIVE) {
  1925. this._sendContentModify();
  1926. }
  1927. return this.peerconnection
  1928. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  1929. }
  1930. return Promise.resolve();
  1931. }
  1932. /**
  1933. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1934. * the remote p2p peer.
  1935. *
  1936. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1937. * @returns {void}
  1938. */
  1939. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1940. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1941. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1942. if (this.isP2P) {
  1943. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1944. // be synced after offer/answer.
  1945. if (this.state === JingleSessionState.ACTIVE) {
  1946. this._sendContentModify();
  1947. }
  1948. }
  1949. }
  1950. /**
  1951. * Sets the resolution constraint on the local video tracks.
  1952. *
  1953. * @param {number} maxFrameHeight - The user preferred max frame height.
  1954. * @param {string} sourceName - The source name of the track.
  1955. * @returns {Promise} promise that will be resolved when the operation is
  1956. * successful and rejected otherwise.
  1957. */
  1958. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1959. if (this._assertNotEnded()) {
  1960. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1961. const jitsiLocalTrack = sourceName
  1962. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1963. : this.rtc.getLocalVideoTrack();
  1964. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1965. }
  1966. return Promise.resolve();
  1967. }
  1968. /**
  1969. * Updates the codecs on the peerconnection and initiates a renegotiation (if needed) for the
  1970. * new codec config to take effect.
  1971. *
  1972. * @param {Array<CodecMimeType>} codecList - Preferred codecs for video.
  1973. * @param {CodecMimeType} screenshareCodec - The preferred screenshare codec.
  1974. * @returns {void}
  1975. */
  1976. setVideoCodecs(codecList, screenshareCodec) {
  1977. if (this._assertNotEnded()) {
  1978. const updated = this.peerconnection.setVideoCodecs(codecList, screenshareCodec);
  1979. if (updated) {
  1980. this.eventEmitter.emit(MediaSessionEvents.VIDEO_CODEC_CHANGED);
  1981. }
  1982. // Browser throws an error when H.264 is set on the encodings. Therefore, munge the SDP when H.264 needs to
  1983. // be selected.
  1984. // TODO: Remove this check when the above issue is fixed.
  1985. if (this.usesCodecSelectionAPI && codecList[0] !== CodecMimeType.H264) {
  1986. return;
  1987. }
  1988. // Skip renegotiation when the selected codec order matches with that of the remote SDP.
  1989. const currentCodecOrder = this.peerconnection.getConfiguredVideoCodecs();
  1990. if (codecList.every((val, index) => val === currentCodecOrder[index])) {
  1991. return;
  1992. }
  1993. this.eventEmitter.emit(MediaSessionEvents.VIDEO_CODEC_CHANGED);
  1994. Statistics.sendAnalytics(
  1995. VIDEO_CODEC_CHANGED,
  1996. {
  1997. value: codecList[0],
  1998. videoType: VideoType.CAMERA
  1999. });
  2000. logger.info(`${this} setVideoCodecs: codecList=${codecList}, screenshareCodec=${screenshareCodec}`);
  2001. // Initiate a renegotiate for the codec setting to take effect.
  2002. const workFunction = finishedCallback => {
  2003. this._renegotiate()
  2004. .then(() => this.peerconnection.configureVideoSenderEncodings())
  2005. .then(
  2006. () => {
  2007. logger.debug(`${this} setVideoCodecs task is done`);
  2008. return finishedCallback();
  2009. }, error => {
  2010. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  2011. return finishedCallback(error);
  2012. });
  2013. };
  2014. logger.debug(`${this} Queued setVideoCodecs task`);
  2015. // Queue and execute
  2016. this.modificationQueue.push(workFunction);
  2017. }
  2018. }
  2019. /**
  2020. * @inheritDoc
  2021. */
  2022. terminate(success, failure, options) {
  2023. if (this.state === JingleSessionState.ENDED) {
  2024. return;
  2025. }
  2026. if (!options || Boolean(options.sendSessionTerminate)) {
  2027. const sessionTerminate
  2028. = $iq({
  2029. to: this.remoteJid,
  2030. type: 'set'
  2031. })
  2032. .c('jingle', {
  2033. xmlns: 'urn:xmpp:jingle:1',
  2034. action: 'session-terminate',
  2035. initiator: this.initiatorJid,
  2036. sid: this.sid
  2037. })
  2038. .c('reason')
  2039. .c((options && options.reason) || 'success')
  2040. .up();
  2041. if (options && options.reasonDescription) {
  2042. sessionTerminate
  2043. .c('text')
  2044. .t(options.reasonDescription)
  2045. .up()
  2046. .up();
  2047. } else {
  2048. sessionTerminate.up();
  2049. }
  2050. this._bridgeSessionId
  2051. && sessionTerminate.c(
  2052. 'bridge-session', {
  2053. xmlns: 'http://jitsi.org/protocol/focus',
  2054. id: this._bridgeSessionId,
  2055. restart: options && options.requestRestart === true
  2056. }).up();
  2057. logger.info(`${this} Sending session-terminate`);
  2058. logger.debug(sessionTerminate.tree());
  2059. this.connection.sendIQ(
  2060. sessionTerminate,
  2061. success,
  2062. this.newJingleErrorHandler(sessionTerminate, failure),
  2063. IQ_TIMEOUT);
  2064. } else {
  2065. logger.info(`${this} Skipped sending session-terminate`);
  2066. }
  2067. // this should result in 'onTerminated' being called by strope.jingle.js
  2068. this.connection.jingle.terminate(this.sid);
  2069. }
  2070. /**
  2071. * Converts to string with minor summary.
  2072. *
  2073. * @return {string}
  2074. */
  2075. toString() {
  2076. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2077. }
  2078. }