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

JingleSessionPC.js 95KB

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