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

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