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

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