您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 95KB

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