Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JingleSessionPC.js 95KB

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