Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 94KB

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