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

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