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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import { $build, $iq, Strophe } from 'strophe.js';
  4. import { JitsiTrackEvents } from '../../JitsiTrackEvents';
  5. import * as CodecMimeType from '../../service/RTC/CodecMimeType';
  6. import { MediaDirection } from '../../service/RTC/MediaDirection';
  7. import { MediaType } from '../../service/RTC/MediaType';
  8. import { VideoType } from '../../service/RTC/VideoType';
  9. import {
  10. ICE_DURATION,
  11. ICE_STATE_CHANGED
  12. } from '../../service/statistics/AnalyticsEvents';
  13. import { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  14. import { SS_DEFAULT_FRAME_RATE } from '../RTC/ScreenObtainer';
  15. import FeatureFlags from '../flags/FeatureFlags';
  16. import SDP from '../sdp/SDP';
  17. import SDPDiffer from '../sdp/SDPDiffer';
  18. import SDPUtil from '../sdp/SDPUtil';
  19. import Statistics from '../statistics/statistics';
  20. import AsyncQueue from '../util/AsyncQueue';
  21. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  22. import { integerHash } from '../util/StringUtils';
  23. import browser from './../browser';
  24. import JingleSession from './JingleSession';
  25. import * as JingleSessionState from './JingleSessionState';
  26. import MediaSessionEvents from './MediaSessionEvents';
  27. import XmppConnection from './XmppConnection';
  28. const logger = getLogger(__filename);
  29. /**
  30. * Constant tells how long we're going to wait for IQ response, before timeout
  31. * error is triggered.
  32. * @type {number}
  33. */
  34. const IQ_TIMEOUT = 10000;
  35. /*
  36. * The default number of samples (per stat) to keep when webrtc stats gathering
  37. * is enabled in TraceablePeerConnection.
  38. */
  39. const DEFAULT_MAX_STATS = 300;
  40. /**
  41. * The time duration for which the client keeps gathering ICE candidates to be sent out in a single IQ.
  42. * @type {number} timeout in ms.
  43. */
  44. const ICE_CAND_GATHERING_TIMEOUT = 150;
  45. /**
  46. * Reads the endpoint ID given a string which represents either the endpoint's full JID, or the endpoint ID itself.
  47. * @param {String} jidOrEndpointId A string which is either the full JID of a participant, or the ID of an
  48. * endpoint/participant.
  49. * @returns The endpoint ID associated with 'jidOrEndpointId'.
  50. */
  51. function getEndpointId(jidOrEndpointId) {
  52. return Strophe.getResourceFromJid(jidOrEndpointId) || jidOrEndpointId;
  53. }
  54. /**
  55. * Add "source" element as a child of "description" element.
  56. * @param {Object} description The "description" element to add to.
  57. * @param {Object} s Contains properties of the source being added.
  58. * @param {Number} ssrc_ The SSRC.
  59. * @param {String} msid The "msid" attribute.
  60. */
  61. function _addSourceElement(description, s, ssrc_, msid) {
  62. description.c('source', {
  63. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  64. ssrc: ssrc_,
  65. name: s.source
  66. })
  67. .c('parameter', {
  68. name: 'msid',
  69. value: msid
  70. })
  71. .up()
  72. .c('ssrc-info', {
  73. xmlns: 'http://jitsi.org/jitmeet',
  74. owner: s.owner
  75. })
  76. .up()
  77. .up();
  78. }
  79. /**
  80. * @typedef {Object} JingleSessionPCOptions
  81. * @property {Object} abTesting - A/B testing related options (ask George).
  82. * @property {boolean} abTesting.enableSuspendVideoTest - enables the suspend
  83. * video test ?(ask George).
  84. * @property {boolean} disableRtx - Described in the config.js[1].
  85. * @property {boolean} disableSimulcast - Described in the config.js[1].
  86. * @property {boolean} enableInsertableStreams - Set to true when the insertable streams constraints is to be enabled
  87. * on the PeerConnection.
  88. * @property {boolean} failICE - it's an option used in the tests. Set to
  89. * <tt>true</tt> to block any real candidates and make the ICE fail.
  90. * @property {boolean} gatherStats - Described in the config.js[1].
  91. * @property {object} p2p - Peer to peer related options (FIXME those could be
  92. * fetched from config.p2p on the upper level).
  93. * @property {boolean} preferH264 - Described in the config.js[1].
  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' or 'transport-replace'.
  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._localVideoActive = 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._remoteVideoActive = true;
  253. /**
  254. * Marks that ICE gathering duration has been reported already. That
  255. * prevents reporting it again, after eventual 'transport-replace' (JVB
  256. * conference migration/ICE restart).
  257. * @type {boolean}
  258. * @private
  259. */
  260. this._gatheringReported = false;
  261. this.lasticecandidate = false;
  262. this.closed = false;
  263. /**
  264. * Indicates whether or not this <tt>JingleSessionPC</tt> is used in
  265. * a peer to peer type of session.
  266. * @type {boolean} <tt>true</tt> if it's a peer to peer
  267. * session or <tt>false</tt> if it's a JVB session
  268. */
  269. this.isP2P = isP2P;
  270. /**
  271. * Remote preference for the receive video max frame height.
  272. *
  273. * @type {Number|undefined}
  274. */
  275. this.remoteRecvMaxFrameHeight = undefined;
  276. /**
  277. * Number of remote video sources, in SSRC rewriting mode.
  278. * Used to generate next unique msid attribute.
  279. *
  280. * @type {Number}
  281. */
  282. this.numRemoteVideoSources = 0;
  283. /**
  284. * Number of remote audio sources, in SSRC rewriting mode.
  285. * Used to generate next unique msid attribute.
  286. *
  287. * @type {Number}
  288. */
  289. this.numRemoteAudioSources = 0;
  290. /**
  291. * Remote preference for the receive video max frame heights when source-name signaling is enabled.
  292. *
  293. * @type {Map<string, number>|undefined}
  294. */
  295. this.remoteSourceMaxFrameHeights = undefined;
  296. /**
  297. * The queue used to serialize operations done on the peerconnection.
  298. *
  299. * @type {AsyncQueue}
  300. */
  301. this.modificationQueue = new AsyncQueue();
  302. /**
  303. * Flag used to guarantee that the connection established event is
  304. * triggered just once.
  305. * @type {boolean}
  306. */
  307. this.wasConnected = false;
  308. /**
  309. * Keeps track of how long (in ms) it took from ICE start to ICE
  310. * connect.
  311. *
  312. * @type {number}
  313. */
  314. this.establishmentDuration = undefined;
  315. this._xmppListeners = [];
  316. this._xmppListeners.push(
  317. connection.addEventListener(
  318. XmppConnection.Events.CONN_STATUS_CHANGED,
  319. this.onXmppStatusChanged.bind(this))
  320. );
  321. this._removeSenderVideoConstraintsChangeListener = undefined;
  322. }
  323. /* eslint-enable max-params */
  324. /**
  325. * Checks whether or not this session instance is still operational.
  326. * @private
  327. * @returns {boolean} {@code true} if operation or {@code false} otherwise.
  328. */
  329. _assertNotEnded() {
  330. return this.state !== JingleSessionState.ENDED;
  331. }
  332. /**
  333. * @inheritDoc
  334. * @param {JingleSessionPCOptions} options - a set of config options.
  335. */
  336. doInitialize(options) {
  337. this.failICE = Boolean(options.failICE);
  338. this.lasticecandidate = false;
  339. this.options = options;
  340. /**
  341. * {@code true} if reconnect is in progress.
  342. * @type {boolean}
  343. */
  344. this.isReconnect = false;
  345. /**
  346. * Set to {@code true} if the connection was ever stable
  347. * @type {boolean}
  348. */
  349. this.wasstable = false;
  350. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  351. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  352. const pcOptions = { disableRtx: options.disableRtx };
  353. if (options.gatherStats) {
  354. pcOptions.maxstats = DEFAULT_MAX_STATS;
  355. }
  356. pcOptions.capScreenshareBitrate = false;
  357. pcOptions.codecSettings = options.codecSettings;
  358. pcOptions.enableInsertableStreams = options.enableInsertableStreams;
  359. pcOptions.videoQuality = options.videoQuality;
  360. pcOptions.forceTurnRelay = options.forceTurnRelay;
  361. pcOptions.audioQuality = options.audioQuality;
  362. pcOptions.usesUnifiedPlan = this.usesUnifiedPlan
  363. = browser.supportsUnifiedPlan()
  364. && (!browser.isChromiumBased()
  365. || (browser.isChromiumBased()
  366. // Provide a way to control the behavior for jvb and p2p connections independently.
  367. && this.isP2P
  368. ? options.p2p?.enableUnifiedOnChrome ?? true
  369. : options.enableUnifiedOnChrome ?? true));
  370. if (this.isP2P) {
  371. // simulcast needs to be disabled for P2P (121) calls
  372. pcOptions.disableSimulcast = true;
  373. const abtestSuspendVideo = this._abtestSuspendVideoEnabled(options);
  374. if (typeof abtestSuspendVideo !== 'undefined') {
  375. pcOptions.abtestSuspendVideo = abtestSuspendVideo;
  376. }
  377. } else {
  378. // H264 scalability is not supported on jvb, so simulcast needs to be disabled when H264 is preferred.
  379. pcOptions.disableSimulcast
  380. = options.disableSimulcast || options.videoQuality?.preferredCodec === CodecMimeType.H264;
  381. // Do not send lower spatial layers for low fps screenshare and enable them only for high fps screenshare.
  382. pcOptions.capScreenshareBitrate = pcOptions.disableSimulcast
  383. || !(typeof options.desktopSharingFrameRate?.max === 'number'
  384. && options.desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE);
  385. }
  386. if (options.startSilent) {
  387. pcOptions.startSilent = true;
  388. }
  389. this.peerconnection
  390. = this.rtc.createPeerConnection(
  391. this._signalingLayer,
  392. this.pcConfig,
  393. this.isP2P,
  394. pcOptions);
  395. this.peerconnection.onicecandidate = ev => {
  396. if (!ev) {
  397. // There was an incomplete check for ev before which left
  398. // the last line of the function unprotected from a potential
  399. // throw of an exception. Consequently, it may be argued that
  400. // the check is unnecessary. Anyway, I'm leaving it and making
  401. // the check complete.
  402. return;
  403. }
  404. // XXX this is broken, candidate is not parsed.
  405. const candidate = ev.candidate;
  406. const now = window.performance.now();
  407. if (candidate) {
  408. if (this._gatheringStartedTimestamp === null) {
  409. this._gatheringStartedTimestamp = now;
  410. }
  411. // Discard candidates of disabled protocols.
  412. let protocol = candidate.protocol;
  413. if (typeof protocol === 'string') {
  414. protocol = protocol.toLowerCase();
  415. if (protocol === 'tcp' || protocol === 'ssltcp') {
  416. if (this.webrtcIceTcpDisable) {
  417. return;
  418. }
  419. } else if (protocol === 'udp') {
  420. if (this.webrtcIceUdpDisable) {
  421. return;
  422. }
  423. }
  424. }
  425. } else if (!this._gatheringReported) {
  426. // End of gathering
  427. Statistics.sendAnalytics(
  428. ICE_DURATION,
  429. {
  430. phase: 'gathering',
  431. value: now - this._gatheringStartedTimestamp,
  432. p2p: this.isP2P,
  433. initiator: this.isInitiator
  434. });
  435. this._gatheringReported = true;
  436. }
  437. if (this.isP2P) {
  438. this.sendIceCandidate(candidate);
  439. }
  440. };
  441. // Note there is a change in the spec about closed:
  442. // This value moved into the RTCPeerConnectionState enum in
  443. // the May 13, 2016 draft of the specification, as it reflects the state
  444. // of the RTCPeerConnection, not the signaling connection. You now
  445. // detect a closed connection by checking for connectionState to be
  446. // "closed" instead.
  447. // I suppose at some point this will be moved to onconnectionstatechange
  448. this.peerconnection.onsignalingstatechange = () => {
  449. if (this.peerconnection.signalingState === 'stable') {
  450. this.wasstable = true;
  451. } else if (this.peerconnection.signalingState === 'closed'
  452. || this.peerconnection.connectionState === 'closed') {
  453. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  454. }
  455. };
  456. /**
  457. * The oniceconnectionstatechange event handler contains the code to
  458. * execute when the iceconnectionstatechange event, of type Event,
  459. * is received by this RTCPeerConnection. Such an event is sent when
  460. * the value of RTCPeerConnection.iceConnectionState changes.
  461. */
  462. this.peerconnection.oniceconnectionstatechange = () => {
  463. const now = window.performance.now();
  464. let isStable = false;
  465. if (!this.isP2P) {
  466. this.room.connectionTimes[
  467. `ice.state.${this.peerconnection.iceConnectionState}`]
  468. = now;
  469. }
  470. logger.log(`(TIME) ICE ${this.peerconnection.iceConnectionState} ${this.isP2P ? 'P2P' : 'JVB'}:\t`, now);
  471. Statistics.sendAnalytics(
  472. ICE_STATE_CHANGED,
  473. {
  474. p2p: this.isP2P,
  475. state: this.peerconnection.iceConnectionState,
  476. 'signaling_state': this.peerconnection.signalingState,
  477. reconnect: this.isReconnect,
  478. value: now
  479. });
  480. this.room.eventEmitter.emit(
  481. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  482. this,
  483. this.peerconnection.iceConnectionState);
  484. switch (this.peerconnection.iceConnectionState) {
  485. case 'checking':
  486. this._iceCheckingStartedTimestamp = now;
  487. break;
  488. case 'connected':
  489. // Informs interested parties that the connection has been restored. This includes the case when
  490. // media connection to the bridge has been restored after an ICE failure by using session-terminate.
  491. if (this.peerconnection.signalingState === 'stable') {
  492. isStable = true;
  493. const usesTerminateForRestart = !this.options.enableIceRestart
  494. && this.room.supportsRestartByTerminate();
  495. if (this.isReconnect || usesTerminateForRestart) {
  496. this.room.eventEmitter.emit(
  497. XMPPEvents.CONNECTION_RESTORED, this);
  498. }
  499. }
  500. // Add a workaround for an issue on chrome in Unified plan when the local endpoint is the offerer.
  501. // The 'signalingstatechange' event for 'stable' is handled after the 'iceconnectionstatechange' event
  502. // for 'completed' is handled by the client. This prevents the client from firing a
  503. // CONNECTION_ESTABLISHED event for the p2p session. As a result, the offerer continues to stay on the
  504. // jvb connection while the remote peer switches to the p2p connection breaking the media flow between
  505. // the endpoints.
  506. // TODO - file a chromium bug and add the information here.
  507. if (!this.wasConnected
  508. && (this.wasstable
  509. || isStable
  510. || (this.usesUnifiedPlan && this.isInitiator
  511. && (browser.isChromiumBased() || browser.isReactNative())))) {
  512. Statistics.sendAnalytics(
  513. ICE_DURATION,
  514. {
  515. phase: 'checking',
  516. value: now - this._iceCheckingStartedTimestamp,
  517. p2p: this.isP2P,
  518. initiator: this.isInitiator
  519. });
  520. // Switch between ICE gathering and ICE checking whichever
  521. // started first (scenarios are different for initiator
  522. // vs responder)
  523. const iceStarted
  524. = Math.min(
  525. this._iceCheckingStartedTimestamp,
  526. this._gatheringStartedTimestamp);
  527. this.establishmentDuration = now - iceStarted;
  528. Statistics.sendAnalytics(
  529. ICE_DURATION,
  530. {
  531. phase: 'establishment',
  532. value: this.establishmentDuration,
  533. p2p: this.isP2P,
  534. initiator: this.isInitiator
  535. });
  536. this.wasConnected = true;
  537. this.room.eventEmitter.emit(
  538. XMPPEvents.CONNECTION_ESTABLISHED, this);
  539. }
  540. this.isReconnect = false;
  541. break;
  542. case 'disconnected':
  543. this.isReconnect = true;
  544. // Informs interested parties that the connection has been
  545. // interrupted.
  546. if (this.wasstable) {
  547. this.room.eventEmitter.emit(
  548. XMPPEvents.CONNECTION_INTERRUPTED, this);
  549. }
  550. break;
  551. case 'failed':
  552. this.room.eventEmitter.emit(
  553. XMPPEvents.CONNECTION_ICE_FAILED, this);
  554. break;
  555. }
  556. };
  557. /**
  558. * The connection state event is fired whenever the aggregate of underlying
  559. * transports change their state.
  560. */
  561. this.peerconnection.onconnectionstatechange = () => {
  562. const icestate = this.peerconnection.iceConnectionState;
  563. switch (this.peerconnection.connectionState) {
  564. case 'failed':
  565. // Since version 76 Chrome no longer switches ICE connection
  566. // state to failed (see
  567. // https://bugs.chromium.org/p/chromium/issues/detail?id=982793
  568. // for details) we use this workaround to recover from lost connections
  569. if (icestate === 'disconnected') {
  570. this.room.eventEmitter.emit(
  571. XMPPEvents.CONNECTION_ICE_FAILED, this);
  572. }
  573. break;
  574. }
  575. };
  576. /**
  577. * The negotiationneeded event is fired whenever we shake the media on the
  578. * RTCPeerConnection object.
  579. */
  580. this.peerconnection.onnegotiationneeded = () => {
  581. const state = this.peerconnection.signalingState;
  582. const remoteDescription = this.peerconnection.remoteDescription;
  583. if (this.usesUnifiedPlan
  584. && !this.isP2P
  585. && state === 'stable'
  586. && remoteDescription
  587. && typeof remoteDescription.sdp === 'string') {
  588. logger.info(`${this} onnegotiationneeded fired on ${this.peerconnection}`);
  589. const workFunction = finishedCallback => {
  590. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  591. this._renegotiate()
  592. .then(() => this.peerconnection.configureSenderVideoEncodings())
  593. .then(() => {
  594. const newSdp = new SDP(this.peerconnection.localDescription.sdp);
  595. this.notifyMySSRCUpdate(oldSdp, newSdp);
  596. })
  597. .then(() => finishedCallback(), error => finishedCallback(error));
  598. };
  599. this.modificationQueue.push(
  600. workFunction,
  601. error => {
  602. if (error) {
  603. logger.error(`${this} onnegotiationneeded error`, error);
  604. } else {
  605. logger.debug(`${this} onnegotiationneeded executed - OK`);
  606. }
  607. });
  608. }
  609. };
  610. }
  611. /**
  612. * Remote preference for receive video max frame height.
  613. *
  614. * @returns {Number|undefined}
  615. */
  616. getRemoteRecvMaxFrameHeight() {
  617. if (this.isP2P) {
  618. return this.remoteRecvMaxFrameHeight;
  619. }
  620. return undefined;
  621. }
  622. /**
  623. * Remote preference for receive video max frame heights when source-name signaling is enabled.
  624. *
  625. * @returns {Map<string, number>|undefined}
  626. */
  627. getRemoteSourcesRecvMaxFrameHeight() {
  628. if (this.isP2P) {
  629. return this.remoteSourceMaxFrameHeights;
  630. }
  631. return undefined;
  632. }
  633. /**
  634. * Sends given candidate in Jingle 'transport-info' message.
  635. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  636. * @private
  637. */
  638. sendIceCandidate(candidate) {
  639. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  640. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  641. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  642. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  643. if (!(ice && jcand)) {
  644. const errorMesssage = 'failed to get ice && jcand';
  645. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  646. logger.error(errorMesssage);
  647. return;
  648. }
  649. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  650. if (this.usedrip) {
  651. if (this.dripContainer.length === 0) {
  652. setTimeout(() => {
  653. if (this.dripContainer.length === 0) {
  654. return;
  655. }
  656. this.sendIceCandidates(this.dripContainer);
  657. this.dripContainer = [];
  658. }, ICE_CAND_GATHERING_TIMEOUT);
  659. }
  660. this.dripContainer.push(candidate);
  661. } else {
  662. this.sendIceCandidates([ candidate ]);
  663. }
  664. } else {
  665. logger.log(`${this} sendIceCandidate: last candidate`);
  666. // FIXME: remember to re-think in ICE-restart
  667. this.lasticecandidate = true;
  668. }
  669. }
  670. /**
  671. * Sends given candidates in Jingle 'transport-info' message.
  672. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  673. * candidate instances
  674. * @private
  675. */
  676. sendIceCandidates(candidates) {
  677. if (!this._assertNotEnded('sendIceCandidates')) {
  678. return;
  679. }
  680. logger.log(`${this} sendIceCandidates ${JSON.stringify(candidates)}`);
  681. const cand = $iq({ to: this.remoteJid,
  682. type: 'set' })
  683. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  684. action: 'transport-info',
  685. initiator: this.initiatorJid,
  686. sid: this.sid });
  687. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  688. for (let mid = 0; mid < localSDP.media.length; mid++) {
  689. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  690. const mline
  691. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  692. if (cands.length > 0) {
  693. const ice
  694. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  695. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  696. cand.c('content', {
  697. creator: this.initiatorJid === this.localJid
  698. ? 'initiator' : 'responder',
  699. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  700. }).c('transport', ice);
  701. for (let i = 0; i < cands.length; i++) {
  702. const candidate
  703. = SDPUtil.candidateToJingle(cands[i].candidate);
  704. // Mangle ICE candidate if 'failICE' test option is enabled
  705. if (this.failICE) {
  706. candidate.ip = '1.1.1.1';
  707. }
  708. cand.c('candidate', candidate).up();
  709. }
  710. // add fingerprint
  711. const fingerprintLine
  712. = SDPUtil.findLine(
  713. localSDP.media[mid],
  714. 'a=fingerprint:', localSDP.session);
  715. if (fingerprintLine) {
  716. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  717. tmp.required = true;
  718. cand.c(
  719. 'fingerprint',
  720. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  721. .t(tmp.fingerprint);
  722. delete tmp.fingerprint;
  723. cand.attrs(tmp);
  724. cand.up();
  725. }
  726. cand.up(); // transport
  727. cand.up(); // content
  728. }
  729. }
  730. // might merge last-candidate notification into this, but it is called
  731. // a lot later. See webrtc issue #2340
  732. // logger.log('was this the last candidate', this.lasticecandidate);
  733. this.connection.sendIQ(
  734. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  735. }
  736. /**
  737. * Sends Jingle 'session-info' message which includes custom Jitsi Meet
  738. * 'ice-state' element with the text value 'failed' to let Jicofo know
  739. * that the ICE connection has entered the failed state. It can then
  740. * choose to re-create JVB channels and send 'transport-replace' to
  741. * retry the connection.
  742. */
  743. sendIceFailedNotification() {
  744. const sessionInfo
  745. = $iq({
  746. to: this.remoteJid,
  747. type: 'set' })
  748. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  749. action: 'session-info',
  750. initiator: this.initiatorJid,
  751. sid: this.sid })
  752. .c('ice-state', { xmlns: 'http://jitsi.org/protocol/focus' })
  753. .t('failed')
  754. .up();
  755. this._bridgeSessionId
  756. && sessionInfo.c(
  757. 'bridge-session', {
  758. xmlns: 'http://jitsi.org/protocol/focus',
  759. id: this._bridgeSessionId
  760. });
  761. this.connection.sendIQ2(
  762. sessionInfo, {
  763. /*
  764. * This message will be often sent when there are connectivity
  765. * issues, so make it slightly longer than Prosody's default BOSH
  766. * inactivity timeout of 60 seconds.
  767. */
  768. timeout: 65
  769. })
  770. .catch(this.newJingleErrorHandler(sessionInfo));
  771. }
  772. /**
  773. * {@inheritDoc}
  774. */
  775. addIceCandidates(elem) {
  776. if (this.peerconnection.signalingState === 'closed') {
  777. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  778. return;
  779. }
  780. const iceCandidates = [];
  781. elem.find('>content>transport>candidate')
  782. .each((idx, candidate) => {
  783. let line = SDPUtil.candidateFromJingle(candidate);
  784. line = line.replace('\r\n', '').replace('a=', '');
  785. // FIXME this code does not care to handle
  786. // non-bundle transport
  787. const rtcCandidate = new RTCIceCandidate({
  788. sdpMLineIndex: 0,
  789. // FF comes up with more complex names like audio-23423,
  790. // Given that it works on both Chrome and FF without
  791. // providing it, let's leave it like this for the time
  792. // being...
  793. // sdpMid: 'audio',
  794. sdpMid: '',
  795. candidate: line
  796. });
  797. iceCandidates.push(rtcCandidate);
  798. });
  799. if (!iceCandidates.length) {
  800. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  801. return;
  802. }
  803. // We want to have this task queued, so that we know it is executed,
  804. // after the initial sRD/sLD offer/answer cycle was done (based on
  805. // the assumption that candidates are spawned after the offer/answer
  806. // and XMPP preserves order).
  807. const workFunction = finishedCallback => {
  808. for (const iceCandidate of iceCandidates) {
  809. this.peerconnection.addIceCandidate(iceCandidate)
  810. .then(
  811. () => logger.debug(`${this} addIceCandidate ok!`),
  812. err => logger.error(`${this} addIceCandidate failed!`, err));
  813. }
  814. finishedCallback();
  815. logger.debug(`${this} ICE candidates task finished`);
  816. };
  817. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  818. this.modificationQueue.push(workFunction);
  819. }
  820. /**
  821. *
  822. * @param contents
  823. */
  824. readSsrcInfo(contents) {
  825. const ssrcs = $(contents).find('>description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  826. ssrcs.each((i, ssrcElement) => {
  827. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  828. if (ssrcElement.hasAttribute('name')) {
  829. const sourceName = ssrcElement.getAttribute('name');
  830. this._signalingLayer.setTrackSourceName(ssrc, sourceName);
  831. }
  832. if (this.isP2P) {
  833. // In P2P all SSRCs are owner by the remote peer
  834. this._signalingLayer.setSSRCOwner(ssrc, Strophe.getResourceFromJid(this.remoteJid));
  835. } else {
  836. $(ssrcElement)
  837. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  838. .each((i3, ssrcInfoElement) => {
  839. const owner = ssrcInfoElement.getAttribute('owner');
  840. if (owner?.length) {
  841. if (isNaN(ssrc) || ssrc < 0) {
  842. logger.warn(`${this} Invalid SSRC ${ssrc} value received for ${owner}`);
  843. } else {
  844. this._signalingLayer.setSSRCOwner(ssrc, getEndpointId(owner));
  845. }
  846. }
  847. });
  848. }
  849. });
  850. }
  851. /**
  852. * Makes the underlying TraceablePeerConnection generate new SSRC for
  853. * the recvonly video stream.
  854. * @deprecated
  855. */
  856. generateRecvonlySsrc() {
  857. if (this.peerconnection) {
  858. this.peerconnection.generateRecvonlySsrc();
  859. } else {
  860. logger.error(`${this} Unable to generate recvonly SSRC - no peerconnection`);
  861. }
  862. }
  863. /**
  864. * Returns the video codec configured as the preferred codec on the peerconnection.
  865. */
  866. getConfiguredVideoCodec() {
  867. return this.peerconnection.getConfiguredVideoCodec();
  868. }
  869. /**
  870. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  871. *
  872. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  873. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  874. * 'session-accept' sent.
  875. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  876. * can be used to log some details about the error.
  877. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  878. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  879. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  880. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  881. * assumption that the initial offer/answer cycle has been executed already.
  882. */
  883. acceptOffer(jingleOffer, success, failure, localTracks) {
  884. this.setOfferAnswerCycle(
  885. jingleOffer,
  886. () => {
  887. // FIXME we may not care about RESULT packet for session-accept
  888. // then we should either call 'success' here immediately or
  889. // modify sendSessionAccept method to do that
  890. this.sendSessionAccept(() => {
  891. success();
  892. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  893. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  894. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  895. // This will happen when someone shares a secondary source to a two people call, the other user
  896. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  897. // point, there are 2 video tracks which need to be signaled to the remote peer.
  898. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  899. videoTracks.length && videoTracks.splice(0, 1);
  900. if (FeatureFlags.isMultiStreamSendSupportEnabled() && videoTracks.length) {
  901. this.addTracks(videoTracks);
  902. }
  903. },
  904. error => {
  905. failure(error);
  906. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  907. });
  908. },
  909. failure,
  910. localTracks);
  911. }
  912. /**
  913. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  914. *
  915. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  916. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  917. */
  918. invite(localTracks = []) {
  919. if (!this.isInitiator) {
  920. throw new Error('Trying to invite from the responder session');
  921. }
  922. const workFunction = finishedCallback => {
  923. const addTracks = [];
  924. for (const track of localTracks) {
  925. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  926. }
  927. Promise.all(addTracks)
  928. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  929. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  930. .then(() => {
  931. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  932. // NOTE that the offer is obtained from the localDescription getter as it needs to go though
  933. // the transformation chain.
  934. this.sendSessionInitiate(this.peerconnection.localDescription.sdp);
  935. })
  936. .then(() => finishedCallback(), error => finishedCallback(error));
  937. };
  938. logger.debug(`${this} Queued invite task`);
  939. this.modificationQueue.push(
  940. workFunction,
  941. error => {
  942. if (error) {
  943. logger.error(`${this} invite error`, error);
  944. } else {
  945. logger.debug(`${this} invite executed - OK`);
  946. }
  947. });
  948. }
  949. /**
  950. * Sends 'session-initiate' to the remote peer.
  951. *
  952. * NOTE this method is synchronous and we're not waiting for the RESULT
  953. * response which would delay the startup process.
  954. *
  955. * @param {string} offerSdp - The local session description which will be
  956. * used to generate an offer.
  957. * @private
  958. */
  959. sendSessionInitiate(offerSdp) {
  960. let init = $iq({
  961. to: this.remoteJid,
  962. type: 'set'
  963. }).c('jingle', {
  964. xmlns: 'urn:xmpp:jingle:1',
  965. action: 'session-initiate',
  966. initiator: this.initiatorJid,
  967. sid: this.sid
  968. });
  969. new SDP(offerSdp).toJingle(
  970. init,
  971. this.isInitiator ? 'initiator' : 'responder');
  972. init = init.tree();
  973. logger.debug(`${this} Session-initiate: `, init);
  974. this.connection.sendIQ(init,
  975. () => {
  976. logger.info(`${this} Got RESULT for "session-initiate"`);
  977. },
  978. error => {
  979. logger.error(`${this} "session-initiate" error`, error);
  980. },
  981. IQ_TIMEOUT);
  982. }
  983. /**
  984. * Sets the answer received from the remote peer as the remote description.
  985. *
  986. * @param jingleAnswer
  987. */
  988. setAnswer(jingleAnswer) {
  989. if (!this.isInitiator) {
  990. throw new Error('Trying to set an answer on the responder session');
  991. }
  992. const workFunction = finishedCallback => {
  993. const newRemoteSdp = this._processNewJingleOfferIq(jingleAnswer);
  994. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  995. const remoteDescription = new RTCSessionDescription({
  996. type: 'answer',
  997. sdp: newRemoteSdp.raw
  998. });
  999. this.peerconnection.setRemoteDescription(remoteDescription)
  1000. .then(() => {
  1001. if (this.state === JingleSessionState.PENDING) {
  1002. this.state = JingleSessionState.ACTIVE;
  1003. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1004. this.sendContentModify();
  1005. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1006. }
  1007. })
  1008. .then(() => finishedCallback(), error => finishedCallback(error));
  1009. };
  1010. logger.debug(`${this} Queued setAnswer task`);
  1011. this.modificationQueue.push(
  1012. workFunction,
  1013. error => {
  1014. if (error) {
  1015. logger.error(`${this} setAnswer task failed: ${error}`);
  1016. } else {
  1017. logger.debug(`${this} setAnswer task done`);
  1018. }
  1019. });
  1020. }
  1021. /**
  1022. * This is a setRemoteDescription/setLocalDescription cycle which starts at converting Strophe Jingle IQ into
  1023. * remote offer SDP. Once converted, setRemoteDescription, createAnswer and setLocalDescription calls follow.
  1024. *
  1025. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element of the offer (or answer) IQ
  1026. * @param success callback called when sRD/sLD cycle finishes successfully.
  1027. * @param failure callback called with an error object as an argument if we fail at any point during setRD,
  1028. * createAnswer, setLD.
  1029. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  1030. * the offer/answer cycle executes (for the local track addition to be an atomic operation together with the
  1031. * offer/answer).
  1032. */
  1033. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  1034. const workFunction = finishedCallback => {
  1035. const addTracks = [];
  1036. const audioTracks = localTracks.filter(track => track.getType() === MediaType.AUDIO);
  1037. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  1038. let tracks = localTracks;
  1039. // Add only 1 video track at a time. Adding 2 or more video tracks to the peerconnection at the same time
  1040. // makes the browser go into a renegotiation loop by firing 'negotiationneeded' event after every
  1041. // renegotiation.
  1042. if (FeatureFlags.isMultiStreamSendSupportEnabled() && videoTracks.length > 1) {
  1043. tracks = [ ...audioTracks, videoTracks[0] ];
  1044. }
  1045. for (const track of tracks) {
  1046. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1047. }
  1048. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  1049. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1050. const bridgeSession = $(jingleOfferAnswerIq)
  1051. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]');
  1052. const bridgeSessionId = bridgeSession.attr('id');
  1053. if (bridgeSessionId !== this._bridgeSessionId) {
  1054. this._bridgeSessionId = bridgeSessionId;
  1055. }
  1056. const remoteDescription = new RTCSessionDescription({
  1057. type: 'offer',
  1058. sdp: newRemoteSdp.raw
  1059. });
  1060. Promise.all(addTracks)
  1061. .then(() => this._responderRenegotiate(remoteDescription))
  1062. .then(() => {
  1063. this.peerconnection.processLocalSdpForTransceiverInfo(tracks);
  1064. if (this.state === JingleSessionState.PENDING) {
  1065. this.state = JingleSessionState.ACTIVE;
  1066. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1067. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1068. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1069. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1070. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1071. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1072. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1073. if (this.isP2P
  1074. && (!this._localVideoActive || this._sourceReceiverConstraints)) {
  1075. this.sendContentModify();
  1076. }
  1077. }
  1078. // Old local SDP will be available when we're setting answer for the first time, but not when offer
  1079. // and it's fine since we're generating an answer now it will contain all our SSRCs.
  1080. if (oldLocalSdp) {
  1081. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1082. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSdp);
  1083. }
  1084. })
  1085. .then(() => finishedCallback(), error => finishedCallback(error));
  1086. };
  1087. logger.debug(`${this} Queued setOfferAnswerCycle task`);
  1088. this.modificationQueue.push(
  1089. workFunction,
  1090. error => {
  1091. if (error) {
  1092. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1093. failure(error);
  1094. } else {
  1095. logger.debug(`${this} setOfferAnswerCycle task done`);
  1096. success();
  1097. }
  1098. });
  1099. }
  1100. /**
  1101. * Updates the codecs on the peerconnection and initiates a renegotiation for the
  1102. * new codec config to take effect.
  1103. *
  1104. * @param {CodecMimeType} preferred the preferred codec.
  1105. * @param {CodecMimeType} disabled the codec that needs to be disabled.
  1106. */
  1107. setVideoCodecs(preferred = null, disabled = null) {
  1108. if (this._assertNotEnded()) {
  1109. logger.info(`${this} setVideoCodecs: preferred=${preferred}, disabled=${disabled}`);
  1110. this.peerconnection.setVideoCodecs(preferred, disabled);
  1111. // Initiate a renegotiate for the codec setting to take effect.
  1112. const workFunction = finishedCallback => {
  1113. this._renegotiate().then(
  1114. () => {
  1115. logger.debug(`${this} setVideoCodecs task is done`);
  1116. return finishedCallback();
  1117. }, error => {
  1118. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  1119. return finishedCallback(error);
  1120. });
  1121. };
  1122. logger.debug(`${this} Queued setVideoCodecs task`);
  1123. // Queue and execute
  1124. this.modificationQueue.push(workFunction);
  1125. }
  1126. }
  1127. /* eslint-enable max-params */
  1128. /**
  1129. * Although it states "replace transport" it does accept full Jingle offer
  1130. * which should contain new ICE transport details.
  1131. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  1132. * transport info.
  1133. * @param success callback called when we succeed to accept new offer.
  1134. * @param failure function(error) called when we fail to accept new offer.
  1135. */
  1136. replaceTransport(jingleOfferElem, success, failure) {
  1137. if (this.options.enableForcedReload) {
  1138. const sdp = new SDP(this.peerconnection.localDescription.sdp);
  1139. this.sendTransportAccept(sdp, success, failure);
  1140. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTARTED, this);
  1141. return;
  1142. }
  1143. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  1144. // We need to first reject the 'data' section to have the SCTP stack
  1145. // cleaned up to signal the known data channel is now invalid. After
  1146. // that the original offer is set to have the SCTP connection
  1147. // established with the new bridge.
  1148. const originalOffer = jingleOfferElem.clone();
  1149. jingleOfferElem
  1150. .find('>content[name=\'data\']')
  1151. .attr('senders', 'rejected');
  1152. // Remove all remote sources in order to reset the client's state
  1153. // for the remote MediaStreams. When a conference is moved to
  1154. // another bridge it will start streaming with a sequence number
  1155. // that is not in sync with the most recently seen by the client.
  1156. // The symptoms include frozen or black video and lots of "failed to
  1157. // unprotect SRTP packets" in Chrome logs.
  1158. jingleOfferElem
  1159. .find('>content>description>source')
  1160. .remove();
  1161. jingleOfferElem
  1162. .find('>content>description>ssrc-group')
  1163. .remove();
  1164. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  1165. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  1166. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  1167. // fingerprint has changed by setting an all zeros key.
  1168. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  1169. newFingerprint.attr('hash', 'sha-1');
  1170. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  1171. // First set an offer with a rejected 'data' section
  1172. this.setOfferAnswerCycle(
  1173. jingleOfferElem,
  1174. () => {
  1175. // Now set the original offer(with the 'data' section)
  1176. this.setOfferAnswerCycle(
  1177. originalOffer,
  1178. () => {
  1179. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1180. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1181. localSDP.initialLastN = this.options.channelLastN;
  1182. }
  1183. this.sendTransportAccept(localSDP, success, failure);
  1184. this.room.eventEmitter.emit(
  1185. XMPPEvents.ICE_RESTART_SUCCESS,
  1186. this,
  1187. originalOffer);
  1188. },
  1189. failure);
  1190. },
  1191. failure
  1192. );
  1193. }
  1194. /**
  1195. * Sends Jingle 'session-accept' message.
  1196. * @param {function()} success callback called when we receive 'RESULT'
  1197. * packet for the 'session-accept'
  1198. * @param {function(error)} failure called when we receive an error response
  1199. * or when the request has timed out.
  1200. * @private
  1201. */
  1202. sendSessionAccept(success, failure) {
  1203. // NOTE: since we're just reading from it, we don't need to be within
  1204. // the modification queue to access the local description
  1205. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1206. const accept = $iq({ to: this.remoteJid,
  1207. type: 'set' })
  1208. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1209. action: 'session-accept',
  1210. initiator: this.initiatorJid,
  1211. responder: this.responderJid,
  1212. sid: this.sid });
  1213. if (this.webrtcIceTcpDisable) {
  1214. localSDP.removeTcpCandidates = true;
  1215. }
  1216. if (this.webrtcIceUdpDisable) {
  1217. localSDP.removeUdpCandidates = true;
  1218. }
  1219. if (this.failICE) {
  1220. localSDP.failICE = true;
  1221. }
  1222. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1223. localSDP.initialLastN = this.options.channelLastN;
  1224. }
  1225. localSDP.toJingle(
  1226. accept,
  1227. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1228. logger.info(`${this} Sending session-accept`);
  1229. logger.debug(accept.tree());
  1230. this.connection.sendIQ(accept,
  1231. success,
  1232. this.newJingleErrorHandler(accept, error => {
  1233. failure(error);
  1234. // 'session-accept' is a critical timeout and we'll
  1235. // have to restart
  1236. this.room.eventEmitter.emit(
  1237. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1238. }),
  1239. IQ_TIMEOUT);
  1240. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1241. // fingerprint and setup) ASAP in order to start the connection
  1242. // establishment.
  1243. //
  1244. // FIXME Flushing the connection at this point triggers an issue with
  1245. // BOSH request handling in Prosody on slow connections.
  1246. //
  1247. // The problem is that this request will be quite large and it may take
  1248. // time before it reaches Prosody. In the meantime Strophe may decide
  1249. // to send the next one. And it was observed that a small request with
  1250. // 'transport-info' usually follows this one. It does reach Prosody
  1251. // before the previous one was completely received. 'rid' on the server
  1252. // is increased and Prosody ignores the request with 'session-accept'.
  1253. // It will never reach Jicofo and everything in the request table is
  1254. // lost. Removing the flush does not guarantee it will never happen, but
  1255. // makes it much less likely('transport-info' is bundled with
  1256. // 'session-accept' and any immediate requests).
  1257. //
  1258. // this.connection.flush();
  1259. }
  1260. /**
  1261. * Will send 'content-modify' IQ in order to ask the remote peer to
  1262. * either stop or resume sending video media or to adjust sender's video constraints.
  1263. * @private
  1264. */
  1265. sendContentModify() {
  1266. const senders = this._localVideoActive ? 'both' : 'none';
  1267. const sessionModify
  1268. = $iq({
  1269. to: this.remoteJid,
  1270. type: 'set'
  1271. })
  1272. .c('jingle', {
  1273. xmlns: 'urn:xmpp:jingle:1',
  1274. action: 'content-modify',
  1275. initiator: this.initiatorJid,
  1276. sid: this.sid
  1277. })
  1278. .c('content', {
  1279. name: MediaType.VIDEO,
  1280. senders
  1281. });
  1282. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  1283. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  1284. sessionModify
  1285. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1286. .attrs({
  1287. sourceName,
  1288. maxHeight
  1289. });
  1290. sessionModify.up();
  1291. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  1292. });
  1293. }
  1294. logger.debug(sessionModify.tree());
  1295. this.connection.sendIQ(
  1296. sessionModify,
  1297. null,
  1298. this.newJingleErrorHandler(sessionModify),
  1299. IQ_TIMEOUT);
  1300. }
  1301. /**
  1302. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1303. * the remote p2p peer.
  1304. *
  1305. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1306. */
  1307. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1308. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1309. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1310. if (this.isP2P) {
  1311. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1312. // be synced after offer/answer.
  1313. if (this.state === JingleSessionState.ACTIVE) {
  1314. this.sendContentModify();
  1315. }
  1316. }
  1317. }
  1318. /**
  1319. * Sends Jingle 'transport-accept' message which is a response to
  1320. * 'transport-replace'.
  1321. * @param localSDP the 'SDP' object with local session description
  1322. * @param success callback called when we receive 'RESULT' packet for
  1323. * 'transport-replace'
  1324. * @param failure function(error) called when we receive an error response
  1325. * or when the request has timed out.
  1326. * @private
  1327. */
  1328. sendTransportAccept(localSDP, success, failure) {
  1329. const transportAccept = $iq({ to: this.remoteJid,
  1330. type: 'set' })
  1331. .c('jingle', {
  1332. xmlns: 'urn:xmpp:jingle:1',
  1333. action: 'transport-accept',
  1334. initiator: this.initiatorJid,
  1335. sid: this.sid
  1336. });
  1337. localSDP.media.forEach((medialines, idx) => {
  1338. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1339. transportAccept.c('content',
  1340. {
  1341. creator:
  1342. this.initiatorJid === this.localJid
  1343. ? 'initiator'
  1344. : 'responder',
  1345. name: mline.media
  1346. }
  1347. );
  1348. localSDP.transportToJingle(idx, transportAccept);
  1349. transportAccept.up();
  1350. });
  1351. logger.info(`${this} Sending transport-accept`);
  1352. logger.debug(transportAccept.tree());
  1353. this.connection.sendIQ(transportAccept,
  1354. success,
  1355. this.newJingleErrorHandler(transportAccept, failure),
  1356. IQ_TIMEOUT);
  1357. }
  1358. /**
  1359. * Sends Jingle 'transport-reject' message which is a response to
  1360. * 'transport-replace'.
  1361. * @param success callback called when we receive 'RESULT' packet for
  1362. * 'transport-replace'
  1363. * @param failure function(error) called when we receive an error response
  1364. * or when the request has timed out.
  1365. *
  1366. * FIXME method should be marked as private, but there's some spaghetti that
  1367. * needs to be fixed prior doing that
  1368. */
  1369. sendTransportReject(success, failure) {
  1370. // Send 'transport-reject', so that the focus will
  1371. // know that we've failed
  1372. const transportReject = $iq({ to: this.remoteJid,
  1373. type: 'set' })
  1374. .c('jingle', {
  1375. xmlns: 'urn:xmpp:jingle:1',
  1376. action: 'transport-reject',
  1377. initiator: this.initiatorJid,
  1378. sid: this.sid
  1379. });
  1380. logger.info(`${this} Sending 'transport-reject'`);
  1381. logger.debug(transportReject.tree());
  1382. this.connection.sendIQ(transportReject,
  1383. success,
  1384. this.newJingleErrorHandler(transportReject, failure),
  1385. IQ_TIMEOUT);
  1386. }
  1387. /**
  1388. * Sets the resolution constraint on the local camera track.
  1389. * @param {number} maxFrameHeight - The user preferred max frame height.
  1390. * @param {string} sourceName - The source name of the track.
  1391. * @returns {Promise} promise that will be resolved when the operation is
  1392. * successful and rejected otherwise.
  1393. */
  1394. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1395. if (this._assertNotEnded()) {
  1396. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1397. const jitsiLocalTrack = sourceName
  1398. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1399. : this.rtc.getLocalVideoTrack();
  1400. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1401. }
  1402. return Promise.resolve();
  1403. }
  1404. /**
  1405. * @inheritDoc
  1406. */
  1407. terminate(success, failure, options) {
  1408. if (this.state === JingleSessionState.ENDED) {
  1409. return;
  1410. }
  1411. if (!options || Boolean(options.sendSessionTerminate)) {
  1412. const sessionTerminate
  1413. = $iq({
  1414. to: this.remoteJid,
  1415. type: 'set'
  1416. })
  1417. .c('jingle', {
  1418. xmlns: 'urn:xmpp:jingle:1',
  1419. action: 'session-terminate',
  1420. initiator: this.initiatorJid,
  1421. sid: this.sid
  1422. })
  1423. .c('reason')
  1424. .c((options && options.reason) || 'success')
  1425. .up();
  1426. if (options && options.reasonDescription) {
  1427. sessionTerminate
  1428. .c('text')
  1429. .t(options.reasonDescription)
  1430. .up()
  1431. .up();
  1432. } else {
  1433. sessionTerminate.up();
  1434. }
  1435. this._bridgeSessionId
  1436. && sessionTerminate.c(
  1437. 'bridge-session', {
  1438. xmlns: 'http://jitsi.org/protocol/focus',
  1439. id: this._bridgeSessionId,
  1440. restart: options && options.requestRestart === true
  1441. }).up();
  1442. logger.info(`${this} Sending session-terminate`);
  1443. logger.debug(sessionTerminate.tree());
  1444. this.connection.sendIQ(
  1445. sessionTerminate,
  1446. success,
  1447. this.newJingleErrorHandler(sessionTerminate, failure),
  1448. IQ_TIMEOUT);
  1449. } else {
  1450. logger.info(`${this} Skipped sending session-terminate`);
  1451. }
  1452. // this should result in 'onTerminated' being called by strope.jingle.js
  1453. this.connection.jingle.terminate(this.sid);
  1454. }
  1455. /**
  1456. *
  1457. * @param reasonCondition
  1458. * @param reasonText
  1459. */
  1460. onTerminated(reasonCondition, reasonText) {
  1461. // Do something with reason and reasonCondition when we start to care
  1462. // this.reasonCondition = reasonCondition;
  1463. // this.reasonText = reasonText;
  1464. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1465. this._xmppListeners.forEach(removeListener => removeListener());
  1466. this._xmppListeners = [];
  1467. if (this._removeSenderVideoConstraintsChangeListener) {
  1468. this._removeSenderVideoConstraintsChangeListener();
  1469. }
  1470. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1471. this.peerconnection.getRemoteTracks().forEach(track => {
  1472. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1473. });
  1474. }
  1475. this.close();
  1476. }
  1477. /**
  1478. * Handles XMPP connection state changes.
  1479. *
  1480. * @param {XmppConnection.Status} status - The new status.
  1481. */
  1482. onXmppStatusChanged(status) {
  1483. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1484. logger.info(`${this} Sending SSRC update on reconnect`);
  1485. this.notifyMySSRCUpdate(
  1486. this._cachedOldLocalSdp,
  1487. this._cachedNewLocalSdp);
  1488. }
  1489. }
  1490. /**
  1491. * Parse the information from the xml sourceAddElem and translate it
  1492. * into sdp lines
  1493. * @param {jquery xml element} sourceAddElem the source-add
  1494. * element from jingle
  1495. * @param {SDP object} currentRemoteSdp the current remote
  1496. * sdp (as of this new source-add)
  1497. * @returns {list} a list of SDP line strings that should
  1498. * be added to the remote SDP
  1499. */
  1500. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1501. const addSsrcInfo = [];
  1502. const self = this;
  1503. $(sourceAddElem).each((i1, content) => {
  1504. const name = $(content).attr('name');
  1505. let lines = '';
  1506. $(content)
  1507. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1508. .each(function() {
  1509. // eslint-disable-next-line no-invalid-this
  1510. const semantics = this.getAttribute('semantics');
  1511. const ssrcs
  1512. = $(this) // eslint-disable-line no-invalid-this
  1513. .find('>source')
  1514. .map(function() {
  1515. // eslint-disable-next-line no-invalid-this
  1516. return this.getAttribute('ssrc');
  1517. })
  1518. .get();
  1519. if (ssrcs.length) {
  1520. lines += `a=ssrc-group:${semantics} ${ssrcs.join(' ')}\r\n`;
  1521. }
  1522. });
  1523. // handles both >source and >description>source
  1524. const tmp
  1525. = $(content).find(
  1526. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1527. /* eslint-disable no-invalid-this */
  1528. tmp.each(function() {
  1529. const ssrc = $(this).attr('ssrc');
  1530. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1531. // Do not print the warning for unified plan p2p case since ssrcs are never removed from the SDP.
  1532. !(self.usesUnifiedPlan && self.isP2P)
  1533. && logger.warn(`${self} Source-add request for existing SSRC: ${ssrc}`);
  1534. return;
  1535. }
  1536. // eslint-disable-next-line newline-per-chained-call
  1537. $(this).find('>parameter').each(function() {
  1538. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1539. if ($(this).attr('value') && $(this).attr('value').length) {
  1540. lines += `:${$(this).attr('value')}`;
  1541. }
  1542. lines += '\r\n';
  1543. });
  1544. });
  1545. let midFound = false;
  1546. /* eslint-enable no-invalid-this */
  1547. currentRemoteSdp.media.forEach((media, i2) => {
  1548. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1549. return;
  1550. }
  1551. if (!addSsrcInfo[i2]) {
  1552. addSsrcInfo[i2] = '';
  1553. }
  1554. addSsrcInfo[i2] += lines;
  1555. midFound = true;
  1556. });
  1557. // In p2p unified mode with multi-stream enabled, the new sources will have content name that doesn't exist
  1558. // in the current remote description. Add a new m-line for this newly signaled source.
  1559. if (!midFound && this.isP2P) {
  1560. addSsrcInfo[name] = lines;
  1561. }
  1562. });
  1563. return addSsrcInfo;
  1564. }
  1565. /**
  1566. * Handles a Jingle source-add message for this Jingle session.
  1567. * @param elem An array of Jingle "content" elements.
  1568. */
  1569. addRemoteStream(elem) {
  1570. this._addOrRemoveRemoteStream(true /* add */, elem);
  1571. }
  1572. /**
  1573. * Handles a Jingle source-remove message for this Jingle session.
  1574. * @param elem An array of Jingle "content" elements.
  1575. */
  1576. removeRemoteStream(elem) {
  1577. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1578. }
  1579. /**
  1580. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1581. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1582. *
  1583. * @param {Object} message - The source map message.
  1584. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1585. * @returns {void}
  1586. */
  1587. processSourceMap(message, mediaType) {
  1588. const newSources = [];
  1589. for (const src of message.mappedSources) {
  1590. if (this.peerconnection.addRemoteSsrc(src.ssrc)) {
  1591. newSources.push(src);
  1592. } else {
  1593. const { owner, source, ssrc, videoType } = src;
  1594. const track = this.peerconnection.getTrackBySSRC(ssrc);
  1595. if (track) {
  1596. logger.debug(`Existing SSRC ${ssrc}: new owner=${owner}, source-name=${source}`);
  1597. // Update the SSRC owner.
  1598. this._signalingLayer.setSSRCOwner(ssrc, owner);
  1599. // Update the track with all the relevant info.
  1600. track.setSourceName(source);
  1601. track.setOwner(owner);
  1602. if (mediaType === MediaType.VIDEO) {
  1603. const type = videoType === 'CAMERA' ? VideoType.CAMERA : VideoType.DESKTOP;
  1604. track._setVideoType(type);
  1605. }
  1606. } else {
  1607. logger.error(`Remote track attached to a remote SSRC=${ssrc} not found`);
  1608. }
  1609. }
  1610. }
  1611. // Add the new SSRCs to the remote description by generating a source message.
  1612. if (newSources.length) {
  1613. let node = $build('content', {
  1614. xmlns: 'urn:xmpp:jingle:1',
  1615. name: mediaType
  1616. }).c('description', {
  1617. xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  1618. media: mediaType
  1619. });
  1620. for (const src of newSources) {
  1621. const { rtx, ssrc } = src;
  1622. let msid;
  1623. if (mediaType === MediaType.VIDEO) {
  1624. const idx = ++this.numRemoteVideoSources;
  1625. msid = `remote-video-${idx} remote-video-${idx}`;
  1626. if (rtx !== '-1') {
  1627. _addSourceElement(node, src, rtx, msid);
  1628. node.c('ssrc-group', {
  1629. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1630. semantics: 'FID'
  1631. })
  1632. .c('source', {
  1633. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1634. ssrc
  1635. })
  1636. .up()
  1637. .c('source', {
  1638. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1639. ssrc: rtx
  1640. })
  1641. .up()
  1642. .up();
  1643. }
  1644. } else {
  1645. const idx = ++this.numRemoteAudioSources;
  1646. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1647. }
  1648. _addSourceElement(node, src, ssrc, msid);
  1649. }
  1650. node = node.up();
  1651. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1652. }
  1653. }
  1654. /**
  1655. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1656. *
  1657. * @param {string} id Endpoint id of the participant that has left the call.
  1658. * @returns {void}
  1659. */
  1660. removeRemoteStreamsOnLeave(id) {
  1661. const workFunction = finishCallback => {
  1662. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1663. if (removeSsrcInfo.length) {
  1664. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1665. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1666. this._renegotiate(newRemoteSdp.raw)
  1667. .then(() => {
  1668. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1669. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSDP);
  1670. finishCallback();
  1671. })
  1672. .catch(err => finishCallback(err));
  1673. } else {
  1674. finishCallback();
  1675. }
  1676. };
  1677. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1678. this.modificationQueue.push(
  1679. workFunction,
  1680. error => {
  1681. if (error) {
  1682. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1683. } else {
  1684. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1685. }
  1686. });
  1687. }
  1688. /**
  1689. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1690. * Jingle session.
  1691. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1692. * otherwise.
  1693. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1694. * @private
  1695. */
  1696. _addOrRemoveRemoteStream(isAdd, elem) {
  1697. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1698. if (isAdd) {
  1699. this.readSsrcInfo(elem);
  1700. }
  1701. const workFunction = finishedCallback => {
  1702. if (!this.peerconnection.localDescription
  1703. || !this.peerconnection.localDescription.sdp) {
  1704. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1705. logger.error(errMsg);
  1706. finishedCallback(errMsg);
  1707. return;
  1708. }
  1709. logger.log(`${this} Processing ${logPrefix}`);
  1710. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1711. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1712. const addOrRemoveSsrcInfo
  1713. = isAdd
  1714. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1715. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1716. const newRemoteSdp
  1717. = isAdd
  1718. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1719. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1720. const remoteDescription = new RTCSessionDescription({
  1721. type: 'offer',
  1722. sdp: newRemoteSdp.raw
  1723. });
  1724. // Always initiate a sRD->cA->sLD cycle when a remote source is added or removed irrespective of whether
  1725. // the local endpoint is an initiator or responder. Fixes bugs on Chromium where decoders are not created
  1726. // when sLD->cO->sRD cycle is initiated for p2p cases when remote sources are received.
  1727. this._responderRenegotiate(remoteDescription).then(() => {
  1728. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1729. logger.log(`${this} ${logPrefix} - OK`);
  1730. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1731. finishedCallback();
  1732. }, error => {
  1733. logger.error(`${this} ${logPrefix} failed:`, error);
  1734. finishedCallback(error);
  1735. });
  1736. };
  1737. logger.debug(`${this} Queued ${logPrefix} task`);
  1738. // Queue and execute
  1739. this.modificationQueue.push(workFunction);
  1740. }
  1741. /**
  1742. * Takes in a jingle offer iq, returns the new sdp offer
  1743. * @param {jquery xml element} offerIq the incoming offer
  1744. * @returns {SDP object} the jingle offer translated to SDP
  1745. */
  1746. _processNewJingleOfferIq(offerIq) {
  1747. const remoteSdp = new SDP('');
  1748. if (this.webrtcIceTcpDisable) {
  1749. remoteSdp.removeTcpCandidates = true;
  1750. }
  1751. if (this.webrtcIceUdpDisable) {
  1752. remoteSdp.removeUdpCandidates = true;
  1753. }
  1754. if (this.failICE) {
  1755. remoteSdp.failICE = true;
  1756. }
  1757. remoteSdp.fromJingle(offerIq);
  1758. this.readSsrcInfo($(offerIq).find('>content'));
  1759. return remoteSdp;
  1760. }
  1761. /**
  1762. * Remove the given ssrc lines from the current remote sdp
  1763. * @param {list} removeSsrcInfo a list of SDP line strings that
  1764. * should be removed from the remote SDP
  1765. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1766. * in removeSsrcInfo
  1767. */
  1768. _processRemoteRemoveSource(removeSsrcInfo) {
  1769. const remoteSdp = this.usesUnifiedPlan
  1770. ? new SDP(this.peerconnection.peerconnection.remoteDescription.sdp)
  1771. : new SDP(this.peerconnection.remoteDescription.sdp);
  1772. let ssrcs;
  1773. removeSsrcInfo.forEach((lines, idx) => {
  1774. // eslint-disable-next-line no-param-reassign
  1775. lines = lines.split('\r\n');
  1776. lines.pop(); // remove empty last element;
  1777. ssrcs = lines.map(line => Number(line.split('a=ssrc:')[1]?.split(' ')[0]));
  1778. if (this.usesUnifiedPlan) {
  1779. let mid;
  1780. lines.forEach(line => {
  1781. mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1782. if (mid > -1) {
  1783. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1784. if (this.isP2P) {
  1785. const mediaType = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0])?.media;
  1786. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, false);
  1787. [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ].forEach(direction => {
  1788. remoteSdp.media[mid] = remoteSdp.media[mid]
  1789. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1790. });
  1791. } else {
  1792. // Jvb connections will have direction set to 'sendonly' for the remote sources.
  1793. remoteSdp.media[mid] = remoteSdp.media[mid]
  1794. .replace(`a=${MediaDirection.SENDONLY}`, `a=${MediaDirection.INACTIVE}`);
  1795. }
  1796. }
  1797. });
  1798. // Reject the m-line so that the browser removes the associated transceiver from the list of available
  1799. // transceivers. This will prevent the client from trying to re-use these inactive transceivers when
  1800. // additional video sources are added to the peerconnection.
  1801. if (mid > -1 && !this.isP2P && FeatureFlags.isMultiStreamSendSupportEnabled()) {
  1802. const { media, port } = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0]);
  1803. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`m=${media} ${port}`, `m=${media} 0`);
  1804. }
  1805. } else {
  1806. lines.forEach(line => {
  1807. remoteSdp.media[idx] = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1808. });
  1809. }
  1810. });
  1811. // Update the ssrc owners list.
  1812. ssrcs?.length && this._signalingLayer.removeSSRCOwners(ssrcs);
  1813. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1814. return remoteSdp;
  1815. }
  1816. /**
  1817. * Add the given ssrc lines to the current remote sdp
  1818. * @param {list} addSsrcInfo a list of SDP line strings that
  1819. * should be added to the remote SDP
  1820. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1821. * in removeSsrcInfo
  1822. */
  1823. _processRemoteAddSource(addSsrcInfo) {
  1824. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1825. // Add a new m-line in the remote description if the source info for a secondary video source is recceived from
  1826. // the remote p2p peer when multi-stream support is enabled.
  1827. if (addSsrcInfo.length > remoteSdp.media.length
  1828. && this.isP2P
  1829. && this.usesUnifiedPlan) {
  1830. remoteSdp.addMlineForNewLocalSource(MediaType.VIDEO);
  1831. remoteSdp = new SDP(remoteSdp.raw);
  1832. }
  1833. addSsrcInfo.forEach((lines, idx) => {
  1834. remoteSdp.media[idx] += lines;
  1835. // Make sure to change the direction to 'sendrecv/sendonly' only for p2p connections. For jvb connections,
  1836. // a new m-line is added for the new remote sources.
  1837. if (this.isP2P && this.usesUnifiedPlan) {
  1838. const mediaType = SDPUtil.parseMLine(remoteSdp.media[idx].split('\r\n')[0])?.media;
  1839. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, true);
  1840. [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ].forEach(direction => {
  1841. remoteSdp.media[idx] = remoteSdp.media[idx]
  1842. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1843. });
  1844. }
  1845. });
  1846. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1847. return remoteSdp;
  1848. }
  1849. /**
  1850. * Do a new o/a flow using the existing remote description
  1851. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1852. * to use. If not provided, the remote sdp from the
  1853. * peerconnection will be used
  1854. * @returns {Promise} promise which resolves when the
  1855. * o/a flow is complete with no arguments or
  1856. * rejects with an error {string}
  1857. */
  1858. _renegotiate(optionalRemoteSdp) {
  1859. if (this.peerconnection.signalingState === 'closed') {
  1860. const error = new Error('Attempted to renegotiate in state closed');
  1861. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1862. return Promise.reject(error);
  1863. }
  1864. const remoteSdp
  1865. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1866. if (!remoteSdp) {
  1867. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1868. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1869. return Promise.reject(error);
  1870. }
  1871. const remoteDescription = new RTCSessionDescription({
  1872. type: this.isInitiator ? 'answer' : 'offer',
  1873. sdp: remoteSdp
  1874. });
  1875. if (this.isInitiator) {
  1876. return this._initiatorRenegotiate(remoteDescription);
  1877. }
  1878. return this._responderRenegotiate(remoteDescription);
  1879. }
  1880. /**
  1881. * Renegotiate cycle implementation for the responder case.
  1882. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1883. * which will be used as remote description in the cycle.
  1884. * @private
  1885. */
  1886. _responderRenegotiate(remoteDescription) {
  1887. logger.debug(`${this} Renegotiate: setting remote description`);
  1888. return this.peerconnection.setRemoteDescription(remoteDescription)
  1889. .then(() => {
  1890. logger.debug(`${this} Renegotiate: creating answer`);
  1891. return this.peerconnection.createAnswer(this.mediaConstraints)
  1892. .then(answer => {
  1893. logger.debug(`${this} Renegotiate: setting local description`);
  1894. return this.peerconnection.setLocalDescription(answer);
  1895. });
  1896. });
  1897. }
  1898. /**
  1899. * Renegotiate cycle implementation for the initiator's case.
  1900. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1901. * which will be used as remote description in the cycle.
  1902. * @private
  1903. */
  1904. _initiatorRenegotiate(remoteDescription) {
  1905. logger.debug(`${this} Renegotiate: creating offer`);
  1906. return this.peerconnection.createOffer(this.mediaConstraints)
  1907. .then(offer => {
  1908. logger.debug(`${this} Renegotiate: setting local description`);
  1909. return this.peerconnection.setLocalDescription(offer)
  1910. .then(() => {
  1911. logger.debug(`${this} Renegotiate: setting remote description`);
  1912. // eslint-disable-next-line max-len
  1913. return this.peerconnection.setRemoteDescription(remoteDescription);
  1914. });
  1915. });
  1916. }
  1917. /**
  1918. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  1919. * being added to the peerconnection for the first time.
  1920. *
  1921. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  1922. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  1923. * otherwise.
  1924. */
  1925. addTracks(localTracks = null) {
  1926. if (!FeatureFlags.isMultiStreamSendSupportEnabled()
  1927. || !localTracks?.length
  1928. || localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  1929. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  1930. }
  1931. const replaceTracks = [];
  1932. const workFunction = finishedCallback => {
  1933. const oldLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1934. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1935. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  1936. .find(t => t.receiver.track.kind === MediaType.VIDEO
  1937. && t.direction === MediaDirection.RECVONLY
  1938. && t.currentDirection === MediaDirection.RECVONLY);
  1939. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  1940. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  1941. // existing one in that case.
  1942. for (const track of localTracks) {
  1943. if (!this.isP2P || !recvOnlyTransceiver) {
  1944. remoteSdp.addMlineForNewLocalSource(track.getType());
  1945. }
  1946. }
  1947. const remoteDescription = new RTCSessionDescription({
  1948. type: 'offer',
  1949. sdp: remoteSdp.raw
  1950. });
  1951. // Always initiate a responder renegotiate since the new m-line is added to remote SDP.
  1952. this._responderRenegotiate(remoteDescription)
  1953. .then(() => {
  1954. // Replace the tracks on the newly generated transceivers.
  1955. for (const track of localTracks) {
  1956. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  1957. }
  1958. return Promise.all(replaceTracks);
  1959. })
  1960. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  1961. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  1962. .then(() => this._renegotiate())
  1963. .then(() => {
  1964. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1965. // Signal the new sources to the peer.
  1966. this.notifyMySSRCUpdate(oldLocalSDP, newLocalSDP);
  1967. finishedCallback();
  1968. })
  1969. .catch(error => finishedCallback(error));
  1970. };
  1971. return new Promise((resolve, reject) => {
  1972. logger.debug(`${this} Queued renegotiation after addTrack`);
  1973. this.modificationQueue.push(
  1974. workFunction,
  1975. error => {
  1976. if (error) {
  1977. logger.error(`${this} renegotiation after addTrack error`, error);
  1978. reject(error);
  1979. } else {
  1980. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1981. resolve();
  1982. }
  1983. });
  1984. });
  1985. }
  1986. /**
  1987. * Resumes or suspends media transfer over the underlying peer connection.
  1988. *
  1989. * @param {boolean} active - <tt>true</tt> to enable media transfer or <tt>false</tt> to suspend media transmission
  1990. * @returns {Promise}
  1991. */
  1992. setMediaTransferActive(active) {
  1993. return this.peerconnection.tpcUtils.setMediaTransferActive(active)
  1994. .then(() => {
  1995. this.peerconnection.audioTransferActive = active;
  1996. this.peerconnection.videoTransferActive = active;
  1997. });
  1998. }
  1999. /**
  2000. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  2001. * offer/answer cycle after both operations are done. Either
  2002. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  2003. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  2004. * <tt>oldTrack</tt>
  2005. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  2006. * replaced
  2007. * @param {JitsiLocalTrack|null} newTrack the new track to use
  2008. * @returns {Promise} which resolves once the replacement is complete
  2009. * with no arguments or rejects with an error {string}
  2010. */
  2011. replaceTrack(oldTrack, newTrack) {
  2012. const workFunction = finishedCallback => {
  2013. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  2014. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  2015. if (!this.usesUnifiedPlan) {
  2016. // NOTE the code below assumes that no more than 1 video track
  2017. // can be added to the peer connection.
  2018. // Transition from camera to desktop share
  2019. // or transition from one camera source to another.
  2020. if (this.peerconnection.options.capScreenshareBitrate
  2021. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  2022. // Clearing current primary SSRC will make
  2023. // the SdpConsistency generate a new one which will result
  2024. // with:
  2025. // 1. source-remove for the old video stream.
  2026. // 2. source-add for the new video stream.
  2027. this.peerconnection.clearRecvonlySsrc();
  2028. }
  2029. // Transition from no video to video (unmute).
  2030. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  2031. // Clearing current primary SSRC will make
  2032. // the SdpConsistency generate a new one which will result
  2033. // with:
  2034. // 1. source-remove for the recvonly
  2035. // 2. source-add for the new video stream
  2036. this.peerconnection.clearRecvonlySsrc();
  2037. // Transition from video to no video
  2038. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  2039. // Clearing current primary SSRC and generating the recvonly
  2040. // will result in:
  2041. // 1. source-remove for the old video stream
  2042. // 2. source-add for the recvonly stream
  2043. this.peerconnection.clearRecvonlySsrc();
  2044. this.peerconnection.generateRecvonlySsrc();
  2045. }
  2046. }
  2047. this.peerconnection.replaceTrack(oldTrack, newTrack)
  2048. .then(shouldRenegotiate => {
  2049. let promise = Promise.resolve();
  2050. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  2051. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  2052. if (shouldRenegotiate
  2053. && (oldTrack || newTrack)
  2054. && this.state === JingleSessionState.ACTIVE) {
  2055. const remoteSdp = this.peerconnection.remoteDescription.sdp;
  2056. const remoteDescription = new RTCSessionDescription({
  2057. type: 'offer',
  2058. sdp: remoteSdp
  2059. });
  2060. // Always initiate a sRD->cA->sLD cycle since renegotiation fails in the following scenario.
  2061. // In a p2p call when channelLastN=0, the direction on the video tranceiver is set to
  2062. // 'inactive'. At this point, if the user unmutes, the track is replaced on the video sender.
  2063. // If a cO->sLD->sRD is triggered, the browser adds a third m-line which isn't expected and
  2064. // possibly is a bug. All renegotiations fail as a result. However, the browser does not add a
  2065. // third m-line in the answer it generates and renegotiation succeeds.
  2066. promise = this._responderRenegotiate(remoteDescription).then(() => {
  2067. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  2068. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  2069. });
  2070. }
  2071. return promise.then(() => {
  2072. // Set the source name of the new track.
  2073. if (oldTrack
  2074. && newTrack
  2075. && oldTrack.isVideoTrack()) {
  2076. newTrack.setSourceName(oldTrack.getSourceName());
  2077. }
  2078. if (newTrack?.isVideoTrack()) {
  2079. logger.debug(`${this} replaceTrack worker: configuring video stream`);
  2080. // Configure the video encodings after the track is replaced.
  2081. return this.peerconnection.configureSenderVideoEncodings(newTrack);
  2082. }
  2083. });
  2084. })
  2085. .then(() => finishedCallback(), error => finishedCallback(error));
  2086. };
  2087. return new Promise((resolve, reject) => {
  2088. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  2089. this.modificationQueue.push(
  2090. workFunction,
  2091. error => {
  2092. if (error) {
  2093. logger.error(`${this} Replace track error:`, error);
  2094. reject(error);
  2095. } else {
  2096. logger.info(`${this} Replace track done!`);
  2097. resolve();
  2098. }
  2099. });
  2100. });
  2101. }
  2102. /**
  2103. * Parse the information from the xml sourceRemoveElem and translate it
  2104. * into sdp lines
  2105. * @param {jquery xml element} sourceRemoveElem the source-remove
  2106. * element from jingle
  2107. * @param {SDP object} currentRemoteSdp the current remote
  2108. * sdp (as of this new source-remove)
  2109. * @returns {list} a list of SDP line strings that should
  2110. * be removed from the remote SDP
  2111. */
  2112. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  2113. const removeSsrcInfo = [];
  2114. $(sourceRemoveElem).each((i1, content) => {
  2115. const name = $(content).attr('name');
  2116. let lines = '';
  2117. $(content)
  2118. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  2119. .each(function() {
  2120. /* eslint-disable no-invalid-this */
  2121. const semantics = this.getAttribute('semantics');
  2122. const ssrcs
  2123. = $(this)
  2124. .find('>source')
  2125. .map(function() {
  2126. return this.getAttribute('ssrc');
  2127. })
  2128. .get();
  2129. if (ssrcs.length) {
  2130. lines
  2131. += `a=ssrc-group:${semantics} ${
  2132. ssrcs.join(' ')}\r\n`;
  2133. }
  2134. /* eslint-enable no-invalid-this */
  2135. });
  2136. const ssrcs = [];
  2137. // handles both >source and >description>source versions
  2138. const tmp
  2139. = $(content).find(
  2140. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  2141. tmp.each(function() {
  2142. // eslint-disable-next-line no-invalid-this
  2143. const ssrc = $(this).attr('ssrc');
  2144. ssrcs.push(ssrc);
  2145. });
  2146. currentRemoteSdp.media.forEach((media, i2) => {
  2147. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  2148. return;
  2149. }
  2150. if (!removeSsrcInfo[i2]) {
  2151. removeSsrcInfo[i2] = '';
  2152. }
  2153. ssrcs.forEach(ssrc => {
  2154. const ssrcLines
  2155. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  2156. if (ssrcLines.length) {
  2157. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  2158. }
  2159. });
  2160. removeSsrcInfo[i2] += lines;
  2161. });
  2162. });
  2163. return removeSsrcInfo;
  2164. }
  2165. /**
  2166. * Will print an error if there is any difference, between the SSRCs given
  2167. * in the <tt>oldSDP</tt> and the ones currently described in
  2168. * the peerconnection's local description.
  2169. * @param {string} operationName the operation's name which will be printed
  2170. * in the error message.
  2171. * @param {SDP} oldSDP the old local SDP which will be compared with
  2172. * the current one.
  2173. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  2174. * otherwise.
  2175. * @private
  2176. */
  2177. _verifyNoSSRCChanged(operationName, oldSDP) {
  2178. const currentLocalSDP
  2179. = new SDP(this.peerconnection.localDescription.sdp);
  2180. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  2181. const addedMedia = sdpDiff.getNewMedia();
  2182. if (Object.keys(addedMedia).length) {
  2183. logger.error(`${this} - some SSRC were added on ${operationName}`, addedMedia);
  2184. return false;
  2185. }
  2186. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  2187. const removedMedia = sdpDiff.getNewMedia();
  2188. if (Object.keys(removedMedia).length) {
  2189. logger.error(`${this} - some SSRCs were removed on ${operationName}`, removedMedia);
  2190. return false;
  2191. }
  2192. return true;
  2193. }
  2194. /**
  2195. * Adds local track back to the peerconnection associated with this session.
  2196. * @param {JitsiLocalTrack} track
  2197. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  2198. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  2199. * details in case something goes wrong.
  2200. */
  2201. addTrackToPc(track) {
  2202. return this._addRemoveTrack(false /* add */, track)
  2203. .then(() => {
  2204. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  2205. // unmutes it the first time, all the parameters need to be configured.
  2206. if (track.isVideoTrack()) {
  2207. return this.peerconnection.configureSenderVideoEncodings(track);
  2208. }
  2209. });
  2210. }
  2211. /**
  2212. * Remove local track as part of the mute operation.
  2213. * @param {JitsiLocalTrack} track the local track to be removed
  2214. * @return {Promise} a promise which will be resolved once the local track
  2215. * is removed from this session and the renegotiation is performed.
  2216. * The promise will be rejected with a <tt>string</tt> that the describes
  2217. * the error if anything goes wrong.
  2218. */
  2219. removeTrackFromPc(track) {
  2220. return this._addRemoveTrack(true /* remove */, track);
  2221. }
  2222. /**
  2223. * See {@link addTrackToPc} and {@link removeTrackFromPc}.
  2224. * @param {boolean} isRemove <tt>true</tt> for "remove" operation or <tt>false</tt> for "add" operation.
  2225. * @param {JitsiLocalTrack} track the track that will be added/removed
  2226. * @private
  2227. */
  2228. _addRemoveTrack(isRemove, track) {
  2229. if (!track) {
  2230. return Promise.reject('invalid "track" argument value');
  2231. }
  2232. const operationName = isRemove ? 'removeTrack' : 'addTrack';
  2233. const workFunction = finishedCallback => {
  2234. const tpc = this.peerconnection;
  2235. if (!tpc) {
  2236. finishedCallback(`Error: tried ${operationName} track with no active peer connection`);
  2237. return;
  2238. }
  2239. const oldLocalSDP = tpc.localDescription.sdp;
  2240. const operationPromise
  2241. = isRemove
  2242. ? tpc.removeTrackFromPc(track)
  2243. : tpc.addTrackToPc(track);
  2244. operationPromise
  2245. .then(shouldRenegotiate => {
  2246. if (shouldRenegotiate && oldLocalSDP && tpc.remoteDescription.sdp) {
  2247. this._renegotiate()
  2248. .then(() => {
  2249. // The results are ignored, as this check failure is not enough to fail the whole
  2250. // operation. It will log an error inside for plan-b.
  2251. !this.usesUnifiedPlan && this._verifyNoSSRCChanged(operationName, new SDP(oldLocalSDP));
  2252. const newLocalSdp = tpc.localDescription.sdp;
  2253. // Signal the ssrc if an unmute operation results in a new ssrc being generated.
  2254. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(newLocalSdp));
  2255. finishedCallback();
  2256. });
  2257. } else {
  2258. finishedCallback();
  2259. }
  2260. },
  2261. finishedCallback /* will be called with an error */);
  2262. };
  2263. logger.debug(`${this} Queued ${operationName} task`);
  2264. return new Promise((resolve, reject) => {
  2265. this.modificationQueue.push(
  2266. workFunction,
  2267. error => {
  2268. if (error) {
  2269. logger.error(`${this} ${operationName} failed`);
  2270. reject(error);
  2271. } else {
  2272. logger.debug(`${this} ${operationName} done`);
  2273. resolve();
  2274. }
  2275. });
  2276. });
  2277. }
  2278. /**
  2279. * Resumes or suspends video media transfer over the p2p peer connection.
  2280. *
  2281. * @param {boolean} videoActive <tt>true</tt> to enable video media transfer or <tt>false</tt> to suspend video
  2282. * media transmission.
  2283. * @return {Promise} a <tt>Promise</tt> which will resolve once the operation is done. It will be rejected with
  2284. * an error description as a string in case anything goes wrong.
  2285. */
  2286. setP2pVideoTransferActive(videoActive) {
  2287. if (!this.peerconnection) {
  2288. return Promise.reject('Can not modify video transfer active state,'
  2289. + ' before "initialize" is called');
  2290. }
  2291. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  2292. logger.info(`${this} Queued make ${logVideoStr} task`);
  2293. const workFunction = finishedCallback => {
  2294. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  2295. if (this._localVideoActive !== videoActive) {
  2296. this._localVideoActive = videoActive;
  2297. if (this.isP2P && isSessionActive) {
  2298. this.sendContentModify();
  2299. }
  2300. }
  2301. this.peerconnection.setVideoTransferActive(this._localVideoActive && this._remoteVideoActive);
  2302. // Always initiate a renegotiation cycle for p2p connection when the media direction is changed.
  2303. this._renegotiate()
  2304. .then(() => finishedCallback())
  2305. .catch(error => finishedCallback(error));
  2306. };
  2307. return new Promise((resolve, reject) => {
  2308. this.modificationQueue.push(
  2309. workFunction,
  2310. error => {
  2311. if (error) {
  2312. logger.error(`${this} Make ${logVideoStr} task failed!`);
  2313. reject(error);
  2314. } else {
  2315. logger.debug(`${this} Make ${logVideoStr} task done!`);
  2316. resolve();
  2317. }
  2318. });
  2319. });
  2320. }
  2321. /**
  2322. * Will put and execute on the queue a session modify task. It checks if the sourceMaxFrameHeight (as requested by
  2323. * the p2p peer) or the senders attribute of the video content has changed and modifies the local video sources
  2324. * accordingly.
  2325. */
  2326. modifyContents(jingleContents) {
  2327. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  2328. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  2329. if (sourceMaxFrameHeights) {
  2330. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  2331. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  2332. }
  2333. if (newVideoSenders === null) {
  2334. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  2335. return;
  2336. }
  2337. const workFunction = finishedCallback => {
  2338. if (this._assertNotEnded() && this._modifyRemoteVideoActive(newVideoSenders)) {
  2339. // Will do the sRD/sLD cycle to update SDPs and adjust the media direction.
  2340. this._renegotiate()
  2341. .then(finishedCallback, finishedCallback /* (error) */);
  2342. } else {
  2343. finishedCallback();
  2344. }
  2345. };
  2346. logger.debug(`${this} queued "content-modify" task(video senders="${newVideoSenders}")`);
  2347. this.modificationQueue.push(
  2348. workFunction,
  2349. error => {
  2350. if (error) {
  2351. logger.error(`${this} "content-modify" failed`, error);
  2352. } else {
  2353. logger.debug(`${this} "content-modify" task(video senders="${newVideoSenders}") done`);
  2354. }
  2355. });
  2356. }
  2357. /**
  2358. * Processes new value of remote video "senders" Jingle attribute and tries to apply it for
  2359. * {@link _remoteVideoActive}.
  2360. * @param {string} remoteVideoSenders the value of "senders" attribute of Jingle video content element advertised
  2361. * by remote peer.
  2362. * @return {boolean} <tt>true</tt> if the change affected state of the underlying peerconnection and renegotiation
  2363. * is required for the changes to take effect.
  2364. * @private
  2365. */
  2366. _modifyRemoteVideoActive(remoteVideoSenders) {
  2367. const isRemoteVideoActive
  2368. = remoteVideoSenders === 'both'
  2369. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  2370. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  2371. if (isRemoteVideoActive !== this._remoteVideoActive) {
  2372. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  2373. this._remoteVideoActive = isRemoteVideoActive;
  2374. return this.peerconnection.setVideoTransferActive(this._localVideoActive && this._remoteVideoActive);
  2375. }
  2376. return false;
  2377. }
  2378. /**
  2379. * Figures out added/removed ssrcs and send update IQs.
  2380. * @param oldSDP SDP object for old description.
  2381. * @param newSDP SDP object for new description.
  2382. */
  2383. notifyMySSRCUpdate(oldSDP, newSDP) {
  2384. if (this.state !== JingleSessionState.ACTIVE) {
  2385. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  2386. return;
  2387. }
  2388. if (!this.connection.connected) {
  2389. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2390. if (!this._cachedOldLocalSdp) {
  2391. this._cachedOldLocalSdp = oldSDP;
  2392. }
  2393. this._cachedNewLocalSdp = newSDP;
  2394. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  2395. return;
  2396. }
  2397. this._cachedOldLocalSdp = undefined;
  2398. this._cachedNewLocalSdp = undefined;
  2399. const getSignaledSourceInfo = sdpDiffer => {
  2400. const newMedia = sdpDiffer.getNewMedia();
  2401. let ssrcs = [];
  2402. let mediaType = null;
  2403. // It is assumed that sources are signaled one at a time.
  2404. Object.keys(newMedia).forEach(mediaIndex => {
  2405. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  2406. mediaType = newMedia[mediaIndex].mid;
  2407. if (signaledSsrcs?.length) {
  2408. ssrcs = ssrcs.concat(signaledSsrcs);
  2409. }
  2410. });
  2411. return {
  2412. mediaType,
  2413. ssrcs
  2414. };
  2415. };
  2416. // send source-remove IQ.
  2417. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2418. const remove = $iq({ to: this.remoteJid,
  2419. type: 'set' })
  2420. .c('jingle', {
  2421. xmlns: 'urn:xmpp:jingle:1',
  2422. action: 'source-remove',
  2423. initiator: this.initiatorJid,
  2424. sid: this.sid
  2425. }
  2426. );
  2427. sdpDiffer.toJingle(remove);
  2428. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  2429. // need to
  2430. const ctx = {};
  2431. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2432. if (removedSsrcInfo.ssrcs.length) {
  2433. // Log only the SSRCs instead of the full IQ.
  2434. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  2435. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  2436. this.connection.sendIQ(
  2437. remove,
  2438. () => {
  2439. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  2440. },
  2441. this.newJingleErrorHandler(remove, error => {
  2442. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  2443. }),
  2444. IQ_TIMEOUT);
  2445. }
  2446. // send source-add IQ.
  2447. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2448. const add = $iq({ to: this.remoteJid,
  2449. type: 'set' })
  2450. .c('jingle', {
  2451. xmlns: 'urn:xmpp:jingle:1',
  2452. action: 'source-add',
  2453. initiator: this.initiatorJid,
  2454. sid: this.sid
  2455. }
  2456. );
  2457. sdpDiffer.toJingle(add);
  2458. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2459. if (addedSsrcInfo.ssrcs.length) {
  2460. // Log only the SSRCs instead of the full IQ.
  2461. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  2462. this.connection.sendIQ(
  2463. add,
  2464. () => {
  2465. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  2466. },
  2467. this.newJingleErrorHandler(add, error => {
  2468. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  2469. }),
  2470. IQ_TIMEOUT);
  2471. }
  2472. }
  2473. /**
  2474. * Method returns function(errorResponse) which is a callback to be passed
  2475. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2476. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2477. * structure is as follows:
  2478. * {
  2479. * code: {XMPP error response code}
  2480. * reason: {the name of XMPP error reason element or 'timeout' if the
  2481. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2482. * source: {request.tree() that provides original request}
  2483. * session: {this JingleSessionPC.toString()}
  2484. * }
  2485. * @param request Strophe IQ instance which is the request to be dumped into
  2486. * the error structure
  2487. * @param failureCb function(error) called when error response was returned
  2488. * or when a timeout has occurred.
  2489. * @returns {function(this:JingleSessionPC)}
  2490. */
  2491. newJingleErrorHandler(request, failureCb) {
  2492. return errResponse => {
  2493. const error = {};
  2494. // Get XMPP error code and condition(reason)
  2495. const errorElSel = $(errResponse).find('error');
  2496. if (errorElSel.length) {
  2497. error.code = errorElSel.attr('code');
  2498. const errorReasonSel = $(errResponse).find('error :first');
  2499. if (errorReasonSel.length) {
  2500. error.reason = errorReasonSel[0].tagName;
  2501. }
  2502. const errorMsgSel = errorElSel.find('>text');
  2503. if (errorMsgSel.length) {
  2504. error.msg = errorMsgSel.text();
  2505. }
  2506. }
  2507. if (!errResponse) {
  2508. error.reason = 'timeout';
  2509. }
  2510. error.session = this.toString();
  2511. if (failureCb) {
  2512. failureCb(error);
  2513. } else if (this.state === JingleSessionState.ENDED
  2514. && error.reason === 'item-not-found') {
  2515. // When remote peer decides to terminate the session, but it
  2516. // still have few messages on the queue for processing,
  2517. // it will first send us 'session-terminate' (we enter ENDED)
  2518. // and then follow with 'item-not-found' for the queued requests
  2519. // We don't want to have that logged on error level.
  2520. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  2521. } else {
  2522. GlobalOnErrorHandler.callErrorHandler(
  2523. new Error(
  2524. `Jingle error: ${JSON.stringify(error)}`));
  2525. }
  2526. };
  2527. }
  2528. /**
  2529. * Returns the ice connection state for the peer connection.
  2530. * @returns the ice connection state for the peer connection.
  2531. */
  2532. getIceConnectionState() {
  2533. return this.peerconnection.getConnectionState();
  2534. }
  2535. /**
  2536. * Closes the peerconnection.
  2537. */
  2538. close() {
  2539. this.state = JingleSessionState.ENDED;
  2540. this.establishmentDuration = undefined;
  2541. if (this.peerconnection) {
  2542. this.peerconnection.onicecandidate = null;
  2543. this.peerconnection.oniceconnectionstatechange = null;
  2544. this.peerconnection.onnegotiationneeded = null;
  2545. this.peerconnection.onsignalingstatechange = null;
  2546. }
  2547. logger.debug(`${this} Clearing modificationQueue`);
  2548. // Remove any pending tasks from the queue
  2549. this.modificationQueue.clear();
  2550. logger.debug(`${this} Queued PC close task`);
  2551. this.modificationQueue.push(finishCallback => {
  2552. // do not try to close if already closed.
  2553. this.peerconnection && this.peerconnection.close();
  2554. finishCallback();
  2555. logger.debug(`${this} PC close task done!`);
  2556. });
  2557. logger.debug(`${this} Shutdown modificationQueue!`);
  2558. // No more tasks can go in after the close task
  2559. this.modificationQueue.shutdown();
  2560. }
  2561. /**
  2562. * Converts to string with minor summary.
  2563. * @return {string}
  2564. */
  2565. toString() {
  2566. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2567. }
  2568. /**
  2569. * If the A/B test for suspend video is disabled according to the room's
  2570. * configuration, returns undefined. Otherwise returns a boolean which
  2571. * indicates whether the suspend video option should be enabled or disabled.
  2572. * @param {JingleSessionPCOptions} options - The config options.
  2573. */
  2574. _abtestSuspendVideoEnabled({ abTesting }) {
  2575. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2576. return;
  2577. }
  2578. // We want the two participants in a P2P call to agree on the value of
  2579. // the "suspend" option. We use the JID of the initiator, because it is
  2580. // both randomly selected and agreed upon by both participants.
  2581. return integerHash(this.initiatorJid) % 2 === 0;
  2582. }
  2583. }