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

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