You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 94KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386
  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. let videoType = $(source).attr('videoType');
  498. // If the videoType is DESKTOP_HIGH_FPS for remote tracks, we should treat it as DESKTOP.
  499. if (videoType === VideoType.DESKTOP_HIGH_FPS) {
  500. videoType = VideoType.DESKTOP;
  501. }
  502. if (sourceDescription.has(sourceName)) {
  503. sourceDescription.get(sourceName).ssrcList?.push(ssrc);
  504. } else {
  505. sourceDescription.set(sourceName, {
  506. groups: [],
  507. mediaType,
  508. msid,
  509. ssrcList: [ ssrc ],
  510. videoType
  511. });
  512. }
  513. // Update the source owner and source name.
  514. const owner = $(source)
  515. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  516. .attr('owner');
  517. if (owner && isAdd) {
  518. // JVB source-add.
  519. this._signalingLayer.setSSRCOwner(Number(ssrc), getEndpointId(owner), sourceName);
  520. } else if (isAdd) {
  521. // P2P source-add.
  522. this._signalingLayer.setSSRCOwner(Number(ssrc),
  523. Strophe.getResourceFromJid(this.remoteJid), sourceName);
  524. } else {
  525. removeSsrcs.push(Number(ssrc));
  526. }
  527. }
  528. // 'source-remove' from remote peer.
  529. removeSsrcs.length && this._signalingLayer.removeSSRCOwners(removeSsrcs);
  530. const groups = $(description).find('>ssrc-group');
  531. if (!groups.length) {
  532. continue; // eslint-disable-line no-continue
  533. }
  534. for (const group of groups) {
  535. const semantics = $(group).attr('semantics');
  536. const groupSsrcs = [];
  537. for (const source of $(group).find('>source')) {
  538. groupSsrcs.push($(source).attr('ssrc'));
  539. }
  540. for (const [ sourceName, { ssrcList } ] of sourceDescription) {
  541. if (isEqual(ssrcList.slice().sort(), groupSsrcs.slice().sort())) {
  542. sourceDescription.get(sourceName).groups.push({
  543. semantics,
  544. ssrcs: groupSsrcs
  545. });
  546. }
  547. }
  548. }
  549. }
  550. }
  551. sourceDescription.size && this.peerconnection.updateRemoteSources(sourceDescription, isAdd);
  552. return sourceDescription;
  553. }
  554. /**
  555. * Does a new offer/answer flow using the existing remote description (if not provided) and signals any new sources
  556. * to Jicofo or the remote peer.
  557. *
  558. * @param {string} [optionalRemoteSdp] optional, raw remote sdp to use. If not provided, the remote sdp from the
  559. * peerconnection will be used.
  560. * @returns {Promise} promise which resolves when the o/a flow is complete with no arguments or rejects with an
  561. * error {string}
  562. * @private
  563. */
  564. _renegotiate(optionalRemoteSdp) {
  565. if (this.peerconnection.signalingState === 'closed') {
  566. const error = new Error('Attempted to renegotiate in state closed');
  567. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  568. return Promise.reject(error);
  569. }
  570. const remoteSdp = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  571. if (!remoteSdp) {
  572. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  573. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  574. return Promise.reject(error);
  575. }
  576. const remoteDescription = {
  577. type: 'offer',
  578. sdp: remoteSdp
  579. };
  580. const oldLocalSDP = this.peerconnection.localDescription.sdp;
  581. logger.debug(`${this} Renegotiate: setting remote description`);
  582. return this.peerconnection.setRemoteDescription(remoteDescription)
  583. .then(() => {
  584. logger.debug(`${this} Renegotiate: creating answer`);
  585. return this.peerconnection.createAnswer(this.mediaConstraints);
  586. })
  587. .then(answer => {
  588. logger.debug(`${this} Renegotiate: setting local description`);
  589. return this.peerconnection.setLocalDescription(answer);
  590. })
  591. .then(() => {
  592. if (oldLocalSDP) {
  593. // Send the source updates after every renegotiation cycle.
  594. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(this.peerconnection.localDescription.sdp));
  595. }
  596. });
  597. }
  598. /**
  599. * Sends 'content-modify' IQ in order to ask the remote peer to either stop or resume sending video media or to
  600. * adjust sender's video constraints.
  601. *
  602. * @returns {void}
  603. * @private
  604. */
  605. _sendContentModify() {
  606. const senders = this._localSendReceiveVideoActive ? 'both' : 'none';
  607. const sessionModify
  608. = $iq({
  609. to: this.remoteJid,
  610. type: 'set'
  611. })
  612. .c('jingle', {
  613. xmlns: 'urn:xmpp:jingle:1',
  614. action: 'content-modify',
  615. initiator: this.initiatorJid,
  616. sid: this.sid
  617. })
  618. .c('content', {
  619. name: MediaType.VIDEO,
  620. senders
  621. });
  622. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  623. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  624. sessionModify
  625. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  626. .attrs({
  627. sourceName,
  628. maxHeight
  629. });
  630. sessionModify.up();
  631. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  632. });
  633. }
  634. logger.debug(sessionModify.tree());
  635. this.connection.sendIQ(
  636. sessionModify,
  637. null,
  638. this.newJingleErrorHandler(sessionModify),
  639. IQ_TIMEOUT);
  640. }
  641. /**
  642. * Sends given candidate in Jingle 'transport-info' message.
  643. *
  644. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  645. * @returns {void}
  646. * @private
  647. */
  648. _sendIceCandidate(candidate) {
  649. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  650. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  651. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  652. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  653. if (!(ice && jcand)) {
  654. logger.error('failed to get ice && jcand');
  655. return;
  656. }
  657. ice.xmlns = XEP.ICE_UDP_TRANSPORT;
  658. if (this.usedrip) {
  659. if (this.dripContainer.length === 0) {
  660. setTimeout(() => {
  661. if (this.dripContainer.length === 0) {
  662. return;
  663. }
  664. this._sendIceCandidates(this.dripContainer);
  665. this.dripContainer = [];
  666. }, ICE_CAND_GATHERING_TIMEOUT);
  667. }
  668. this.dripContainer.push(candidate);
  669. } else {
  670. this._sendIceCandidates([ candidate ]);
  671. }
  672. } else {
  673. logger.log(`${this} _sendIceCandidate: last candidate`);
  674. // FIXME: remember to re-think in ICE-restart
  675. this.lasticecandidate = true;
  676. }
  677. }
  678. /**
  679. * Sends given candidates in Jingle 'transport-info' message.
  680. *
  681. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE candidate instances.
  682. * @returns {void}
  683. * @private
  684. */
  685. _sendIceCandidates(candidates) {
  686. if (!this._assertNotEnded('_sendIceCandidates')) {
  687. return;
  688. }
  689. logger.log(`${this} _sendIceCandidates ${JSON.stringify(candidates)}`);
  690. const cand = $iq({ to: this.remoteJid,
  691. type: 'set' })
  692. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  693. action: 'transport-info',
  694. initiator: this.initiatorJid,
  695. sid: this.sid });
  696. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  697. for (let mid = 0; mid < localSDP.media.length; mid++) {
  698. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  699. const mline
  700. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  701. if (cands.length > 0) {
  702. const ice
  703. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  704. ice.xmlns = XEP.ICE_UDP_TRANSPORT;
  705. cand.c('content', {
  706. creator: this.initiatorJid === this.localJid
  707. ? 'initiator' : 'responder',
  708. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  709. }).c('transport', ice);
  710. for (let i = 0; i < cands.length; i++) {
  711. const candidate
  712. = SDPUtil.candidateToJingle(cands[i].candidate);
  713. // Mangle ICE candidate if 'failICE' test option is enabled
  714. if (this.failICE) {
  715. candidate.ip = '1.1.1.1';
  716. }
  717. cand.c('candidate', candidate).up();
  718. }
  719. // add fingerprint
  720. const fingerprintLine
  721. = SDPUtil.findLine(
  722. localSDP.media[mid],
  723. 'a=fingerprint:', localSDP.session);
  724. if (fingerprintLine) {
  725. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  726. tmp.required = true;
  727. cand.c(
  728. 'fingerprint',
  729. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  730. .t(tmp.fingerprint);
  731. delete tmp.fingerprint;
  732. cand.attrs(tmp);
  733. cand.up();
  734. }
  735. cand.up(); // transport
  736. cand.up(); // content
  737. }
  738. }
  739. // might merge last-candidate notification into this, but it is called
  740. // a lot later. See webrtc issue #2340
  741. // logger.log('was this the last candidate', this.lasticecandidate);
  742. this.connection.sendIQ(
  743. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  744. }
  745. /**
  746. * Sends Jingle 'session-accept' message.
  747. *
  748. * @param {function()} success callback called when we receive 'RESULT' packet for the 'session-accept'.
  749. * @param {function(error)} failure called when we receive an error response or when the request has timed out.
  750. * @returns {void}
  751. * @private
  752. */
  753. _sendSessionAccept(success, failure) {
  754. // NOTE: since we're just reading from it, we don't need to be within
  755. // the modification queue to access the local description
  756. const localSDP = new SDP(this.peerconnection.localDescription.sdp, this.isP2P);
  757. const accept = $iq({ to: this.remoteJid,
  758. type: 'set' })
  759. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  760. action: 'session-accept',
  761. initiator: this.initiatorJid,
  762. responder: this.responderJid,
  763. sid: this.sid });
  764. if (this.webrtcIceTcpDisable) {
  765. localSDP.removeTcpCandidates = true;
  766. }
  767. if (this.webrtcIceUdpDisable) {
  768. localSDP.removeUdpCandidates = true;
  769. }
  770. if (this.failICE) {
  771. localSDP.failICE = true;
  772. }
  773. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  774. localSDP.initialLastN = this.options.channelLastN;
  775. }
  776. localSDP.toJingle(
  777. accept,
  778. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  779. logger.info(`${this} Sending session-accept`);
  780. logger.debug(accept.tree());
  781. this.connection.sendIQ(accept,
  782. success,
  783. this.newJingleErrorHandler(accept, error => {
  784. failure(error);
  785. // 'session-accept' is a critical timeout and we'll
  786. // have to restart
  787. this.room.eventEmitter.emit(
  788. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  789. }),
  790. IQ_TIMEOUT);
  791. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  792. // fingerprint and setup) ASAP in order to start the connection
  793. // establishment.
  794. //
  795. // FIXME Flushing the connection at this point triggers an issue with
  796. // BOSH request handling in Prosody on slow connections.
  797. //
  798. // The problem is that this request will be quite large and it may take
  799. // time before it reaches Prosody. In the meantime Strophe may decide
  800. // to send the next one. And it was observed that a small request with
  801. // 'transport-info' usually follows this one. It does reach Prosody
  802. // before the previous one was completely received. 'rid' on the server
  803. // is increased and Prosody ignores the request with 'session-accept'.
  804. // It will never reach Jicofo and everything in the request table is
  805. // lost. Removing the flush does not guarantee it will never happen, but
  806. // makes it much less likely('transport-info' is bundled with
  807. // 'session-accept' and any immediate requests).
  808. //
  809. // this.connection.flush();
  810. }
  811. /**
  812. * Sends 'session-initiate' to the remote peer.
  813. *
  814. * NOTE this method is synchronous and we're not waiting for the RESULT
  815. * response which would delay the startup process.
  816. *
  817. * @param {string} offerSdp - The local session description which will be used to generate an offer.
  818. * @returns {void}
  819. * @private
  820. */
  821. _sendSessionInitiate(offerSdp) {
  822. let init = $iq({
  823. to: this.remoteJid,
  824. type: 'set'
  825. }).c('jingle', {
  826. xmlns: 'urn:xmpp:jingle:1',
  827. action: 'session-initiate',
  828. initiator: this.initiatorJid,
  829. sid: this.sid
  830. });
  831. new SDP(offerSdp, this.isP2P).toJingle(
  832. init,
  833. this.isInitiator ? 'initiator' : 'responder');
  834. init = init.tree();
  835. logger.debug(`${this} Session-initiate: `, init);
  836. this.connection.sendIQ(init,
  837. () => {
  838. logger.info(`${this} Got RESULT for "session-initiate"`);
  839. },
  840. error => {
  841. logger.error(`${this} "session-initiate" error`, error);
  842. },
  843. IQ_TIMEOUT);
  844. }
  845. /**
  846. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  847. *
  848. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  849. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  850. * 'session-accept' sent.
  851. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  852. * can be used to log some details about the error.
  853. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  854. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  855. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  856. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  857. * assumption that the initial offer/answer cycle has been executed already.
  858. */
  859. acceptOffer(jingleOffer, success, failure, localTracks = []) {
  860. this.setOfferAnswerCycle(
  861. jingleOffer,
  862. () => {
  863. // FIXME we may not care about RESULT packet for session-accept
  864. // then we should either call 'success' here immediately or
  865. // modify sendSessionAccept method to do that
  866. this._sendSessionAccept(() => {
  867. // Start processing tasks on the modification queue.
  868. logger.debug(`${this} Resuming the modification queue after session is established!`);
  869. this.modificationQueue.resume();
  870. success();
  871. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  872. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  873. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  874. // This will happen when someone shares a secondary source to a two people call, the other user
  875. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  876. // point, there are 2 video tracks which need to be signaled to the remote peer.
  877. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  878. videoTracks.length && videoTracks.splice(0, 1);
  879. videoTracks.length && this.addTracks(videoTracks);
  880. },
  881. error => {
  882. failure(error);
  883. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  884. });
  885. },
  886. failure,
  887. localTracks);
  888. }
  889. /**
  890. * {@inheritDoc}
  891. */
  892. addIceCandidates(elem) {
  893. if (this.peerconnection.signalingState === 'closed') {
  894. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  895. return;
  896. }
  897. const iceCandidates = [];
  898. elem.find('>content>transport>candidate')
  899. .each((idx, candidate) => {
  900. let line = SDPUtil.candidateFromJingle(candidate);
  901. line = line.replace('\r\n', '').replace('a=', '');
  902. // FIXME this code does not care to handle
  903. // non-bundle transport
  904. const rtcCandidate = new RTCIceCandidate({
  905. sdpMLineIndex: 0,
  906. // FF comes up with more complex names like audio-23423,
  907. // Given that it works on both Chrome and FF without
  908. // providing it, let's leave it like this for the time
  909. // being...
  910. // sdpMid: 'audio',
  911. sdpMid: '',
  912. candidate: line
  913. });
  914. iceCandidates.push(rtcCandidate);
  915. });
  916. if (!iceCandidates.length) {
  917. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  918. return;
  919. }
  920. // We want to have this task queued, so that we know it is executed,
  921. // after the initial sRD/sLD offer/answer cycle was done (based on
  922. // the assumption that candidates are spawned after the offer/answer
  923. // and XMPP preserves order).
  924. const workFunction = finishedCallback => {
  925. for (const iceCandidate of iceCandidates) {
  926. this.peerconnection.addIceCandidate(iceCandidate)
  927. .then(
  928. () => logger.debug(`${this} addIceCandidate ok!`),
  929. err => logger.error(`${this} addIceCandidate failed!`, err));
  930. }
  931. finishedCallback();
  932. logger.debug(`${this} ICE candidates task finished`);
  933. };
  934. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  935. this.modificationQueue.push(workFunction);
  936. }
  937. /**
  938. * Handles a Jingle source-add message for this Jingle session.
  939. *
  940. * @param {Array<Element>} elem an array of Jingle "content" elements.
  941. * @returns {Promise} resolved when the operation is done or rejected with an error.
  942. */
  943. addRemoteStream(elem) {
  944. this._addOrRemoveRemoteStream(true /* add */, elem);
  945. }
  946. /**
  947. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  948. * being added to the peerconnection for the first time.
  949. *
  950. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  951. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  952. * otherwise.
  953. */
  954. addTracks(localTracks = null) {
  955. if (!localTracks?.length) {
  956. Promise.reject(new Error('No tracks passed'));
  957. }
  958. if (localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  959. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  960. }
  961. const replaceTracks = [];
  962. const workFunction = finishedCallback => {
  963. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp, this.isP2P);
  964. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  965. .find(t => t.receiver.track.kind === MediaType.VIDEO
  966. && t.direction === MediaDirection.RECVONLY
  967. && t.currentDirection === MediaDirection.RECVONLY);
  968. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  969. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  970. // existing one in that case.
  971. for (const track of localTracks) {
  972. if (!this.isP2P || !recvOnlyTransceiver) {
  973. remoteSdp.addMlineForNewSource(track.getType());
  974. }
  975. }
  976. this._renegotiate(remoteSdp.raw)
  977. .then(() => {
  978. // Replace the tracks on the newly generated transceivers.
  979. for (const track of localTracks) {
  980. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  981. }
  982. return Promise.all(replaceTracks);
  983. })
  984. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  985. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  986. .then(() => this._renegotiate())
  987. .then(() => finishedCallback(), error => finishedCallback(error));
  988. };
  989. return new Promise((resolve, reject) => {
  990. logger.debug(`${this} Queued renegotiation after addTrack`);
  991. this.modificationQueue.push(
  992. workFunction,
  993. error => {
  994. if (error) {
  995. if (error instanceof ClearedQueueError) {
  996. // The session might have been terminated before the task was executed, making it obsolete.
  997. logger.debug(`${this} renegotiation after addTrack aborted: session terminated`);
  998. resolve();
  999. return;
  1000. }
  1001. logger.error(`${this} renegotiation after addTrack error`, error);
  1002. reject(error);
  1003. } else {
  1004. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1005. resolve();
  1006. }
  1007. });
  1008. });
  1009. }
  1010. /**
  1011. * Adds local track back to the peerconnection associated with this session.
  1012. *
  1013. * @param {JitsiLocalTrack} track - the local track to be added back to the peerconnection.
  1014. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  1015. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  1016. * details in case something goes wrong.
  1017. * @returns {Promise<void>}
  1018. */
  1019. addTrackToPc(track) {
  1020. return this._addRemoveTrack(false /* add */, track)
  1021. .then(() => {
  1022. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  1023. // unmutes it the first time, all the parameters need to be configured.
  1024. if (track.isVideoTrack()) {
  1025. return this.peerconnection.configureVideoSenderEncodings(track);
  1026. }
  1027. });
  1028. }
  1029. /**
  1030. * Closes the underlying peerconnection and shuts down the modification queue.
  1031. *
  1032. * @returns {void}
  1033. */
  1034. close() {
  1035. this.state = JingleSessionState.ENDED;
  1036. this.establishmentDuration = undefined;
  1037. if (this.peerconnection) {
  1038. this.peerconnection.onicecandidate = null;
  1039. this.peerconnection.oniceconnectionstatechange = null;
  1040. this.peerconnection.onnegotiationneeded = null;
  1041. this.peerconnection.onsignalingstatechange = null;
  1042. }
  1043. logger.debug(`${this} Clearing modificationQueue`);
  1044. // Remove any pending tasks from the queue
  1045. this.modificationQueue.clear();
  1046. logger.debug(`${this} Queued PC close task`);
  1047. this.modificationQueue.push(finishCallback => {
  1048. // do not try to close if already closed.
  1049. this.peerconnection && this.peerconnection.close();
  1050. finishCallback();
  1051. logger.debug(`${this} PC close task done!`);
  1052. });
  1053. logger.debug(`${this} Shutdown modificationQueue!`);
  1054. // No more tasks can go in after the close task
  1055. this.modificationQueue.shutdown();
  1056. }
  1057. /**
  1058. * @inheritDoc
  1059. * @param {JingleSessionPCOptions} options - a set of config options.
  1060. * @returns {void}
  1061. */
  1062. doInitialize(options) {
  1063. this.failICE = Boolean(options.testing?.failICE);
  1064. this.lasticecandidate = false;
  1065. this.options = options;
  1066. /**
  1067. * {@code true} if reconnect is in progress.
  1068. * @type {boolean}
  1069. */
  1070. this.isReconnect = false;
  1071. /**
  1072. * Set to {@code true} if the connection was ever stable
  1073. * @type {boolean}
  1074. */
  1075. this.wasstable = false;
  1076. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  1077. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  1078. const pcOptions = { disableRtx: options.disableRtx };
  1079. if (options.gatherStats) {
  1080. pcOptions.maxstats = DEFAULT_MAX_STATS;
  1081. }
  1082. pcOptions.capScreenshareBitrate = false;
  1083. pcOptions.codecSettings = options.codecSettings;
  1084. pcOptions.enableInsertableStreams = options.enableInsertableStreams;
  1085. pcOptions.usesCodecSelectionAPI = this.usesCodecSelectionAPI
  1086. = browser.supportsCodecSelectionAPI() && options.testing?.enableCodecSelectionAPI && !this.isP2P;
  1087. if (options.videoQuality) {
  1088. const settings = Object.entries(options.videoQuality)
  1089. .map(entry => {
  1090. entry[0] = entry[0].toLowerCase();
  1091. return entry;
  1092. });
  1093. pcOptions.videoQuality = Object.fromEntries(settings);
  1094. }
  1095. pcOptions.forceTurnRelay = options.forceTurnRelay;
  1096. pcOptions.audioQuality = options.audioQuality;
  1097. pcOptions.disableSimulcast = this.isP2P ? true : options.disableSimulcast;
  1098. if (!this.isP2P) {
  1099. // Do not send lower spatial layers for low fps screenshare and enable them only for high fps screenshare.
  1100. pcOptions.capScreenshareBitrate = !(options.desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE);
  1101. }
  1102. if (options.startSilent) {
  1103. pcOptions.startSilent = true;
  1104. }
  1105. this.peerconnection
  1106. = this.rtc.createPeerConnection(
  1107. this._signalingLayer,
  1108. this.pcConfig,
  1109. this.isP2P,
  1110. pcOptions);
  1111. this.peerconnection.onicecandidate = ev => {
  1112. if (!ev) {
  1113. // There was an incomplete check for ev before which left
  1114. // the last line of the function unprotected from a potential
  1115. // throw of an exception. Consequently, it may be argued that
  1116. // the check is unnecessary. Anyway, I'm leaving it and making
  1117. // the check complete.
  1118. return;
  1119. }
  1120. // XXX this is broken, candidate is not parsed.
  1121. const candidate = ev.candidate;
  1122. const now = window.performance.now();
  1123. if (candidate) {
  1124. if (this._gatheringStartedTimestamp === null) {
  1125. this._gatheringStartedTimestamp = now;
  1126. }
  1127. // Discard candidates of disabled protocols.
  1128. let protocol = candidate.protocol;
  1129. if (typeof protocol === 'string') {
  1130. protocol = protocol.toLowerCase();
  1131. if (protocol === 'tcp' || protocol === 'ssltcp') {
  1132. if (this.webrtcIceTcpDisable) {
  1133. return;
  1134. }
  1135. } else if (protocol === 'udp') {
  1136. if (this.webrtcIceUdpDisable) {
  1137. return;
  1138. }
  1139. }
  1140. }
  1141. } else if (!this._gatheringReported) {
  1142. // End of gathering
  1143. Statistics.sendAnalytics(
  1144. ICE_DURATION,
  1145. {
  1146. phase: 'gathering',
  1147. value: now - this._gatheringStartedTimestamp,
  1148. p2p: this.isP2P,
  1149. initiator: this.isInitiator
  1150. });
  1151. this._gatheringReported = true;
  1152. }
  1153. if (this.isP2P) {
  1154. this._sendIceCandidate(candidate);
  1155. }
  1156. };
  1157. // Note there is a change in the spec about closed:
  1158. // This value moved into the RTCPeerConnectionState enum in
  1159. // the May 13, 2016 draft of the specification, as it reflects the state
  1160. // of the RTCPeerConnection, not the signaling connection. You now
  1161. // detect a closed connection by checking for connectionState to be
  1162. // "closed" instead.
  1163. // I suppose at some point this will be moved to onconnectionstatechange
  1164. this.peerconnection.onsignalingstatechange = () => {
  1165. if (this.peerconnection.signalingState === 'stable') {
  1166. this.wasstable = true;
  1167. } else if (this.peerconnection.signalingState === 'closed'
  1168. || this.peerconnection.connectionState === 'closed') {
  1169. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  1170. }
  1171. };
  1172. /**
  1173. * The oniceconnectionstatechange event handler contains the code to
  1174. * execute when the iceconnectionstatechange event, of type Event,
  1175. * is received by this RTCPeerConnection. Such an event is sent when
  1176. * the value of RTCPeerConnection.iceConnectionState changes.
  1177. */
  1178. this.peerconnection.oniceconnectionstatechange = () => {
  1179. const now = window.performance.now();
  1180. let isStable = false;
  1181. if (!this.isP2P) {
  1182. this.room.connectionTimes[
  1183. `ice.state.${this.peerconnection.iceConnectionState}`]
  1184. = now;
  1185. }
  1186. logger.log(`(TIME) ICE ${this.peerconnection.iceConnectionState} ${this.isP2P ? 'P2P' : 'JVB'}:\t`, now);
  1187. Statistics.sendAnalytics(
  1188. ICE_STATE_CHANGED,
  1189. {
  1190. p2p: this.isP2P,
  1191. state: this.peerconnection.iceConnectionState,
  1192. 'signaling_state': this.peerconnection.signalingState,
  1193. reconnect: this.isReconnect,
  1194. value: now
  1195. });
  1196. this.room.eventEmitter.emit(
  1197. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  1198. this,
  1199. this.peerconnection.iceConnectionState);
  1200. switch (this.peerconnection.iceConnectionState) {
  1201. case 'checking':
  1202. this._iceCheckingStartedTimestamp = now;
  1203. break;
  1204. case 'connected':
  1205. case 'completed':
  1206. // Informs interested parties that the connection has been restored. This includes the case when
  1207. // media connection to the bridge has been restored after an ICE failure by using session-terminate.
  1208. if (this.peerconnection.signalingState === 'stable') {
  1209. isStable = true;
  1210. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED, this);
  1211. }
  1212. // Add a workaround for an issue on chrome in Unified plan when the local endpoint is the offerer.
  1213. // The 'signalingstatechange' event for 'stable' is handled after the 'iceconnectionstatechange' event
  1214. // for 'completed' is handled by the client. This prevents the client from firing a
  1215. // CONNECTION_ESTABLISHED event for the p2p session. As a result, the offerer continues to stay on the
  1216. // jvb connection while the remote peer switches to the p2p connection breaking the media flow between
  1217. // the endpoints.
  1218. // TODO - file a chromium bug and add the information here.
  1219. if (!this.wasConnected
  1220. && (this.wasstable
  1221. || isStable
  1222. || (this.isInitiator && (browser.isChromiumBased() || browser.isReactNative())))) {
  1223. Statistics.sendAnalytics(
  1224. ICE_DURATION,
  1225. {
  1226. phase: 'checking',
  1227. value: now - this._iceCheckingStartedTimestamp,
  1228. p2p: this.isP2P,
  1229. initiator: this.isInitiator
  1230. });
  1231. // Switch between ICE gathering and ICE checking whichever
  1232. // started first (scenarios are different for initiator
  1233. // vs responder)
  1234. const iceStarted
  1235. = Math.min(
  1236. this._iceCheckingStartedTimestamp,
  1237. this._gatheringStartedTimestamp);
  1238. this.establishmentDuration = now - iceStarted;
  1239. Statistics.sendAnalytics(
  1240. ICE_DURATION,
  1241. {
  1242. phase: 'establishment',
  1243. value: this.establishmentDuration,
  1244. p2p: this.isP2P,
  1245. initiator: this.isInitiator
  1246. });
  1247. this.wasConnected = true;
  1248. this.room.eventEmitter.emit(
  1249. XMPPEvents.CONNECTION_ESTABLISHED, this);
  1250. }
  1251. this.isReconnect = false;
  1252. break;
  1253. case 'disconnected':
  1254. this.isReconnect = true;
  1255. // Informs interested parties that the connection has been
  1256. // interrupted.
  1257. if (this.wasstable) {
  1258. this.room.eventEmitter.emit(
  1259. XMPPEvents.CONNECTION_INTERRUPTED, this);
  1260. }
  1261. break;
  1262. case 'failed':
  1263. this.room.eventEmitter.emit(
  1264. XMPPEvents.CONNECTION_ICE_FAILED, this);
  1265. break;
  1266. }
  1267. };
  1268. /**
  1269. * The connection state event is fired whenever the aggregate of underlying
  1270. * transports change their state.
  1271. */
  1272. this.peerconnection.onconnectionstatechange = () => {
  1273. const icestate = this.peerconnection.iceConnectionState;
  1274. switch (this.peerconnection.connectionState) {
  1275. case 'failed':
  1276. // Since version 76 Chrome no longer switches ICE connection
  1277. // state to failed (see
  1278. // https://bugs.chromium.org/p/chromium/issues/detail?id=982793
  1279. // for details) we use this workaround to recover from lost connections
  1280. if (icestate === 'disconnected') {
  1281. this.room.eventEmitter.emit(
  1282. XMPPEvents.CONNECTION_ICE_FAILED, this);
  1283. }
  1284. break;
  1285. }
  1286. };
  1287. /**
  1288. * The negotiationneeded event is fired whenever we shake the media on the
  1289. * RTCPeerConnection object.
  1290. */
  1291. this.peerconnection.onnegotiationneeded = () => {
  1292. const state = this.peerconnection.signalingState;
  1293. const remoteDescription = this.peerconnection.remoteDescription;
  1294. if (!this.isP2P
  1295. && state === 'stable'
  1296. && remoteDescription
  1297. && typeof remoteDescription.sdp === 'string') {
  1298. logger.info(`${this} onnegotiationneeded fired on ${this.peerconnection}`);
  1299. const workFunction = finishedCallback => {
  1300. this._renegotiate()
  1301. .then(() => this.peerconnection.configureAudioSenderEncodings())
  1302. .then(() => finishedCallback(), error => finishedCallback(error));
  1303. };
  1304. this.modificationQueue.push(
  1305. workFunction,
  1306. error => {
  1307. if (error) {
  1308. logger.error(`${this} onnegotiationneeded error`, error);
  1309. } else {
  1310. logger.debug(`${this} onnegotiationneeded executed - OK`);
  1311. }
  1312. });
  1313. }
  1314. };
  1315. }
  1316. /**
  1317. * Returns the ice connection state for the peer connection.
  1318. *
  1319. * @returns the ice connection state for the peer connection.
  1320. */
  1321. getIceConnectionState() {
  1322. return this.peerconnection.getConnectionState();
  1323. }
  1324. /**
  1325. * Returns the preference for max frame height for the remote video sources.
  1326. *
  1327. * @returns {Map<string, number>|undefined}
  1328. */
  1329. getRemoteSourcesRecvMaxFrameHeight() {
  1330. if (this.isP2P) {
  1331. return this.remoteSourceMaxFrameHeights;
  1332. }
  1333. return undefined;
  1334. }
  1335. /**
  1336. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  1337. *
  1338. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  1339. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  1340. * @returns {void}
  1341. */
  1342. invite(localTracks = []) {
  1343. if (!this.isInitiator) {
  1344. throw new Error('Trying to invite from the responder session');
  1345. }
  1346. logger.debug(`${this} Executing invite task`);
  1347. const addTracks = [];
  1348. for (const track of localTracks) {
  1349. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1350. }
  1351. Promise.all(addTracks)
  1352. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  1353. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  1354. .then(() => {
  1355. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  1356. this._sendSessionInitiate(this.peerconnection.localDescription.sdp);
  1357. })
  1358. .then(() => {
  1359. logger.debug(`${this} invite executed - OK`);
  1360. })
  1361. .catch(error => {
  1362. logger.error(`${this} invite error`, error);
  1363. });
  1364. }
  1365. /**
  1366. * Enables/disables local video based on 'senders' attribute of the video conent in 'content-modify' IQ sent by the
  1367. * remote peer. Also, checks if the sourceMaxFrameHeight (as requested by the p2p peer) or the senders attribute of
  1368. * the video content has changed and modifies the local video resolution accordingly.
  1369. *
  1370. * @param {Element} jingleContents - The content of the 'content-modify' IQ sent by the remote peer.
  1371. * @returns {void}
  1372. */
  1373. modifyContents(jingleContents) {
  1374. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  1375. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  1376. if (sourceMaxFrameHeights) {
  1377. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  1378. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  1379. }
  1380. if (newVideoSenders === null) {
  1381. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  1382. return;
  1383. }
  1384. if (!this._assertNotEnded()) {
  1385. return;
  1386. }
  1387. const isRemoteVideoActive
  1388. = newVideoSenders === 'both'
  1389. || (newVideoSenders === 'initiator' && this.isInitiator)
  1390. || (newVideoSenders === 'responder' && !this.isInitiator);
  1391. if (isRemoteVideoActive !== this._remoteSendReceiveVideoActive) {
  1392. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  1393. this._remoteSendReceiveVideoActive = isRemoteVideoActive;
  1394. this.peerconnection
  1395. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  1396. }
  1397. }
  1398. /**
  1399. * Method returns function(errorResponse) which is a callback to be passed to Strophe connection.sendIQ method. An
  1400. * 'error' structure is created that is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1401. * structure is as follows:
  1402. * {
  1403. * code: {XMPP error response code}
  1404. * reason: {the name of XMPP error reason element or 'timeout' if the
  1405. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1406. * source: {request.tree() that provides original request}
  1407. * session: {this JingleSessionPC.toString()}
  1408. * }
  1409. * @param request Strophe IQ instance which is the request to be dumped into the error structure.
  1410. * @param failureCb function(error) called when error response was returned or when a timeout has occurred.
  1411. * @returns {function(this:JingleSessionPC)}
  1412. */
  1413. newJingleErrorHandler(request, failureCb) {
  1414. return errResponse => {
  1415. const error = {};
  1416. // Get XMPP error code and condition(reason)
  1417. const errorElSel = $(errResponse).find('error');
  1418. if (errorElSel.length) {
  1419. error.code = errorElSel.attr('code');
  1420. const errorReasonSel = $(errResponse).find('error :first');
  1421. if (errorReasonSel.length) {
  1422. error.reason = errorReasonSel[0].tagName;
  1423. }
  1424. const errorMsgSel = errorElSel.find('>text');
  1425. if (errorMsgSel.length) {
  1426. error.msg = errorMsgSel.text();
  1427. }
  1428. }
  1429. if (!errResponse) {
  1430. error.reason = 'timeout';
  1431. }
  1432. error.session = this.toString();
  1433. if (failureCb) {
  1434. failureCb(error);
  1435. } else if (this.state === JingleSessionState.ENDED
  1436. && error.reason === 'item-not-found') {
  1437. // When remote peer decides to terminate the session, but it
  1438. // still have few messages on the queue for processing,
  1439. // it will first send us 'session-terminate' (we enter ENDED)
  1440. // and then follow with 'item-not-found' for the queued requests
  1441. // We don't want to have that logged on error level.
  1442. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  1443. } else {
  1444. logger.error(`Jingle error: ${JSON.stringify(error)}`);
  1445. }
  1446. };
  1447. }
  1448. /**
  1449. * Figures out added/removed ssrcs and sends updated IQs to the remote peer or Jicofo.
  1450. *
  1451. * @param oldSDP SDP object for old description.
  1452. * @param newSDP SDP object for new description.
  1453. * @returns {void}
  1454. */
  1455. notifyMySSRCUpdate(oldSDP, newSDP) {
  1456. if (this.state !== JingleSessionState.ACTIVE) {
  1457. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  1458. return;
  1459. }
  1460. if (!this.connection.connected) {
  1461. // The goal is to compare the oldest SDP with the latest one upon reconnect
  1462. if (!this._cachedOldLocalSdp) {
  1463. this._cachedOldLocalSdp = oldSDP;
  1464. }
  1465. this._cachedNewLocalSdp = newSDP;
  1466. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  1467. return;
  1468. }
  1469. this._cachedOldLocalSdp = undefined;
  1470. this._cachedNewLocalSdp = undefined;
  1471. const getSignaledSourceInfo = sdpDiffer => {
  1472. const newMedia = sdpDiffer.getNewMedia();
  1473. let ssrcs = [];
  1474. let mediaType = null;
  1475. // It is assumed that sources are signaled one at a time.
  1476. Object.keys(newMedia).forEach(mediaIndex => {
  1477. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  1478. mediaType = newMedia[mediaIndex].mediaType;
  1479. if (signaledSsrcs?.length) {
  1480. ssrcs = ssrcs.concat(signaledSsrcs);
  1481. }
  1482. });
  1483. return {
  1484. mediaType,
  1485. ssrcs
  1486. };
  1487. };
  1488. // send source-remove IQ.
  1489. let sdpDiffer = new SDPDiffer(newSDP, oldSDP, this.isP2P);
  1490. const remove = $iq({ to: this.remoteJid,
  1491. type: 'set' })
  1492. .c('jingle', {
  1493. xmlns: 'urn:xmpp:jingle:1',
  1494. action: 'source-remove',
  1495. initiator: this.initiatorJid,
  1496. sid: this.sid
  1497. }
  1498. );
  1499. sdpDiffer.toJingle(remove);
  1500. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  1501. // need to
  1502. const ctx = {};
  1503. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  1504. if (removedSsrcInfo.ssrcs.length) {
  1505. // Log only the SSRCs instead of the full IQ.
  1506. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  1507. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  1508. this.connection.sendIQ(
  1509. remove,
  1510. () => {
  1511. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  1512. },
  1513. this.newJingleErrorHandler(remove, error => {
  1514. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  1515. }),
  1516. IQ_TIMEOUT);
  1517. }
  1518. // send source-add IQ.
  1519. sdpDiffer = new SDPDiffer(oldSDP, newSDP, this.isP2P);
  1520. const add = $iq({ to: this.remoteJid,
  1521. type: 'set' })
  1522. .c('jingle', {
  1523. xmlns: 'urn:xmpp:jingle:1',
  1524. action: 'source-add',
  1525. initiator: this.initiatorJid,
  1526. sid: this.sid
  1527. }
  1528. );
  1529. sdpDiffer.toJingle(add);
  1530. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  1531. if (addedSsrcInfo.ssrcs.length) {
  1532. // Log only the SSRCs instead of the full IQ.
  1533. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  1534. this.connection.sendIQ(
  1535. add,
  1536. () => {
  1537. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  1538. },
  1539. this.newJingleErrorHandler(add, error => {
  1540. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  1541. }),
  1542. IQ_TIMEOUT);
  1543. }
  1544. }
  1545. /**
  1546. * Handles the termination of the session.
  1547. *
  1548. * @param {string} reasonCondition - The XMPP Jingle reason condition.
  1549. * @param {string} reasonText - The XMPP Jingle reason text.
  1550. * @returns {void}
  1551. */
  1552. onTerminated(reasonCondition, reasonText) {
  1553. // Do something with reason and reasonCondition when we start to care
  1554. // this.reasonCondition = reasonCondition;
  1555. // this.reasonText = reasonText;
  1556. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1557. this._xmppListeners.forEach(removeListener => removeListener());
  1558. this._xmppListeners = [];
  1559. if (this._removeSenderVideoConstraintsChangeListener) {
  1560. this._removeSenderVideoConstraintsChangeListener();
  1561. }
  1562. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1563. this.peerconnection.getRemoteTracks().forEach(track => {
  1564. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1565. });
  1566. }
  1567. this.close();
  1568. }
  1569. /**
  1570. * Handles XMPP connection state changes. Resends any session updates that were cached while the XMPP connection
  1571. * was down.
  1572. *
  1573. * @param {XmppConnection.Status} status - The new status.
  1574. * @returns {void}
  1575. */
  1576. onXmppStatusChanged(status) {
  1577. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1578. logger.info(`${this} Sending SSRC update on reconnect`);
  1579. this.notifyMySSRCUpdate(
  1580. this._cachedOldLocalSdp,
  1581. this._cachedNewLocalSdp);
  1582. }
  1583. }
  1584. /**
  1585. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1586. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1587. *
  1588. * @param {Object} message - The source map message.
  1589. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1590. * @returns {void}
  1591. */
  1592. processSourceMap(message, mediaType) {
  1593. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1594. return;
  1595. }
  1596. const newSsrcs = [];
  1597. for (const src of message.mappedSources) {
  1598. const { owner, source, ssrc } = src;
  1599. const isNewSsrc = this.peerconnection.addRemoteSsrc(ssrc, source);
  1600. if (isNewSsrc) {
  1601. newSsrcs.push(src);
  1602. logger.debug(`New SSRC signaled ${ssrc}: owner=${owner}, source-name=${source}`);
  1603. // Check if there is an old mapping for the given source and clear the owner on the associated track.
  1604. const oldSsrc = this.peerconnection.remoteSources.get(source);
  1605. if (oldSsrc) {
  1606. this._signalingLayer.removeSSRCOwners([ oldSsrc ]);
  1607. const track = this.peerconnection.getTrackBySSRC(oldSsrc);
  1608. if (track) {
  1609. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_SET, track);
  1610. }
  1611. }
  1612. } else {
  1613. const track = this.peerconnection.getTrackBySSRC(ssrc);
  1614. if (!track || (track.getParticipantId() === owner && track.getSourceName() === source)) {
  1615. !track && logger.warn(`Remote track for SSRC=${ssrc} hasn't been created yet,`
  1616. + 'not processing the source map');
  1617. continue; // eslint-disable-line no-continue
  1618. }
  1619. logger.debug(`Existing SSRC re-mapped ${ssrc}: new owner=${owner}, source-name=${source}`);
  1620. this._signalingLayer.setSSRCOwner(ssrc, owner, source);
  1621. const oldSourceName = track.getSourceName();
  1622. const sourceInfo = this.peerconnection.getRemoteSourceInfoBySourceName(oldSourceName);
  1623. // Update the SSRC map on the peerconnection.
  1624. if (sourceInfo) {
  1625. this.peerconnection.updateRemoteSources(new Map([ [ oldSourceName, sourceInfo ] ]), false);
  1626. this.peerconnection.updateRemoteSources(new Map([ [ source, sourceInfo ] ]), true /* isAdd */);
  1627. }
  1628. // Update the muted state and the video type on the track since the presence for this track could have
  1629. // been received before the updated source map is received on the bridge channel.
  1630. const { muted, videoType } = this._signalingLayer.getPeerMediaInfo(owner, mediaType, source);
  1631. muted && this.peerconnection._sourceMutedChanged(source, muted);
  1632. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_SET, track, owner, source, videoType);
  1633. }
  1634. }
  1635. // Add the new SSRCs to the remote description by generating a source message.
  1636. if (newSsrcs.length) {
  1637. let node = $build('content', {
  1638. xmlns: 'urn:xmpp:jingle:1',
  1639. name: mediaType
  1640. }).c('description', {
  1641. xmlns: XEP.RTP_MEDIA,
  1642. media: mediaType
  1643. });
  1644. for (const src of newSsrcs) {
  1645. const { rtx, ssrc, source } = src;
  1646. let msid;
  1647. if (mediaType === MediaType.VIDEO) {
  1648. const idx = ++this.numRemoteVideoSources;
  1649. msid = `remote-video-${idx} remote-video-${idx}`;
  1650. if (rtx !== '-1') {
  1651. _addSourceElement(node, src, rtx, msid);
  1652. node.c('ssrc-group', {
  1653. xmlns: XEP.SOURCE_ATTRIBUTES,
  1654. semantics: SSRC_GROUP_SEMANTICS.FID
  1655. })
  1656. .c('source', {
  1657. xmlns: XEP.SOURCE_ATTRIBUTES,
  1658. ssrc
  1659. })
  1660. .up()
  1661. .c('source', {
  1662. xmlns: XEP.SOURCE_ATTRIBUTES,
  1663. ssrc: rtx
  1664. })
  1665. .up()
  1666. .up();
  1667. }
  1668. } else {
  1669. const idx = ++this.numRemoteAudioSources;
  1670. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1671. }
  1672. _addSourceElement(node, src, ssrc, msid);
  1673. this.peerconnection.remoteSources.set(source, ssrc);
  1674. }
  1675. node = node.up();
  1676. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1677. }
  1678. }
  1679. /**
  1680. * Handles a Jingle source-remove message for this Jingle session.
  1681. *
  1682. * @param {Array<Element>} contents - An array of content elements from the source-remove message.
  1683. * @returns {void}
  1684. */
  1685. removeRemoteStream(elem) {
  1686. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1687. }
  1688. /**
  1689. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1690. *
  1691. * @param {string} id Endpoint id of the participant that has left the call.
  1692. * @returns {void}
  1693. */
  1694. removeRemoteStreamsOnLeave(id) {
  1695. const workFunction = finishCallback => {
  1696. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1697. if (removeSsrcInfo.size) {
  1698. logger.debug(`${this} Removing SSRCs for user ${id}, sources=${Array.from(removeSsrcInfo.keys())}`);
  1699. const newRemoteSdp = new SDP(this.peerconnection.remoteDescription.sdp, this.isP2P);
  1700. newRemoteSdp.updateRemoteSources(removeSsrcInfo, false /* isAdd */);
  1701. this.peerconnection.updateRemoteSources(removeSsrcInfo, false /* isAdd */);
  1702. this._renegotiate(newRemoteSdp.raw)
  1703. .then(() => finishCallback(), error => finishCallback(error));
  1704. } else {
  1705. finishCallback();
  1706. }
  1707. };
  1708. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1709. this.modificationQueue.push(
  1710. workFunction,
  1711. error => {
  1712. if (error) {
  1713. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1714. } else {
  1715. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1716. }
  1717. });
  1718. }
  1719. /**
  1720. * Removes local track from the peerconnection as part of the mute operation.
  1721. *
  1722. * @param {JitsiLocalTrack} track the local track to be removed.
  1723. * @return {Promise} a promise which will be resolved once the local track is removed from this session or rejected
  1724. * with a <tt>string</tt> that the describes the error if anything goes wrong.
  1725. */
  1726. removeTrackFromPc(track) {
  1727. return this._addRemoveTrack(true /* remove */, track);
  1728. }
  1729. /**
  1730. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single offer/answer cycle (if needed) after
  1731. * both operations are done.
  1732. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid <tt>oldTrack</tt> with a null
  1733. * <tt>newTrack</tt> effectively just removes <tt>oldTrack</tt>.
  1734. *
  1735. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be replaced.
  1736. * @param {JitsiLocalTrack|null} newTrack the new track to use.
  1737. * @returns {Promise} which resolves once the replacement is complete with no arguments or rejects with an error.
  1738. */
  1739. replaceTrack(oldTrack, newTrack) {
  1740. const workFunction = finishedCallback => {
  1741. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  1742. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1743. .then(shouldRenegotiate => {
  1744. let promise = Promise.resolve();
  1745. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  1746. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  1747. if (shouldRenegotiate && (oldTrack || newTrack) && this.state === JingleSessionState.ACTIVE) {
  1748. promise = this._renegotiate();
  1749. }
  1750. return promise.then(() => {
  1751. // Set the source name of the new track.
  1752. if (oldTrack && newTrack && oldTrack.isVideoTrack()) {
  1753. newTrack.setSourceName(oldTrack.getSourceName());
  1754. }
  1755. });
  1756. })
  1757. .then(() => finishedCallback(), error => finishedCallback(error));
  1758. };
  1759. return new Promise((resolve, reject) => {
  1760. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  1761. this.modificationQueue.push(
  1762. workFunction,
  1763. error => {
  1764. if (error) {
  1765. if (error instanceof ClearedQueueError) {
  1766. // The session might have been terminated before the task was executed, making it obsolete.
  1767. logger.debug('Replace track aborted: session terminated');
  1768. resolve();
  1769. return;
  1770. }
  1771. logger.error(`${this} Replace track error:`, error);
  1772. reject(error);
  1773. } else {
  1774. logger.info(`${this} Replace track done!`);
  1775. resolve();
  1776. }
  1777. });
  1778. });
  1779. }
  1780. /**
  1781. * Sets the answer received from the remote peer as the remote description.
  1782. *
  1783. * @param {Element} jingleAnswer - The jingle answer element.
  1784. * @returns {void}
  1785. * @throws {Error} if the method is called on a responder session.
  1786. */
  1787. setAnswer(jingleAnswer) {
  1788. if (!this.isInitiator) {
  1789. throw new Error('Trying to set an answer on the responder session');
  1790. }
  1791. logger.debug(`${this} Executing setAnswer task`);
  1792. const newRemoteSdp = this._processNewJingleOfferIq(jingleAnswer);
  1793. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1794. const remoteDescription = {
  1795. type: 'answer',
  1796. sdp: newRemoteSdp.raw
  1797. };
  1798. this.peerconnection.setRemoteDescription(remoteDescription)
  1799. .then(() => {
  1800. if (this.state === JingleSessionState.PENDING) {
  1801. this.state = JingleSessionState.ACTIVE;
  1802. // Start processing tasks on the modification queue.
  1803. logger.debug(`${this} Resuming the modification queue after session is established!`);
  1804. this.modificationQueue.resume();
  1805. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1806. this._sendContentModify();
  1807. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1808. }
  1809. })
  1810. .then(() => {
  1811. logger.debug(`${this} setAnswer task done`);
  1812. })
  1813. .catch(error => {
  1814. logger.error(`${this} setAnswer task failed: ${error}`);
  1815. });
  1816. }
  1817. /**
  1818. * Resumes or suspends media transfer over the underlying peer connection.
  1819. *
  1820. * @param {boolean} active - <tt>true</tt> to enable media transfer or <tt>false</tt> to suspend media transmission.
  1821. * @returns {Promise}
  1822. */
  1823. setMediaTransferActive(active) {
  1824. const changed = this.peerconnection.audioTransferActive !== active
  1825. || this.peerconnection.videoTransferActive !== active;
  1826. if (!changed) {
  1827. return Promise.resolve();
  1828. }
  1829. return this.peerconnection.setMediaTransferActive(active)
  1830. .then(() => {
  1831. this.peerconnection.audioTransferActive = active;
  1832. this.peerconnection.videoTransferActive = active;
  1833. // Reconfigure the audio and video tracks so that only the correct encodings are active.
  1834. const promises = [];
  1835. promises.push(this.peerconnection.configureVideoSenderEncodings());
  1836. promises.push(this.peerconnection.configureAudioSenderEncodings());
  1837. return Promise.allSettled(promises);
  1838. });
  1839. }
  1840. /**
  1841. * This is a setRemoteDescription/setLocalDescription cycle which starts at converting Strophe Jingle IQ into
  1842. * remote offer SDP. Once converted, setRemoteDescription, createAnswer and setLocalDescription calls follow.
  1843. *
  1844. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element of the offer (or answer) IQ
  1845. * @param success callback called when sRD/sLD cycle finishes successfully.
  1846. * @param failure callback called with an error object as an argument if we fail at any point during setRD,
  1847. * createAnswer, setLD.
  1848. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  1849. * the offer/answer cycle executes (for the local track addition to be an atomic operation together with the
  1850. * offer/answer).
  1851. * @returns {void}
  1852. */
  1853. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  1854. logger.debug(`${this} Executing setOfferAnswerCycle task`);
  1855. const addTracks = [];
  1856. const audioTracks = localTracks.filter(track => track.getType() === MediaType.AUDIO);
  1857. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  1858. let tracks = localTracks;
  1859. // Add only 1 video track at a time. Adding 2 or more video tracks to the peerconnection at the same time
  1860. // makes the browser go into a renegotiation loop by firing 'negotiationneeded' event after every
  1861. // renegotiation.
  1862. if (videoTracks.length > 1) {
  1863. tracks = [ ...audioTracks, videoTracks[0] ];
  1864. }
  1865. for (const track of tracks) {
  1866. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1867. }
  1868. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  1869. const bridgeSession = $(jingleOfferAnswerIq).find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]');
  1870. const bridgeSessionId = bridgeSession.attr('id');
  1871. if (bridgeSessionId !== this._bridgeSessionId) {
  1872. this._bridgeSessionId = bridgeSessionId;
  1873. }
  1874. Promise.all(addTracks)
  1875. .then(() => this._renegotiate(newRemoteSdp.raw))
  1876. .then(() => {
  1877. this.peerconnection.processLocalSdpForTransceiverInfo(tracks);
  1878. if (this.state === JingleSessionState.PENDING) {
  1879. this.state = JingleSessionState.ACTIVE;
  1880. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1881. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1882. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1883. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1884. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1885. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1886. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1887. if (this.isP2P && (!this._localSendReceiveVideoActive || this._sourceReceiverConstraints)) {
  1888. this._sendContentModify();
  1889. }
  1890. }
  1891. })
  1892. .then(() => {
  1893. logger.debug(`${this} setOfferAnswerCycle task done`);
  1894. success();
  1895. })
  1896. .catch(error => {
  1897. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1898. failure(error);
  1899. });
  1900. }
  1901. /**
  1902. * Resumes or suspends video media transfer over the p2p peer connection.
  1903. *
  1904. * @param {boolean} videoActive <tt>true</tt> to enable video media transfer or <tt>false</tt> to suspend video
  1905. * media transmission.
  1906. * @return {Promise} a <tt>Promise</tt> which will resolve once the operation is done. It will be rejected with
  1907. * an error description as a string in case anything goes wrong.
  1908. */
  1909. setP2pVideoTransferActive(videoActive) {
  1910. if (!this.peerconnection) {
  1911. return Promise.reject('Can not modify video transfer active state,'
  1912. + ' before "initialize" is called');
  1913. }
  1914. if (this._localSendReceiveVideoActive !== videoActive) {
  1915. this._localSendReceiveVideoActive = videoActive;
  1916. if (this.isP2P && this.state === JingleSessionState.ACTIVE) {
  1917. this._sendContentModify();
  1918. }
  1919. return this.peerconnection
  1920. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  1921. }
  1922. return Promise.resolve();
  1923. }
  1924. /**
  1925. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1926. * the remote p2p peer.
  1927. *
  1928. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1929. * @returns {void}
  1930. */
  1931. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1932. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1933. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1934. if (this.isP2P) {
  1935. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1936. // be synced after offer/answer.
  1937. if (this.state === JingleSessionState.ACTIVE) {
  1938. this._sendContentModify();
  1939. }
  1940. }
  1941. }
  1942. /**
  1943. * Sets the resolution constraint on the local video tracks.
  1944. *
  1945. * @param {number} maxFrameHeight - The user preferred max frame height.
  1946. * @param {string} sourceName - The source name of the track.
  1947. * @returns {Promise} promise that will be resolved when the operation is
  1948. * successful and rejected otherwise.
  1949. */
  1950. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1951. if (this._assertNotEnded()) {
  1952. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1953. const jitsiLocalTrack = sourceName
  1954. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1955. : this.rtc.getLocalVideoTrack();
  1956. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1957. }
  1958. return Promise.resolve();
  1959. }
  1960. /**
  1961. * Updates the codecs on the peerconnection and initiates a renegotiation (if needed) for the
  1962. * new codec config to take effect.
  1963. *
  1964. * @param {Array<CodecMimeType>} codecList - Preferred codecs for video.
  1965. * @param {CodecMimeType} screenshareCodec - The preferred screenshare codec.
  1966. * @returns {void}
  1967. */
  1968. setVideoCodecs(codecList, screenshareCodec) {
  1969. if (this._assertNotEnded()) {
  1970. logger.info(`${this} setVideoCodecs: codecList=${codecList}, screenshareCodec=${screenshareCodec}`);
  1971. this.peerconnection.setVideoCodecs(codecList, screenshareCodec);
  1972. // Browser throws an error when H.264 is set on the encodings. Therefore, munge the SDP when H.264 needs to
  1973. // be selected.
  1974. // TODO: Remove this check when the above issue is fixed.
  1975. if (this.usesCodecSelectionAPI && codecList[0] !== CodecMimeType.H264) {
  1976. return;
  1977. }
  1978. // Skip renegotiation when the selected codec order matches with that of the remote SDP.
  1979. const currentCodecOrder = this.peerconnection.getConfiguredVideoCodecs();
  1980. if (codecList.every((val, index) => val === currentCodecOrder[index])) {
  1981. return;
  1982. }
  1983. Statistics.sendAnalytics(
  1984. VIDEO_CODEC_CHANGED,
  1985. {
  1986. value: codecList[0],
  1987. videoType: VideoType.CAMERA
  1988. });
  1989. // Initiate a renegotiate for the codec setting to take effect.
  1990. const workFunction = finishedCallback => {
  1991. this._renegotiate()
  1992. .then(() => this.peerconnection.configureVideoSenderEncodings())
  1993. .then(
  1994. () => {
  1995. logger.debug(`${this} setVideoCodecs task is done`);
  1996. return finishedCallback();
  1997. }, error => {
  1998. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  1999. return finishedCallback(error);
  2000. });
  2001. };
  2002. logger.debug(`${this} Queued setVideoCodecs task`);
  2003. // Queue and execute
  2004. this.modificationQueue.push(workFunction);
  2005. }
  2006. }
  2007. /**
  2008. * @inheritDoc
  2009. */
  2010. terminate(success, failure, options) {
  2011. if (this.state === JingleSessionState.ENDED) {
  2012. return;
  2013. }
  2014. if (!options || Boolean(options.sendSessionTerminate)) {
  2015. const sessionTerminate
  2016. = $iq({
  2017. to: this.remoteJid,
  2018. type: 'set'
  2019. })
  2020. .c('jingle', {
  2021. xmlns: 'urn:xmpp:jingle:1',
  2022. action: 'session-terminate',
  2023. initiator: this.initiatorJid,
  2024. sid: this.sid
  2025. })
  2026. .c('reason')
  2027. .c((options && options.reason) || 'success')
  2028. .up();
  2029. if (options && options.reasonDescription) {
  2030. sessionTerminate
  2031. .c('text')
  2032. .t(options.reasonDescription)
  2033. .up()
  2034. .up();
  2035. } else {
  2036. sessionTerminate.up();
  2037. }
  2038. this._bridgeSessionId
  2039. && sessionTerminate.c(
  2040. 'bridge-session', {
  2041. xmlns: 'http://jitsi.org/protocol/focus',
  2042. id: this._bridgeSessionId,
  2043. restart: options && options.requestRestart === true
  2044. }).up();
  2045. logger.info(`${this} Sending session-terminate`);
  2046. logger.debug(sessionTerminate.tree());
  2047. this.connection.sendIQ(
  2048. sessionTerminate,
  2049. success,
  2050. this.newJingleErrorHandler(sessionTerminate, failure),
  2051. IQ_TIMEOUT);
  2052. } else {
  2053. logger.info(`${this} Skipped sending session-terminate`);
  2054. }
  2055. // this should result in 'onTerminated' being called by strope.jingle.js
  2056. this.connection.jingle.terminate(this.sid);
  2057. }
  2058. /**
  2059. * Converts to string with minor summary.
  2060. *
  2061. * @return {string}
  2062. */
  2063. toString() {
  2064. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2065. }
  2066. }