Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JingleSessionPC.js 95KB

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