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 89KB

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