You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 95KB

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