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 94KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393
  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.debug(`${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.debug(`${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. async _renegotiate(optionalRemoteSdp) {
  569. if (this.peerconnection.signalingState === 'closed') {
  570. throw new Error('Attempted to renegotiate in state closed');
  571. }
  572. const remoteSdp = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  573. if (!remoteSdp) {
  574. throw new Error(`Cannot renegotiate without remote description, state=${this.state}`);
  575. }
  576. const remoteDescription = {
  577. type: 'offer',
  578. sdp: remoteSdp
  579. };
  580. const oldLocalSDP = this.peerconnection.localDescription.sdp;
  581. logger.debug(`${this} Renegotiate: setting remote description`);
  582. try {
  583. await this.peerconnection.setRemoteDescription(remoteDescription);
  584. logger.debug(`${this} Renegotiate: creating answer`);
  585. const answer = await this.peerconnection.createAnswer(this.mediaConstraints);
  586. logger.debug(`${this} Renegotiate: setting local description`);
  587. await this.peerconnection.setLocalDescription(answer);
  588. if (oldLocalSDP) {
  589. // Send the source updates after every renegotiation cycle.
  590. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(this.peerconnection.localDescription.sdp));
  591. }
  592. } catch (error) {
  593. logger.error(`${this} Renegotiate failed:`, error);
  594. throw error;
  595. }
  596. }
  597. /**
  598. * Sends 'content-modify' IQ in order to ask the remote peer to either stop or resume sending video media or to
  599. * adjust sender's video constraints.
  600. *
  601. * @returns {void}
  602. * @private
  603. */
  604. _sendContentModify() {
  605. const senders = this._localSendReceiveVideoActive ? 'both' : 'none';
  606. const sessionModify
  607. = $iq({
  608. to: this.remoteJid,
  609. type: 'set'
  610. })
  611. .c('jingle', {
  612. xmlns: 'urn:xmpp:jingle:1',
  613. action: 'content-modify',
  614. initiator: this.initiatorJid,
  615. sid: this.sid
  616. })
  617. .c('content', {
  618. name: MediaType.VIDEO,
  619. senders
  620. });
  621. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  622. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  623. sessionModify
  624. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  625. .attrs({
  626. sourceName,
  627. maxHeight
  628. });
  629. sessionModify.up();
  630. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  631. });
  632. }
  633. logger.debug(sessionModify.tree());
  634. this.connection.sendIQ(
  635. sessionModify,
  636. null,
  637. this.newJingleErrorHandler(sessionModify),
  638. IQ_TIMEOUT);
  639. }
  640. /**
  641. * Sends given candidate in Jingle 'transport-info' message.
  642. *
  643. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  644. * @returns {void}
  645. * @private
  646. */
  647. _sendIceCandidate(candidate) {
  648. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  649. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  650. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  651. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  652. if (!(ice && jcand)) {
  653. logger.error('failed to get ice && jcand');
  654. return;
  655. }
  656. ice.xmlns = XEP.ICE_UDP_TRANSPORT;
  657. if (this.usedrip) {
  658. if (this.dripContainer.length === 0) {
  659. setTimeout(() => {
  660. if (this.dripContainer.length === 0) {
  661. return;
  662. }
  663. this._sendIceCandidates(this.dripContainer);
  664. this.dripContainer = [];
  665. }, ICE_CAND_GATHERING_TIMEOUT);
  666. }
  667. this.dripContainer.push(candidate);
  668. } else {
  669. this._sendIceCandidates([ candidate ]);
  670. }
  671. } else {
  672. logger.debug(`${this} _sendIceCandidate: last candidate`);
  673. // FIXME: remember to re-think in ICE-restart
  674. this.lasticecandidate = true;
  675. }
  676. }
  677. /**
  678. * Sends given candidates in Jingle 'transport-info' message.
  679. *
  680. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE candidate instances.
  681. * @returns {void}
  682. * @private
  683. */
  684. _sendIceCandidates(candidates) {
  685. if (!this._assertNotEnded('_sendIceCandidates')) {
  686. return;
  687. }
  688. logger.debug(`${this} _sendIceCandidates count: ${candidates?.length}`);
  689. const cand = $iq({ to: this.remoteJid,
  690. type: 'set' })
  691. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  692. action: 'transport-info',
  693. initiator: this.initiatorJid,
  694. sid: this.sid });
  695. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  696. for (let mid = 0; mid < localSDP.media.length; mid++) {
  697. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  698. const mline
  699. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  700. if (cands.length > 0) {
  701. const ice
  702. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  703. ice.xmlns = XEP.ICE_UDP_TRANSPORT;
  704. cand.c('content', {
  705. creator: this.initiatorJid === this.localJid
  706. ? 'initiator' : 'responder',
  707. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  708. }).c('transport', ice);
  709. for (let i = 0; i < cands.length; i++) {
  710. const candidate
  711. = SDPUtil.candidateToJingle(cands[i].candidate);
  712. // Mangle ICE candidate if 'failICE' test option is enabled
  713. if (this.failICE) {
  714. candidate.ip = '1.1.1.1';
  715. }
  716. cand.c('candidate', candidate).up();
  717. }
  718. // add fingerprint
  719. const fingerprintLine
  720. = SDPUtil.findLine(
  721. localSDP.media[mid],
  722. 'a=fingerprint:', localSDP.session);
  723. if (fingerprintLine) {
  724. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  725. tmp.required = true;
  726. cand.c(
  727. 'fingerprint',
  728. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  729. .t(tmp.fingerprint);
  730. delete tmp.fingerprint;
  731. cand.attrs(tmp);
  732. cand.up();
  733. }
  734. cand.up(); // transport
  735. cand.up(); // content
  736. }
  737. }
  738. // might merge last-candidate notification into this, but it is called
  739. // a lot later. See webrtc issue #2340
  740. // logger.debug('was this the last candidate', this.lasticecandidate);
  741. this.connection.sendIQ(
  742. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  743. }
  744. /**
  745. * Sends Jingle 'session-accept' message.
  746. *
  747. * @param {function()} success callback called when we receive 'RESULT' packet for the 'session-accept'.
  748. * @param {function(error)} failure called when we receive an error response or when the request has timed out.
  749. * @returns {void}
  750. * @private
  751. */
  752. _sendSessionAccept(success, failure) {
  753. // NOTE: since we're just reading from it, we don't need to be within
  754. // the modification queue to access the local description
  755. const localSDP = new SDP(this.peerconnection.localDescription.sdp, this.isP2P);
  756. const accept = $iq({ to: this.remoteJid,
  757. type: 'set' })
  758. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  759. action: 'session-accept',
  760. initiator: this.initiatorJid,
  761. responder: this.responderJid,
  762. sid: this.sid });
  763. if (this.webrtcIceTcpDisable) {
  764. localSDP.removeTcpCandidates = true;
  765. }
  766. if (this.webrtcIceUdpDisable) {
  767. localSDP.removeUdpCandidates = true;
  768. }
  769. if (this.failICE) {
  770. localSDP.failICE = true;
  771. }
  772. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  773. localSDP.initialLastN = this.options.channelLastN;
  774. }
  775. localSDP.toJingle(
  776. accept,
  777. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  778. logger.info(`${this} Sending session-accept`);
  779. logger.debug(accept.tree());
  780. this.connection.sendIQ(accept,
  781. success,
  782. this.newJingleErrorHandler(accept, error => {
  783. failure(error);
  784. // 'session-accept' is a critical timeout and we'll
  785. // have to restart
  786. this.room.eventEmitter.emit(
  787. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  788. }),
  789. IQ_TIMEOUT);
  790. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  791. // fingerprint and setup) ASAP in order to start the connection
  792. // establishment.
  793. //
  794. // FIXME Flushing the connection at this point triggers an issue with
  795. // BOSH request handling in Prosody on slow connections.
  796. //
  797. // The problem is that this request will be quite large and it may take
  798. // time before it reaches Prosody. In the meantime Strophe may decide
  799. // to send the next one. And it was observed that a small request with
  800. // 'transport-info' usually follows this one. It does reach Prosody
  801. // before the previous one was completely received. 'rid' on the server
  802. // is increased and Prosody ignores the request with 'session-accept'.
  803. // It will never reach Jicofo and everything in the request table is
  804. // lost. Removing the flush does not guarantee it will never happen, but
  805. // makes it much less likely('transport-info' is bundled with
  806. // 'session-accept' and any immediate requests).
  807. //
  808. // this.connection.flush();
  809. }
  810. /**
  811. * Sends 'session-initiate' to the remote peer.
  812. *
  813. * NOTE this method is synchronous and we're not waiting for the RESULT
  814. * response which would delay the startup process.
  815. *
  816. * @param {string} offerSdp - The local session description which will be used to generate an offer.
  817. * @returns {void}
  818. * @private
  819. */
  820. _sendSessionInitiate(offerSdp) {
  821. let init = $iq({
  822. to: this.remoteJid,
  823. type: 'set'
  824. }).c('jingle', {
  825. xmlns: 'urn:xmpp:jingle:1',
  826. action: 'session-initiate',
  827. initiator: this.initiatorJid,
  828. sid: this.sid
  829. });
  830. new SDP(offerSdp, this.isP2P).toJingle(
  831. init,
  832. this.isInitiator ? 'initiator' : 'responder');
  833. init = init.tree();
  834. logger.debug(`${this} Session-initiate: `, init);
  835. this.connection.sendIQ(init,
  836. () => {
  837. logger.info(`${this} Got RESULT for "session-initiate"`);
  838. },
  839. error => {
  840. logger.error(`${this} "session-initiate" error`, error);
  841. },
  842. IQ_TIMEOUT);
  843. }
  844. /**
  845. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  846. *
  847. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  848. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  849. * 'session-accept' sent.
  850. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  851. * can be used to log some details about the error.
  852. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  853. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  854. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  855. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  856. * assumption that the initial offer/answer cycle has been executed already.
  857. */
  858. acceptOffer(jingleOffer, success, failure, localTracks = []) {
  859. this.setOfferAnswerCycle(
  860. jingleOffer,
  861. () => {
  862. // FIXME we may not care about RESULT packet for session-accept
  863. // then we should either call 'success' here immediately or
  864. // modify sendSessionAccept method to do that
  865. this._sendSessionAccept(() => {
  866. // Start processing tasks on the modification queue.
  867. logger.debug(`${this} Resuming the modification queue after session is established!`);
  868. this.modificationQueue.resume();
  869. success();
  870. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  871. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  872. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  873. // This will happen when someone shares a secondary source to a two people call, the other user
  874. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  875. // point, there are 2 video tracks which need to be signaled to the remote peer.
  876. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  877. videoTracks.length && videoTracks.splice(0, 1);
  878. videoTracks.length && this.addTracks(videoTracks);
  879. },
  880. error => {
  881. failure(error);
  882. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  883. });
  884. },
  885. failure,
  886. localTracks);
  887. }
  888. /**
  889. * {@inheritDoc}
  890. */
  891. addIceCandidates(elem) {
  892. if (this.peerconnection.signalingState === 'closed') {
  893. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  894. return;
  895. }
  896. const iceCandidates = [];
  897. elem.find('>content>transport>candidate')
  898. .each((idx, candidate) => {
  899. let line = SDPUtil.candidateFromJingle(candidate);
  900. line = line.replace('\r\n', '').replace('a=', '');
  901. // FIXME this code does not care to handle
  902. // non-bundle transport
  903. const rtcCandidate = new RTCIceCandidate({
  904. sdpMLineIndex: 0,
  905. // FF comes up with more complex names like audio-23423,
  906. // Given that it works on both Chrome and FF without
  907. // providing it, let's leave it like this for the time
  908. // being...
  909. // sdpMid: 'audio',
  910. sdpMid: '',
  911. candidate: line
  912. });
  913. iceCandidates.push(rtcCandidate);
  914. });
  915. if (!iceCandidates.length) {
  916. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  917. return;
  918. }
  919. // We want to have this task queued, so that we know it is executed,
  920. // after the initial sRD/sLD offer/answer cycle was done (based on
  921. // the assumption that candidates are spawned after the offer/answer
  922. // and XMPP preserves order).
  923. const workFunction = finishedCallback => {
  924. for (const iceCandidate of iceCandidates) {
  925. this.peerconnection.addIceCandidate(iceCandidate)
  926. .then(
  927. () => logger.debug(`${this} addIceCandidate ok!`),
  928. err => logger.error(`${this} addIceCandidate failed!`, err));
  929. }
  930. finishedCallback();
  931. logger.debug(`${this} ICE candidates task finished`);
  932. };
  933. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  934. this.modificationQueue.push(workFunction);
  935. }
  936. /**
  937. * Handles a Jingle source-add message for this Jingle session.
  938. *
  939. * @param {Array<Element>} elem an array of Jingle "content" elements.
  940. * @returns {Promise} resolved when the operation is done or rejected with an error.
  941. */
  942. addRemoteStream(elem) {
  943. this._addOrRemoveRemoteStream(true /* add */, elem);
  944. }
  945. /**
  946. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  947. * being added to the peerconnection for the first time.
  948. *
  949. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  950. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  951. * otherwise.
  952. */
  953. addTracks(localTracks = null) {
  954. if (!localTracks?.length) {
  955. Promise.reject(new Error('No tracks passed'));
  956. }
  957. const replaceTracks = [];
  958. const workFunction = finishedCallback => {
  959. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp, this.isP2P);
  960. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  961. .find(t => t.receiver.track.kind === MediaType.VIDEO
  962. && t.direction === MediaDirection.RECVONLY
  963. && t.currentDirection === MediaDirection.RECVONLY);
  964. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  965. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  966. // existing one in that case.
  967. for (const track of localTracks) {
  968. if (!this.isP2P || !recvOnlyTransceiver) {
  969. remoteSdp.addMlineForNewSource(track.getType());
  970. }
  971. }
  972. this._renegotiate(remoteSdp.raw)
  973. .then(() => {
  974. // Replace the tracks on the newly generated transceivers.
  975. for (const track of localTracks) {
  976. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  977. }
  978. return Promise.all(replaceTracks);
  979. })
  980. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  981. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  982. .then(() => this._renegotiate())
  983. .then(() => finishedCallback(), error => finishedCallback(error));
  984. };
  985. return new Promise((resolve, reject) => {
  986. logger.debug(`${this} Queued renegotiation after addTrack`);
  987. this.modificationQueue.push(
  988. workFunction,
  989. error => {
  990. if (error) {
  991. if (error instanceof ClearedQueueError) {
  992. // The session might have been terminated before the task was executed, making it obsolete.
  993. logger.debug(`${this} renegotiation after addTrack aborted: session terminated`);
  994. resolve();
  995. return;
  996. }
  997. logger.error(`${this} renegotiation after addTrack error`, error);
  998. reject(error);
  999. } else {
  1000. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1001. resolve();
  1002. }
  1003. });
  1004. });
  1005. }
  1006. /**
  1007. * Adds local track back to the peerconnection associated with this session.
  1008. *
  1009. * @param {JitsiLocalTrack} track - the local track to be added back to the peerconnection.
  1010. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  1011. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  1012. * details in case something goes wrong.
  1013. * @returns {Promise<void>}
  1014. */
  1015. addTrackToPc(track) {
  1016. return this._addRemoveTrack(false /* add */, track)
  1017. .then(() => {
  1018. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  1019. // unmutes it the first time, all the parameters need to be configured.
  1020. if (track.isVideoTrack()) {
  1021. return this.peerconnection.configureVideoSenderEncodings(track);
  1022. }
  1023. });
  1024. }
  1025. /**
  1026. * Closes the underlying peerconnection and shuts down the modification queue.
  1027. *
  1028. * @returns {void}
  1029. */
  1030. close() {
  1031. this.state = JingleSessionState.ENDED;
  1032. this.establishmentDuration = undefined;
  1033. if (this.peerconnection) {
  1034. this.peerconnection.onicecandidate = null;
  1035. this.peerconnection.oniceconnectionstatechange = null;
  1036. this.peerconnection.onnegotiationneeded = null;
  1037. this.peerconnection.onsignalingstatechange = null;
  1038. }
  1039. logger.debug(`${this} Clearing modificationQueue`);
  1040. // Remove any pending tasks from the queue
  1041. this.modificationQueue.clear();
  1042. logger.debug(`${this} Queued PC close task`);
  1043. this.modificationQueue.push(finishCallback => {
  1044. // do not try to close if already closed.
  1045. this.peerconnection && this.peerconnection.close();
  1046. finishCallback();
  1047. logger.debug(`${this} PC close task done!`);
  1048. });
  1049. logger.debug(`${this} Shutdown modificationQueue!`);
  1050. // No more tasks can go in after the close task
  1051. this.modificationQueue.shutdown();
  1052. }
  1053. /**
  1054. * @inheritDoc
  1055. * @param {JingleSessionPCOptions} options - a set of config options.
  1056. * @returns {void}
  1057. */
  1058. doInitialize(options) {
  1059. this.failICE = Boolean(options.testing?.failICE);
  1060. this.lasticecandidate = false;
  1061. this.options = options;
  1062. /**
  1063. * {@code true} if reconnect is in progress.
  1064. * @type {boolean}
  1065. */
  1066. this.isReconnect = false;
  1067. /**
  1068. * Set to {@code true} if the connection was ever stable
  1069. * @type {boolean}
  1070. */
  1071. this.wasstable = false;
  1072. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  1073. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  1074. const pcOptions = { disableRtx: options.disableRtx };
  1075. if (options.gatherStats) {
  1076. pcOptions.maxstats = DEFAULT_MAX_STATS;
  1077. }
  1078. pcOptions.capScreenshareBitrate = false;
  1079. pcOptions.codecSettings = options.codecSettings;
  1080. pcOptions.enableInsertableStreams = options.enableInsertableStreams;
  1081. pcOptions.usesCodecSelectionAPI = this.usesCodecSelectionAPI
  1082. = browser.supportsCodecSelectionAPI()
  1083. && (options.testing?.enableCodecSelectionAPI ?? true)
  1084. && !this.isP2P;
  1085. if (options.videoQuality) {
  1086. const settings = Object.entries(options.videoQuality)
  1087. .map(entry => {
  1088. entry[0] = entry[0].toLowerCase();
  1089. return entry;
  1090. });
  1091. pcOptions.videoQuality = Object.fromEntries(settings);
  1092. }
  1093. pcOptions.forceTurnRelay = options.forceTurnRelay;
  1094. pcOptions.audioQuality = options.audioQuality;
  1095. pcOptions.disableSimulcast = this.isP2P ? true : options.disableSimulcast;
  1096. if (!this.isP2P) {
  1097. // Do not send lower spatial layers for low fps screenshare and enable them only for high fps screenshare.
  1098. pcOptions.capScreenshareBitrate = !(options.desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE);
  1099. }
  1100. if (options.startSilent) {
  1101. pcOptions.startSilent = true;
  1102. }
  1103. this.peerconnection
  1104. = this.rtc.createPeerConnection(
  1105. this._signalingLayer,
  1106. this.pcConfig,
  1107. this.isP2P,
  1108. pcOptions);
  1109. this.peerconnection.onicecandidate = ev => {
  1110. if (!ev) {
  1111. // There was an incomplete check for ev before which left
  1112. // the last line of the function unprotected from a potential
  1113. // throw of an exception. Consequently, it may be argued that
  1114. // the check is unnecessary. Anyway, I'm leaving it and making
  1115. // the check complete.
  1116. return;
  1117. }
  1118. // XXX this is broken, candidate is not parsed.
  1119. const candidate = ev.candidate;
  1120. const now = window.performance.now();
  1121. if (candidate) {
  1122. if (this._gatheringStartedTimestamp === null) {
  1123. this._gatheringStartedTimestamp = now;
  1124. }
  1125. // Discard candidates of disabled protocols.
  1126. let protocol = candidate.protocol;
  1127. if (typeof protocol === 'string') {
  1128. protocol = protocol.toLowerCase();
  1129. if (protocol === 'tcp' || protocol === 'ssltcp') {
  1130. if (this.webrtcIceTcpDisable) {
  1131. return;
  1132. }
  1133. } else if (protocol === 'udp') {
  1134. if (this.webrtcIceUdpDisable) {
  1135. return;
  1136. }
  1137. }
  1138. }
  1139. } else if (!this._gatheringReported) {
  1140. // End of gathering
  1141. Statistics.sendAnalytics(
  1142. ICE_DURATION,
  1143. {
  1144. phase: 'gathering',
  1145. value: now - this._gatheringStartedTimestamp,
  1146. p2p: this.isP2P,
  1147. initiator: this.isInitiator
  1148. });
  1149. this._gatheringReported = true;
  1150. }
  1151. if (this.isP2P) {
  1152. this._sendIceCandidate(candidate);
  1153. }
  1154. };
  1155. // Note there is a change in the spec about closed:
  1156. // This value moved into the RTCPeerConnectionState enum in
  1157. // the May 13, 2016 draft of the specification, as it reflects the state
  1158. // of the RTCPeerConnection, not the signaling connection. You now
  1159. // detect a closed connection by checking for connectionState to be
  1160. // "closed" instead.
  1161. // I suppose at some point this will be moved to onconnectionstatechange
  1162. this.peerconnection.onsignalingstatechange = () => {
  1163. if (this.peerconnection.signalingState === 'stable') {
  1164. this.wasstable = true;
  1165. } else if (this.peerconnection.signalingState === 'closed'
  1166. || this.peerconnection.connectionState === 'closed') {
  1167. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  1168. }
  1169. };
  1170. /**
  1171. * The oniceconnectionstatechange event handler contains the code to
  1172. * execute when the iceconnectionstatechange event, of type Event,
  1173. * is received by this RTCPeerConnection. Such an event is sent when
  1174. * the value of RTCPeerConnection.iceConnectionState changes.
  1175. */
  1176. this.peerconnection.oniceconnectionstatechange = () => {
  1177. const now = window.performance.now();
  1178. let isStable = false;
  1179. if (!this.isP2P) {
  1180. this.room.connectionTimes[
  1181. `ice.state.${this.peerconnection.iceConnectionState}`]
  1182. = now;
  1183. }
  1184. logger.info(`(TIME) ICE ${this.peerconnection.iceConnectionState} ${this.isP2P ? 'P2P' : 'JVB'}:\t`, now);
  1185. Statistics.sendAnalytics(
  1186. ICE_STATE_CHANGED,
  1187. {
  1188. p2p: this.isP2P,
  1189. state: this.peerconnection.iceConnectionState,
  1190. 'signaling_state': this.peerconnection.signalingState,
  1191. reconnect: this.isReconnect,
  1192. value: now
  1193. });
  1194. this.room.eventEmitter.emit(
  1195. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  1196. this,
  1197. this.peerconnection.iceConnectionState);
  1198. switch (this.peerconnection.iceConnectionState) {
  1199. case 'checking':
  1200. this._iceCheckingStartedTimestamp = now;
  1201. break;
  1202. case 'connected':
  1203. case 'completed':
  1204. // Informs interested parties that the connection has been restored. This includes the case when
  1205. // media connection to the bridge has been restored after an ICE failure by using session-terminate.
  1206. if (this.peerconnection.signalingState === 'stable') {
  1207. isStable = true;
  1208. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED, this);
  1209. }
  1210. // Add a workaround for an issue on chrome in Unified plan when the local endpoint is the offerer.
  1211. // The 'signalingstatechange' event for 'stable' is handled after the 'iceconnectionstatechange' event
  1212. // for 'completed' is handled by the client. This prevents the client from firing a
  1213. // CONNECTION_ESTABLISHED event for the p2p session. As a result, the offerer continues to stay on the
  1214. // jvb connection while the remote peer switches to the p2p connection breaking the media flow between
  1215. // the endpoints.
  1216. // TODO - file a chromium bug and add the information here.
  1217. if (!this.wasConnected
  1218. && (this.wasstable
  1219. || isStable
  1220. || (this.isInitiator && (browser.isChromiumBased() || browser.isReactNative())))) {
  1221. Statistics.sendAnalytics(
  1222. ICE_DURATION,
  1223. {
  1224. phase: 'checking',
  1225. value: now - this._iceCheckingStartedTimestamp,
  1226. p2p: this.isP2P,
  1227. initiator: this.isInitiator
  1228. });
  1229. // Switch between ICE gathering and ICE checking whichever
  1230. // started first (scenarios are different for initiator
  1231. // vs responder)
  1232. const iceStarted
  1233. = Math.min(
  1234. this._iceCheckingStartedTimestamp,
  1235. this._gatheringStartedTimestamp);
  1236. this.establishmentDuration = now - iceStarted;
  1237. Statistics.sendAnalytics(
  1238. ICE_DURATION,
  1239. {
  1240. phase: 'establishment',
  1241. value: this.establishmentDuration,
  1242. p2p: this.isP2P,
  1243. initiator: this.isInitiator
  1244. });
  1245. this.wasConnected = true;
  1246. this.room.eventEmitter.emit(
  1247. XMPPEvents.CONNECTION_ESTABLISHED, this);
  1248. }
  1249. this.isReconnect = false;
  1250. break;
  1251. case 'disconnected':
  1252. this.isReconnect = true;
  1253. // Informs interested parties that the connection has been
  1254. // interrupted.
  1255. if (this.wasstable) {
  1256. this.room.eventEmitter.emit(
  1257. XMPPEvents.CONNECTION_INTERRUPTED, this);
  1258. }
  1259. break;
  1260. case 'failed':
  1261. this.room.eventEmitter.emit(
  1262. XMPPEvents.CONNECTION_ICE_FAILED, this);
  1263. break;
  1264. }
  1265. };
  1266. /**
  1267. * The connection state event is fired whenever the aggregate of underlying
  1268. * transports change their state.
  1269. */
  1270. this.peerconnection.onconnectionstatechange = () => {
  1271. const icestate = this.peerconnection.iceConnectionState;
  1272. logger.info(`(TIME) ${this.isP2P ? 'P2P' : 'JVB'} PC state is now ${this.peerconnection.connectionState} `
  1273. + `(ICE state ${this.peerconnection.iceConnectionState}):\t`, window.performance.now());
  1274. switch (this.peerconnection.connectionState) {
  1275. case 'failed':
  1276. // Since version 76 Chrome no longer switches ICE connection
  1277. // state to failed (see
  1278. // https://bugs.chromium.org/p/chromium/issues/detail?id=982793
  1279. // for details) we use this workaround to recover from lost connections
  1280. if (icestate === 'disconnected') {
  1281. this.room.eventEmitter.emit(
  1282. XMPPEvents.CONNECTION_ICE_FAILED, this);
  1283. }
  1284. break;
  1285. }
  1286. };
  1287. /**
  1288. * The negotiationneeded event is fired whenever we shake the media on the
  1289. * RTCPeerConnection object.
  1290. */
  1291. this.peerconnection.onnegotiationneeded = () => {
  1292. const state = this.peerconnection.signalingState;
  1293. const remoteDescription = this.peerconnection.remoteDescription;
  1294. if (!this.isP2P
  1295. && state === 'stable'
  1296. && remoteDescription
  1297. && typeof remoteDescription.sdp === 'string') {
  1298. logger.info(`${this} onnegotiationneeded fired on ${this.peerconnection}`);
  1299. const workFunction = finishedCallback => {
  1300. this._renegotiate()
  1301. .then(() => this.peerconnection.configureAudioSenderEncodings())
  1302. .then(() => finishedCallback(), error => finishedCallback(error));
  1303. };
  1304. this.modificationQueue.push(
  1305. workFunction,
  1306. error => {
  1307. if (error) {
  1308. logger.error(`${this} onnegotiationneeded error`, error);
  1309. } else {
  1310. logger.debug(`${this} onnegotiationneeded executed - OK`);
  1311. }
  1312. });
  1313. }
  1314. };
  1315. }
  1316. /**
  1317. * Returns the ice connection state for the peer connection.
  1318. *
  1319. * @returns the ice connection state for the peer connection.
  1320. */
  1321. getIceConnectionState() {
  1322. return this.peerconnection.getConnectionState();
  1323. }
  1324. /**
  1325. * Returns the preference for max frame height for the remote video sources.
  1326. *
  1327. * @returns {Map<string, number>|undefined}
  1328. */
  1329. getRemoteSourcesRecvMaxFrameHeight() {
  1330. if (this.isP2P) {
  1331. return this.remoteSourceMaxFrameHeights;
  1332. }
  1333. return undefined;
  1334. }
  1335. /**
  1336. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  1337. *
  1338. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  1339. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  1340. * @returns {Promise<void>} that resolves when the offer is sent to the remote peer, rejected otherwise.
  1341. */
  1342. async invite(localTracks = []) {
  1343. if (!this.isInitiator) {
  1344. throw new Error('Trying to invite from the responder session');
  1345. }
  1346. logger.debug(`${this} Executing invite task`);
  1347. const addTracks = [];
  1348. for (const track of localTracks) {
  1349. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1350. }
  1351. try {
  1352. await Promise.all(addTracks);
  1353. const offerSdp = await this.peerconnection.createOffer(this.mediaConstraints);
  1354. await this.peerconnection.setLocalDescription(offerSdp);
  1355. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  1356. this._sendSessionInitiate(this.peerconnection.localDescription.sdp);
  1357. logger.debug(`${this} invite executed - OK`);
  1358. } catch (error) {
  1359. logger.error(`${this} invite error`, error);
  1360. throw error;
  1361. }
  1362. }
  1363. /**
  1364. * Enables/disables local video based on 'senders' attribute of the video conent in 'content-modify' IQ sent by the
  1365. * remote peer. Also, checks if the sourceMaxFrameHeight (as requested by the p2p peer) or the senders attribute of
  1366. * the video content has changed and modifies the local video resolution accordingly.
  1367. *
  1368. * @param {Element} jingleContents - The content of the 'content-modify' IQ sent by the remote peer.
  1369. * @returns {void}
  1370. */
  1371. modifyContents(jingleContents) {
  1372. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  1373. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  1374. if (sourceMaxFrameHeights) {
  1375. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  1376. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  1377. }
  1378. if (newVideoSenders === null) {
  1379. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  1380. return;
  1381. }
  1382. if (!this._assertNotEnded()) {
  1383. return;
  1384. }
  1385. const isRemoteVideoActive
  1386. = newVideoSenders === 'both'
  1387. || (newVideoSenders === 'initiator' && this.isInitiator)
  1388. || (newVideoSenders === 'responder' && !this.isInitiator);
  1389. if (isRemoteVideoActive !== this._remoteSendReceiveVideoActive) {
  1390. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  1391. this._remoteSendReceiveVideoActive = isRemoteVideoActive;
  1392. this.peerconnection
  1393. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  1394. }
  1395. }
  1396. /**
  1397. * Method returns function(errorResponse) which is a callback to be passed to Strophe connection.sendIQ method. An
  1398. * 'error' structure is created that is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1399. * structure is as follows:
  1400. * {
  1401. * code: {XMPP error response code}
  1402. * reason: {the name of XMPP error reason element or 'timeout' if the
  1403. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1404. * source: {request.tree() that provides original request}
  1405. * session: {this JingleSessionPC.toString()}
  1406. * }
  1407. * @param request Strophe IQ instance which is the request to be dumped into the error structure.
  1408. * @param failureCb function(error) called when error response was returned or when a timeout has occurred.
  1409. * @returns {function(this:JingleSessionPC)}
  1410. */
  1411. newJingleErrorHandler(request, failureCb) {
  1412. return errResponse => {
  1413. const error = {};
  1414. // Get XMPP error code and condition(reason)
  1415. const errorElSel = $(errResponse).find('error');
  1416. if (errorElSel.length) {
  1417. error.code = errorElSel.attr('code');
  1418. const errorReasonSel = $(errResponse).find('error :first');
  1419. if (errorReasonSel.length) {
  1420. error.reason = errorReasonSel[0].tagName;
  1421. }
  1422. const errorMsgSel = errorElSel.find('>text');
  1423. if (errorMsgSel.length) {
  1424. error.msg = errorMsgSel.text();
  1425. }
  1426. }
  1427. if (!errResponse) {
  1428. error.reason = 'timeout';
  1429. }
  1430. error.session = this.toString();
  1431. if (failureCb) {
  1432. failureCb(error);
  1433. } else if (this.state === JingleSessionState.ENDED
  1434. && error.reason === 'item-not-found') {
  1435. // When remote peer decides to terminate the session, but it
  1436. // still have few messages on the queue for processing,
  1437. // it will first send us 'session-terminate' (we enter ENDED)
  1438. // and then follow with 'item-not-found' for the queued requests
  1439. // We don't want to have that logged on error level.
  1440. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  1441. } else {
  1442. logger.error(`Jingle error: ${JSON.stringify(error)}`);
  1443. }
  1444. };
  1445. }
  1446. /**
  1447. * Figures out added/removed ssrcs and sends updated IQs to the remote peer or Jicofo.
  1448. *
  1449. * @param oldSDP SDP object for old description.
  1450. * @param newSDP SDP object for new description.
  1451. * @returns {void}
  1452. */
  1453. notifyMySSRCUpdate(oldSDP, newSDP) {
  1454. if (this.state !== JingleSessionState.ACTIVE) {
  1455. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  1456. return;
  1457. }
  1458. if (!this.connection.connected) {
  1459. // The goal is to compare the oldest SDP with the latest one upon reconnect
  1460. if (!this._cachedOldLocalSdp) {
  1461. this._cachedOldLocalSdp = oldSDP;
  1462. }
  1463. this._cachedNewLocalSdp = newSDP;
  1464. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  1465. return;
  1466. }
  1467. this._cachedOldLocalSdp = undefined;
  1468. this._cachedNewLocalSdp = undefined;
  1469. const getSignaledSourceInfo = sdpDiffer => {
  1470. const newMedia = sdpDiffer.getNewMedia();
  1471. let ssrcs = [];
  1472. let mediaType = null;
  1473. // It is assumed that sources are signaled one at a time.
  1474. Object.keys(newMedia).forEach(mediaIndex => {
  1475. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  1476. mediaType = newMedia[mediaIndex].mediaType;
  1477. if (signaledSsrcs?.length) {
  1478. ssrcs = ssrcs.concat(signaledSsrcs);
  1479. }
  1480. });
  1481. return {
  1482. mediaType,
  1483. ssrcs
  1484. };
  1485. };
  1486. // send source-remove IQ.
  1487. let sdpDiffer = new SDPDiffer(newSDP, oldSDP, this.isP2P);
  1488. const remove = $iq({ to: this.remoteJid,
  1489. type: 'set' })
  1490. .c('jingle', {
  1491. xmlns: 'urn:xmpp:jingle:1',
  1492. action: 'source-remove',
  1493. initiator: this.initiatorJid,
  1494. sid: this.sid
  1495. }
  1496. );
  1497. sdpDiffer.toJingle(remove);
  1498. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  1499. // need to
  1500. const ctx = {};
  1501. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  1502. if (removedSsrcInfo.ssrcs.length) {
  1503. // Log only the SSRCs instead of the full IQ.
  1504. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  1505. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  1506. this.connection.sendIQ(
  1507. remove,
  1508. () => {
  1509. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  1510. },
  1511. this.newJingleErrorHandler(remove, error => {
  1512. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  1513. }),
  1514. IQ_TIMEOUT);
  1515. }
  1516. // send source-add IQ.
  1517. sdpDiffer = new SDPDiffer(oldSDP, newSDP, this.isP2P);
  1518. const add = $iq({ to: this.remoteJid,
  1519. type: 'set' })
  1520. .c('jingle', {
  1521. xmlns: 'urn:xmpp:jingle:1',
  1522. action: 'source-add',
  1523. initiator: this.initiatorJid,
  1524. sid: this.sid
  1525. }
  1526. );
  1527. sdpDiffer.toJingle(add);
  1528. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  1529. if (addedSsrcInfo.ssrcs.length) {
  1530. // Log only the SSRCs instead of the full IQ.
  1531. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  1532. this.connection.sendIQ(
  1533. add,
  1534. () => {
  1535. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  1536. },
  1537. this.newJingleErrorHandler(add, error => {
  1538. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  1539. }),
  1540. IQ_TIMEOUT);
  1541. }
  1542. }
  1543. /**
  1544. * Handles the termination of the session.
  1545. *
  1546. * @param {string} reasonCondition - The XMPP Jingle reason condition.
  1547. * @param {string} reasonText - The XMPP Jingle reason text.
  1548. * @returns {void}
  1549. */
  1550. onTerminated(reasonCondition, reasonText) {
  1551. // Do something with reason and reasonCondition when we start to care
  1552. // this.reasonCondition = reasonCondition;
  1553. // this.reasonText = reasonText;
  1554. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1555. this._xmppListeners.forEach(removeListener => removeListener());
  1556. this._xmppListeners = [];
  1557. if (this._removeSenderVideoConstraintsChangeListener) {
  1558. this._removeSenderVideoConstraintsChangeListener();
  1559. }
  1560. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1561. this.peerconnection.getRemoteTracks().forEach(track => {
  1562. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1563. });
  1564. }
  1565. this.close();
  1566. }
  1567. /**
  1568. * Handles XMPP connection state changes. Resends any session updates that were cached while the XMPP connection
  1569. * was down.
  1570. *
  1571. * @param {XmppConnection.Status} status - The new status.
  1572. * @returns {void}
  1573. */
  1574. onXmppStatusChanged(status) {
  1575. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1576. logger.info(`${this} Sending SSRC update on reconnect`);
  1577. this.notifyMySSRCUpdate(
  1578. this._cachedOldLocalSdp,
  1579. this._cachedNewLocalSdp);
  1580. }
  1581. }
  1582. /**
  1583. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1584. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1585. *
  1586. * @param {Object} message - The source map message.
  1587. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1588. * @returns {void}
  1589. */
  1590. processSourceMap(message, mediaType) {
  1591. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1592. return;
  1593. }
  1594. if (mediaType === MediaType.AUDIO && this.options.startSilent) {
  1595. return;
  1596. }
  1597. const newSsrcs = [];
  1598. for (const src of message.mappedSources) {
  1599. const { owner, source, ssrc } = src;
  1600. const isNewSsrc = this.peerconnection.addRemoteSsrc(ssrc, source);
  1601. if (isNewSsrc) {
  1602. newSsrcs.push(src);
  1603. logger.debug(`New SSRC signaled ${ssrc}: owner=${owner}, source-name=${source}`);
  1604. // Check if there is an old mapping for the given source and clear the owner on the associated track.
  1605. const oldSsrc = this.peerconnection.remoteSources.get(source);
  1606. if (oldSsrc) {
  1607. this._signalingLayer.removeSSRCOwners([ oldSsrc ]);
  1608. const track = this.peerconnection.getTrackBySSRC(oldSsrc);
  1609. if (track) {
  1610. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_SET, track);
  1611. }
  1612. }
  1613. } else {
  1614. const track = this.peerconnection.getTrackBySSRC(ssrc);
  1615. if (!track || (track.getParticipantId() === owner && track.getSourceName() === source)) {
  1616. !track && logger.warn(`Remote track for SSRC=${ssrc} hasn't been created yet,`
  1617. + 'not processing the source map');
  1618. continue; // eslint-disable-line no-continue
  1619. }
  1620. logger.debug(`Existing SSRC re-mapped ${ssrc}: new owner=${owner}, source-name=${source}`);
  1621. this._signalingLayer.setSSRCOwner(ssrc, owner, source);
  1622. const oldSourceName = track.getSourceName();
  1623. const sourceInfo = this.peerconnection.getRemoteSourceInfoBySourceName(oldSourceName);
  1624. // Update the SSRC map on the peerconnection.
  1625. if (sourceInfo) {
  1626. this.peerconnection.updateRemoteSources(new Map([ [ oldSourceName, sourceInfo ] ]), false);
  1627. this.peerconnection.updateRemoteSources(new Map([ [ source, sourceInfo ] ]), true /* isAdd */);
  1628. }
  1629. // Update the muted state and the video type on the track since the presence for this track could have
  1630. // been received before the updated source map is received on the bridge channel.
  1631. const { muted, videoType } = this._signalingLayer.getPeerMediaInfo(owner, mediaType, source);
  1632. muted && this.peerconnection._sourceMutedChanged(source, muted);
  1633. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_SET, track, owner, source, videoType);
  1634. }
  1635. }
  1636. // Add the new SSRCs to the remote description by generating a source message.
  1637. if (newSsrcs.length) {
  1638. let node = $build('content', {
  1639. xmlns: 'urn:xmpp:jingle:1',
  1640. name: mediaType
  1641. }).c('description', {
  1642. xmlns: XEP.RTP_MEDIA,
  1643. media: mediaType
  1644. });
  1645. for (const src of newSsrcs) {
  1646. const { rtx, ssrc, source } = src;
  1647. let msid;
  1648. if (mediaType === MediaType.VIDEO) {
  1649. const idx = ++this.numRemoteVideoSources;
  1650. msid = `remote-video-${idx} remote-video-${idx}`;
  1651. if (rtx !== '-1') {
  1652. _addSourceElement(node, src, rtx, msid);
  1653. node.c('ssrc-group', {
  1654. xmlns: XEP.SOURCE_ATTRIBUTES,
  1655. semantics: SSRC_GROUP_SEMANTICS.FID
  1656. })
  1657. .c('source', {
  1658. xmlns: XEP.SOURCE_ATTRIBUTES,
  1659. ssrc
  1660. })
  1661. .up()
  1662. .c('source', {
  1663. xmlns: XEP.SOURCE_ATTRIBUTES,
  1664. ssrc: rtx
  1665. })
  1666. .up()
  1667. .up();
  1668. }
  1669. } else {
  1670. const idx = ++this.numRemoteAudioSources;
  1671. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1672. }
  1673. _addSourceElement(node, src, ssrc, msid);
  1674. this.peerconnection.remoteSources.set(source, ssrc);
  1675. }
  1676. node = node.up();
  1677. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1678. }
  1679. }
  1680. /**
  1681. * Handles a Jingle source-remove message for this Jingle session.
  1682. *
  1683. * @param {Array<Element>} contents - An array of content elements from the source-remove message.
  1684. * @returns {void}
  1685. */
  1686. removeRemoteStream(elem) {
  1687. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1688. }
  1689. /**
  1690. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1691. *
  1692. * @param {string} id Endpoint id of the participant that has left the call.
  1693. * @returns {void}
  1694. */
  1695. removeRemoteStreamsOnLeave(id) {
  1696. const workFunction = finishCallback => {
  1697. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1698. if (removeSsrcInfo.size) {
  1699. logger.debug(`${this} Removing SSRCs for user ${id}, sources=${Array.from(removeSsrcInfo.keys())}`);
  1700. const newRemoteSdp = new SDP(this.peerconnection.remoteDescription.sdp, this.isP2P);
  1701. newRemoteSdp.updateRemoteSources(removeSsrcInfo, false /* isAdd */);
  1702. this.peerconnection.updateRemoteSources(removeSsrcInfo, false /* isAdd */);
  1703. this._renegotiate(newRemoteSdp.raw)
  1704. .then(() => finishCallback(), error => finishCallback(error));
  1705. } else {
  1706. finishCallback();
  1707. }
  1708. };
  1709. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1710. this.modificationQueue.push(
  1711. workFunction,
  1712. error => {
  1713. if (error) {
  1714. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1715. } else {
  1716. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1717. }
  1718. });
  1719. }
  1720. /**
  1721. * Removes local track from the peerconnection as part of the mute operation.
  1722. *
  1723. * @param {JitsiLocalTrack} track the local track to be removed.
  1724. * @return {Promise} a promise which will be resolved once the local track is removed from this session or rejected
  1725. * with a <tt>string</tt> that the describes the error if anything goes wrong.
  1726. */
  1727. removeTrackFromPc(track) {
  1728. return this._addRemoveTrack(true /* remove */, track);
  1729. }
  1730. /**
  1731. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single offer/answer cycle (if needed) after
  1732. * both operations are done.
  1733. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid <tt>oldTrack</tt> with a null
  1734. * <tt>newTrack</tt> effectively just removes <tt>oldTrack</tt>.
  1735. *
  1736. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be replaced.
  1737. * @param {JitsiLocalTrack|null} newTrack the new track to use.
  1738. * @returns {Promise} which resolves once the replacement is complete with no arguments or rejects with an error.
  1739. */
  1740. replaceTrack(oldTrack, newTrack) {
  1741. const workFunction = finishedCallback => {
  1742. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  1743. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1744. .then(shouldRenegotiate => {
  1745. let promise = Promise.resolve();
  1746. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  1747. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  1748. if (shouldRenegotiate && (oldTrack || newTrack) && this.state === JingleSessionState.ACTIVE) {
  1749. promise = this._renegotiate();
  1750. }
  1751. return promise.then(() => {
  1752. // Set the source name of the new track.
  1753. if (oldTrack && newTrack && oldTrack.isVideoTrack()) {
  1754. newTrack.setSourceName(oldTrack.getSourceName());
  1755. }
  1756. });
  1757. })
  1758. .then(() => finishedCallback(), error => finishedCallback(error));
  1759. };
  1760. return new Promise((resolve, reject) => {
  1761. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  1762. this.modificationQueue.push(
  1763. workFunction,
  1764. error => {
  1765. if (error) {
  1766. if (error instanceof ClearedQueueError) {
  1767. // The session might have been terminated before the task was executed, making it obsolete.
  1768. logger.debug('Replace track aborted: session terminated');
  1769. resolve();
  1770. return;
  1771. }
  1772. logger.error(`${this} Replace track error:`, error);
  1773. reject(error);
  1774. } else {
  1775. logger.info(`${this} Replace track done!`);
  1776. resolve();
  1777. }
  1778. });
  1779. });
  1780. }
  1781. /**
  1782. * Sets the answer received from the remote peer as the remote description.
  1783. *
  1784. * @param {Element} jingleAnswer - The jingle answer element.
  1785. * @returns {Promise<void>} that resolves when the answer is set as the remote description, rejected otherwise.
  1786. */
  1787. async setAnswer(jingleAnswer) {
  1788. if (!this.isInitiator) {
  1789. throw new Error('Trying to set an answer on the responder session');
  1790. }
  1791. logger.debug(`${this} Executing setAnswer task`);
  1792. const newRemoteSdp = this._processNewJingleOfferIq(jingleAnswer);
  1793. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1794. const remoteDescription = {
  1795. type: 'answer',
  1796. sdp: newRemoteSdp.raw
  1797. };
  1798. try {
  1799. await this.peerconnection.setRemoteDescription(remoteDescription);
  1800. if (this.state === JingleSessionState.PENDING) {
  1801. this.state = JingleSessionState.ACTIVE;
  1802. // Start processing tasks on the modification queue.
  1803. logger.debug(`${this} Resuming the modification queue after session is established!`);
  1804. this.modificationQueue.resume();
  1805. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1806. this._sendContentModify();
  1807. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1808. }
  1809. logger.debug(`${this} setAnswer task done`);
  1810. } catch (error) {
  1811. logger.error(`${this} setAnswer task failed: ${error}`);
  1812. throw error;
  1813. }
  1814. }
  1815. /**
  1816. * Resumes or suspends media transfer over the underlying peer connection.
  1817. *
  1818. * @param {boolean} active - <tt>true</tt> to enable media transfer or <tt>false</tt> to suspend media transmission.
  1819. * @returns {Promise}
  1820. */
  1821. setMediaTransferActive(active) {
  1822. const changed = this.peerconnection.audioTransferActive !== active
  1823. || this.peerconnection.videoTransferActive !== active;
  1824. if (!changed) {
  1825. return Promise.resolve();
  1826. }
  1827. return this.peerconnection.setMediaTransferActive(active)
  1828. .then(() => {
  1829. this.peerconnection.audioTransferActive = active;
  1830. this.peerconnection.videoTransferActive = active;
  1831. // Reconfigure the audio and video tracks so that only the correct encodings are active.
  1832. const promises = [];
  1833. promises.push(this.peerconnection.configureVideoSenderEncodings());
  1834. promises.push(this.peerconnection.configureAudioSenderEncodings());
  1835. return Promise.allSettled(promises);
  1836. });
  1837. }
  1838. /**
  1839. * This is a setRemoteDescription/setLocalDescription cycle which starts at converting Strophe Jingle IQ into
  1840. * remote offer SDP. Once converted, setRemoteDescription, createAnswer and setLocalDescription calls follow.
  1841. *
  1842. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element of the offer (or answer) IQ
  1843. * @param success callback called when sRD/sLD cycle finishes successfully.
  1844. * @param failure callback called with an error object as an argument if we fail at any point during setRD,
  1845. * createAnswer, setLD.
  1846. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  1847. * the offer/answer cycle executes (for the local track addition to be an atomic operation together with the
  1848. * offer/answer).
  1849. * @returns {void}
  1850. */
  1851. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  1852. logger.debug(`${this} Executing setOfferAnswerCycle task`);
  1853. const addTracks = [];
  1854. const audioTracks = localTracks.filter(track => track.getType() === MediaType.AUDIO);
  1855. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  1856. let tracks = localTracks;
  1857. // Add only 1 video track at a time. Adding 2 or more video tracks to the peerconnection at the same time
  1858. // makes the browser go into a renegotiation loop by firing 'negotiationneeded' event after every
  1859. // renegotiation.
  1860. if (videoTracks.length > 1) {
  1861. tracks = [ ...audioTracks, videoTracks[0] ];
  1862. }
  1863. for (const track of tracks) {
  1864. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1865. }
  1866. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  1867. const bridgeSession = $(jingleOfferAnswerIq).find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]');
  1868. const bridgeSessionId = bridgeSession.attr('id');
  1869. if (bridgeSessionId !== this._bridgeSessionId) {
  1870. this._bridgeSessionId = bridgeSessionId;
  1871. }
  1872. Promise.all(addTracks)
  1873. .then(() => this._renegotiate(newRemoteSdp.raw))
  1874. .then(() => {
  1875. this.peerconnection.processLocalSdpForTransceiverInfo(tracks);
  1876. if (this.state === JingleSessionState.PENDING) {
  1877. this.state = JingleSessionState.ACTIVE;
  1878. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1879. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1880. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1881. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1882. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1883. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1884. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1885. if (this.isP2P && (!this._localSendReceiveVideoActive || this._sourceReceiverConstraints)) {
  1886. this._sendContentModify();
  1887. }
  1888. }
  1889. })
  1890. .then(() => {
  1891. logger.debug(`${this} setOfferAnswerCycle task done`);
  1892. success();
  1893. })
  1894. .catch(error => {
  1895. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1896. failure(error);
  1897. });
  1898. }
  1899. /**
  1900. * Resumes or suspends video media transfer over the p2p peer connection.
  1901. *
  1902. * @param {boolean} videoActive <tt>true</tt> to enable video media transfer or <tt>false</tt> to suspend video
  1903. * media transmission.
  1904. * @return {Promise} a <tt>Promise</tt> which will resolve once the operation is done. It will be rejected with
  1905. * an error description as a string in case anything goes wrong.
  1906. */
  1907. setP2pVideoTransferActive(videoActive) {
  1908. if (!this.peerconnection) {
  1909. return Promise.reject('Can not modify video transfer active state,'
  1910. + ' before "initialize" is called');
  1911. }
  1912. if (this._localSendReceiveVideoActive !== videoActive) {
  1913. this._localSendReceiveVideoActive = videoActive;
  1914. if (this.isP2P && this.state === JingleSessionState.ACTIVE) {
  1915. this._sendContentModify();
  1916. }
  1917. return this.peerconnection
  1918. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  1919. }
  1920. return Promise.resolve();
  1921. }
  1922. /**
  1923. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1924. * the remote p2p peer.
  1925. *
  1926. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1927. * @returns {void}
  1928. */
  1929. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1930. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1931. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1932. if (this.isP2P) {
  1933. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1934. // be synced after offer/answer.
  1935. if (this.state === JingleSessionState.ACTIVE) {
  1936. this._sendContentModify();
  1937. }
  1938. }
  1939. }
  1940. /**
  1941. * Sets the resolution constraint on the local video tracks.
  1942. *
  1943. * @param {number} maxFrameHeight - The user preferred max frame height.
  1944. * @param {string} sourceName - The source name of the track.
  1945. * @returns {Promise} promise that will be resolved when the operation is
  1946. * successful and rejected otherwise.
  1947. */
  1948. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1949. if (this._assertNotEnded()) {
  1950. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1951. const jitsiLocalTrack = sourceName
  1952. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1953. : this.rtc.getLocalVideoTrack();
  1954. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1955. }
  1956. return Promise.resolve();
  1957. }
  1958. /**
  1959. * Updates the codecs on the peerconnection and initiates a renegotiation (if needed) for the
  1960. * new codec config to take effect.
  1961. *
  1962. * @param {Array<CodecMimeType>} codecList - Preferred codecs for video.
  1963. * @param {CodecMimeType} screenshareCodec - The preferred screenshare codec.
  1964. * @returns {void}
  1965. */
  1966. setVideoCodecs(codecList, screenshareCodec) {
  1967. if (this._assertNotEnded()) {
  1968. const updated = this.peerconnection.setVideoCodecs(codecList, screenshareCodec);
  1969. if (updated) {
  1970. this.eventEmitter.emit(MediaSessionEvents.VIDEO_CODEC_CHANGED);
  1971. }
  1972. // Browser throws an error when H.264 is set on the encodings. Therefore, munge the SDP when H.264 needs to
  1973. // be selected.
  1974. // TODO: Remove this check when the above issue is fixed.
  1975. if (this.usesCodecSelectionAPI && codecList[0] !== CodecMimeType.H264) {
  1976. return;
  1977. }
  1978. // Skip renegotiation when the selected codec order matches with that of the remote SDP.
  1979. const currentCodecOrder = this.peerconnection.getConfiguredVideoCodecs();
  1980. if (codecList.every((val, index) => val === currentCodecOrder[index])) {
  1981. return;
  1982. }
  1983. this.eventEmitter.emit(MediaSessionEvents.VIDEO_CODEC_CHANGED);
  1984. Statistics.sendAnalytics(
  1985. VIDEO_CODEC_CHANGED,
  1986. {
  1987. value: codecList[0],
  1988. videoType: VideoType.CAMERA
  1989. });
  1990. logger.info(`${this} setVideoCodecs: codecList=${codecList}, screenshareCodec=${screenshareCodec}`);
  1991. // Initiate a renegotiate for the codec setting to take effect.
  1992. const workFunction = finishedCallback => {
  1993. this._renegotiate()
  1994. .then(() => this.peerconnection.configureVideoSenderEncodings())
  1995. .then(
  1996. () => {
  1997. logger.debug(`${this} setVideoCodecs task is done`);
  1998. return finishedCallback();
  1999. }, error => {
  2000. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  2001. return finishedCallback(error);
  2002. });
  2003. };
  2004. logger.debug(`${this} Queued setVideoCodecs task`);
  2005. // Queue and execute
  2006. this.modificationQueue.push(workFunction);
  2007. }
  2008. }
  2009. /**
  2010. * @inheritDoc
  2011. */
  2012. terminate(success, failure, options) {
  2013. if (this.state === JingleSessionState.ENDED) {
  2014. return;
  2015. }
  2016. if (!options || Boolean(options.sendSessionTerminate)) {
  2017. const sessionTerminate
  2018. = $iq({
  2019. to: this.remoteJid,
  2020. type: 'set'
  2021. })
  2022. .c('jingle', {
  2023. xmlns: 'urn:xmpp:jingle:1',
  2024. action: 'session-terminate',
  2025. initiator: this.initiatorJid,
  2026. sid: this.sid
  2027. })
  2028. .c('reason')
  2029. .c((options && options.reason) || 'success')
  2030. .up();
  2031. if (options && options.reasonDescription) {
  2032. sessionTerminate
  2033. .c('text')
  2034. .t(options.reasonDescription)
  2035. .up()
  2036. .up();
  2037. } else {
  2038. sessionTerminate.up();
  2039. }
  2040. this._bridgeSessionId
  2041. && sessionTerminate.c(
  2042. 'bridge-session', {
  2043. xmlns: 'http://jitsi.org/protocol/focus',
  2044. id: this._bridgeSessionId,
  2045. restart: options && options.requestRestart === true
  2046. }).up();
  2047. logger.info(`${this} Sending session-terminate`);
  2048. logger.debug(sessionTerminate.tree());
  2049. this.connection.sendIQ(
  2050. sessionTerminate,
  2051. success,
  2052. this.newJingleErrorHandler(sessionTerminate, failure),
  2053. IQ_TIMEOUT);
  2054. } else {
  2055. logger.info(`${this} Skipped sending session-terminate`);
  2056. }
  2057. // this should result in 'onTerminated' being called by strope.jingle.js
  2058. this.connection.jingle.terminate(this.sid);
  2059. }
  2060. /**
  2061. * Converts to string with minor summary.
  2062. *
  2063. * @return {string}
  2064. */
  2065. toString() {
  2066. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2067. }
  2068. }