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

JingleSessionPC.js 95KB

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