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

JingleSessionPC.js 95KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519
  1. /* global __filename, $ */
  2. import { 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 {Promise<void>} promise that will be resolved when the operation is
  1221. * successful and rejected otherwise.
  1222. */
  1223. setSenderMaxBitrates() {
  1224. if (this._assertNotEnded() && !this.isP2P) {
  1225. return this.peerconnection.setMaxBitRate();
  1226. }
  1227. return Promise.resolve();
  1228. }
  1229. /**
  1230. * Sets the resolution constraint on the local camera track.
  1231. * @param {number} maxFrameHeight - The user preferred max frame height.
  1232. * @returns {Promise} promise that will be resolved when the operation is
  1233. * successful and rejected otherwise.
  1234. */
  1235. setSenderVideoConstraint(maxFrameHeight) {
  1236. if (this._assertNotEnded()) {
  1237. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}`);
  1238. return this.peerconnection.setSenderVideoConstraint(maxFrameHeight);
  1239. }
  1240. return Promise.resolve();
  1241. }
  1242. /**
  1243. * Sets the degradation preference on the video sender. This setting determines if
  1244. * resolution or framerate will be preferred when bandwidth or cpu is constrained.
  1245. * @returns {Promise<void>} promise that will be resolved when the operation is
  1246. * successful and rejected otherwise.
  1247. */
  1248. setSenderVideoDegradationPreference() {
  1249. if (this._assertNotEnded()) {
  1250. return this.peerconnection.setSenderVideoDegradationPreference();
  1251. }
  1252. return Promise.resolve();
  1253. }
  1254. /**
  1255. * @inheritDoc
  1256. */
  1257. terminate(success, failure, options) {
  1258. if (this.state === JingleSessionState.ENDED) {
  1259. return;
  1260. }
  1261. if (!options || Boolean(options.sendSessionTerminate)) {
  1262. let sessionTerminate
  1263. = $iq({
  1264. to: this.remoteJid,
  1265. type: 'set'
  1266. })
  1267. .c('jingle', {
  1268. xmlns: 'urn:xmpp:jingle:1',
  1269. action: 'session-terminate',
  1270. initiator: this.initiatorJid,
  1271. sid: this.sid
  1272. })
  1273. .c('reason')
  1274. .c((options && options.reason) || 'success')
  1275. .up();
  1276. if (options && options.reasonDescription) {
  1277. sessionTerminate
  1278. .c('text')
  1279. .t(options.reasonDescription)
  1280. .up()
  1281. .up();
  1282. } else {
  1283. sessionTerminate.up();
  1284. }
  1285. this._bridgeSessionId
  1286. && sessionTerminate.c(
  1287. 'bridge-session', {
  1288. xmlns: 'http://jitsi.org/protocol/focus',
  1289. id: this._bridgeSessionId,
  1290. restart: options && options.requestRestart === true
  1291. }).up();
  1292. // Calling tree() to print something useful
  1293. sessionTerminate = sessionTerminate.tree();
  1294. logger.info('Sending session-terminate', sessionTerminate);
  1295. this.connection.sendIQ(
  1296. sessionTerminate,
  1297. success,
  1298. this.newJingleErrorHandler(sessionTerminate, failure),
  1299. IQ_TIMEOUT);
  1300. } else {
  1301. logger.info(`Skipped sending session-terminate for ${this}`);
  1302. }
  1303. // this should result in 'onTerminated' being called by strope.jingle.js
  1304. this.connection.jingle.terminate(this.sid);
  1305. }
  1306. /**
  1307. *
  1308. * @param reasonCondition
  1309. * @param reasonText
  1310. */
  1311. onTerminated(reasonCondition, reasonText) {
  1312. // Do something with reason and reasonCondition when we start to care
  1313. // this.reasonCondition = reasonCondition;
  1314. // this.reasonText = reasonText;
  1315. logger.info(`Session terminated ${this}`, reasonCondition, reasonText);
  1316. this._xmppListeners.forEach(removeListener => removeListener());
  1317. this._xmppListeners = [];
  1318. if (this._removeSenderVideoConstraintsChangeListener) {
  1319. this._removeSenderVideoConstraintsChangeListener();
  1320. }
  1321. this.close();
  1322. }
  1323. /**
  1324. * Handles XMPP connection state changes.
  1325. *
  1326. * @param {XmppConnection.Status} status - The new status.
  1327. */
  1328. onXmppStatusChanged(status) {
  1329. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1330. logger.info('Sending SSRC update on reconnect');
  1331. this.notifyMySSRCUpdate(
  1332. this._cachedOldLocalSdp,
  1333. this._cachedNewLocalSdp);
  1334. }
  1335. }
  1336. /**
  1337. * Parse the information from the xml sourceAddElem and translate it
  1338. * into sdp lines
  1339. * @param {jquery xml element} sourceAddElem the source-add
  1340. * element from jingle
  1341. * @param {SDP object} currentRemoteSdp the current remote
  1342. * sdp (as of this new source-add)
  1343. * @returns {list} a list of SDP line strings that should
  1344. * be added to the remote SDP
  1345. */
  1346. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1347. const addSsrcInfo = [];
  1348. $(sourceAddElem).each((i1, content) => {
  1349. const name = $(content).attr('name');
  1350. let lines = '';
  1351. $(content)
  1352. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1353. .each(function() {
  1354. // eslint-disable-next-line no-invalid-this
  1355. const semantics = this.getAttribute('semantics');
  1356. const ssrcs
  1357. = $(this) // eslint-disable-line no-invalid-this
  1358. .find('>source')
  1359. .map(function() {
  1360. // eslint-disable-next-line no-invalid-this
  1361. return this.getAttribute('ssrc');
  1362. })
  1363. .get();
  1364. if (ssrcs.length) {
  1365. lines
  1366. += `a=ssrc-group:${semantics} ${
  1367. ssrcs.join(' ')}\r\n`;
  1368. }
  1369. });
  1370. // handles both >source and >description>source
  1371. const tmp
  1372. = $(content).find(
  1373. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1374. /* eslint-disable no-invalid-this */
  1375. tmp.each(function() {
  1376. const ssrc = $(this).attr('ssrc');
  1377. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1378. logger.warn(
  1379. `Source-add request for existing SSRC: ${ssrc}`);
  1380. return;
  1381. }
  1382. // eslint-disable-next-line newline-per-chained-call
  1383. $(this).find('>parameter').each(function() {
  1384. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1385. if ($(this).attr('value') && $(this).attr('value').length) {
  1386. lines += `:${$(this).attr('value')}`;
  1387. }
  1388. lines += '\r\n';
  1389. });
  1390. });
  1391. /* eslint-enable no-invalid-this */
  1392. currentRemoteSdp.media.forEach((media, i2) => {
  1393. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1394. return;
  1395. }
  1396. if (!addSsrcInfo[i2]) {
  1397. addSsrcInfo[i2] = '';
  1398. }
  1399. addSsrcInfo[i2] += lines;
  1400. });
  1401. });
  1402. return addSsrcInfo;
  1403. }
  1404. /**
  1405. * Handles a Jingle source-add message for this Jingle session.
  1406. * @param elem An array of Jingle "content" elements.
  1407. */
  1408. addRemoteStream(elem) {
  1409. this._addOrRemoveRemoteStream(true /* add */, elem);
  1410. }
  1411. /**
  1412. * Handles a Jingle source-remove message for this Jingle session.
  1413. * @param elem An array of Jingle "content" elements.
  1414. */
  1415. removeRemoteStream(elem) {
  1416. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1417. }
  1418. /**
  1419. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1420. * Jingle session.
  1421. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1422. * otherwise.
  1423. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1424. * @private
  1425. */
  1426. _addOrRemoveRemoteStream(isAdd, elem) {
  1427. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1428. if (isAdd) {
  1429. this.readSsrcInfo(elem);
  1430. }
  1431. const workFunction = finishedCallback => {
  1432. if (!this.peerconnection.localDescription
  1433. || !this.peerconnection.localDescription.sdp) {
  1434. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1435. logger.error(errMsg);
  1436. finishedCallback(errMsg);
  1437. return;
  1438. }
  1439. logger.log(`Processing ${logPrefix}`);
  1440. logger.log(
  1441. 'ICE connection state: ',
  1442. this.peerconnection.iceConnectionState);
  1443. const oldLocalSdp
  1444. = new SDP(this.peerconnection.localDescription.sdp);
  1445. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1446. const addOrRemoveSsrcInfo
  1447. = isAdd
  1448. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1449. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1450. const newRemoteSdp
  1451. = isAdd
  1452. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1453. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1454. this._renegotiate(newRemoteSdp.raw)
  1455. .then(() => {
  1456. const newLocalSdp
  1457. = new SDP(this.peerconnection.localDescription.sdp);
  1458. logger.log(
  1459. `${logPrefix} - OK, SDPs: `, oldLocalSdp, newLocalSdp);
  1460. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1461. finishedCallback();
  1462. }, error => {
  1463. logger.error(`${logPrefix} failed:`, error);
  1464. finishedCallback(error);
  1465. });
  1466. };
  1467. // Queue and execute
  1468. this.modificationQueue.push(workFunction);
  1469. }
  1470. /**
  1471. * Takes in a jingle offer iq, returns the new sdp offer
  1472. * @param {jquery xml element} offerIq the incoming offer
  1473. * @returns {SDP object} the jingle offer translated to SDP
  1474. */
  1475. _processNewJingleOfferIq(offerIq) {
  1476. const remoteSdp = new SDP('');
  1477. if (this.webrtcIceTcpDisable) {
  1478. remoteSdp.removeTcpCandidates = true;
  1479. }
  1480. if (this.webrtcIceUdpDisable) {
  1481. remoteSdp.removeUdpCandidates = true;
  1482. }
  1483. if (this.failICE) {
  1484. remoteSdp.failICE = true;
  1485. }
  1486. remoteSdp.fromJingle(offerIq);
  1487. this.readSsrcInfo($(offerIq).find('>content'));
  1488. return remoteSdp;
  1489. }
  1490. /**
  1491. * Remove the given ssrc lines from the current remote sdp
  1492. * @param {list} removeSsrcInfo a list of SDP line strings that
  1493. * should be removed from the remote SDP
  1494. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1495. * in removeSsrcInfo
  1496. */
  1497. _processRemoteRemoveSource(removeSsrcInfo) {
  1498. const remoteSdp = browser.usesPlanB()
  1499. ? new SDP(this.peerconnection.remoteDescription.sdp)
  1500. : new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1501. removeSsrcInfo.forEach((lines, idx) => {
  1502. // eslint-disable-next-line no-param-reassign
  1503. lines = lines.split('\r\n');
  1504. lines.pop(); // remove empty last element;
  1505. if (browser.usesPlanB()) {
  1506. lines.forEach(line => {
  1507. remoteSdp.media[idx]
  1508. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1509. });
  1510. } else {
  1511. lines.forEach(line => {
  1512. const mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1513. if (mid > -1) {
  1514. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1515. // Change the direction to "inactive" only on Firefox. Audio fails on
  1516. // Safari (possibly Chrome in unified plan mode) when we try to re-use inactive
  1517. // m-lines due to a webkit bug.
  1518. // https://bugs.webkit.org/show_bug.cgi?id=211181
  1519. if (browser.isFirefox()) {
  1520. remoteSdp.media[mid] = remoteSdp.media[mid].replace('a=sendonly', 'a=inactive');
  1521. }
  1522. }
  1523. });
  1524. }
  1525. });
  1526. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1527. return remoteSdp;
  1528. }
  1529. /**
  1530. * Add the given ssrc lines to the current remote sdp
  1531. * @param {list} addSsrcInfo a list of SDP line strings that
  1532. * should be added to the remote SDP
  1533. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1534. * in removeSsrcInfo
  1535. */
  1536. _processRemoteAddSource(addSsrcInfo) {
  1537. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1538. addSsrcInfo.forEach((lines, idx) => {
  1539. remoteSdp.media[idx] += lines;
  1540. });
  1541. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1542. return remoteSdp;
  1543. }
  1544. /**
  1545. * Do a new o/a flow using the existing remote description
  1546. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1547. * to use. If not provided, the remote sdp from the
  1548. * peerconnection will be used
  1549. * @returns {Promise} promise which resolves when the
  1550. * o/a flow is complete with no arguments or
  1551. * rejects with an error {string}
  1552. */
  1553. _renegotiate(optionalRemoteSdp) {
  1554. if (this.peerconnection.signalingState === 'closed') {
  1555. const error = new Error('Attempted to renegotiate in state closed');
  1556. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1557. return Promise.reject(error);
  1558. }
  1559. const remoteSdp
  1560. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1561. if (!remoteSdp) {
  1562. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1563. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1564. return Promise.reject(error);
  1565. }
  1566. const remoteDescription = new RTCSessionDescription({
  1567. type: this.isInitiator ? 'answer' : 'offer',
  1568. sdp: remoteSdp
  1569. });
  1570. if (this.isInitiator) {
  1571. return this._initiatorRenegotiate(remoteDescription);
  1572. }
  1573. return this._responderRenegotiate(remoteDescription);
  1574. }
  1575. /**
  1576. * Renegotiate cycle implementation for the responder case.
  1577. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1578. * which will be used as remote description in the cycle.
  1579. * @private
  1580. */
  1581. _responderRenegotiate(remoteDescription) {
  1582. logger.debug('Renegotiate: setting remote description');
  1583. return this.peerconnection.setRemoteDescription(remoteDescription)
  1584. .then(() => {
  1585. logger.debug('Renegotiate: creating answer');
  1586. return this.peerconnection.createAnswer(this.mediaConstraints)
  1587. .then(answer => {
  1588. logger.debug('Renegotiate: setting local description');
  1589. return this.peerconnection.setLocalDescription(answer);
  1590. });
  1591. });
  1592. }
  1593. /**
  1594. * Renegotiate cycle implementation for the initiator's case.
  1595. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1596. * which will be used as remote description in the cycle.
  1597. * @private
  1598. */
  1599. _initiatorRenegotiate(remoteDescription) {
  1600. logger.debug('Renegotiate: creating offer');
  1601. return this.peerconnection.createOffer(this.mediaConstraints)
  1602. .then(offer => {
  1603. logger.debug('Renegotiate: setting local description');
  1604. return this.peerconnection.setLocalDescription(offer)
  1605. .then(() => {
  1606. logger.debug(
  1607. 'Renegotiate: setting remote description');
  1608. // eslint-disable-next-line max-len
  1609. return this.peerconnection.setRemoteDescription(remoteDescription);
  1610. });
  1611. });
  1612. }
  1613. /**
  1614. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1615. * offer/answer cycle after both operations are done. Either
  1616. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1617. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1618. * <tt>oldTrack</tt>
  1619. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1620. * replaced
  1621. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1622. * @returns {Promise} which resolves once the replacement is complete
  1623. * with no arguments or rejects with an error {string}
  1624. */
  1625. replaceTrack(oldTrack, newTrack) {
  1626. const workFunction = finishedCallback => {
  1627. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1628. if (browser.usesPlanB()) {
  1629. // NOTE the code below assumes that no more than 1 video track
  1630. // can be added to the peer connection.
  1631. // Transition from camera to desktop share
  1632. // or transition from one camera source to another.
  1633. if (this.peerconnection.options.capScreenshareBitrate
  1634. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  1635. // Clearing current primary SSRC will make
  1636. // the SdpConsistency generate a new one which will result
  1637. // with:
  1638. // 1. source-remove for the old video stream.
  1639. // 2. source-add for the new video stream.
  1640. this.peerconnection.clearRecvonlySsrc();
  1641. }
  1642. // Transition from no video to video (unmute).
  1643. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  1644. // Clearing current primary SSRC will make
  1645. // the SdpConsistency generate a new one which will result
  1646. // with:
  1647. // 1. source-remove for the recvonly
  1648. // 2. source-add for the new video stream
  1649. this.peerconnection.clearRecvonlySsrc();
  1650. // Transition from video to no video
  1651. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  1652. // Clearing current primary SSRC and generating the recvonly
  1653. // will result in:
  1654. // 1. source-remove for the old video stream
  1655. // 2. source-add for the recvonly stream
  1656. this.peerconnection.clearRecvonlySsrc();
  1657. this.peerconnection.generateRecvonlySsrc();
  1658. }
  1659. }
  1660. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1661. .then(shouldRenegotiate => {
  1662. let promise = Promise.resolve();
  1663. if (shouldRenegotiate
  1664. && (oldTrack || newTrack)
  1665. && this.state === JingleSessionState.ACTIVE) {
  1666. promise = this._renegotiate().then(() => {
  1667. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1668. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  1669. });
  1670. }
  1671. return promise.then(() => {
  1672. if (newTrack && newTrack.isVideoTrack()) {
  1673. // FIXME set all sender parameters in one go?
  1674. // Set the degradation preference on the new video sender.
  1675. return this.peerconnection.setSenderVideoDegradationPreference()
  1676. // Apply the cached video constraints on the new video sender.
  1677. .then(() => this.peerconnection.setSenderVideoConstraint())
  1678. .then(() => {
  1679. // Configure max bitrate on the video sender when media is routed through JVB.
  1680. if (!this.isP2P) {
  1681. return this.peerconnection.setMaxBitRate(newTrack);
  1682. }
  1683. });
  1684. }
  1685. });
  1686. })
  1687. .then(() => finishedCallback(), error => finishedCallback(error));
  1688. };
  1689. return new Promise((resolve, reject) => {
  1690. this.modificationQueue.push(
  1691. workFunction,
  1692. error => {
  1693. if (error) {
  1694. logger.error('Replace track error:', error);
  1695. reject(error);
  1696. } else {
  1697. logger.info('Replace track done!');
  1698. resolve();
  1699. }
  1700. });
  1701. });
  1702. }
  1703. /**
  1704. * Parse the information from the xml sourceRemoveElem and translate it
  1705. * into sdp lines
  1706. * @param {jquery xml element} sourceRemoveElem the source-remove
  1707. * element from jingle
  1708. * @param {SDP object} currentRemoteSdp the current remote
  1709. * sdp (as of this new source-remove)
  1710. * @returns {list} a list of SDP line strings that should
  1711. * be removed from the remote SDP
  1712. */
  1713. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1714. const removeSsrcInfo = [];
  1715. $(sourceRemoveElem).each((i1, content) => {
  1716. const name = $(content).attr('name');
  1717. let lines = '';
  1718. $(content)
  1719. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1720. .each(function() {
  1721. /* eslint-disable no-invalid-this */
  1722. const semantics = this.getAttribute('semantics');
  1723. const ssrcs
  1724. = $(this)
  1725. .find('>source')
  1726. .map(function() {
  1727. return this.getAttribute('ssrc');
  1728. })
  1729. .get();
  1730. if (ssrcs.length) {
  1731. lines
  1732. += `a=ssrc-group:${semantics} ${
  1733. ssrcs.join(' ')}\r\n`;
  1734. }
  1735. /* eslint-enable no-invalid-this */
  1736. });
  1737. const ssrcs = [];
  1738. // handles both >source and >description>source versions
  1739. const tmp
  1740. = $(content).find(
  1741. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1742. tmp.each(function() {
  1743. // eslint-disable-next-line no-invalid-this
  1744. const ssrc = $(this).attr('ssrc');
  1745. ssrcs.push(ssrc);
  1746. });
  1747. currentRemoteSdp.media.forEach((media, i2) => {
  1748. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1749. return;
  1750. }
  1751. if (!removeSsrcInfo[i2]) {
  1752. removeSsrcInfo[i2] = '';
  1753. }
  1754. ssrcs.forEach(ssrc => {
  1755. const ssrcLines
  1756. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1757. if (ssrcLines.length) {
  1758. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1759. }
  1760. });
  1761. removeSsrcInfo[i2] += lines;
  1762. });
  1763. });
  1764. return removeSsrcInfo;
  1765. }
  1766. /**
  1767. * Will print an error if there is any difference, between the SSRCs given
  1768. * in the <tt>oldSDP</tt> and the ones currently described in
  1769. * the peerconnection's local description.
  1770. * @param {string} operationName the operation's name which will be printed
  1771. * in the error message.
  1772. * @param {SDP} oldSDP the old local SDP which will be compared with
  1773. * the current one.
  1774. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  1775. * otherwise.
  1776. * @private
  1777. */
  1778. _verifyNoSSRCChanged(operationName, oldSDP) {
  1779. const currentLocalSDP
  1780. = new SDP(this.peerconnection.localDescription.sdp);
  1781. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  1782. const addedMedia = sdpDiff.getNewMedia();
  1783. if (Object.keys(addedMedia).length) {
  1784. logger.error(
  1785. `${this} - some SSRC were added on ${operationName}`,
  1786. addedMedia);
  1787. return false;
  1788. }
  1789. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  1790. const removedMedia = sdpDiff.getNewMedia();
  1791. if (Object.keys(removedMedia).length) {
  1792. logger.error(
  1793. `${this} - some SSRCs were removed on ${operationName}`,
  1794. removedMedia);
  1795. return false;
  1796. }
  1797. return true;
  1798. }
  1799. /**
  1800. * Adds local track back to this session, as part of the unmute operation.
  1801. * @param {JitsiLocalTrack} track
  1802. * @return {Promise} a promise that will resolve once the local track is
  1803. * added back to this session and renegotiation succeeds. Will be rejected
  1804. * with a <tt>string</tt> that provides some error details in case something
  1805. * goes wrong.
  1806. */
  1807. addTrackAsUnmute(track) {
  1808. return this._addRemoveTrackAsMuteUnmute(
  1809. false /* add as unmute */, track)
  1810. .then(() => {
  1811. // Apply the video constraints, max bitrates and degradation preference on
  1812. // the video sender if needed.
  1813. if (track.isVideoTrack() && browser.doesVideoMuteByStreamRemove()) {
  1814. return this.setSenderMaxBitrates()
  1815. .then(() => this.setSenderVideoDegradationPreference())
  1816. .then(() => this.setSenderVideoConstraint());
  1817. }
  1818. });
  1819. }
  1820. /**
  1821. * Remove local track as part of the mute operation.
  1822. * @param {JitsiLocalTrack} track the local track to be removed
  1823. * @return {Promise} a promise which will be resolved once the local track
  1824. * is removed from this session and the renegotiation is performed.
  1825. * The promise will be rejected with a <tt>string</tt> that the describes
  1826. * the error if anything goes wrong.
  1827. */
  1828. removeTrackAsMute(track) {
  1829. return this._addRemoveTrackAsMuteUnmute(
  1830. true /* remove as mute */, track);
  1831. }
  1832. /**
  1833. * See {@link addTrackAsUnmute} and {@link removeTrackAsMute}.
  1834. * @param {boolean} isMute <tt>true</tt> for "remove as mute" or
  1835. * <tt>false</tt> for "add as unmute".
  1836. * @param {JitsiLocalTrack} track the track that will be added/removed
  1837. * @private
  1838. */
  1839. _addRemoveTrackAsMuteUnmute(isMute, track) {
  1840. if (!track) {
  1841. return Promise.reject('invalid "track" argument value');
  1842. }
  1843. const operationName = isMute ? 'removeTrackMute' : 'addTrackUnmute';
  1844. const workFunction = finishedCallback => {
  1845. const tpc = this.peerconnection;
  1846. if (!tpc) {
  1847. finishedCallback(
  1848. `Error: tried ${operationName} track with no active peer`
  1849. + 'connection');
  1850. return;
  1851. }
  1852. const oldLocalSDP = tpc.localDescription.sdp;
  1853. const operationPromise
  1854. = isMute
  1855. ? tpc.removeTrackMute(track)
  1856. : tpc.addTrackUnmute(track);
  1857. operationPromise
  1858. .then(shouldRenegotiate => {
  1859. if (shouldRenegotiate && oldLocalSDP && tpc.remoteDescription.sdp) {
  1860. this._renegotiate()
  1861. .then(() => {
  1862. // The results are ignored, as this check failure is not
  1863. // enough to fail the whole operation. It will log
  1864. // an error inside.
  1865. this._verifyNoSSRCChanged(
  1866. operationName, new SDP(oldLocalSDP));
  1867. finishedCallback();
  1868. });
  1869. } else {
  1870. finishedCallback();
  1871. }
  1872. },
  1873. finishedCallback /* will be called with an error */);
  1874. };
  1875. return new Promise((resolve, reject) => {
  1876. this.modificationQueue.push(
  1877. workFunction,
  1878. error => {
  1879. if (error) {
  1880. reject(error);
  1881. } else {
  1882. resolve();
  1883. }
  1884. });
  1885. });
  1886. }
  1887. /**
  1888. * Resumes or suspends media transfer over the underlying peer connection.
  1889. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  1890. * transfer or <tt>false</tt> to suspend audio media transmission.
  1891. * @param {boolean} videoActive <tt>true</tt> to enable video media
  1892. * transfer or <tt>false</tt> to suspend video media transmission.
  1893. * @return {Promise} a <tt>Promise</tt> which will resolve once
  1894. * the operation is done. It will be rejected with an error description as
  1895. * a string in case anything goes wrong.
  1896. */
  1897. setMediaTransferActive(audioActive, videoActive) {
  1898. if (!this.peerconnection) {
  1899. return Promise.reject(
  1900. 'Can not modify transfer active state,'
  1901. + ' before "initialize" is called');
  1902. }
  1903. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  1904. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  1905. logger.info(`Queued make ${logVideoStr}, ${logAudioStr} task...`);
  1906. const workFunction = finishedCallback => {
  1907. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  1908. // Because the value is modified on the queue it's impossible to
  1909. // check it's final value reliably prior to submitting the task.
  1910. // The rule here is that the last submitted state counts.
  1911. // Check the values here to avoid unnecessary renegotiation cycle.
  1912. const audioActiveChanged
  1913. = this.peerconnection.setAudioTransferActive(audioActive);
  1914. if (this._localVideoActive !== videoActive) {
  1915. this._localVideoActive = videoActive;
  1916. // Do only for P2P - Jicofo will reply with 'bad-request'
  1917. // We don't want to send 'content-modify', before the initial
  1918. // O/A (state === JingleSessionState.ACTIVE), because that will
  1919. // mess up video media direction in the remote SDP.
  1920. // 'content-modify' when processed only affects the media
  1921. // direction in the local SDP. We're doing that, because setting
  1922. // 'inactive' on video media in remote SDP will mess up our SDP
  1923. // translation chain (simulcast, RTX, video mute etc.).
  1924. if (this.isP2P && isSessionActive) {
  1925. this.sendContentModify();
  1926. }
  1927. }
  1928. const pcVideoActiveChanged
  1929. = this.peerconnection.setVideoTransferActive(
  1930. this._localVideoActive && this._remoteVideoActive);
  1931. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  1932. // direction
  1933. if (isSessionActive
  1934. && (audioActiveChanged || pcVideoActiveChanged)) {
  1935. this._renegotiate()
  1936. .then(
  1937. finishedCallback,
  1938. finishedCallback /* will be called with an error */);
  1939. } else {
  1940. finishedCallback();
  1941. }
  1942. };
  1943. return new Promise((resolve, reject) => {
  1944. this.modificationQueue.push(
  1945. workFunction,
  1946. error => {
  1947. if (error) {
  1948. reject(error);
  1949. } else {
  1950. resolve();
  1951. }
  1952. });
  1953. });
  1954. }
  1955. /**
  1956. * Will put and execute on the queue a session modify task. Currently it
  1957. * only checks the senders attribute of the video content in order to figure
  1958. * out if the remote peer has video in the inactive state (stored locally
  1959. * in {@link _remoteVideoActive} - see field description for more info).
  1960. * @param {jQuery} jingleContents jQuery selector pointing to the jingle
  1961. * element of the session modify IQ.
  1962. * @see {@link _remoteVideoActive}
  1963. * @see {@link _localVideoActive}
  1964. */
  1965. modifyContents(jingleContents) {
  1966. const newVideoSenders
  1967. = JingleSessionPC.parseVideoSenders(jingleContents);
  1968. const newMaxFrameHeight
  1969. = JingleSessionPC.parseMaxFrameHeight(jingleContents);
  1970. // frame height is optional in our content-modify protocol
  1971. if (newMaxFrameHeight) {
  1972. logger.info(`${this} received remote max frame height: ${newMaxFrameHeight}`);
  1973. this.remoteRecvMaxFrameHeight = newMaxFrameHeight;
  1974. this.eventEmitter.emit(
  1975. MediaSessionEvents.REMOTE_VIDEO_CONSTRAINTS_CHANGED, this);
  1976. }
  1977. if (newVideoSenders === null) {
  1978. logger.error(
  1979. `${this} - failed to parse video "senders" attribute in`
  1980. + '"content-modify" action');
  1981. return;
  1982. }
  1983. const workFunction = finishedCallback => {
  1984. if (this._assertNotEnded('content-modify')
  1985. && this._modifyRemoteVideoActive(newVideoSenders)) {
  1986. // Will do the sRD/sLD cycle to update SDPs and adjust
  1987. // the media direction
  1988. this._renegotiate()
  1989. .then(finishedCallback, finishedCallback /* (error) */);
  1990. } else {
  1991. finishedCallback();
  1992. }
  1993. };
  1994. logger.debug(
  1995. `${this} queued "content-modify" task`
  1996. + `(video senders="${newVideoSenders}")`);
  1997. this.modificationQueue.push(
  1998. workFunction,
  1999. error => {
  2000. if (error) {
  2001. logger.error('"content-modify" failed', error);
  2002. }
  2003. });
  2004. }
  2005. /**
  2006. * Processes new value of remote video "senders" Jingle attribute and tries
  2007. * to apply it for {@link _remoteVideoActive}.
  2008. * @param {string} remoteVideoSenders the value of "senders" attribute of
  2009. * Jingle video content element advertised by remote peer.
  2010. * @return {boolean} <tt>true</tt> if the change affected state of
  2011. * the underlying peerconnection and renegotiation is required for
  2012. * the changes to take effect.
  2013. * @private
  2014. */
  2015. _modifyRemoteVideoActive(remoteVideoSenders) {
  2016. const isRemoteVideoActive
  2017. = remoteVideoSenders === 'both'
  2018. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  2019. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  2020. if (isRemoteVideoActive !== this._remoteVideoActive) {
  2021. logger.debug(
  2022. `${this} new remote video active: ${isRemoteVideoActive}`);
  2023. this._remoteVideoActive = isRemoteVideoActive;
  2024. }
  2025. return this.peerconnection.setVideoTransferActive(
  2026. this._localVideoActive && this._remoteVideoActive);
  2027. }
  2028. /**
  2029. * Figures out added/removed ssrcs and send update IQs.
  2030. * @param oldSDP SDP object for old description.
  2031. * @param newSDP SDP object for new description.
  2032. */
  2033. notifyMySSRCUpdate(oldSDP, newSDP) {
  2034. if (this.state !== JingleSessionState.ACTIVE) {
  2035. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  2036. return;
  2037. }
  2038. if (!this.connection.connected) {
  2039. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2040. if (!this._cachedOldLocalSdp) {
  2041. this._cachedOldLocalSdp = oldSDP;
  2042. }
  2043. this._cachedNewLocalSdp = newSDP;
  2044. logger.warn('Not sending SSRC update while the signaling is disconnected');
  2045. return;
  2046. }
  2047. this._cachedOldLocalSdp = undefined;
  2048. this._cachedNewLocalSdp = undefined;
  2049. // send source-remove IQ.
  2050. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2051. const remove = $iq({ to: this.remoteJid,
  2052. type: 'set' })
  2053. .c('jingle', {
  2054. xmlns: 'urn:xmpp:jingle:1',
  2055. action: 'source-remove',
  2056. initiator: this.initiatorJid,
  2057. sid: this.sid
  2058. }
  2059. );
  2060. const removedAnySSRCs = sdpDiffer.toJingle(remove);
  2061. if (removedAnySSRCs) {
  2062. logger.info('Sending source-remove', remove.tree());
  2063. this.connection.sendIQ(
  2064. remove, null,
  2065. this.newJingleErrorHandler(remove), IQ_TIMEOUT);
  2066. } else {
  2067. logger.log('removal not necessary');
  2068. }
  2069. // send source-add IQ.
  2070. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2071. const add = $iq({ to: this.remoteJid,
  2072. type: 'set' })
  2073. .c('jingle', {
  2074. xmlns: 'urn:xmpp:jingle:1',
  2075. action: 'source-add',
  2076. initiator: this.initiatorJid,
  2077. sid: this.sid
  2078. }
  2079. );
  2080. const containsNewSSRCs = sdpDiffer.toJingle(add);
  2081. if (containsNewSSRCs) {
  2082. logger.info('Sending source-add', add.tree());
  2083. this.connection.sendIQ(
  2084. add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
  2085. } else {
  2086. logger.log('addition not necessary');
  2087. }
  2088. }
  2089. /**
  2090. * Method returns function(errorResponse) which is a callback to be passed
  2091. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2092. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2093. * structure is as follows:
  2094. * {
  2095. * code: {XMPP error response code}
  2096. * reason: {the name of XMPP error reason element or 'timeout' if the
  2097. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2098. * source: {request.tree() that provides original request}
  2099. * session: {this JingleSessionPC.toString()}
  2100. * }
  2101. * @param request Strophe IQ instance which is the request to be dumped into
  2102. * the error structure
  2103. * @param failureCb function(error) called when error response was returned
  2104. * or when a timeout has occurred.
  2105. * @returns {function(this:JingleSessionPC)}
  2106. */
  2107. newJingleErrorHandler(request, failureCb) {
  2108. return errResponse => {
  2109. const error = {};
  2110. // Get XMPP error code and condition(reason)
  2111. const errorElSel = $(errResponse).find('error');
  2112. if (errorElSel.length) {
  2113. error.code = errorElSel.attr('code');
  2114. const errorReasonSel = $(errResponse).find('error :first');
  2115. if (errorReasonSel.length) {
  2116. error.reason = errorReasonSel[0].tagName;
  2117. }
  2118. const errorMsgSel = errorElSel.find('>text');
  2119. if (errorMsgSel.length) {
  2120. error.msg = errorMsgSel.text();
  2121. }
  2122. }
  2123. if (!errResponse) {
  2124. error.reason = 'timeout';
  2125. }
  2126. error.session = this.toString();
  2127. if (failureCb) {
  2128. failureCb(error);
  2129. } else if (this.state === JingleSessionState.ENDED
  2130. && error.reason === 'item-not-found') {
  2131. // When remote peer decides to terminate the session, but it
  2132. // still have few messages on the queue for processing,
  2133. // it will first send us 'session-terminate' (we enter ENDED)
  2134. // and then follow with 'item-not-found' for the queued requests
  2135. // We don't want to have that logged on error level.
  2136. logger.debug(`Jingle error: ${JSON.stringify(error)}`);
  2137. } else {
  2138. GlobalOnErrorHandler.callErrorHandler(
  2139. new Error(
  2140. `Jingle error: ${JSON.stringify(error)}`));
  2141. }
  2142. };
  2143. }
  2144. /**
  2145. * Returns the ice connection state for the peer connection.
  2146. * @returns the ice connection state for the peer connection.
  2147. */
  2148. getIceConnectionState() {
  2149. return this.peerconnection.getConnectionState();
  2150. }
  2151. /**
  2152. * Closes the peerconnection.
  2153. */
  2154. close() {
  2155. this.state = JingleSessionState.ENDED;
  2156. this.establishmentDuration = undefined;
  2157. if (this.peerconnection) {
  2158. this.peerconnection.onicecandidate = null;
  2159. this.peerconnection.oniceconnectionstatechange = null;
  2160. this.peerconnection.onnegotiationneeded = null;
  2161. this.peerconnection.onsignalingstatechange = null;
  2162. }
  2163. // Remove any pending tasks from the queue
  2164. this.modificationQueue.clear();
  2165. this.modificationQueue.push(finishCallback => {
  2166. // The signaling layer will remove it's listeners
  2167. this.signalingLayer.setChatRoom(null);
  2168. // do not try to close if already closed.
  2169. this.peerconnection && this.peerconnection.close();
  2170. finishCallback();
  2171. });
  2172. // No more tasks can go in after the close task
  2173. this.modificationQueue.shutdown();
  2174. }
  2175. /**
  2176. * Converts to string with minor summary.
  2177. * @return {string}
  2178. */
  2179. toString() {
  2180. return `JingleSessionPC[p2p=${this.isP2P},`
  2181. + `initiator=${this.isInitiator},sid=${this.sid}]`;
  2182. }
  2183. /**
  2184. * If the A/B test for suspend video is disabled according to the room's
  2185. * configuration, returns undefined. Otherwise returns a boolean which
  2186. * indicates whether the suspend video option should be enabled or disabled.
  2187. * @param {JingleSessionPCOptions} options - The config options.
  2188. */
  2189. _abtestSuspendVideoEnabled({ abTesting }) {
  2190. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2191. return;
  2192. }
  2193. // We want the two participants in a P2P call to agree on the value of
  2194. // the "suspend" option. We use the JID of the initiator, because it is
  2195. // both randomly selected and agreed upon by both participants.
  2196. const jid = this._getInitiatorJid();
  2197. return integerHash(jid) % 2 === 0;
  2198. }
  2199. }