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

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