modified lib-jitsi-meet dev repo
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 96KB

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