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

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