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

JingleSessionPC.js 95KB

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