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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import { $build, $iq, Strophe } from 'strophe.js';
  4. import { JitsiTrackEvents } from '../../JitsiTrackEvents';
  5. import * as CodecMimeType from '../../service/RTC/CodecMimeType';
  6. import { MediaDirection } from '../../service/RTC/MediaDirection';
  7. import { MediaType } from '../../service/RTC/MediaType';
  8. import {
  9. ICE_DURATION,
  10. ICE_STATE_CHANGED
  11. } from '../../service/statistics/AnalyticsEvents';
  12. import { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  13. import { SS_DEFAULT_FRAME_RATE } from '../RTC/ScreenObtainer';
  14. import FeatureFlags from '../flags/FeatureFlags';
  15. import SDP from '../sdp/SDP';
  16. import SDPDiffer from '../sdp/SDPDiffer';
  17. import SDPUtil from '../sdp/SDPUtil';
  18. import Statistics from '../statistics/statistics';
  19. import AsyncQueue from '../util/AsyncQueue';
  20. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  21. import { integerHash } from '../util/StringUtils';
  22. import browser from './../browser';
  23. import JingleSession from './JingleSession';
  24. import * as JingleSessionState from './JingleSessionState';
  25. import MediaSessionEvents from './MediaSessionEvents';
  26. import XmppConnection from './XmppConnection';
  27. const logger = getLogger(__filename);
  28. /**
  29. * Constant tells how long we're going to wait for IQ response, before timeout
  30. * error is triggered.
  31. * @type {number}
  32. */
  33. const IQ_TIMEOUT = 10000;
  34. /*
  35. * The default number of samples (per stat) to keep when webrtc stats gathering
  36. * is enabled in TraceablePeerConnection.
  37. */
  38. const DEFAULT_MAX_STATS = 300;
  39. /**
  40. * The time duration for which the client keeps gathering ICE candidates to be sent out in a single IQ.
  41. * @type {number} timeout in ms.
  42. */
  43. const ICE_CAND_GATHERING_TIMEOUT = 150;
  44. /**
  45. * Reads the endpoint ID given a string which represents either the endpoint's full JID, or the endpoint ID itself.
  46. * @param {String} jidOrEndpointId A string which is either the full JID of a participant, or the ID of an
  47. * endpoint/participant.
  48. * @returns The endpoint ID associated with 'jidOrEndpointId'.
  49. */
  50. function getEndpointId(jidOrEndpointId) {
  51. return Strophe.getResourceFromJid(jidOrEndpointId) || jidOrEndpointId;
  52. }
  53. /**
  54. * Add "source" element as a child of "description" element.
  55. * @param {Object} description The "description" element to add to.
  56. * @param {Object} s Contains properties of the source being added.
  57. * @param {Number} ssrc_ The SSRC.
  58. * @param {String} msid The "msid" attribute.
  59. */
  60. function _addSourceElement(description, s, ssrc_, msid) {
  61. description.c('source', {
  62. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  63. ssrc: ssrc_,
  64. name: s.source
  65. })
  66. .c('parameter', {
  67. name: 'msid',
  68. value: msid
  69. })
  70. .up()
  71. .c('ssrc-info', {
  72. xmlns: 'http://jitsi.org/jitmeet',
  73. owner: s.owner
  74. })
  75. .up()
  76. .up();
  77. }
  78. /**
  79. * @typedef {Object} JingleSessionPCOptions
  80. * @property {Object} abTesting - A/B testing related options (ask George).
  81. * @property {boolean} abTesting.enableSuspendVideoTest - enables the suspend
  82. * video test ?(ask George).
  83. * @property {boolean} disableRtx - Described in the config.js[1].
  84. * @property {boolean} disableSimulcast - Described in the config.js[1].
  85. * @property {boolean} enableInsertableStreams - Set to true when the insertable streams constraints is to be enabled
  86. * on the PeerConnection.
  87. * @property {boolean} failICE - it's an option used in the tests. Set to
  88. * <tt>true</tt> to block any real candidates and make the ICE fail.
  89. * @property {boolean} gatherStats - Described in the config.js[1].
  90. * @property {object} p2p - Peer to peer related options (FIXME those could be
  91. * fetched from config.p2p on the upper level).
  92. * @property {boolean} preferH264 - Described in the config.js[1].
  93. * @property {Object} testing - Testing and/or experimental options.
  94. * @property {boolean} webrtcIceUdpDisable - Described in the config.js[1].
  95. * @property {boolean} webrtcIceTcpDisable - Described in the config.js[1].
  96. *
  97. * [1]: https://github.com/jitsi/jitsi-meet/blob/master/config.js
  98. */
  99. /**
  100. *
  101. */
  102. export default class JingleSessionPC extends JingleSession {
  103. /**
  104. * Parses 'senders' attribute of the video content.
  105. * @param {jQuery} jingleContents
  106. * @return {string|null} one of the values of content "senders" attribute
  107. * defined by Jingle. If there is no "senders" attribute or if the value is
  108. * invalid then <tt>null</tt> will be returned.
  109. * @private
  110. */
  111. static parseVideoSenders(jingleContents) {
  112. const videoContents = jingleContents.find('>content[name="video"]');
  113. if (videoContents.length) {
  114. const senders = videoContents[0].getAttribute('senders');
  115. if (senders === 'both'
  116. || senders === 'initiator'
  117. || senders === 'responder'
  118. || senders === 'none') {
  119. return senders;
  120. }
  121. }
  122. return null;
  123. }
  124. /**
  125. * Parses the source-name and max frame height value of the 'content-modify' IQ when source-name signaling
  126. * is enabled.
  127. *
  128. * @param {jQuery} jingleContents - A jQuery selector pointing to the '>jingle' element.
  129. * @returns {Object|null}
  130. */
  131. static parseSourceMaxFrameHeight(jingleContents) {
  132. const receiverConstraints = [];
  133. const sourceFrameHeightSel = jingleContents.find('>content[name="video"]>source-frame-height');
  134. let maxHeight, sourceName;
  135. if (sourceFrameHeightSel.length) {
  136. sourceFrameHeightSel.each((_, source) => {
  137. sourceName = source.getAttribute('sourceName');
  138. maxHeight = source.getAttribute('maxHeight');
  139. receiverConstraints.push({
  140. maxHeight,
  141. sourceName
  142. });
  143. });
  144. return receiverConstraints;
  145. }
  146. return null;
  147. }
  148. /* eslint-disable max-params */
  149. /**
  150. * Creates new <tt>JingleSessionPC</tt>
  151. * @param {string} sid the Jingle Session ID - random string which identifies the session
  152. * @param {string} localJid our JID
  153. * @param {string} remoteJid remote peer JID
  154. * @param {XmppConnection} connection - The XMPP connection instance.
  155. * @param mediaConstraints the media constraints object passed to createOffer/Answer, as defined
  156. * by the WebRTC standard
  157. * @param pcConfig The {@code RTCConfiguration} to use for the WebRTC peer connection.
  158. * @param {boolean} isP2P indicates whether this instance is meant to be used in a direct, peer to
  159. * peer connection or <tt>false</tt> if it's a JVB connection.
  160. * @param {boolean} isInitiator indicates if it will be the side which initiates the session.
  161. * @constructor
  162. *
  163. * @implements {SignalingLayer}
  164. */
  165. constructor(
  166. sid,
  167. localJid,
  168. remoteJid,
  169. connection,
  170. mediaConstraints,
  171. pcConfig,
  172. isP2P,
  173. isInitiator) {
  174. super(
  175. sid,
  176. localJid,
  177. remoteJid, connection, mediaConstraints, pcConfig, isInitiator);
  178. /**
  179. * The bridge session's identifier. One Jingle session can during
  180. * it's lifetime participate in multiple bridge sessions managed by
  181. * Jicofo. A new bridge session is started whenever Jicofo sends
  182. * 'session-initiate' or 'transport-replace'.
  183. *
  184. * @type {?string}
  185. * @private
  186. */
  187. this._bridgeSessionId = null;
  188. /**
  189. * The oldest SDP passed to {@link notifyMySSRCUpdate} while the XMPP connection was offline that will be
  190. * used to update Jicofo once the XMPP connection goes back online.
  191. * @type {SDP|undefined}
  192. * @private
  193. */
  194. this._cachedOldLocalSdp = undefined;
  195. /**
  196. * The latest SDP passed to {@link notifyMySSRCUpdate} while the XMPP connection was offline that will be
  197. * used to update Jicofo once the XMPP connection goes back online.
  198. * @type {SDP|undefined}
  199. * @private
  200. */
  201. this._cachedNewLocalSdp = undefined;
  202. /**
  203. * Stores result of {@link window.performance.now()} at the time when
  204. * ICE enters 'checking' state.
  205. * @type {number|null} null if no value has been stored yet
  206. * @private
  207. */
  208. this._iceCheckingStartedTimestamp = null;
  209. /**
  210. * Stores result of {@link window.performance.now()} at the time when
  211. * first ICE candidate is spawned by the peerconnection to mark when
  212. * ICE gathering started. That's, because ICE gathering state changed
  213. * events are not supported by most of the browsers, so we try something
  214. * that will work everywhere. It may not be as accurate, but given that
  215. * 'host' candidate usually comes first, the delay should be minimal.
  216. * @type {number|null} null if no value has been stored yet
  217. * @private
  218. */
  219. this._gatheringStartedTimestamp = null;
  220. /**
  221. * Receiver constraints (max height) set by the application per remote source. Will be used for p2p connection.
  222. *
  223. * @type {Map<string, number>}
  224. */
  225. this._sourceReceiverConstraints = undefined;
  226. /**
  227. * Indicates whether or not this session is willing to send/receive
  228. * video media. When set to <tt>false</tt> the underlying peer
  229. * connection will disable local video transfer and the remote peer will
  230. * be will be asked to stop sending video via 'content-modify' IQ
  231. * (the senders attribute of video contents will be adjusted
  232. * accordingly). Note that this notification is sent only in P2P
  233. * session, because Jicofo does not support it yet. Obviously when
  234. * the value is changed from <tt>false</tt> to <tt>true</tt> another
  235. * notification will be sent to resume video transfer on the remote
  236. * side.
  237. * @type {boolean}
  238. * @private
  239. */
  240. this._localVideoActive = true;
  241. /**
  242. * Indicates whether or not the remote peer has video transfer active.
  243. * When set to <tt>true</tt> it means that remote peer is neither
  244. * sending nor willing to receive video. In such case we'll ask
  245. * our peerconnection to stop sending video by calling
  246. * {@link TraceablePeerConnection.setVideoTransferActive} with
  247. * <tt>false</tt>.
  248. * @type {boolean}
  249. * @private
  250. */
  251. this._remoteVideoActive = true;
  252. /**
  253. * Marks that ICE gathering duration has been reported already. That
  254. * prevents reporting it again, after eventual 'transport-replace' (JVB
  255. * conference migration/ICE restart).
  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.
  297. *
  298. * @type {AsyncQueue}
  299. */
  300. this.modificationQueue = new AsyncQueue();
  301. /**
  302. * Flag used to guarantee that the connection established event is
  303. * triggered just once.
  304. * @type {boolean}
  305. */
  306. this.wasConnected = false;
  307. /**
  308. * Keeps track of how long (in ms) it took from ICE start to ICE
  309. * connect.
  310. *
  311. * @type {number}
  312. */
  313. this.establishmentDuration = undefined;
  314. this._xmppListeners = [];
  315. this._xmppListeners.push(
  316. connection.addEventListener(
  317. XmppConnection.Events.CONN_STATUS_CHANGED,
  318. this.onXmppStatusChanged.bind(this))
  319. );
  320. this._removeSenderVideoConstraintsChangeListener = undefined;
  321. }
  322. /* eslint-enable max-params */
  323. /**
  324. * Checks whether or not this session instance is still operational.
  325. * @private
  326. * @returns {boolean} {@code true} if operation or {@code false} otherwise.
  327. */
  328. _assertNotEnded() {
  329. return this.state !== JingleSessionState.ENDED;
  330. }
  331. /**
  332. * @inheritDoc
  333. * @param {JingleSessionPCOptions} options - a set of config options.
  334. */
  335. doInitialize(options) {
  336. this.failICE = Boolean(options.failICE);
  337. this.lasticecandidate = false;
  338. this.options = options;
  339. /**
  340. * {@code true} if reconnect is in progress.
  341. * @type {boolean}
  342. */
  343. this.isReconnect = false;
  344. /**
  345. * Set to {@code true} if the connection was ever stable
  346. * @type {boolean}
  347. */
  348. this.wasstable = false;
  349. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  350. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  351. const pcOptions = { disableRtx: options.disableRtx };
  352. if (options.gatherStats) {
  353. pcOptions.maxstats = DEFAULT_MAX_STATS;
  354. }
  355. pcOptions.capScreenshareBitrate = false;
  356. pcOptions.enableInsertableStreams = options.enableInsertableStreams;
  357. pcOptions.videoQuality = options.videoQuality;
  358. pcOptions.forceTurnRelay = options.forceTurnRelay;
  359. pcOptions.audioQuality = options.audioQuality;
  360. pcOptions.usesUnifiedPlan = this.usesUnifiedPlan
  361. = browser.supportsUnifiedPlan()
  362. && (!browser.isChromiumBased()
  363. || (browser.isChromiumBased()
  364. // Provide a way to control the behavior for jvb and p2p connections independently.
  365. && this.isP2P
  366. ? options.p2p?.enableUnifiedOnChrome ?? true
  367. : options.enableUnifiedOnChrome ?? true));
  368. if (this.isP2P) {
  369. // simulcast needs to be disabled for P2P (121) calls
  370. pcOptions.disableSimulcast = true;
  371. const abtestSuspendVideo = this._abtestSuspendVideoEnabled(options);
  372. if (typeof abtestSuspendVideo !== 'undefined') {
  373. pcOptions.abtestSuspendVideo = abtestSuspendVideo;
  374. }
  375. } else {
  376. // H264 scalability is not supported on jvb, so simulcast needs to be disabled when H264 is preferred.
  377. pcOptions.disableSimulcast
  378. = options.disableSimulcast || options.videoQuality?.preferredCodec === CodecMimeType.H264;
  379. // Do not send lower spatial layers for low fps screenshare and enable them only for high fps screenshare.
  380. pcOptions.capScreenshareBitrate = pcOptions.disableSimulcast
  381. || !(typeof options.desktopSharingFrameRate?.max === 'number'
  382. && options.desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE);
  383. }
  384. if (options.startSilent) {
  385. pcOptions.startSilent = true;
  386. }
  387. this.peerconnection
  388. = this.rtc.createPeerConnection(
  389. this._signalingLayer,
  390. this.pcConfig,
  391. this.isP2P,
  392. pcOptions);
  393. this.peerconnection.onicecandidate = ev => {
  394. if (!ev) {
  395. // There was an incomplete check for ev before which left
  396. // the last line of the function unprotected from a potential
  397. // throw of an exception. Consequently, it may be argued that
  398. // the check is unnecessary. Anyway, I'm leaving it and making
  399. // the check complete.
  400. return;
  401. }
  402. // XXX this is broken, candidate is not parsed.
  403. const candidate = ev.candidate;
  404. const now = window.performance.now();
  405. if (candidate) {
  406. if (this._gatheringStartedTimestamp === null) {
  407. this._gatheringStartedTimestamp = now;
  408. }
  409. // Discard candidates of disabled protocols.
  410. let protocol = candidate.protocol;
  411. if (typeof protocol === 'string') {
  412. protocol = protocol.toLowerCase();
  413. if (protocol === 'tcp' || protocol === 'ssltcp') {
  414. if (this.webrtcIceTcpDisable) {
  415. return;
  416. }
  417. } else if (protocol === 'udp') {
  418. if (this.webrtcIceUdpDisable) {
  419. return;
  420. }
  421. }
  422. }
  423. } else if (!this._gatheringReported) {
  424. // End of gathering
  425. Statistics.sendAnalytics(
  426. ICE_DURATION,
  427. {
  428. phase: 'gathering',
  429. value: now - this._gatheringStartedTimestamp,
  430. p2p: this.isP2P,
  431. initiator: this.isInitiator
  432. });
  433. this._gatheringReported = true;
  434. }
  435. if (this.isP2P) {
  436. this.sendIceCandidate(candidate);
  437. }
  438. };
  439. // Note there is a change in the spec about closed:
  440. // This value moved into the RTCPeerConnectionState enum in
  441. // the May 13, 2016 draft of the specification, as it reflects the state
  442. // of the RTCPeerConnection, not the signaling connection. You now
  443. // detect a closed connection by checking for connectionState to be
  444. // "closed" instead.
  445. // I suppose at some point this will be moved to onconnectionstatechange
  446. this.peerconnection.onsignalingstatechange = () => {
  447. if (this.peerconnection.signalingState === 'stable') {
  448. this.wasstable = true;
  449. } else if (this.peerconnection.signalingState === 'closed'
  450. || this.peerconnection.connectionState === 'closed') {
  451. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  452. }
  453. };
  454. /**
  455. * The oniceconnectionstatechange event handler contains the code to
  456. * execute when the iceconnectionstatechange event, of type Event,
  457. * is received by this RTCPeerConnection. Such an event is sent when
  458. * the value of RTCPeerConnection.iceConnectionState changes.
  459. */
  460. this.peerconnection.oniceconnectionstatechange = () => {
  461. const now = window.performance.now();
  462. let isStable = false;
  463. if (!this.isP2P) {
  464. this.room.connectionTimes[
  465. `ice.state.${this.peerconnection.iceConnectionState}`]
  466. = now;
  467. }
  468. logger.log(`(TIME) ICE ${this.peerconnection.iceConnectionState} ${this.isP2P ? 'P2P' : 'JVB'}:\t`, now);
  469. Statistics.sendAnalytics(
  470. ICE_STATE_CHANGED,
  471. {
  472. p2p: this.isP2P,
  473. state: this.peerconnection.iceConnectionState,
  474. 'signaling_state': this.peerconnection.signalingState,
  475. reconnect: this.isReconnect,
  476. value: now
  477. });
  478. this.room.eventEmitter.emit(
  479. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  480. this,
  481. this.peerconnection.iceConnectionState);
  482. switch (this.peerconnection.iceConnectionState) {
  483. case 'checking':
  484. this._iceCheckingStartedTimestamp = now;
  485. break;
  486. case 'connected':
  487. // Informs interested parties that the connection has been restored. This includes the case when
  488. // media connection to the bridge has been restored after an ICE failure by using session-terminate.
  489. if (this.peerconnection.signalingState === 'stable') {
  490. isStable = true;
  491. const usesTerminateForRestart = !this.options.enableIceRestart
  492. && this.room.supportsRestartByTerminate();
  493. if (this.isReconnect || usesTerminateForRestart) {
  494. this.room.eventEmitter.emit(
  495. XMPPEvents.CONNECTION_RESTORED, this);
  496. }
  497. }
  498. // Add a workaround for an issue on chrome in Unified plan when the local endpoint is the offerer.
  499. // The 'signalingstatechange' event for 'stable' is handled after the 'iceconnectionstatechange' event
  500. // for 'completed' is handled by the client. This prevents the client from firing a
  501. // CONNECTION_ESTABLISHED event for the p2p session. As a result, the offerer continues to stay on the
  502. // jvb connection while the remote peer switches to the p2p connection breaking the media flow between
  503. // the endpoints.
  504. // TODO - file a chromium bug and add the information here.
  505. if (!this.wasConnected
  506. && (this.wasstable
  507. || isStable
  508. || (this.usesUnifiedPlan && this.isInitiator
  509. && (browser.isChromiumBased() || browser.isReactNative())))) {
  510. Statistics.sendAnalytics(
  511. ICE_DURATION,
  512. {
  513. phase: 'checking',
  514. value: now - this._iceCheckingStartedTimestamp,
  515. p2p: this.isP2P,
  516. initiator: this.isInitiator
  517. });
  518. // Switch between ICE gathering and ICE checking whichever
  519. // started first (scenarios are different for initiator
  520. // vs responder)
  521. const iceStarted
  522. = Math.min(
  523. this._iceCheckingStartedTimestamp,
  524. this._gatheringStartedTimestamp);
  525. this.establishmentDuration = now - iceStarted;
  526. Statistics.sendAnalytics(
  527. ICE_DURATION,
  528. {
  529. phase: 'establishment',
  530. value: this.establishmentDuration,
  531. p2p: this.isP2P,
  532. initiator: this.isInitiator
  533. });
  534. this.wasConnected = true;
  535. this.room.eventEmitter.emit(
  536. XMPPEvents.CONNECTION_ESTABLISHED, this);
  537. }
  538. this.isReconnect = false;
  539. break;
  540. case 'disconnected':
  541. this.isReconnect = true;
  542. // Informs interested parties that the connection has been
  543. // interrupted.
  544. if (this.wasstable) {
  545. this.room.eventEmitter.emit(
  546. XMPPEvents.CONNECTION_INTERRUPTED, this);
  547. }
  548. break;
  549. case 'failed':
  550. this.room.eventEmitter.emit(
  551. XMPPEvents.CONNECTION_ICE_FAILED, this);
  552. break;
  553. }
  554. };
  555. /**
  556. * The connection state event is fired whenever the aggregate of underlying
  557. * transports change their state.
  558. */
  559. this.peerconnection.onconnectionstatechange = () => {
  560. const icestate = this.peerconnection.iceConnectionState;
  561. switch (this.peerconnection.connectionState) {
  562. case 'failed':
  563. // Since version 76 Chrome no longer switches ICE connection
  564. // state to failed (see
  565. // https://bugs.chromium.org/p/chromium/issues/detail?id=982793
  566. // for details) we use this workaround to recover from lost connections
  567. if (icestate === 'disconnected') {
  568. this.room.eventEmitter.emit(
  569. XMPPEvents.CONNECTION_ICE_FAILED, this);
  570. }
  571. break;
  572. }
  573. };
  574. /**
  575. * The negotiationneeded event is fired whenever we shake the media on the
  576. * RTCPeerConnection object.
  577. */
  578. this.peerconnection.onnegotiationneeded = () => {
  579. const state = this.peerconnection.signalingState;
  580. const remoteDescription = this.peerconnection.remoteDescription;
  581. if (this.usesUnifiedPlan
  582. && !this.isP2P
  583. && state === 'stable'
  584. && remoteDescription
  585. && typeof remoteDescription.sdp === 'string') {
  586. logger.info(`${this} onnegotiationneeded fired on ${this.peerconnection}`);
  587. const workFunction = finishedCallback => {
  588. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  589. this._renegotiate()
  590. .then(() => this.peerconnection.configureSenderVideoEncodings())
  591. .then(() => {
  592. const newSdp = new SDP(this.peerconnection.localDescription.sdp);
  593. this.notifyMySSRCUpdate(oldSdp, newSdp);
  594. })
  595. .then(() => finishedCallback(), error => finishedCallback(error));
  596. };
  597. this.modificationQueue.push(
  598. workFunction,
  599. error => {
  600. if (error) {
  601. logger.error(`${this} onnegotiationneeded error`, error);
  602. } else {
  603. logger.debug(`${this} onnegotiationneeded executed - OK`);
  604. }
  605. });
  606. }
  607. };
  608. }
  609. /**
  610. * Remote preference for receive video max frame height.
  611. *
  612. * @returns {Number|undefined}
  613. */
  614. getRemoteRecvMaxFrameHeight() {
  615. if (this.isP2P) {
  616. return this.remoteRecvMaxFrameHeight;
  617. }
  618. return undefined;
  619. }
  620. /**
  621. * Remote preference for receive video max frame heights when source-name signaling is enabled.
  622. *
  623. * @returns {Map<string, number>|undefined}
  624. */
  625. getRemoteSourcesRecvMaxFrameHeight() {
  626. if (this.isP2P) {
  627. return this.remoteSourceMaxFrameHeights;
  628. }
  629. return undefined;
  630. }
  631. /**
  632. * Sends given candidate in Jingle 'transport-info' message.
  633. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  634. * @private
  635. */
  636. sendIceCandidate(candidate) {
  637. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  638. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  639. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  640. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  641. if (!(ice && jcand)) {
  642. const errorMesssage = 'failed to get ice && jcand';
  643. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  644. logger.error(errorMesssage);
  645. return;
  646. }
  647. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  648. if (this.usedrip) {
  649. if (this.dripContainer.length === 0) {
  650. setTimeout(() => {
  651. if (this.dripContainer.length === 0) {
  652. return;
  653. }
  654. this.sendIceCandidates(this.dripContainer);
  655. this.dripContainer = [];
  656. }, ICE_CAND_GATHERING_TIMEOUT);
  657. }
  658. this.dripContainer.push(candidate);
  659. } else {
  660. this.sendIceCandidates([ candidate ]);
  661. }
  662. } else {
  663. logger.log(`${this} sendIceCandidate: last candidate`);
  664. // FIXME: remember to re-think in ICE-restart
  665. this.lasticecandidate = true;
  666. }
  667. }
  668. /**
  669. * Sends given candidates in Jingle 'transport-info' message.
  670. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  671. * candidate instances
  672. * @private
  673. */
  674. sendIceCandidates(candidates) {
  675. if (!this._assertNotEnded('sendIceCandidates')) {
  676. return;
  677. }
  678. logger.log(`${this} sendIceCandidates ${JSON.stringify(candidates)}`);
  679. const cand = $iq({ to: this.remoteJid,
  680. type: 'set' })
  681. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  682. action: 'transport-info',
  683. initiator: this.initiatorJid,
  684. sid: this.sid });
  685. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  686. for (let mid = 0; mid < localSDP.media.length; mid++) {
  687. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  688. const mline
  689. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  690. if (cands.length > 0) {
  691. const ice
  692. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  693. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  694. cand.c('content', {
  695. creator: this.initiatorJid === this.localJid
  696. ? 'initiator' : 'responder',
  697. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  698. }).c('transport', ice);
  699. for (let i = 0; i < cands.length; i++) {
  700. const candidate
  701. = SDPUtil.candidateToJingle(cands[i].candidate);
  702. // Mangle ICE candidate if 'failICE' test option is enabled
  703. if (this.failICE) {
  704. candidate.ip = '1.1.1.1';
  705. }
  706. cand.c('candidate', candidate).up();
  707. }
  708. // add fingerprint
  709. const fingerprintLine
  710. = SDPUtil.findLine(
  711. localSDP.media[mid],
  712. 'a=fingerprint:', localSDP.session);
  713. if (fingerprintLine) {
  714. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  715. tmp.required = true;
  716. cand.c(
  717. 'fingerprint',
  718. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  719. .t(tmp.fingerprint);
  720. delete tmp.fingerprint;
  721. cand.attrs(tmp);
  722. cand.up();
  723. }
  724. cand.up(); // transport
  725. cand.up(); // content
  726. }
  727. }
  728. // might merge last-candidate notification into this, but it is called
  729. // a lot later. See webrtc issue #2340
  730. // logger.log('was this the last candidate', this.lasticecandidate);
  731. this.connection.sendIQ(
  732. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  733. }
  734. /**
  735. * Sends Jingle 'session-info' message which includes custom Jitsi Meet
  736. * 'ice-state' element with the text value 'failed' to let Jicofo know
  737. * that the ICE connection has entered the failed state. It can then
  738. * choose to re-create JVB channels and send 'transport-replace' to
  739. * retry the connection.
  740. */
  741. sendIceFailedNotification() {
  742. const sessionInfo
  743. = $iq({
  744. to: this.remoteJid,
  745. type: 'set' })
  746. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  747. action: 'session-info',
  748. initiator: this.initiatorJid,
  749. sid: this.sid })
  750. .c('ice-state', { xmlns: 'http://jitsi.org/protocol/focus' })
  751. .t('failed')
  752. .up();
  753. this._bridgeSessionId
  754. && sessionInfo.c(
  755. 'bridge-session', {
  756. xmlns: 'http://jitsi.org/protocol/focus',
  757. id: this._bridgeSessionId
  758. });
  759. this.connection.sendIQ2(
  760. sessionInfo, {
  761. /*
  762. * This message will be often sent when there are connectivity
  763. * issues, so make it slightly longer than Prosody's default BOSH
  764. * inactivity timeout of 60 seconds.
  765. */
  766. timeout: 65
  767. })
  768. .catch(this.newJingleErrorHandler(sessionInfo));
  769. }
  770. /**
  771. * {@inheritDoc}
  772. */
  773. addIceCandidates(elem) {
  774. if (this.peerconnection.signalingState === 'closed') {
  775. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  776. return;
  777. }
  778. const iceCandidates = [];
  779. elem.find('>content>transport>candidate')
  780. .each((idx, candidate) => {
  781. let line = SDPUtil.candidateFromJingle(candidate);
  782. line = line.replace('\r\n', '').replace('a=', '');
  783. // FIXME this code does not care to handle
  784. // non-bundle transport
  785. const rtcCandidate = new RTCIceCandidate({
  786. sdpMLineIndex: 0,
  787. // FF comes up with more complex names like audio-23423,
  788. // Given that it works on both Chrome and FF without
  789. // providing it, let's leave it like this for the time
  790. // being...
  791. // sdpMid: 'audio',
  792. sdpMid: '',
  793. candidate: line
  794. });
  795. iceCandidates.push(rtcCandidate);
  796. });
  797. if (!iceCandidates.length) {
  798. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  799. return;
  800. }
  801. // We want to have this task queued, so that we know it is executed,
  802. // after the initial sRD/sLD offer/answer cycle was done (based on
  803. // the assumption that candidates are spawned after the offer/answer
  804. // and XMPP preserves order).
  805. const workFunction = finishedCallback => {
  806. for (const iceCandidate of iceCandidates) {
  807. this.peerconnection.addIceCandidate(iceCandidate)
  808. .then(
  809. () => logger.debug(`${this} addIceCandidate ok!`),
  810. err => logger.error(`${this} addIceCandidate failed!`, err));
  811. }
  812. finishedCallback();
  813. logger.debug(`${this} ICE candidates task finished`);
  814. };
  815. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  816. this.modificationQueue.push(workFunction);
  817. }
  818. /**
  819. *
  820. * @param contents
  821. */
  822. readSsrcInfo(contents) {
  823. const ssrcs = $(contents).find('>description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  824. ssrcs.each((i, ssrcElement) => {
  825. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  826. if (ssrcElement.hasAttribute('name')) {
  827. const sourceName = ssrcElement.getAttribute('name');
  828. this._signalingLayer.setTrackSourceName(ssrc, sourceName);
  829. }
  830. if (this.isP2P) {
  831. // In P2P all SSRCs are owner by the remote peer
  832. this._signalingLayer.setSSRCOwner(ssrc, Strophe.getResourceFromJid(this.remoteJid));
  833. } else {
  834. $(ssrcElement)
  835. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  836. .each((i3, ssrcInfoElement) => {
  837. const owner = ssrcInfoElement.getAttribute('owner');
  838. if (owner?.length) {
  839. if (isNaN(ssrc) || ssrc < 0) {
  840. logger.warn(`${this} Invalid SSRC ${ssrc} value received for ${owner}`);
  841. } else {
  842. this._signalingLayer.setSSRCOwner(ssrc, getEndpointId(owner));
  843. }
  844. }
  845. });
  846. }
  847. });
  848. }
  849. /**
  850. * Makes the underlying TraceablePeerConnection generate new SSRC for
  851. * the recvonly video stream.
  852. * @deprecated
  853. */
  854. generateRecvonlySsrc() {
  855. if (this.peerconnection) {
  856. this.peerconnection.generateRecvonlySsrc();
  857. } else {
  858. logger.error(`${this} Unable to generate recvonly SSRC - no peerconnection`);
  859. }
  860. }
  861. /**
  862. * Returns the video codec configured as the preferred codec on the peerconnection.
  863. */
  864. getConfiguredVideoCodec() {
  865. return this.peerconnection.getConfiguredVideoCodec();
  866. }
  867. /**
  868. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  869. *
  870. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  871. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  872. * 'session-accept' sent.
  873. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  874. * can be used to log some details about the error.
  875. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  876. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  877. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  878. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  879. * assumption that the initial offer/answer cycle has been executed already.
  880. */
  881. acceptOffer(jingleOffer, success, failure, localTracks) {
  882. this.setOfferAnswerCycle(
  883. jingleOffer,
  884. () => {
  885. // FIXME we may not care about RESULT packet for session-accept
  886. // then we should either call 'success' here immediately or
  887. // modify sendSessionAccept method to do that
  888. this.sendSessionAccept(() => {
  889. success();
  890. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  891. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  892. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  893. // This will happen when someone shares a secondary source to a two people call, the other user
  894. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  895. // point, there are 2 video tracks which need to be signaled to the remote peer.
  896. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  897. videoTracks.length && videoTracks.splice(0, 1);
  898. if (FeatureFlags.isMultiStreamSendSupportEnabled() && videoTracks.length) {
  899. this.addTracks(videoTracks);
  900. }
  901. },
  902. error => {
  903. failure(error);
  904. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  905. });
  906. },
  907. failure,
  908. localTracks);
  909. }
  910. /**
  911. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  912. *
  913. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  914. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  915. */
  916. invite(localTracks = []) {
  917. if (!this.isInitiator) {
  918. throw new Error('Trying to invite from the responder session');
  919. }
  920. const workFunction = finishedCallback => {
  921. const addTracks = [];
  922. for (const track of localTracks) {
  923. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  924. }
  925. Promise.all(addTracks)
  926. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  927. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  928. .then(() => {
  929. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  930. // NOTE that the offer is obtained from the localDescription getter as it needs to go though
  931. // the transformation chain.
  932. this.sendSessionInitiate(this.peerconnection.localDescription.sdp);
  933. })
  934. .then(() => finishedCallback(), error => finishedCallback(error));
  935. };
  936. logger.debug(`${this} Queued invite task`);
  937. this.modificationQueue.push(
  938. workFunction,
  939. error => {
  940. if (error) {
  941. logger.error(`${this} invite error`, error);
  942. } else {
  943. logger.debug(`${this} invite executed - OK`);
  944. }
  945. });
  946. }
  947. /**
  948. * Sends 'session-initiate' to the remote peer.
  949. *
  950. * NOTE this method is synchronous and we're not waiting for the RESULT
  951. * response which would delay the startup process.
  952. *
  953. * @param {string} offerSdp - The local session description which will be
  954. * used to generate an offer.
  955. * @private
  956. */
  957. sendSessionInitiate(offerSdp) {
  958. let init = $iq({
  959. to: this.remoteJid,
  960. type: 'set'
  961. }).c('jingle', {
  962. xmlns: 'urn:xmpp:jingle:1',
  963. action: 'session-initiate',
  964. initiator: this.initiatorJid,
  965. sid: this.sid
  966. });
  967. new SDP(offerSdp).toJingle(
  968. init,
  969. this.isInitiator ? 'initiator' : 'responder');
  970. init = init.tree();
  971. logger.debug(`${this} Session-initiate: `, init);
  972. this.connection.sendIQ(init,
  973. () => {
  974. logger.info(`${this} Got RESULT for "session-initiate"`);
  975. },
  976. error => {
  977. logger.error(`${this} "session-initiate" error`, error);
  978. },
  979. IQ_TIMEOUT);
  980. }
  981. /**
  982. * Sets the answer received from the remote peer as the remote description.
  983. *
  984. * @param jingleAnswer
  985. */
  986. setAnswer(jingleAnswer) {
  987. if (!this.isInitiator) {
  988. throw new Error('Trying to set an answer on the responder session');
  989. }
  990. const workFunction = finishedCallback => {
  991. const newRemoteSdp = this._processNewJingleOfferIq(jingleAnswer);
  992. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  993. const remoteDescription = new RTCSessionDescription({
  994. type: 'answer',
  995. sdp: newRemoteSdp.raw
  996. });
  997. this.peerconnection.setRemoteDescription(remoteDescription)
  998. .then(() => {
  999. if (this.state === JingleSessionState.PENDING) {
  1000. this.state = JingleSessionState.ACTIVE;
  1001. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1002. this.sendContentModify();
  1003. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1004. }
  1005. })
  1006. .then(() => finishedCallback(), error => finishedCallback(error));
  1007. };
  1008. logger.debug(`${this} Queued setAnswer task`);
  1009. this.modificationQueue.push(
  1010. workFunction,
  1011. error => {
  1012. if (error) {
  1013. logger.error(`${this} setAnswer task failed: ${error}`);
  1014. } else {
  1015. logger.debug(`${this} setAnswer task done`);
  1016. }
  1017. });
  1018. }
  1019. /**
  1020. * This is a setRemoteDescription/setLocalDescription cycle which starts at converting Strophe Jingle IQ into
  1021. * remote offer SDP. Once converted, setRemoteDescription, createAnswer and setLocalDescription calls follow.
  1022. *
  1023. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element of the offer (or answer) IQ
  1024. * @param success callback called when sRD/sLD cycle finishes successfully.
  1025. * @param failure callback called with an error object as an argument if we fail at any point during setRD,
  1026. * createAnswer, setLD.
  1027. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  1028. * the offer/answer cycle executes (for the local track addition to be an atomic operation together with the
  1029. * offer/answer).
  1030. */
  1031. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  1032. const workFunction = finishedCallback => {
  1033. const addTracks = [];
  1034. const audioTracks = localTracks.filter(track => track.getType() === MediaType.AUDIO);
  1035. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  1036. let tracks = localTracks;
  1037. // Add only 1 video track at a time. Adding 2 or more video tracks to the peerconnection at the same time
  1038. // makes the browser go into a renegotiation loop by firing 'negotiationneeded' event after every
  1039. // renegotiation.
  1040. if (FeatureFlags.isMultiStreamSendSupportEnabled() && videoTracks.length > 1) {
  1041. tracks = [ ...audioTracks, videoTracks[0] ];
  1042. }
  1043. for (const track of tracks) {
  1044. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1045. }
  1046. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  1047. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1048. const bridgeSession = $(jingleOfferAnswerIq)
  1049. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]');
  1050. const bridgeSessionId = bridgeSession.attr('id');
  1051. if (bridgeSessionId !== this._bridgeSessionId) {
  1052. this._bridgeSessionId = bridgeSessionId;
  1053. }
  1054. const remoteDescription = new RTCSessionDescription({
  1055. type: 'offer',
  1056. sdp: newRemoteSdp.raw
  1057. });
  1058. Promise.all(addTracks)
  1059. .then(() => this._responderRenegotiate(remoteDescription))
  1060. .then(() => {
  1061. this.peerconnection.processLocalSdpForTransceiverInfo(tracks);
  1062. if (this.state === JingleSessionState.PENDING) {
  1063. this.state = JingleSessionState.ACTIVE;
  1064. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1065. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1066. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1067. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1068. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1069. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1070. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1071. if (this.isP2P
  1072. && (!this._localVideoActive || this._sourceReceiverConstraints)) {
  1073. this.sendContentModify();
  1074. }
  1075. }
  1076. // Old local SDP will be available when we're setting answer for the first time, but not when offer
  1077. // and it's fine since we're generating an answer now it will contain all our SSRCs.
  1078. if (oldLocalSdp) {
  1079. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1080. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSdp);
  1081. }
  1082. })
  1083. .then(() => finishedCallback(), error => finishedCallback(error));
  1084. };
  1085. logger.debug(`${this} Queued setOfferAnswerCycle task`);
  1086. this.modificationQueue.push(
  1087. workFunction,
  1088. error => {
  1089. if (error) {
  1090. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1091. failure(error);
  1092. } else {
  1093. logger.debug(`${this} setOfferAnswerCycle task done`);
  1094. success();
  1095. }
  1096. });
  1097. }
  1098. /**
  1099. * Updates the codecs on the peerconnection and initiates a renegotiation for the
  1100. * new codec config to take effect.
  1101. *
  1102. * @param {CodecMimeType} preferred the preferred codec.
  1103. * @param {CodecMimeType} disabled the codec that needs to be disabled.
  1104. */
  1105. setVideoCodecs(preferred = null, disabled = null) {
  1106. if (this._assertNotEnded()) {
  1107. logger.info(`${this} setVideoCodecs: preferred=${preferred}, disabled=${disabled}`);
  1108. this.peerconnection.setVideoCodecs(preferred, disabled);
  1109. // Initiate a renegotiate for the codec setting to take effect.
  1110. const workFunction = finishedCallback => {
  1111. this._renegotiate().then(
  1112. () => {
  1113. logger.debug(`${this} setVideoCodecs task is done`);
  1114. return finishedCallback();
  1115. }, error => {
  1116. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  1117. return finishedCallback(error);
  1118. });
  1119. };
  1120. logger.debug(`${this} Queued setVideoCodecs task`);
  1121. // Queue and execute
  1122. this.modificationQueue.push(workFunction);
  1123. }
  1124. }
  1125. /* eslint-enable max-params */
  1126. /**
  1127. * Although it states "replace transport" it does accept full Jingle offer
  1128. * which should contain new ICE transport details.
  1129. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  1130. * transport info.
  1131. * @param success callback called when we succeed to accept new offer.
  1132. * @param failure function(error) called when we fail to accept new offer.
  1133. */
  1134. replaceTransport(jingleOfferElem, success, failure) {
  1135. if (this.options.enableForcedReload) {
  1136. const sdp = new SDP(this.peerconnection.localDescription.sdp);
  1137. this.sendTransportAccept(sdp, success, failure);
  1138. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTARTED, this);
  1139. return;
  1140. }
  1141. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  1142. // We need to first reject the 'data' section to have the SCTP stack
  1143. // cleaned up to signal the known data channel is now invalid. After
  1144. // that the original offer is set to have the SCTP connection
  1145. // established with the new bridge.
  1146. const originalOffer = jingleOfferElem.clone();
  1147. jingleOfferElem
  1148. .find('>content[name=\'data\']')
  1149. .attr('senders', 'rejected');
  1150. // Remove all remote sources in order to reset the client's state
  1151. // for the remote MediaStreams. When a conference is moved to
  1152. // another bridge it will start streaming with a sequence number
  1153. // that is not in sync with the most recently seen by the client.
  1154. // The symptoms include frozen or black video and lots of "failed to
  1155. // unprotect SRTP packets" in Chrome logs.
  1156. jingleOfferElem
  1157. .find('>content>description>source')
  1158. .remove();
  1159. jingleOfferElem
  1160. .find('>content>description>ssrc-group')
  1161. .remove();
  1162. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  1163. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  1164. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  1165. // fingerprint has changed by setting an all zeros key.
  1166. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  1167. newFingerprint.attr('hash', 'sha-1');
  1168. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  1169. // First set an offer with a rejected 'data' section
  1170. this.setOfferAnswerCycle(
  1171. jingleOfferElem,
  1172. () => {
  1173. // Now set the original offer(with the 'data' section)
  1174. this.setOfferAnswerCycle(
  1175. originalOffer,
  1176. () => {
  1177. const localSDP
  1178. = new SDP(this.peerconnection.localDescription.sdp);
  1179. this.sendTransportAccept(localSDP, success, failure);
  1180. this.room.eventEmitter.emit(
  1181. XMPPEvents.ICE_RESTART_SUCCESS,
  1182. this,
  1183. originalOffer);
  1184. },
  1185. failure);
  1186. },
  1187. failure
  1188. );
  1189. }
  1190. /**
  1191. * Sends Jingle 'session-accept' message.
  1192. * @param {function()} success callback called when we receive 'RESULT'
  1193. * packet for the 'session-accept'
  1194. * @param {function(error)} failure called when we receive an error response
  1195. * or when the request has timed out.
  1196. * @private
  1197. */
  1198. sendSessionAccept(success, failure) {
  1199. // NOTE: since we're just reading from it, we don't need to be within
  1200. // the modification queue to access the local description
  1201. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1202. const accept = $iq({ to: this.remoteJid,
  1203. type: 'set' })
  1204. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1205. action: 'session-accept',
  1206. initiator: this.initiatorJid,
  1207. responder: this.responderJid,
  1208. sid: this.sid });
  1209. if (this.webrtcIceTcpDisable) {
  1210. localSDP.removeTcpCandidates = true;
  1211. }
  1212. if (this.webrtcIceUdpDisable) {
  1213. localSDP.removeUdpCandidates = true;
  1214. }
  1215. if (this.failICE) {
  1216. localSDP.failICE = true;
  1217. }
  1218. localSDP.toJingle(
  1219. accept,
  1220. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1221. logger.info(`${this} Sending session-accept`);
  1222. logger.debug(accept.tree());
  1223. this.connection.sendIQ(accept,
  1224. success,
  1225. this.newJingleErrorHandler(accept, error => {
  1226. failure(error);
  1227. // 'session-accept' is a critical timeout and we'll
  1228. // have to restart
  1229. this.room.eventEmitter.emit(
  1230. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1231. }),
  1232. IQ_TIMEOUT);
  1233. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1234. // fingerprint and setup) ASAP in order to start the connection
  1235. // establishment.
  1236. //
  1237. // FIXME Flushing the connection at this point triggers an issue with
  1238. // BOSH request handling in Prosody on slow connections.
  1239. //
  1240. // The problem is that this request will be quite large and it may take
  1241. // time before it reaches Prosody. In the meantime Strophe may decide
  1242. // to send the next one. And it was observed that a small request with
  1243. // 'transport-info' usually follows this one. It does reach Prosody
  1244. // before the previous one was completely received. 'rid' on the server
  1245. // is increased and Prosody ignores the request with 'session-accept'.
  1246. // It will never reach Jicofo and everything in the request table is
  1247. // lost. Removing the flush does not guarantee it will never happen, but
  1248. // makes it much less likely('transport-info' is bundled with
  1249. // 'session-accept' and any immediate requests).
  1250. //
  1251. // this.connection.flush();
  1252. }
  1253. /**
  1254. * Will send 'content-modify' IQ in order to ask the remote peer to
  1255. * either stop or resume sending video media or to adjust sender's video constraints.
  1256. * @private
  1257. */
  1258. sendContentModify() {
  1259. const senders = this._localVideoActive ? 'both' : 'none';
  1260. const sessionModify
  1261. = $iq({
  1262. to: this.remoteJid,
  1263. type: 'set'
  1264. })
  1265. .c('jingle', {
  1266. xmlns: 'urn:xmpp:jingle:1',
  1267. action: 'content-modify',
  1268. initiator: this.initiatorJid,
  1269. sid: this.sid
  1270. })
  1271. .c('content', {
  1272. name: MediaType.VIDEO,
  1273. senders
  1274. });
  1275. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  1276. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  1277. sessionModify
  1278. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1279. .attrs({
  1280. sourceName,
  1281. maxHeight
  1282. });
  1283. sessionModify.up();
  1284. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  1285. });
  1286. }
  1287. logger.debug(sessionModify.tree());
  1288. this.connection.sendIQ(
  1289. sessionModify,
  1290. null,
  1291. this.newJingleErrorHandler(sessionModify),
  1292. IQ_TIMEOUT);
  1293. }
  1294. /**
  1295. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1296. * the remote p2p peer.
  1297. *
  1298. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1299. */
  1300. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1301. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1302. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1303. if (this.isP2P) {
  1304. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1305. // be synced after offer/answer.
  1306. if (this.state === JingleSessionState.ACTIVE) {
  1307. this.sendContentModify();
  1308. }
  1309. }
  1310. }
  1311. /**
  1312. * Sends Jingle 'transport-accept' message which is a response to
  1313. * 'transport-replace'.
  1314. * @param localSDP the 'SDP' object with local session description
  1315. * @param success callback called when we receive 'RESULT' packet for
  1316. * 'transport-replace'
  1317. * @param failure function(error) called when we receive an error response
  1318. * or when the request has timed out.
  1319. * @private
  1320. */
  1321. sendTransportAccept(localSDP, success, failure) {
  1322. const transportAccept = $iq({ to: this.remoteJid,
  1323. type: 'set' })
  1324. .c('jingle', {
  1325. xmlns: 'urn:xmpp:jingle:1',
  1326. action: 'transport-accept',
  1327. initiator: this.initiatorJid,
  1328. sid: this.sid
  1329. });
  1330. localSDP.media.forEach((medialines, idx) => {
  1331. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1332. transportAccept.c('content',
  1333. {
  1334. creator:
  1335. this.initiatorJid === this.localJid
  1336. ? 'initiator'
  1337. : 'responder',
  1338. name: mline.media
  1339. }
  1340. );
  1341. localSDP.transportToJingle(idx, transportAccept);
  1342. transportAccept.up();
  1343. });
  1344. logger.info(`${this} Sending transport-accept`);
  1345. logger.debug(transportAccept.tree());
  1346. this.connection.sendIQ(transportAccept,
  1347. success,
  1348. this.newJingleErrorHandler(transportAccept, failure),
  1349. IQ_TIMEOUT);
  1350. }
  1351. /**
  1352. * Sends Jingle 'transport-reject' message which is a response to
  1353. * 'transport-replace'.
  1354. * @param success callback called when we receive 'RESULT' packet for
  1355. * 'transport-replace'
  1356. * @param failure function(error) called when we receive an error response
  1357. * or when the request has timed out.
  1358. *
  1359. * FIXME method should be marked as private, but there's some spaghetti that
  1360. * needs to be fixed prior doing that
  1361. */
  1362. sendTransportReject(success, failure) {
  1363. // Send 'transport-reject', so that the focus will
  1364. // know that we've failed
  1365. const transportReject = $iq({ to: this.remoteJid,
  1366. type: 'set' })
  1367. .c('jingle', {
  1368. xmlns: 'urn:xmpp:jingle:1',
  1369. action: 'transport-reject',
  1370. initiator: this.initiatorJid,
  1371. sid: this.sid
  1372. });
  1373. logger.info(`${this} Sending 'transport-reject'`);
  1374. logger.debug(transportReject.tree());
  1375. this.connection.sendIQ(transportReject,
  1376. success,
  1377. this.newJingleErrorHandler(transportReject, failure),
  1378. IQ_TIMEOUT);
  1379. }
  1380. /**
  1381. * Sets the resolution constraint on the local camera track.
  1382. * @param {number} maxFrameHeight - The user preferred max frame height.
  1383. * @param {string} sourceName - The source name of the track.
  1384. * @returns {Promise} promise that will be resolved when the operation is
  1385. * successful and rejected otherwise.
  1386. */
  1387. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1388. if (this._assertNotEnded()) {
  1389. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1390. const jitsiLocalTrack = sourceName
  1391. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1392. : this.rtc.getLocalVideoTrack();
  1393. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1394. }
  1395. return Promise.resolve();
  1396. }
  1397. /**
  1398. * @inheritDoc
  1399. */
  1400. terminate(success, failure, options) {
  1401. if (this.state === JingleSessionState.ENDED) {
  1402. return;
  1403. }
  1404. if (!options || Boolean(options.sendSessionTerminate)) {
  1405. const sessionTerminate
  1406. = $iq({
  1407. to: this.remoteJid,
  1408. type: 'set'
  1409. })
  1410. .c('jingle', {
  1411. xmlns: 'urn:xmpp:jingle:1',
  1412. action: 'session-terminate',
  1413. initiator: this.initiatorJid,
  1414. sid: this.sid
  1415. })
  1416. .c('reason')
  1417. .c((options && options.reason) || 'success')
  1418. .up();
  1419. if (options && options.reasonDescription) {
  1420. sessionTerminate
  1421. .c('text')
  1422. .t(options.reasonDescription)
  1423. .up()
  1424. .up();
  1425. } else {
  1426. sessionTerminate.up();
  1427. }
  1428. this._bridgeSessionId
  1429. && sessionTerminate.c(
  1430. 'bridge-session', {
  1431. xmlns: 'http://jitsi.org/protocol/focus',
  1432. id: this._bridgeSessionId,
  1433. restart: options && options.requestRestart === true
  1434. }).up();
  1435. logger.info(`${this} Sending session-terminate`);
  1436. logger.debug(sessionTerminate.tree());
  1437. this.connection.sendIQ(
  1438. sessionTerminate,
  1439. success,
  1440. this.newJingleErrorHandler(sessionTerminate, failure),
  1441. IQ_TIMEOUT);
  1442. } else {
  1443. logger.info(`${this} Skipped sending session-terminate`);
  1444. }
  1445. // this should result in 'onTerminated' being called by strope.jingle.js
  1446. this.connection.jingle.terminate(this.sid);
  1447. }
  1448. /**
  1449. *
  1450. * @param reasonCondition
  1451. * @param reasonText
  1452. */
  1453. onTerminated(reasonCondition, reasonText) {
  1454. // Do something with reason and reasonCondition when we start to care
  1455. // this.reasonCondition = reasonCondition;
  1456. // this.reasonText = reasonText;
  1457. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1458. this._xmppListeners.forEach(removeListener => removeListener());
  1459. this._xmppListeners = [];
  1460. if (this._removeSenderVideoConstraintsChangeListener) {
  1461. this._removeSenderVideoConstraintsChangeListener();
  1462. }
  1463. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1464. this.peerconnection.getRemoteTracks().forEach(track => {
  1465. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1466. });
  1467. }
  1468. this.close();
  1469. }
  1470. /**
  1471. * Handles XMPP connection state changes.
  1472. *
  1473. * @param {XmppConnection.Status} status - The new status.
  1474. */
  1475. onXmppStatusChanged(status) {
  1476. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1477. logger.info(`${this} Sending SSRC update on reconnect`);
  1478. this.notifyMySSRCUpdate(
  1479. this._cachedOldLocalSdp,
  1480. this._cachedNewLocalSdp);
  1481. }
  1482. }
  1483. /**
  1484. * Parse the information from the xml sourceAddElem and translate it
  1485. * into sdp lines
  1486. * @param {jquery xml element} sourceAddElem the source-add
  1487. * element from jingle
  1488. * @param {SDP object} currentRemoteSdp the current remote
  1489. * sdp (as of this new source-add)
  1490. * @returns {list} a list of SDP line strings that should
  1491. * be added to the remote SDP
  1492. */
  1493. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1494. const addSsrcInfo = [];
  1495. const self = this;
  1496. $(sourceAddElem).each((i1, content) => {
  1497. const name = $(content).attr('name');
  1498. let lines = '';
  1499. $(content)
  1500. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1501. .each(function() {
  1502. // eslint-disable-next-line no-invalid-this
  1503. const semantics = this.getAttribute('semantics');
  1504. const ssrcs
  1505. = $(this) // eslint-disable-line no-invalid-this
  1506. .find('>source')
  1507. .map(function() {
  1508. // eslint-disable-next-line no-invalid-this
  1509. return this.getAttribute('ssrc');
  1510. })
  1511. .get();
  1512. if (ssrcs.length) {
  1513. lines += `a=ssrc-group:${semantics} ${ssrcs.join(' ')}\r\n`;
  1514. }
  1515. });
  1516. // handles both >source and >description>source
  1517. const tmp
  1518. = $(content).find(
  1519. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1520. /* eslint-disable no-invalid-this */
  1521. tmp.each(function() {
  1522. const ssrc = $(this).attr('ssrc');
  1523. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1524. // Do not print the warning for unified plan p2p case since ssrcs are never removed from the SDP.
  1525. !(self.usesUnifiedPlan && self.isP2P)
  1526. && logger.warn(`${self} Source-add request for existing SSRC: ${ssrc}`);
  1527. return;
  1528. }
  1529. // eslint-disable-next-line newline-per-chained-call
  1530. $(this).find('>parameter').each(function() {
  1531. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1532. if ($(this).attr('value') && $(this).attr('value').length) {
  1533. lines += `:${$(this).attr('value')}`;
  1534. }
  1535. lines += '\r\n';
  1536. });
  1537. });
  1538. let midFound = false;
  1539. /* eslint-enable no-invalid-this */
  1540. currentRemoteSdp.media.forEach((media, i2) => {
  1541. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1542. return;
  1543. }
  1544. if (!addSsrcInfo[i2]) {
  1545. addSsrcInfo[i2] = '';
  1546. }
  1547. addSsrcInfo[i2] += lines;
  1548. midFound = true;
  1549. });
  1550. // In p2p unified mode with multi-stream enabled, the new sources will have content name that doesn't exist
  1551. // in the current remote description. Add a new m-line for this newly signaled source.
  1552. if (!midFound && this.isP2P) {
  1553. addSsrcInfo[name] = lines;
  1554. }
  1555. });
  1556. return addSsrcInfo;
  1557. }
  1558. /**
  1559. * Handles a Jingle source-add message for this Jingle session.
  1560. * @param elem An array of Jingle "content" elements.
  1561. */
  1562. addRemoteStream(elem) {
  1563. this._addOrRemoveRemoteStream(true /* add */, elem);
  1564. }
  1565. /**
  1566. * Handles a Jingle source-remove message for this Jingle session.
  1567. * @param elem An array of Jingle "content" elements.
  1568. */
  1569. removeRemoteStream(elem) {
  1570. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1571. }
  1572. /**
  1573. * Filter remapped SSRCs.
  1574. * Process owner change for existing SSRCs.
  1575. * Return new ones for further processing.
  1576. */
  1577. getNewSources(msg) {
  1578. const newSources = [];
  1579. for (const s of msg.mappedSources) {
  1580. if (this.peerconnection.addRemoteSsrc(s.ssrc)) {
  1581. logger.debug(`New SSRC ${s.ssrc}`);
  1582. newSources[newSources.length] = s;
  1583. } else {
  1584. const track = this.peerconnection.getTrackBySSRC(s.ssrc);
  1585. if (track) {
  1586. logger.debug(`Existing SSRC ${s.ssrc}: new owner ${s.owner}. name=${s.source}`);
  1587. if (s.videoType === 'CAMERA') {
  1588. track._setVideoType('camera');
  1589. } else if (s.videoType === 'DESKTOP') {
  1590. track._setVideoType('desktop');
  1591. }
  1592. track.setSourceName(s.source);
  1593. track.setOwner(s.owner);
  1594. } else {
  1595. logger.error(`Remapped SSRC ${s.ssrc} not found`);
  1596. }
  1597. }
  1598. }
  1599. return newSources;
  1600. }
  1601. /**
  1602. * Process SSRC remappings for video sources.
  1603. */
  1604. videoSsrcsRemapped(msg) {
  1605. const newSources = this.getNewSources(msg);
  1606. if (newSources.length > 0) {
  1607. let node = $build('content', {
  1608. xmlns: 'urn:xmpp:jingle:1',
  1609. name: 'video'
  1610. }).c('description', {
  1611. xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  1612. media: MediaType.VIDEO
  1613. });
  1614. for (const s of newSources) {
  1615. const idx = ++this.numRemoteVideoSources;
  1616. const msid = `remote-video-${idx} remote-video-${idx}`;
  1617. _addSourceElement(node, s, s.ssrc, msid);
  1618. if (s.rtx !== '-1') {
  1619. _addSourceElement(node, s, s.rtx, msid);
  1620. node.c('ssrc-group', {
  1621. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1622. semantics: 'FID'
  1623. })
  1624. .c('source', {
  1625. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1626. ssrc: s.ssrc
  1627. })
  1628. .up()
  1629. .c('source', {
  1630. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1631. ssrc: s.rtx
  1632. })
  1633. .up()
  1634. .up();
  1635. }
  1636. }
  1637. node = node.up();
  1638. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1639. }
  1640. }
  1641. /**
  1642. * Process SSRC remappings for audio sources.
  1643. */
  1644. audioSsrcsRemapped(msg) {
  1645. const newSources = this.getNewSources(msg);
  1646. if (newSources.length > 0) {
  1647. let node = $build('content', {
  1648. xmlns: 'urn:xmpp:jingle:1',
  1649. name: 'audio'
  1650. }).c('description', {
  1651. xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  1652. media: MediaType.AUDIO
  1653. });
  1654. for (const s of newSources) {
  1655. const idx = ++this.numRemoteAudioSources;
  1656. const msid = `remote-audio-${idx} remote-audio-${idx}`;
  1657. _addSourceElement(node, s, s.ssrc, msid);
  1658. }
  1659. node = node.up();
  1660. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1661. }
  1662. }
  1663. /**
  1664. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1665. *
  1666. * @param {string} id Endpoint id of the participant that has left the call.
  1667. * @returns {void}
  1668. */
  1669. removeRemoteStreamsOnLeave(id) {
  1670. const workFunction = finishCallback => {
  1671. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1672. if (removeSsrcInfo.length) {
  1673. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1674. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1675. this._renegotiate(newRemoteSdp.raw)
  1676. .then(() => {
  1677. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1678. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSDP);
  1679. finishCallback();
  1680. })
  1681. .catch(err => finishCallback(err));
  1682. } else {
  1683. finishCallback();
  1684. }
  1685. };
  1686. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1687. this.modificationQueue.push(
  1688. workFunction,
  1689. error => {
  1690. if (error) {
  1691. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1692. } else {
  1693. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1694. }
  1695. });
  1696. }
  1697. /**
  1698. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1699. * Jingle session.
  1700. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1701. * otherwise.
  1702. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1703. * @private
  1704. */
  1705. _addOrRemoveRemoteStream(isAdd, elem) {
  1706. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1707. if (isAdd) {
  1708. this.readSsrcInfo(elem);
  1709. }
  1710. const workFunction = finishedCallback => {
  1711. if (!this.peerconnection.localDescription
  1712. || !this.peerconnection.localDescription.sdp) {
  1713. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1714. logger.error(errMsg);
  1715. finishedCallback(errMsg);
  1716. return;
  1717. }
  1718. logger.log(`${this} Processing ${logPrefix}`);
  1719. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1720. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1721. const addOrRemoveSsrcInfo
  1722. = isAdd
  1723. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1724. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1725. const newRemoteSdp
  1726. = isAdd
  1727. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1728. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1729. const remoteDescription = new RTCSessionDescription({
  1730. type: 'offer',
  1731. sdp: newRemoteSdp.raw
  1732. });
  1733. // Always initiate a sRD->cA->sLD cycle when a remote source is added or removed irrespective of whether
  1734. // the local endpoint is an initiator or responder. Fixes bugs on Chromium where decoders are not created
  1735. // when sLD->cO->sRD cycle is initiated for p2p cases when remote sources are received.
  1736. this._responderRenegotiate(remoteDescription).then(() => {
  1737. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1738. logger.log(`${this} ${logPrefix} - OK`);
  1739. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1740. finishedCallback();
  1741. }, error => {
  1742. logger.error(`${this} ${logPrefix} failed:`, error);
  1743. finishedCallback(error);
  1744. });
  1745. };
  1746. logger.debug(`${this} Queued ${logPrefix} task`);
  1747. // Queue and execute
  1748. this.modificationQueue.push(workFunction);
  1749. }
  1750. /**
  1751. * Takes in a jingle offer iq, returns the new sdp offer
  1752. * @param {jquery xml element} offerIq the incoming offer
  1753. * @returns {SDP object} the jingle offer translated to SDP
  1754. */
  1755. _processNewJingleOfferIq(offerIq) {
  1756. const remoteSdp = new SDP('');
  1757. if (this.webrtcIceTcpDisable) {
  1758. remoteSdp.removeTcpCandidates = true;
  1759. }
  1760. if (this.webrtcIceUdpDisable) {
  1761. remoteSdp.removeUdpCandidates = true;
  1762. }
  1763. if (this.failICE) {
  1764. remoteSdp.failICE = true;
  1765. }
  1766. remoteSdp.fromJingle(offerIq);
  1767. this.readSsrcInfo($(offerIq).find('>content'));
  1768. return remoteSdp;
  1769. }
  1770. /**
  1771. * Remove the given ssrc lines from the current remote sdp
  1772. * @param {list} removeSsrcInfo a list of SDP line strings that
  1773. * should be removed from the remote SDP
  1774. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1775. * in removeSsrcInfo
  1776. */
  1777. _processRemoteRemoveSource(removeSsrcInfo) {
  1778. const remoteSdp = this.usesUnifiedPlan
  1779. ? new SDP(this.peerconnection.peerconnection.remoteDescription.sdp)
  1780. : new SDP(this.peerconnection.remoteDescription.sdp);
  1781. removeSsrcInfo.forEach((lines, idx) => {
  1782. // eslint-disable-next-line no-param-reassign
  1783. lines = lines.split('\r\n');
  1784. lines.pop(); // remove empty last element;
  1785. if (this.usesUnifiedPlan) {
  1786. let mid;
  1787. lines.forEach(line => {
  1788. mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1789. if (mid > -1) {
  1790. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1791. if (this.isP2P) {
  1792. const mediaType = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0])?.media;
  1793. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, false);
  1794. [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ].forEach(direction => {
  1795. remoteSdp.media[mid] = remoteSdp.media[mid]
  1796. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1797. });
  1798. } else {
  1799. // Jvb connections will have direction set to 'sendonly' for the remote sources.
  1800. remoteSdp.media[mid] = remoteSdp.media[mid]
  1801. .replace(`a=${MediaDirection.SENDONLY}`, `a=${MediaDirection.INACTIVE}`);
  1802. }
  1803. }
  1804. });
  1805. // Reject the m-line so that the browser removes the associated transceiver from the list of available
  1806. // transceivers. This will prevent the client from trying to re-use these inactive transceivers when
  1807. // additional video sources are added to the peerconnection.
  1808. if (mid > -1 && !this.isP2P && FeatureFlags.isMultiStreamSendSupportEnabled()) {
  1809. const { media, port } = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0]);
  1810. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`m=${media} ${port}`, `m=${media} 0`);
  1811. }
  1812. } else {
  1813. lines.forEach(line => {
  1814. remoteSdp.media[idx] = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1815. });
  1816. }
  1817. });
  1818. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1819. return remoteSdp;
  1820. }
  1821. /**
  1822. * Add the given ssrc lines to the current remote sdp
  1823. * @param {list} addSsrcInfo a list of SDP line strings that
  1824. * should be added to the remote SDP
  1825. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1826. * in removeSsrcInfo
  1827. */
  1828. _processRemoteAddSource(addSsrcInfo) {
  1829. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1830. // Add a new m-line in the remote description if the source info for a secondary video source is recceived from
  1831. // the remote p2p peer when multi-stream support is enabled.
  1832. if (addSsrcInfo.length > remoteSdp.media.length
  1833. && this.isP2P
  1834. && this.usesUnifiedPlan) {
  1835. remoteSdp.addMlineForNewLocalSource(MediaType.VIDEO);
  1836. remoteSdp = new SDP(remoteSdp.raw);
  1837. }
  1838. addSsrcInfo.forEach((lines, idx) => {
  1839. remoteSdp.media[idx] += lines;
  1840. // Make sure to change the direction to 'sendrecv/sendonly' only for p2p connections. For jvb connections,
  1841. // a new m-line is added for the new remote sources.
  1842. if (this.isP2P && this.usesUnifiedPlan) {
  1843. const mediaType = SDPUtil.parseMLine(remoteSdp.media[idx].split('\r\n')[0])?.media;
  1844. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, true);
  1845. [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ].forEach(direction => {
  1846. remoteSdp.media[idx] = remoteSdp.media[idx]
  1847. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1848. });
  1849. }
  1850. });
  1851. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1852. return remoteSdp;
  1853. }
  1854. /**
  1855. * Do a new o/a flow using the existing remote description
  1856. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1857. * to use. If not provided, the remote sdp from the
  1858. * peerconnection will be used
  1859. * @returns {Promise} promise which resolves when the
  1860. * o/a flow is complete with no arguments or
  1861. * rejects with an error {string}
  1862. */
  1863. _renegotiate(optionalRemoteSdp) {
  1864. if (this.peerconnection.signalingState === 'closed') {
  1865. const error = new Error('Attempted to renegotiate in state closed');
  1866. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1867. return Promise.reject(error);
  1868. }
  1869. const remoteSdp
  1870. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1871. if (!remoteSdp) {
  1872. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1873. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1874. return Promise.reject(error);
  1875. }
  1876. const remoteDescription = new RTCSessionDescription({
  1877. type: this.isInitiator ? 'answer' : 'offer',
  1878. sdp: remoteSdp
  1879. });
  1880. if (this.isInitiator) {
  1881. return this._initiatorRenegotiate(remoteDescription);
  1882. }
  1883. return this._responderRenegotiate(remoteDescription);
  1884. }
  1885. /**
  1886. * Renegotiate cycle implementation for the responder case.
  1887. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1888. * which will be used as remote description in the cycle.
  1889. * @private
  1890. */
  1891. _responderRenegotiate(remoteDescription) {
  1892. logger.debug(`${this} Renegotiate: setting remote description`);
  1893. return this.peerconnection.setRemoteDescription(remoteDescription)
  1894. .then(() => {
  1895. logger.debug(`${this} Renegotiate: creating answer`);
  1896. return this.peerconnection.createAnswer(this.mediaConstraints)
  1897. .then(answer => {
  1898. logger.debug(`${this} Renegotiate: setting local description`);
  1899. return this.peerconnection.setLocalDescription(answer);
  1900. });
  1901. });
  1902. }
  1903. /**
  1904. * Renegotiate cycle implementation for the initiator's case.
  1905. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1906. * which will be used as remote description in the cycle.
  1907. * @private
  1908. */
  1909. _initiatorRenegotiate(remoteDescription) {
  1910. logger.debug(`${this} Renegotiate: creating offer`);
  1911. return this.peerconnection.createOffer(this.mediaConstraints)
  1912. .then(offer => {
  1913. logger.debug(`${this} Renegotiate: setting local description`);
  1914. return this.peerconnection.setLocalDescription(offer)
  1915. .then(() => {
  1916. logger.debug(`${this} Renegotiate: setting remote description`);
  1917. // eslint-disable-next-line max-len
  1918. return this.peerconnection.setRemoteDescription(remoteDescription);
  1919. });
  1920. });
  1921. }
  1922. /**
  1923. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  1924. * being added to the peerconnection for the first time.
  1925. *
  1926. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  1927. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  1928. * otherwise.
  1929. */
  1930. addTracks(localTracks = null) {
  1931. if (!FeatureFlags.isMultiStreamSendSupportEnabled()
  1932. || !localTracks?.length
  1933. || localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  1934. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  1935. }
  1936. const replaceTracks = [];
  1937. const workFunction = finishedCallback => {
  1938. const oldLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1939. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1940. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  1941. .find(t => t.receiver.track.kind === MediaType.VIDEO
  1942. && t.direction === MediaDirection.RECVONLY
  1943. && t.currentDirection === MediaDirection.RECVONLY);
  1944. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  1945. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  1946. // existing one in that case.
  1947. for (const track of localTracks) {
  1948. if (!this.isP2P || !recvOnlyTransceiver) {
  1949. remoteSdp.addMlineForNewLocalSource(track.getType());
  1950. }
  1951. }
  1952. const remoteDescription = new RTCSessionDescription({
  1953. type: 'offer',
  1954. sdp: remoteSdp.raw
  1955. });
  1956. // Always initiate a responder renegotiate since the new m-line is added to remote SDP.
  1957. this._responderRenegotiate(remoteDescription)
  1958. .then(() => {
  1959. // Replace the tracks on the newly generated transceivers.
  1960. for (const track of localTracks) {
  1961. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  1962. }
  1963. return Promise.all(replaceTracks);
  1964. })
  1965. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  1966. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  1967. .then(() => this._renegotiate())
  1968. .then(() => {
  1969. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1970. // Signal the new sources to the peer.
  1971. this.notifyMySSRCUpdate(oldLocalSDP, newLocalSDP);
  1972. finishedCallback();
  1973. })
  1974. .catch(error => finishedCallback(error));
  1975. };
  1976. return new Promise((resolve, reject) => {
  1977. logger.debug(`${this} Queued renegotiation after addTrack`);
  1978. this.modificationQueue.push(
  1979. workFunction,
  1980. error => {
  1981. if (error) {
  1982. logger.error(`${this} renegotiation after addTrack error`, error);
  1983. reject(error);
  1984. } else {
  1985. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1986. resolve();
  1987. }
  1988. });
  1989. });
  1990. }
  1991. /**
  1992. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1993. * offer/answer cycle after both operations are done. Either
  1994. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1995. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1996. * <tt>oldTrack</tt>
  1997. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1998. * replaced
  1999. * @param {JitsiLocalTrack|null} newTrack the new track to use
  2000. * @returns {Promise} which resolves once the replacement is complete
  2001. * with no arguments or rejects with an error {string}
  2002. */
  2003. replaceTrack(oldTrack, newTrack) {
  2004. const workFunction = finishedCallback => {
  2005. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  2006. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  2007. if (!this.usesUnifiedPlan) {
  2008. // NOTE the code below assumes that no more than 1 video track
  2009. // can be added to the peer connection.
  2010. // Transition from camera to desktop share
  2011. // or transition from one camera source to another.
  2012. if (this.peerconnection.options.capScreenshareBitrate
  2013. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  2014. // Clearing current primary SSRC will make
  2015. // the SdpConsistency generate a new one which will result
  2016. // with:
  2017. // 1. source-remove for the old video stream.
  2018. // 2. source-add for the new video stream.
  2019. this.peerconnection.clearRecvonlySsrc();
  2020. }
  2021. // Transition from no video to video (unmute).
  2022. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  2023. // Clearing current primary SSRC will make
  2024. // the SdpConsistency generate a new one which will result
  2025. // with:
  2026. // 1. source-remove for the recvonly
  2027. // 2. source-add for the new video stream
  2028. this.peerconnection.clearRecvonlySsrc();
  2029. // Transition from video to no video
  2030. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  2031. // Clearing current primary SSRC and generating the recvonly
  2032. // will result in:
  2033. // 1. source-remove for the old video stream
  2034. // 2. source-add for the recvonly stream
  2035. this.peerconnection.clearRecvonlySsrc();
  2036. this.peerconnection.generateRecvonlySsrc();
  2037. }
  2038. }
  2039. this.peerconnection.replaceTrack(oldTrack, newTrack)
  2040. .then(shouldRenegotiate => {
  2041. let promise = Promise.resolve();
  2042. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  2043. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  2044. if (shouldRenegotiate
  2045. && (oldTrack || newTrack)
  2046. && this.state === JingleSessionState.ACTIVE) {
  2047. const remoteSdp = this.peerconnection.remoteDescription.sdp;
  2048. const remoteDescription = new RTCSessionDescription({
  2049. type: 'offer',
  2050. sdp: remoteSdp
  2051. });
  2052. // Always initiate a sRD->cA->sLD cycle since renegotiation fails in the following scenario.
  2053. // In a p2p call when channelLastN=0, the direction on the video tranceiver is set to
  2054. // 'inactive'. At this point, if the user unmutes, the track is replaced on the video sender.
  2055. // If a cO->sLD->sRD is triggered, the browser adds a third m-line which isn't expected and
  2056. // possibly is a bug. All renegotiations fail as a result. However, the browser does not add a
  2057. // third m-line in the answer it generates and renegotiation succeeds.
  2058. promise = this._responderRenegotiate(remoteDescription).then(() => {
  2059. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  2060. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  2061. });
  2062. }
  2063. return promise.then(() => {
  2064. // Set the source name of the new track.
  2065. if (oldTrack
  2066. && newTrack
  2067. && oldTrack.isVideoTrack()) {
  2068. newTrack.setSourceName(oldTrack.getSourceName());
  2069. }
  2070. if (newTrack?.isVideoTrack()) {
  2071. logger.debug(`${this} replaceTrack worker: configuring video stream`);
  2072. // Configure the video encodings after the track is replaced.
  2073. return this.peerconnection.configureSenderVideoEncodings(newTrack);
  2074. }
  2075. });
  2076. })
  2077. .then(() => finishedCallback(), error => finishedCallback(error));
  2078. };
  2079. return new Promise((resolve, reject) => {
  2080. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  2081. this.modificationQueue.push(
  2082. workFunction,
  2083. error => {
  2084. if (error) {
  2085. logger.error(`${this} Replace track error:`, error);
  2086. reject(error);
  2087. } else {
  2088. logger.info(`${this} Replace track done!`);
  2089. resolve();
  2090. }
  2091. });
  2092. });
  2093. }
  2094. /**
  2095. * Parse the information from the xml sourceRemoveElem and translate it
  2096. * into sdp lines
  2097. * @param {jquery xml element} sourceRemoveElem the source-remove
  2098. * element from jingle
  2099. * @param {SDP object} currentRemoteSdp the current remote
  2100. * sdp (as of this new source-remove)
  2101. * @returns {list} a list of SDP line strings that should
  2102. * be removed from the remote SDP
  2103. */
  2104. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  2105. const removeSsrcInfo = [];
  2106. $(sourceRemoveElem).each((i1, content) => {
  2107. const name = $(content).attr('name');
  2108. let lines = '';
  2109. $(content)
  2110. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  2111. .each(function() {
  2112. /* eslint-disable no-invalid-this */
  2113. const semantics = this.getAttribute('semantics');
  2114. const ssrcs
  2115. = $(this)
  2116. .find('>source')
  2117. .map(function() {
  2118. return this.getAttribute('ssrc');
  2119. })
  2120. .get();
  2121. if (ssrcs.length) {
  2122. lines
  2123. += `a=ssrc-group:${semantics} ${
  2124. ssrcs.join(' ')}\r\n`;
  2125. }
  2126. /* eslint-enable no-invalid-this */
  2127. });
  2128. const ssrcs = [];
  2129. // handles both >source and >description>source versions
  2130. const tmp
  2131. = $(content).find(
  2132. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  2133. tmp.each(function() {
  2134. // eslint-disable-next-line no-invalid-this
  2135. const ssrc = $(this).attr('ssrc');
  2136. ssrcs.push(ssrc);
  2137. });
  2138. currentRemoteSdp.media.forEach((media, i2) => {
  2139. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  2140. return;
  2141. }
  2142. if (!removeSsrcInfo[i2]) {
  2143. removeSsrcInfo[i2] = '';
  2144. }
  2145. ssrcs.forEach(ssrc => {
  2146. const ssrcLines
  2147. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  2148. if (ssrcLines.length) {
  2149. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  2150. }
  2151. });
  2152. removeSsrcInfo[i2] += lines;
  2153. });
  2154. });
  2155. return removeSsrcInfo;
  2156. }
  2157. /**
  2158. * Will print an error if there is any difference, between the SSRCs given
  2159. * in the <tt>oldSDP</tt> and the ones currently described in
  2160. * the peerconnection's local description.
  2161. * @param {string} operationName the operation's name which will be printed
  2162. * in the error message.
  2163. * @param {SDP} oldSDP the old local SDP which will be compared with
  2164. * the current one.
  2165. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  2166. * otherwise.
  2167. * @private
  2168. */
  2169. _verifyNoSSRCChanged(operationName, oldSDP) {
  2170. const currentLocalSDP
  2171. = new SDP(this.peerconnection.localDescription.sdp);
  2172. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  2173. const addedMedia = sdpDiff.getNewMedia();
  2174. if (Object.keys(addedMedia).length) {
  2175. logger.error(`${this} - some SSRC were added on ${operationName}`, addedMedia);
  2176. return false;
  2177. }
  2178. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  2179. const removedMedia = sdpDiff.getNewMedia();
  2180. if (Object.keys(removedMedia).length) {
  2181. logger.error(`${this} - some SSRCs were removed on ${operationName}`, removedMedia);
  2182. return false;
  2183. }
  2184. return true;
  2185. }
  2186. /**
  2187. * Adds local track back to the peerconnection associated with this session.
  2188. * @param {JitsiLocalTrack} track
  2189. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  2190. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  2191. * details in case something goes wrong.
  2192. */
  2193. addTrackToPc(track) {
  2194. return this._addRemoveTrack(false /* add */, track)
  2195. .then(() => {
  2196. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  2197. // unmutes it the first time, all the parameters need to be configured.
  2198. if (track.isVideoTrack()) {
  2199. return this.peerconnection.configureSenderVideoEncodings(track);
  2200. }
  2201. });
  2202. }
  2203. /**
  2204. * Remove local track as part of the mute operation.
  2205. * @param {JitsiLocalTrack} track the local track to be removed
  2206. * @return {Promise} a promise which will be resolved once the local track
  2207. * is removed from this session and the renegotiation is performed.
  2208. * The promise will be rejected with a <tt>string</tt> that the describes
  2209. * the error if anything goes wrong.
  2210. */
  2211. removeTrackFromPc(track) {
  2212. return this._addRemoveTrack(true /* remove */, track);
  2213. }
  2214. /**
  2215. * See {@link addTrackToPc} and {@link removeTrackFromPc}.
  2216. * @param {boolean} isRemove <tt>true</tt> for "remove" operation or <tt>false</tt> for "add" operation.
  2217. * @param {JitsiLocalTrack} track the track that will be added/removed
  2218. * @private
  2219. */
  2220. _addRemoveTrack(isRemove, track) {
  2221. if (!track) {
  2222. return Promise.reject('invalid "track" argument value');
  2223. }
  2224. const operationName = isRemove ? 'removeTrack' : 'addTrack';
  2225. const workFunction = finishedCallback => {
  2226. const tpc = this.peerconnection;
  2227. if (!tpc) {
  2228. finishedCallback(`Error: tried ${operationName} track with no active peer connection`);
  2229. return;
  2230. }
  2231. const oldLocalSDP = tpc.localDescription.sdp;
  2232. const operationPromise
  2233. = isRemove
  2234. ? tpc.removeTrackFromPc(track)
  2235. : tpc.addTrackToPc(track);
  2236. operationPromise
  2237. .then(shouldRenegotiate => {
  2238. if (shouldRenegotiate && oldLocalSDP && tpc.remoteDescription.sdp) {
  2239. this._renegotiate()
  2240. .then(() => {
  2241. // The results are ignored, as this check failure is not enough to fail the whole
  2242. // operation. It will log an error inside for plan-b.
  2243. !this.usesUnifiedPlan && this._verifyNoSSRCChanged(operationName, new SDP(oldLocalSDP));
  2244. const newLocalSdp = tpc.localDescription.sdp;
  2245. // Signal the ssrc if an unmute operation results in a new ssrc being generated.
  2246. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(newLocalSdp));
  2247. finishedCallback();
  2248. });
  2249. } else {
  2250. finishedCallback();
  2251. }
  2252. },
  2253. finishedCallback /* will be called with an error */);
  2254. };
  2255. logger.debug(`${this} Queued ${operationName} task`);
  2256. return new Promise((resolve, reject) => {
  2257. this.modificationQueue.push(
  2258. workFunction,
  2259. error => {
  2260. if (error) {
  2261. logger.error(`${this} ${operationName} failed`);
  2262. reject(error);
  2263. } else {
  2264. logger.debug(`${this} ${operationName} done`);
  2265. resolve();
  2266. }
  2267. });
  2268. });
  2269. }
  2270. /**
  2271. * Resumes or suspends media transfer over the underlying peer connection.
  2272. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  2273. * transfer or <tt>false</tt> to suspend audio media transmission.
  2274. * @param {boolean} videoActive <tt>true</tt> to enable video media
  2275. * transfer or <tt>false</tt> to suspend video media transmission.
  2276. * @return {Promise} a <tt>Promise</tt> which will resolve once
  2277. * the operation is done. It will be rejected with an error description as
  2278. * a string in case anything goes wrong.
  2279. */
  2280. setMediaTransferActive(audioActive, videoActive) {
  2281. if (!this.peerconnection) {
  2282. return Promise.reject(
  2283. 'Can not modify transfer active state,'
  2284. + ' before "initialize" is called');
  2285. }
  2286. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  2287. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  2288. logger.info(`${this} Queued make ${logVideoStr}, ${logAudioStr} task`);
  2289. const workFunction = finishedCallback => {
  2290. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  2291. // Because the value is modified on the queue it's impossible to
  2292. // check it's final value reliably prior to submitting the task.
  2293. // The rule here is that the last submitted state counts.
  2294. // Check the values here to avoid unnecessary renegotiation cycle.
  2295. const audioActiveChanged
  2296. = this.peerconnection.setAudioTransferActive(audioActive);
  2297. if (this._localVideoActive !== videoActive) {
  2298. this._localVideoActive = videoActive;
  2299. // Do only for P2P - Jicofo will reply with 'bad-request'
  2300. // We don't want to send 'content-modify', before the initial
  2301. // O/A (state === JingleSessionState.ACTIVE), because that will
  2302. // mess up video media direction in the remote SDP.
  2303. // 'content-modify' when processed only affects the media
  2304. // direction in the local SDP. We're doing that, because setting
  2305. // 'inactive' on video media in remote SDP will mess up our SDP
  2306. // translation chain (simulcast, RTX, video mute etc.).
  2307. if (this.isP2P && isSessionActive) {
  2308. this.sendContentModify();
  2309. }
  2310. }
  2311. const pcVideoActiveChanged
  2312. = this.peerconnection.setVideoTransferActive(
  2313. this._localVideoActive && this._remoteVideoActive);
  2314. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  2315. // direction
  2316. if (isSessionActive
  2317. && (audioActiveChanged || pcVideoActiveChanged)) {
  2318. this._renegotiate()
  2319. .then(
  2320. finishedCallback,
  2321. finishedCallback /* will be called with an error */);
  2322. } else {
  2323. finishedCallback();
  2324. }
  2325. };
  2326. return new Promise((resolve, reject) => {
  2327. this.modificationQueue.push(
  2328. workFunction,
  2329. error => {
  2330. if (error) {
  2331. logger.error(`${this} Make ${logVideoStr}, ${logAudioStr} task failed!`);
  2332. reject(error);
  2333. } else {
  2334. logger.debug(`${this} Make ${logVideoStr}, ${logAudioStr} task done!`);
  2335. resolve();
  2336. }
  2337. });
  2338. });
  2339. }
  2340. /**
  2341. * Will put and execute on the queue a session modify task. It checks if the sourceMaxFrameHeight (as requested by
  2342. * the p2p peer) or the senders attribute of the video content has changed and modifies the local video sources
  2343. * accordingly.
  2344. */
  2345. modifyContents(jingleContents) {
  2346. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  2347. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  2348. if (sourceMaxFrameHeights) {
  2349. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  2350. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  2351. }
  2352. if (newVideoSenders === null) {
  2353. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  2354. return;
  2355. }
  2356. const workFunction = finishedCallback => {
  2357. if (this._assertNotEnded() && this._modifyRemoteVideoActive(newVideoSenders)) {
  2358. // Will do the sRD/sLD cycle to update SDPs and adjust the media direction.
  2359. this._renegotiate()
  2360. .then(finishedCallback, finishedCallback /* (error) */);
  2361. } else {
  2362. finishedCallback();
  2363. }
  2364. };
  2365. logger.debug(`${this} queued "content-modify" task(video senders="${newVideoSenders}")`);
  2366. this.modificationQueue.push(
  2367. workFunction,
  2368. error => {
  2369. if (error) {
  2370. logger.error(`${this} "content-modify" failed`, error);
  2371. } else {
  2372. logger.debug(`${this} "content-modify" task(video senders="${newVideoSenders}") done`);
  2373. }
  2374. });
  2375. }
  2376. /**
  2377. * Processes new value of remote video "senders" Jingle attribute and tries
  2378. * to apply it for {@link _remoteVideoActive}.
  2379. * @param {string} remoteVideoSenders the value of "senders" attribute of
  2380. * Jingle video content element advertised by remote peer.
  2381. * @return {boolean} <tt>true</tt> if the change affected state of
  2382. * the underlying peerconnection and renegotiation is required for
  2383. * the changes to take effect.
  2384. * @private
  2385. */
  2386. _modifyRemoteVideoActive(remoteVideoSenders) {
  2387. const isRemoteVideoActive
  2388. = remoteVideoSenders === 'both'
  2389. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  2390. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  2391. if (isRemoteVideoActive !== this._remoteVideoActive) {
  2392. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  2393. this._remoteVideoActive = isRemoteVideoActive;
  2394. }
  2395. return this.peerconnection.setVideoTransferActive(this._localVideoActive && this._remoteVideoActive);
  2396. }
  2397. /**
  2398. * Figures out added/removed ssrcs and send update IQs.
  2399. * @param oldSDP SDP object for old description.
  2400. * @param newSDP SDP object for new description.
  2401. */
  2402. notifyMySSRCUpdate(oldSDP, newSDP) {
  2403. if (this.state !== JingleSessionState.ACTIVE) {
  2404. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  2405. return;
  2406. }
  2407. if (!this.connection.connected) {
  2408. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2409. if (!this._cachedOldLocalSdp) {
  2410. this._cachedOldLocalSdp = oldSDP;
  2411. }
  2412. this._cachedNewLocalSdp = newSDP;
  2413. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  2414. return;
  2415. }
  2416. this._cachedOldLocalSdp = undefined;
  2417. this._cachedNewLocalSdp = undefined;
  2418. const getSignaledSourceInfo = sdpDiffer => {
  2419. const newMedia = sdpDiffer.getNewMedia();
  2420. let ssrcs = [];
  2421. let mediaType = null;
  2422. // It is assumed that sources are signaled one at a time.
  2423. Object.keys(newMedia).forEach(mediaIndex => {
  2424. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  2425. mediaType = newMedia[mediaIndex].mid;
  2426. if (signaledSsrcs?.length) {
  2427. ssrcs = ssrcs.concat(signaledSsrcs);
  2428. }
  2429. });
  2430. return {
  2431. mediaType,
  2432. ssrcs
  2433. };
  2434. };
  2435. // send source-remove IQ.
  2436. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2437. const remove = $iq({ to: this.remoteJid,
  2438. type: 'set' })
  2439. .c('jingle', {
  2440. xmlns: 'urn:xmpp:jingle:1',
  2441. action: 'source-remove',
  2442. initiator: this.initiatorJid,
  2443. sid: this.sid
  2444. }
  2445. );
  2446. sdpDiffer.toJingle(remove);
  2447. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  2448. // need to
  2449. const ctx = {};
  2450. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2451. if (removedSsrcInfo.ssrcs.length) {
  2452. // Log only the SSRCs instead of the full IQ.
  2453. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  2454. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  2455. this.connection.sendIQ(
  2456. remove,
  2457. () => {
  2458. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  2459. },
  2460. this.newJingleErrorHandler(remove, error => {
  2461. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  2462. }),
  2463. IQ_TIMEOUT);
  2464. }
  2465. // send source-add IQ.
  2466. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2467. const add = $iq({ to: this.remoteJid,
  2468. type: 'set' })
  2469. .c('jingle', {
  2470. xmlns: 'urn:xmpp:jingle:1',
  2471. action: 'source-add',
  2472. initiator: this.initiatorJid,
  2473. sid: this.sid
  2474. }
  2475. );
  2476. sdpDiffer.toJingle(add);
  2477. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2478. if (addedSsrcInfo.ssrcs.length) {
  2479. // Log only the SSRCs instead of the full IQ.
  2480. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  2481. this.connection.sendIQ(
  2482. add,
  2483. () => {
  2484. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  2485. },
  2486. this.newJingleErrorHandler(add, error => {
  2487. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  2488. }),
  2489. IQ_TIMEOUT);
  2490. }
  2491. }
  2492. /**
  2493. * Method returns function(errorResponse) which is a callback to be passed
  2494. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2495. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2496. * structure is as follows:
  2497. * {
  2498. * code: {XMPP error response code}
  2499. * reason: {the name of XMPP error reason element or 'timeout' if the
  2500. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2501. * source: {request.tree() that provides original request}
  2502. * session: {this JingleSessionPC.toString()}
  2503. * }
  2504. * @param request Strophe IQ instance which is the request to be dumped into
  2505. * the error structure
  2506. * @param failureCb function(error) called when error response was returned
  2507. * or when a timeout has occurred.
  2508. * @returns {function(this:JingleSessionPC)}
  2509. */
  2510. newJingleErrorHandler(request, failureCb) {
  2511. return errResponse => {
  2512. const error = {};
  2513. // Get XMPP error code and condition(reason)
  2514. const errorElSel = $(errResponse).find('error');
  2515. if (errorElSel.length) {
  2516. error.code = errorElSel.attr('code');
  2517. const errorReasonSel = $(errResponse).find('error :first');
  2518. if (errorReasonSel.length) {
  2519. error.reason = errorReasonSel[0].tagName;
  2520. }
  2521. const errorMsgSel = errorElSel.find('>text');
  2522. if (errorMsgSel.length) {
  2523. error.msg = errorMsgSel.text();
  2524. }
  2525. }
  2526. if (!errResponse) {
  2527. error.reason = 'timeout';
  2528. }
  2529. error.session = this.toString();
  2530. if (failureCb) {
  2531. failureCb(error);
  2532. } else if (this.state === JingleSessionState.ENDED
  2533. && error.reason === 'item-not-found') {
  2534. // When remote peer decides to terminate the session, but it
  2535. // still have few messages on the queue for processing,
  2536. // it will first send us 'session-terminate' (we enter ENDED)
  2537. // and then follow with 'item-not-found' for the queued requests
  2538. // We don't want to have that logged on error level.
  2539. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  2540. } else {
  2541. GlobalOnErrorHandler.callErrorHandler(
  2542. new Error(
  2543. `Jingle error: ${JSON.stringify(error)}`));
  2544. }
  2545. };
  2546. }
  2547. /**
  2548. * Returns the ice connection state for the peer connection.
  2549. * @returns the ice connection state for the peer connection.
  2550. */
  2551. getIceConnectionState() {
  2552. return this.peerconnection.getConnectionState();
  2553. }
  2554. /**
  2555. * Closes the peerconnection.
  2556. */
  2557. close() {
  2558. this.state = JingleSessionState.ENDED;
  2559. this.establishmentDuration = undefined;
  2560. if (this.peerconnection) {
  2561. this.peerconnection.onicecandidate = null;
  2562. this.peerconnection.oniceconnectionstatechange = null;
  2563. this.peerconnection.onnegotiationneeded = null;
  2564. this.peerconnection.onsignalingstatechange = null;
  2565. }
  2566. logger.debug(`${this} Clearing modificationQueue`);
  2567. // Remove any pending tasks from the queue
  2568. this.modificationQueue.clear();
  2569. logger.debug(`${this} Queued PC close task`);
  2570. this.modificationQueue.push(finishCallback => {
  2571. // do not try to close if already closed.
  2572. this.peerconnection && this.peerconnection.close();
  2573. finishCallback();
  2574. logger.debug(`${this} PC close task done!`);
  2575. });
  2576. logger.debug(`${this} Shutdown modificationQueue!`);
  2577. // No more tasks can go in after the close task
  2578. this.modificationQueue.shutdown();
  2579. }
  2580. /**
  2581. * Converts to string with minor summary.
  2582. * @return {string}
  2583. */
  2584. toString() {
  2585. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2586. }
  2587. /**
  2588. * If the A/B test for suspend video is disabled according to the room's
  2589. * configuration, returns undefined. Otherwise returns a boolean which
  2590. * indicates whether the suspend video option should be enabled or disabled.
  2591. * @param {JingleSessionPCOptions} options - The config options.
  2592. */
  2593. _abtestSuspendVideoEnabled({ abTesting }) {
  2594. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2595. return;
  2596. }
  2597. // We want the two participants in a P2P call to agree on the value of
  2598. // the "suspend" option. We use the JID of the initiator, because it is
  2599. // both randomly selected and agreed upon by both participants.
  2600. return integerHash(this.initiatorJid) % 2 === 0;
  2601. }
  2602. }