Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JingleSessionPC.js 117KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973
  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.codecSettings = options.codecSettings;
  358. pcOptions.enableInsertableStreams = options.enableInsertableStreams;
  359. pcOptions.videoQuality = options.videoQuality;
  360. pcOptions.forceTurnRelay = options.forceTurnRelay;
  361. pcOptions.audioQuality = options.audioQuality;
  362. pcOptions.usesUnifiedPlan = this.usesUnifiedPlan
  363. = browser.supportsUnifiedPlan()
  364. && (!browser.isChromiumBased()
  365. || (browser.isChromiumBased()
  366. // Provide a way to control the behavior for jvb and p2p connections independently.
  367. && this.isP2P
  368. ? options.p2p?.enableUnifiedOnChrome ?? true
  369. : options.enableUnifiedOnChrome ?? true));
  370. if (this.isP2P) {
  371. // simulcast needs to be disabled for P2P (121) calls
  372. pcOptions.disableSimulcast = true;
  373. const abtestSuspendVideo = this._abtestSuspendVideoEnabled(options);
  374. if (typeof abtestSuspendVideo !== 'undefined') {
  375. pcOptions.abtestSuspendVideo = abtestSuspendVideo;
  376. }
  377. } else {
  378. // H264 scalability is not supported on jvb, so simulcast needs to be disabled when H264 is preferred.
  379. pcOptions.disableSimulcast
  380. = options.disableSimulcast || options.videoQuality?.preferredCodec === CodecMimeType.H264;
  381. // Do not send lower spatial layers for low fps screenshare and enable them only for high fps screenshare.
  382. pcOptions.capScreenshareBitrate = pcOptions.disableSimulcast
  383. || !(typeof options.desktopSharingFrameRate?.max === 'number'
  384. && options.desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE);
  385. }
  386. if (options.startSilent) {
  387. pcOptions.startSilent = true;
  388. }
  389. this.peerconnection
  390. = this.rtc.createPeerConnection(
  391. this._signalingLayer,
  392. this.pcConfig,
  393. this.isP2P,
  394. pcOptions);
  395. this.peerconnection.onicecandidate = ev => {
  396. if (!ev) {
  397. // There was an incomplete check for ev before which left
  398. // the last line of the function unprotected from a potential
  399. // throw of an exception. Consequently, it may be argued that
  400. // the check is unnecessary. Anyway, I'm leaving it and making
  401. // the check complete.
  402. return;
  403. }
  404. // XXX this is broken, candidate is not parsed.
  405. const candidate = ev.candidate;
  406. const now = window.performance.now();
  407. if (candidate) {
  408. if (this._gatheringStartedTimestamp === null) {
  409. this._gatheringStartedTimestamp = now;
  410. }
  411. // Discard candidates of disabled protocols.
  412. let protocol = candidate.protocol;
  413. if (typeof protocol === 'string') {
  414. protocol = protocol.toLowerCase();
  415. if (protocol === 'tcp' || protocol === 'ssltcp') {
  416. if (this.webrtcIceTcpDisable) {
  417. return;
  418. }
  419. } else if (protocol === 'udp') {
  420. if (this.webrtcIceUdpDisable) {
  421. return;
  422. }
  423. }
  424. }
  425. } else if (!this._gatheringReported) {
  426. // End of gathering
  427. Statistics.sendAnalytics(
  428. ICE_DURATION,
  429. {
  430. phase: 'gathering',
  431. value: now - this._gatheringStartedTimestamp,
  432. p2p: this.isP2P,
  433. initiator: this.isInitiator
  434. });
  435. this._gatheringReported = true;
  436. }
  437. if (this.isP2P) {
  438. this.sendIceCandidate(candidate);
  439. }
  440. };
  441. // Note there is a change in the spec about closed:
  442. // This value moved into the RTCPeerConnectionState enum in
  443. // the May 13, 2016 draft of the specification, as it reflects the state
  444. // of the RTCPeerConnection, not the signaling connection. You now
  445. // detect a closed connection by checking for connectionState to be
  446. // "closed" instead.
  447. // I suppose at some point this will be moved to onconnectionstatechange
  448. this.peerconnection.onsignalingstatechange = () => {
  449. if (this.peerconnection.signalingState === 'stable') {
  450. this.wasstable = true;
  451. } else if (this.peerconnection.signalingState === 'closed'
  452. || this.peerconnection.connectionState === 'closed') {
  453. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  454. }
  455. };
  456. /**
  457. * The oniceconnectionstatechange event handler contains the code to
  458. * execute when the iceconnectionstatechange event, of type Event,
  459. * is received by this RTCPeerConnection. Such an event is sent when
  460. * the value of RTCPeerConnection.iceConnectionState changes.
  461. */
  462. this.peerconnection.oniceconnectionstatechange = () => {
  463. const now = window.performance.now();
  464. let isStable = false;
  465. if (!this.isP2P) {
  466. this.room.connectionTimes[
  467. `ice.state.${this.peerconnection.iceConnectionState}`]
  468. = now;
  469. }
  470. logger.log(`(TIME) ICE ${this.peerconnection.iceConnectionState} ${this.isP2P ? 'P2P' : 'JVB'}:\t`, now);
  471. Statistics.sendAnalytics(
  472. ICE_STATE_CHANGED,
  473. {
  474. p2p: this.isP2P,
  475. state: this.peerconnection.iceConnectionState,
  476. 'signaling_state': this.peerconnection.signalingState,
  477. reconnect: this.isReconnect,
  478. value: now
  479. });
  480. this.room.eventEmitter.emit(
  481. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  482. this,
  483. this.peerconnection.iceConnectionState);
  484. switch (this.peerconnection.iceConnectionState) {
  485. case 'checking':
  486. this._iceCheckingStartedTimestamp = now;
  487. break;
  488. case 'connected':
  489. // Informs interested parties that the connection has been restored. This includes the case when
  490. // media connection to the bridge has been restored after an ICE failure by using session-terminate.
  491. if (this.peerconnection.signalingState === 'stable') {
  492. isStable = true;
  493. const usesTerminateForRestart = !this.options.enableIceRestart
  494. && this.room.supportsRestartByTerminate();
  495. if (this.isReconnect || usesTerminateForRestart) {
  496. this.room.eventEmitter.emit(
  497. XMPPEvents.CONNECTION_RESTORED, this);
  498. }
  499. }
  500. // Add a workaround for an issue on chrome in Unified plan when the local endpoint is the offerer.
  501. // The 'signalingstatechange' event for 'stable' is handled after the 'iceconnectionstatechange' event
  502. // for 'completed' is handled by the client. This prevents the client from firing a
  503. // CONNECTION_ESTABLISHED event for the p2p session. As a result, the offerer continues to stay on the
  504. // jvb connection while the remote peer switches to the p2p connection breaking the media flow between
  505. // the endpoints.
  506. // TODO - file a chromium bug and add the information here.
  507. if (!this.wasConnected
  508. && (this.wasstable
  509. || isStable
  510. || (this.usesUnifiedPlan && this.isInitiator
  511. && (browser.isChromiumBased() || browser.isReactNative())))) {
  512. Statistics.sendAnalytics(
  513. ICE_DURATION,
  514. {
  515. phase: 'checking',
  516. value: now - this._iceCheckingStartedTimestamp,
  517. p2p: this.isP2P,
  518. initiator: this.isInitiator
  519. });
  520. // Switch between ICE gathering and ICE checking whichever
  521. // started first (scenarios are different for initiator
  522. // vs responder)
  523. const iceStarted
  524. = Math.min(
  525. this._iceCheckingStartedTimestamp,
  526. this._gatheringStartedTimestamp);
  527. this.establishmentDuration = now - iceStarted;
  528. Statistics.sendAnalytics(
  529. ICE_DURATION,
  530. {
  531. phase: 'establishment',
  532. value: this.establishmentDuration,
  533. p2p: this.isP2P,
  534. initiator: this.isInitiator
  535. });
  536. this.wasConnected = true;
  537. this.room.eventEmitter.emit(
  538. XMPPEvents.CONNECTION_ESTABLISHED, this);
  539. }
  540. this.isReconnect = false;
  541. break;
  542. case 'disconnected':
  543. this.isReconnect = true;
  544. // Informs interested parties that the connection has been
  545. // interrupted.
  546. if (this.wasstable) {
  547. this.room.eventEmitter.emit(
  548. XMPPEvents.CONNECTION_INTERRUPTED, this);
  549. }
  550. break;
  551. case 'failed':
  552. this.room.eventEmitter.emit(
  553. XMPPEvents.CONNECTION_ICE_FAILED, this);
  554. break;
  555. }
  556. };
  557. /**
  558. * The connection state event is fired whenever the aggregate of underlying
  559. * transports change their state.
  560. */
  561. this.peerconnection.onconnectionstatechange = () => {
  562. const icestate = this.peerconnection.iceConnectionState;
  563. switch (this.peerconnection.connectionState) {
  564. case 'failed':
  565. // Since version 76 Chrome no longer switches ICE connection
  566. // state to failed (see
  567. // https://bugs.chromium.org/p/chromium/issues/detail?id=982793
  568. // for details) we use this workaround to recover from lost connections
  569. if (icestate === 'disconnected') {
  570. this.room.eventEmitter.emit(
  571. XMPPEvents.CONNECTION_ICE_FAILED, this);
  572. }
  573. break;
  574. }
  575. };
  576. /**
  577. * The negotiationneeded event is fired whenever we shake the media on the
  578. * RTCPeerConnection object.
  579. */
  580. this.peerconnection.onnegotiationneeded = () => {
  581. const state = this.peerconnection.signalingState;
  582. const remoteDescription = this.peerconnection.remoteDescription;
  583. if (this.usesUnifiedPlan
  584. && !this.isP2P
  585. && state === 'stable'
  586. && remoteDescription
  587. && typeof remoteDescription.sdp === 'string') {
  588. logger.info(`${this} onnegotiationneeded fired on ${this.peerconnection}`);
  589. const workFunction = finishedCallback => {
  590. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  591. this._renegotiate()
  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 = new SDP(this.peerconnection.localDescription.sdp);
  1179. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1180. localSDP.initialLastN = this.options.channelLastN;
  1181. }
  1182. this.sendTransportAccept(localSDP, success, failure);
  1183. this.room.eventEmitter.emit(
  1184. XMPPEvents.ICE_RESTART_SUCCESS,
  1185. this,
  1186. originalOffer);
  1187. },
  1188. failure);
  1189. },
  1190. failure
  1191. );
  1192. }
  1193. /**
  1194. * Sends Jingle 'session-accept' message.
  1195. * @param {function()} success callback called when we receive 'RESULT'
  1196. * packet for the 'session-accept'
  1197. * @param {function(error)} failure called when we receive an error response
  1198. * or when the request has timed out.
  1199. * @private
  1200. */
  1201. sendSessionAccept(success, failure) {
  1202. // NOTE: since we're just reading from it, we don't need to be within
  1203. // the modification queue to access the local description
  1204. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1205. const accept = $iq({ to: this.remoteJid,
  1206. type: 'set' })
  1207. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1208. action: 'session-accept',
  1209. initiator: this.initiatorJid,
  1210. responder: this.responderJid,
  1211. sid: this.sid });
  1212. if (this.webrtcIceTcpDisable) {
  1213. localSDP.removeTcpCandidates = true;
  1214. }
  1215. if (this.webrtcIceUdpDisable) {
  1216. localSDP.removeUdpCandidates = true;
  1217. }
  1218. if (this.failICE) {
  1219. localSDP.failICE = true;
  1220. }
  1221. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1222. localSDP.initialLastN = this.options.channelLastN;
  1223. }
  1224. localSDP.toJingle(
  1225. accept,
  1226. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1227. logger.info(`${this} Sending session-accept`);
  1228. logger.debug(accept.tree());
  1229. this.connection.sendIQ(accept,
  1230. success,
  1231. this.newJingleErrorHandler(accept, error => {
  1232. failure(error);
  1233. // 'session-accept' is a critical timeout and we'll
  1234. // have to restart
  1235. this.room.eventEmitter.emit(
  1236. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1237. }),
  1238. IQ_TIMEOUT);
  1239. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1240. // fingerprint and setup) ASAP in order to start the connection
  1241. // establishment.
  1242. //
  1243. // FIXME Flushing the connection at this point triggers an issue with
  1244. // BOSH request handling in Prosody on slow connections.
  1245. //
  1246. // The problem is that this request will be quite large and it may take
  1247. // time before it reaches Prosody. In the meantime Strophe may decide
  1248. // to send the next one. And it was observed that a small request with
  1249. // 'transport-info' usually follows this one. It does reach Prosody
  1250. // before the previous one was completely received. 'rid' on the server
  1251. // is increased and Prosody ignores the request with 'session-accept'.
  1252. // It will never reach Jicofo and everything in the request table is
  1253. // lost. Removing the flush does not guarantee it will never happen, but
  1254. // makes it much less likely('transport-info' is bundled with
  1255. // 'session-accept' and any immediate requests).
  1256. //
  1257. // this.connection.flush();
  1258. }
  1259. /**
  1260. * Will send 'content-modify' IQ in order to ask the remote peer to
  1261. * either stop or resume sending video media or to adjust sender's video constraints.
  1262. * @private
  1263. */
  1264. sendContentModify() {
  1265. const senders = this._localVideoActive ? 'both' : 'none';
  1266. const sessionModify
  1267. = $iq({
  1268. to: this.remoteJid,
  1269. type: 'set'
  1270. })
  1271. .c('jingle', {
  1272. xmlns: 'urn:xmpp:jingle:1',
  1273. action: 'content-modify',
  1274. initiator: this.initiatorJid,
  1275. sid: this.sid
  1276. })
  1277. .c('content', {
  1278. name: MediaType.VIDEO,
  1279. senders
  1280. });
  1281. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  1282. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  1283. sessionModify
  1284. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1285. .attrs({
  1286. sourceName,
  1287. maxHeight
  1288. });
  1289. sessionModify.up();
  1290. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  1291. });
  1292. }
  1293. logger.debug(sessionModify.tree());
  1294. this.connection.sendIQ(
  1295. sessionModify,
  1296. null,
  1297. this.newJingleErrorHandler(sessionModify),
  1298. IQ_TIMEOUT);
  1299. }
  1300. /**
  1301. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1302. * the remote p2p peer.
  1303. *
  1304. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1305. */
  1306. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1307. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1308. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1309. if (this.isP2P) {
  1310. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1311. // be synced after offer/answer.
  1312. if (this.state === JingleSessionState.ACTIVE) {
  1313. this.sendContentModify();
  1314. }
  1315. }
  1316. }
  1317. /**
  1318. * Sends Jingle 'transport-accept' message which is a response to
  1319. * 'transport-replace'.
  1320. * @param localSDP the 'SDP' object with local session description
  1321. * @param success callback called when we receive 'RESULT' packet for
  1322. * 'transport-replace'
  1323. * @param failure function(error) called when we receive an error response
  1324. * or when the request has timed out.
  1325. * @private
  1326. */
  1327. sendTransportAccept(localSDP, success, failure) {
  1328. const transportAccept = $iq({ to: this.remoteJid,
  1329. type: 'set' })
  1330. .c('jingle', {
  1331. xmlns: 'urn:xmpp:jingle:1',
  1332. action: 'transport-accept',
  1333. initiator: this.initiatorJid,
  1334. sid: this.sid
  1335. });
  1336. localSDP.media.forEach((medialines, idx) => {
  1337. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1338. transportAccept.c('content',
  1339. {
  1340. creator:
  1341. this.initiatorJid === this.localJid
  1342. ? 'initiator'
  1343. : 'responder',
  1344. name: mline.media
  1345. }
  1346. );
  1347. localSDP.transportToJingle(idx, transportAccept);
  1348. transportAccept.up();
  1349. });
  1350. logger.info(`${this} Sending transport-accept`);
  1351. logger.debug(transportAccept.tree());
  1352. this.connection.sendIQ(transportAccept,
  1353. success,
  1354. this.newJingleErrorHandler(transportAccept, failure),
  1355. IQ_TIMEOUT);
  1356. }
  1357. /**
  1358. * Sends Jingle 'transport-reject' message which is a response to
  1359. * 'transport-replace'.
  1360. * @param success callback called when we receive 'RESULT' packet for
  1361. * 'transport-replace'
  1362. * @param failure function(error) called when we receive an error response
  1363. * or when the request has timed out.
  1364. *
  1365. * FIXME method should be marked as private, but there's some spaghetti that
  1366. * needs to be fixed prior doing that
  1367. */
  1368. sendTransportReject(success, failure) {
  1369. // Send 'transport-reject', so that the focus will
  1370. // know that we've failed
  1371. const transportReject = $iq({ to: this.remoteJid,
  1372. type: 'set' })
  1373. .c('jingle', {
  1374. xmlns: 'urn:xmpp:jingle:1',
  1375. action: 'transport-reject',
  1376. initiator: this.initiatorJid,
  1377. sid: this.sid
  1378. });
  1379. logger.info(`${this} Sending 'transport-reject'`);
  1380. logger.debug(transportReject.tree());
  1381. this.connection.sendIQ(transportReject,
  1382. success,
  1383. this.newJingleErrorHandler(transportReject, failure),
  1384. IQ_TIMEOUT);
  1385. }
  1386. /**
  1387. * Sets the resolution constraint on the local camera track.
  1388. * @param {number} maxFrameHeight - The user preferred max frame height.
  1389. * @param {string} sourceName - The source name of the track.
  1390. * @returns {Promise} promise that will be resolved when the operation is
  1391. * successful and rejected otherwise.
  1392. */
  1393. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1394. if (this._assertNotEnded()) {
  1395. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1396. const jitsiLocalTrack = sourceName
  1397. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1398. : this.rtc.getLocalVideoTrack();
  1399. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1400. }
  1401. return Promise.resolve();
  1402. }
  1403. /**
  1404. * @inheritDoc
  1405. */
  1406. terminate(success, failure, options) {
  1407. if (this.state === JingleSessionState.ENDED) {
  1408. return;
  1409. }
  1410. if (!options || Boolean(options.sendSessionTerminate)) {
  1411. const sessionTerminate
  1412. = $iq({
  1413. to: this.remoteJid,
  1414. type: 'set'
  1415. })
  1416. .c('jingle', {
  1417. xmlns: 'urn:xmpp:jingle:1',
  1418. action: 'session-terminate',
  1419. initiator: this.initiatorJid,
  1420. sid: this.sid
  1421. })
  1422. .c('reason')
  1423. .c((options && options.reason) || 'success')
  1424. .up();
  1425. if (options && options.reasonDescription) {
  1426. sessionTerminate
  1427. .c('text')
  1428. .t(options.reasonDescription)
  1429. .up()
  1430. .up();
  1431. } else {
  1432. sessionTerminate.up();
  1433. }
  1434. this._bridgeSessionId
  1435. && sessionTerminate.c(
  1436. 'bridge-session', {
  1437. xmlns: 'http://jitsi.org/protocol/focus',
  1438. id: this._bridgeSessionId,
  1439. restart: options && options.requestRestart === true
  1440. }).up();
  1441. logger.info(`${this} Sending session-terminate`);
  1442. logger.debug(sessionTerminate.tree());
  1443. this.connection.sendIQ(
  1444. sessionTerminate,
  1445. success,
  1446. this.newJingleErrorHandler(sessionTerminate, failure),
  1447. IQ_TIMEOUT);
  1448. } else {
  1449. logger.info(`${this} Skipped sending session-terminate`);
  1450. }
  1451. // this should result in 'onTerminated' being called by strope.jingle.js
  1452. this.connection.jingle.terminate(this.sid);
  1453. }
  1454. /**
  1455. *
  1456. * @param reasonCondition
  1457. * @param reasonText
  1458. */
  1459. onTerminated(reasonCondition, reasonText) {
  1460. // Do something with reason and reasonCondition when we start to care
  1461. // this.reasonCondition = reasonCondition;
  1462. // this.reasonText = reasonText;
  1463. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1464. this._xmppListeners.forEach(removeListener => removeListener());
  1465. this._xmppListeners = [];
  1466. if (this._removeSenderVideoConstraintsChangeListener) {
  1467. this._removeSenderVideoConstraintsChangeListener();
  1468. }
  1469. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1470. this.peerconnection.getRemoteTracks().forEach(track => {
  1471. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1472. });
  1473. }
  1474. this.close();
  1475. }
  1476. /**
  1477. * Handles XMPP connection state changes.
  1478. *
  1479. * @param {XmppConnection.Status} status - The new status.
  1480. */
  1481. onXmppStatusChanged(status) {
  1482. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1483. logger.info(`${this} Sending SSRC update on reconnect`);
  1484. this.notifyMySSRCUpdate(
  1485. this._cachedOldLocalSdp,
  1486. this._cachedNewLocalSdp);
  1487. }
  1488. }
  1489. /**
  1490. * Parse the information from the xml sourceAddElem and translate it
  1491. * into sdp lines
  1492. * @param {jquery xml element} sourceAddElem the source-add
  1493. * element from jingle
  1494. * @param {SDP object} currentRemoteSdp the current remote
  1495. * sdp (as of this new source-add)
  1496. * @returns {list} a list of SDP line strings that should
  1497. * be added to the remote SDP
  1498. */
  1499. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1500. const addSsrcInfo = [];
  1501. const self = this;
  1502. $(sourceAddElem).each((i1, content) => {
  1503. const name = $(content).attr('name');
  1504. let lines = '';
  1505. $(content)
  1506. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1507. .each(function() {
  1508. // eslint-disable-next-line no-invalid-this
  1509. const semantics = this.getAttribute('semantics');
  1510. const ssrcs
  1511. = $(this) // eslint-disable-line no-invalid-this
  1512. .find('>source')
  1513. .map(function() {
  1514. // eslint-disable-next-line no-invalid-this
  1515. return this.getAttribute('ssrc');
  1516. })
  1517. .get();
  1518. if (ssrcs.length) {
  1519. lines += `a=ssrc-group:${semantics} ${ssrcs.join(' ')}\r\n`;
  1520. }
  1521. });
  1522. // handles both >source and >description>source
  1523. const tmp
  1524. = $(content).find(
  1525. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1526. /* eslint-disable no-invalid-this */
  1527. tmp.each(function() {
  1528. const ssrc = $(this).attr('ssrc');
  1529. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1530. // Do not print the warning for unified plan p2p case since ssrcs are never removed from the SDP.
  1531. !(self.usesUnifiedPlan && self.isP2P)
  1532. && logger.warn(`${self} Source-add request for existing SSRC: ${ssrc}`);
  1533. return;
  1534. }
  1535. // eslint-disable-next-line newline-per-chained-call
  1536. $(this).find('>parameter').each(function() {
  1537. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1538. if ($(this).attr('value') && $(this).attr('value').length) {
  1539. lines += `:${$(this).attr('value')}`;
  1540. }
  1541. lines += '\r\n';
  1542. });
  1543. });
  1544. let midFound = false;
  1545. /* eslint-enable no-invalid-this */
  1546. currentRemoteSdp.media.forEach((media, i2) => {
  1547. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1548. return;
  1549. }
  1550. if (!addSsrcInfo[i2]) {
  1551. addSsrcInfo[i2] = '';
  1552. }
  1553. addSsrcInfo[i2] += lines;
  1554. midFound = true;
  1555. });
  1556. // In p2p unified mode with multi-stream enabled, the new sources will have content name that doesn't exist
  1557. // in the current remote description. Add a new m-line for this newly signaled source.
  1558. if (!midFound && this.isP2P) {
  1559. addSsrcInfo[name] = lines;
  1560. }
  1561. });
  1562. return addSsrcInfo;
  1563. }
  1564. /**
  1565. * Handles a Jingle source-add message for this Jingle session.
  1566. * @param elem An array of Jingle "content" elements.
  1567. */
  1568. addRemoteStream(elem) {
  1569. this._addOrRemoveRemoteStream(true /* add */, elem);
  1570. }
  1571. /**
  1572. * Handles a Jingle source-remove message for this Jingle session.
  1573. * @param elem An array of Jingle "content" elements.
  1574. */
  1575. removeRemoteStream(elem) {
  1576. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1577. }
  1578. /**
  1579. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1580. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1581. *
  1582. * @param {Object} message - The source map message.
  1583. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1584. * @returns {void}
  1585. */
  1586. processSourceMap(message, mediaType) {
  1587. const newSources = [];
  1588. for (const src of message.mappedSources) {
  1589. if (this.peerconnection.addRemoteSsrc(src.ssrc)) {
  1590. newSources.push(src);
  1591. } else {
  1592. const { owner, source, ssrc, videoType } = src;
  1593. const track = this.peerconnection.getTrackBySSRC(ssrc);
  1594. if (track) {
  1595. logger.debug(`Existing SSRC ${ssrc}: new owner=${owner}, source-name=${source}`);
  1596. // Update the SSRC owner.
  1597. this._signalingLayer.setSSRCOwner(ssrc, owner);
  1598. // Update the track with all the relevant info.
  1599. track.setSourceName(source);
  1600. track.setOwner(owner);
  1601. if (mediaType === MediaType.VIDEO) {
  1602. const type = videoType === 'CAMERA' ? VideoType.CAMERA : VideoType.DESKTOP;
  1603. track._setVideoType(type);
  1604. }
  1605. } else {
  1606. logger.error(`Remote track attached to a remote SSRC=${ssrc} not found`);
  1607. }
  1608. }
  1609. }
  1610. // Add the new SSRCs to the remote description by generating a source message.
  1611. if (newSources.length) {
  1612. let node = $build('content', {
  1613. xmlns: 'urn:xmpp:jingle:1',
  1614. name: mediaType
  1615. }).c('description', {
  1616. xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  1617. media: mediaType
  1618. });
  1619. for (const src of newSources) {
  1620. const { rtx, ssrc } = src;
  1621. let msid;
  1622. if (mediaType === MediaType.VIDEO) {
  1623. const idx = ++this.numRemoteVideoSources;
  1624. msid = `remote-video-${idx} remote-video-${idx}`;
  1625. if (rtx !== '-1') {
  1626. _addSourceElement(node, src, rtx, msid);
  1627. node.c('ssrc-group', {
  1628. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1629. semantics: 'FID'
  1630. })
  1631. .c('source', {
  1632. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1633. ssrc
  1634. })
  1635. .up()
  1636. .c('source', {
  1637. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1638. ssrc: rtx
  1639. })
  1640. .up()
  1641. .up();
  1642. }
  1643. } else {
  1644. const idx = ++this.numRemoteAudioSources;
  1645. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1646. }
  1647. _addSourceElement(node, src, ssrc, msid);
  1648. }
  1649. node = node.up();
  1650. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1651. }
  1652. }
  1653. /**
  1654. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1655. *
  1656. * @param {string} id Endpoint id of the participant that has left the call.
  1657. * @returns {void}
  1658. */
  1659. removeRemoteStreamsOnLeave(id) {
  1660. const workFunction = finishCallback => {
  1661. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1662. if (removeSsrcInfo.length) {
  1663. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1664. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1665. this._renegotiate(newRemoteSdp.raw)
  1666. .then(() => {
  1667. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1668. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSDP);
  1669. finishCallback();
  1670. })
  1671. .catch(err => finishCallback(err));
  1672. } else {
  1673. finishCallback();
  1674. }
  1675. };
  1676. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1677. this.modificationQueue.push(
  1678. workFunction,
  1679. error => {
  1680. if (error) {
  1681. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1682. } else {
  1683. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1684. }
  1685. });
  1686. }
  1687. /**
  1688. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1689. * Jingle session.
  1690. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1691. * otherwise.
  1692. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1693. * @private
  1694. */
  1695. _addOrRemoveRemoteStream(isAdd, elem) {
  1696. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1697. if (isAdd) {
  1698. this.readSsrcInfo(elem);
  1699. }
  1700. const workFunction = finishedCallback => {
  1701. if (!this.peerconnection.localDescription
  1702. || !this.peerconnection.localDescription.sdp) {
  1703. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1704. logger.error(errMsg);
  1705. finishedCallback(errMsg);
  1706. return;
  1707. }
  1708. logger.log(`${this} Processing ${logPrefix}`);
  1709. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1710. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1711. const addOrRemoveSsrcInfo
  1712. = isAdd
  1713. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1714. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1715. const newRemoteSdp
  1716. = isAdd
  1717. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1718. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1719. const remoteDescription = new RTCSessionDescription({
  1720. type: 'offer',
  1721. sdp: newRemoteSdp.raw
  1722. });
  1723. // Always initiate a sRD->cA->sLD cycle when a remote source is added or removed irrespective of whether
  1724. // the local endpoint is an initiator or responder. Fixes bugs on Chromium where decoders are not created
  1725. // when sLD->cO->sRD cycle is initiated for p2p cases when remote sources are received.
  1726. this._responderRenegotiate(remoteDescription).then(() => {
  1727. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1728. logger.log(`${this} ${logPrefix} - OK`);
  1729. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1730. finishedCallback();
  1731. }, error => {
  1732. logger.error(`${this} ${logPrefix} failed:`, error);
  1733. finishedCallback(error);
  1734. });
  1735. };
  1736. logger.debug(`${this} Queued ${logPrefix} task`);
  1737. // Queue and execute
  1738. this.modificationQueue.push(workFunction);
  1739. }
  1740. /**
  1741. * Takes in a jingle offer iq, returns the new sdp offer
  1742. * @param {jquery xml element} offerIq the incoming offer
  1743. * @returns {SDP object} the jingle offer translated to SDP
  1744. */
  1745. _processNewJingleOfferIq(offerIq) {
  1746. const remoteSdp = new SDP('');
  1747. if (this.webrtcIceTcpDisable) {
  1748. remoteSdp.removeTcpCandidates = true;
  1749. }
  1750. if (this.webrtcIceUdpDisable) {
  1751. remoteSdp.removeUdpCandidates = true;
  1752. }
  1753. if (this.failICE) {
  1754. remoteSdp.failICE = true;
  1755. }
  1756. remoteSdp.fromJingle(offerIq);
  1757. this.readSsrcInfo($(offerIq).find('>content'));
  1758. return remoteSdp;
  1759. }
  1760. /**
  1761. * Remove the given ssrc lines from the current remote sdp
  1762. * @param {list} removeSsrcInfo a list of SDP line strings that
  1763. * should be removed from the remote SDP
  1764. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1765. * in removeSsrcInfo
  1766. */
  1767. _processRemoteRemoveSource(removeSsrcInfo) {
  1768. const remoteSdp = this.usesUnifiedPlan
  1769. ? new SDP(this.peerconnection.peerconnection.remoteDescription.sdp)
  1770. : new SDP(this.peerconnection.remoteDescription.sdp);
  1771. let ssrcs;
  1772. removeSsrcInfo.forEach((lines, idx) => {
  1773. // eslint-disable-next-line no-param-reassign
  1774. lines = lines.split('\r\n');
  1775. lines.pop(); // remove empty last element;
  1776. ssrcs = lines.map(line => Number(line.split('a=ssrc:')[1]?.split(' ')[0]));
  1777. if (this.usesUnifiedPlan) {
  1778. let mid;
  1779. lines.forEach(line => {
  1780. mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1781. if (mid > -1) {
  1782. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1783. if (this.isP2P) {
  1784. const mediaType = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0])?.media;
  1785. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, false);
  1786. [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ].forEach(direction => {
  1787. remoteSdp.media[mid] = remoteSdp.media[mid]
  1788. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1789. });
  1790. } else {
  1791. // Jvb connections will have direction set to 'sendonly' for the remote sources.
  1792. remoteSdp.media[mid] = remoteSdp.media[mid]
  1793. .replace(`a=${MediaDirection.SENDONLY}`, `a=${MediaDirection.INACTIVE}`);
  1794. }
  1795. }
  1796. });
  1797. // Reject the m-line so that the browser removes the associated transceiver from the list of available
  1798. // transceivers. This will prevent the client from trying to re-use these inactive transceivers when
  1799. // additional video sources are added to the peerconnection.
  1800. if (mid > -1 && !this.isP2P && FeatureFlags.isMultiStreamSendSupportEnabled()) {
  1801. const { media, port } = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0]);
  1802. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`m=${media} ${port}`, `m=${media} 0`);
  1803. }
  1804. } else {
  1805. lines.forEach(line => {
  1806. remoteSdp.media[idx] = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1807. });
  1808. }
  1809. });
  1810. // Update the ssrc owners list.
  1811. ssrcs?.length && this._signalingLayer.removeSSRCOwners(ssrcs);
  1812. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1813. return remoteSdp;
  1814. }
  1815. /**
  1816. * Add the given ssrc lines to the current remote sdp
  1817. * @param {list} addSsrcInfo a list of SDP line strings that
  1818. * should be added to the remote SDP
  1819. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1820. * in removeSsrcInfo
  1821. */
  1822. _processRemoteAddSource(addSsrcInfo) {
  1823. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1824. // Add a new m-line in the remote description if the source info for a secondary video source is recceived from
  1825. // the remote p2p peer when multi-stream support is enabled.
  1826. if (addSsrcInfo.length > remoteSdp.media.length
  1827. && this.isP2P
  1828. && this.usesUnifiedPlan) {
  1829. remoteSdp.addMlineForNewLocalSource(MediaType.VIDEO);
  1830. remoteSdp = new SDP(remoteSdp.raw);
  1831. }
  1832. addSsrcInfo.forEach((lines, idx) => {
  1833. remoteSdp.media[idx] += lines;
  1834. // Make sure to change the direction to 'sendrecv/sendonly' only for p2p connections. For jvb connections,
  1835. // a new m-line is added for the new remote sources.
  1836. if (this.isP2P && this.usesUnifiedPlan) {
  1837. const mediaType = SDPUtil.parseMLine(remoteSdp.media[idx].split('\r\n')[0])?.media;
  1838. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, true);
  1839. [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ].forEach(direction => {
  1840. remoteSdp.media[idx] = remoteSdp.media[idx]
  1841. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1842. });
  1843. }
  1844. });
  1845. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1846. return remoteSdp;
  1847. }
  1848. /**
  1849. * Do a new o/a flow using the existing remote description
  1850. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1851. * to use. If not provided, the remote sdp from the
  1852. * peerconnection will be used
  1853. * @returns {Promise} promise which resolves when the
  1854. * o/a flow is complete with no arguments or
  1855. * rejects with an error {string}
  1856. */
  1857. _renegotiate(optionalRemoteSdp) {
  1858. if (this.peerconnection.signalingState === 'closed') {
  1859. const error = new Error('Attempted to renegotiate in state closed');
  1860. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1861. return Promise.reject(error);
  1862. }
  1863. const remoteSdp
  1864. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1865. if (!remoteSdp) {
  1866. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1867. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1868. return Promise.reject(error);
  1869. }
  1870. const remoteDescription = new RTCSessionDescription({
  1871. type: this.isInitiator ? 'answer' : 'offer',
  1872. sdp: remoteSdp
  1873. });
  1874. if (this.isInitiator) {
  1875. return this._initiatorRenegotiate(remoteDescription);
  1876. }
  1877. return this._responderRenegotiate(remoteDescription);
  1878. }
  1879. /**
  1880. * Renegotiate cycle implementation for the responder case.
  1881. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1882. * which will be used as remote description in the cycle.
  1883. * @private
  1884. */
  1885. _responderRenegotiate(remoteDescription) {
  1886. logger.debug(`${this} Renegotiate: setting remote description`);
  1887. return this.peerconnection.setRemoteDescription(remoteDescription)
  1888. .then(() => {
  1889. logger.debug(`${this} Renegotiate: creating answer`);
  1890. return this.peerconnection.createAnswer(this.mediaConstraints)
  1891. .then(answer => {
  1892. logger.debug(`${this} Renegotiate: setting local description`);
  1893. return this.peerconnection.setLocalDescription(answer);
  1894. });
  1895. });
  1896. }
  1897. /**
  1898. * Renegotiate cycle implementation for the initiator's case.
  1899. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1900. * which will be used as remote description in the cycle.
  1901. * @private
  1902. */
  1903. _initiatorRenegotiate(remoteDescription) {
  1904. logger.debug(`${this} Renegotiate: creating offer`);
  1905. return this.peerconnection.createOffer(this.mediaConstraints)
  1906. .then(offer => {
  1907. logger.debug(`${this} Renegotiate: setting local description`);
  1908. return this.peerconnection.setLocalDescription(offer)
  1909. .then(() => {
  1910. logger.debug(`${this} Renegotiate: setting remote description`);
  1911. // eslint-disable-next-line max-len
  1912. return this.peerconnection.setRemoteDescription(remoteDescription);
  1913. });
  1914. });
  1915. }
  1916. /**
  1917. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  1918. * being added to the peerconnection for the first time.
  1919. *
  1920. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  1921. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  1922. * otherwise.
  1923. */
  1924. addTracks(localTracks = null) {
  1925. if (!FeatureFlags.isMultiStreamSendSupportEnabled()
  1926. || !localTracks?.length
  1927. || localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  1928. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  1929. }
  1930. const replaceTracks = [];
  1931. const workFunction = finishedCallback => {
  1932. const oldLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1933. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1934. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  1935. .find(t => t.receiver.track.kind === MediaType.VIDEO
  1936. && t.direction === MediaDirection.RECVONLY
  1937. && t.currentDirection === MediaDirection.RECVONLY);
  1938. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  1939. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  1940. // existing one in that case.
  1941. for (const track of localTracks) {
  1942. if (!this.isP2P || !recvOnlyTransceiver) {
  1943. remoteSdp.addMlineForNewLocalSource(track.getType());
  1944. }
  1945. }
  1946. const remoteDescription = new RTCSessionDescription({
  1947. type: 'offer',
  1948. sdp: remoteSdp.raw
  1949. });
  1950. // Always initiate a responder renegotiate since the new m-line is added to remote SDP.
  1951. this._responderRenegotiate(remoteDescription)
  1952. .then(() => {
  1953. // Replace the tracks on the newly generated transceivers.
  1954. for (const track of localTracks) {
  1955. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  1956. }
  1957. return Promise.all(replaceTracks);
  1958. })
  1959. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  1960. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  1961. .then(() => this._renegotiate())
  1962. .then(() => {
  1963. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1964. // Signal the new sources to the peer.
  1965. this.notifyMySSRCUpdate(oldLocalSDP, newLocalSDP);
  1966. finishedCallback();
  1967. })
  1968. .catch(error => finishedCallback(error));
  1969. };
  1970. return new Promise((resolve, reject) => {
  1971. logger.debug(`${this} Queued renegotiation after addTrack`);
  1972. this.modificationQueue.push(
  1973. workFunction,
  1974. error => {
  1975. if (error) {
  1976. logger.error(`${this} renegotiation after addTrack error`, error);
  1977. reject(error);
  1978. } else {
  1979. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1980. resolve();
  1981. }
  1982. });
  1983. });
  1984. }
  1985. /**
  1986. * Resumes or suspends media transfer over the underlying peer connection.
  1987. *
  1988. * @param {boolean} active - <tt>true</tt> to enable media transfer or <tt>false</tt> to suspend media transmission
  1989. * @returns {Promise}
  1990. */
  1991. setMediaTransferActive(active) {
  1992. return this.peerconnection.tpcUtils.setMediaTransferActive(active)
  1993. .then(() => {
  1994. this.peerconnection.audioTransferActive = active;
  1995. this.peerconnection.videoTransferActive = active;
  1996. });
  1997. }
  1998. /**
  1999. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  2000. * offer/answer cycle after both operations are done. Either
  2001. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  2002. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  2003. * <tt>oldTrack</tt>
  2004. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  2005. * replaced
  2006. * @param {JitsiLocalTrack|null} newTrack the new track to use
  2007. * @returns {Promise} which resolves once the replacement is complete
  2008. * with no arguments or rejects with an error {string}
  2009. */
  2010. replaceTrack(oldTrack, newTrack) {
  2011. const workFunction = finishedCallback => {
  2012. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  2013. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  2014. if (!this.usesUnifiedPlan) {
  2015. // NOTE the code below assumes that no more than 1 video track
  2016. // can be added to the peer connection.
  2017. // Transition from camera to desktop share
  2018. // or transition from one camera source to another.
  2019. if (this.peerconnection.options.capScreenshareBitrate
  2020. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  2021. // Clearing current primary SSRC will make
  2022. // the SdpConsistency generate a new one which will result
  2023. // with:
  2024. // 1. source-remove for the old video stream.
  2025. // 2. source-add for the new video stream.
  2026. this.peerconnection.clearRecvonlySsrc();
  2027. }
  2028. // Transition from no video to video (unmute).
  2029. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  2030. // Clearing current primary SSRC will make
  2031. // the SdpConsistency generate a new one which will result
  2032. // with:
  2033. // 1. source-remove for the recvonly
  2034. // 2. source-add for the new video stream
  2035. this.peerconnection.clearRecvonlySsrc();
  2036. // Transition from video to no video
  2037. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  2038. // Clearing current primary SSRC and generating the recvonly
  2039. // will result in:
  2040. // 1. source-remove for the old video stream
  2041. // 2. source-add for the recvonly stream
  2042. this.peerconnection.clearRecvonlySsrc();
  2043. this.peerconnection.generateRecvonlySsrc();
  2044. }
  2045. }
  2046. this.peerconnection.replaceTrack(oldTrack, newTrack)
  2047. .then(shouldRenegotiate => {
  2048. let promise = Promise.resolve();
  2049. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  2050. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  2051. if (shouldRenegotiate
  2052. && (oldTrack || newTrack)
  2053. && this.state === JingleSessionState.ACTIVE) {
  2054. const remoteSdp = this.peerconnection.remoteDescription.sdp;
  2055. const remoteDescription = new RTCSessionDescription({
  2056. type: 'offer',
  2057. sdp: remoteSdp
  2058. });
  2059. // Always initiate a sRD->cA->sLD cycle since renegotiation fails in the following scenario.
  2060. // In a p2p call when channelLastN=0, the direction on the video tranceiver is set to
  2061. // 'inactive'. At this point, if the user unmutes, the track is replaced on the video sender.
  2062. // If a cO->sLD->sRD is triggered, the browser adds a third m-line which isn't expected and
  2063. // possibly is a bug. All renegotiations fail as a result. However, the browser does not add a
  2064. // third m-line in the answer it generates and renegotiation succeeds.
  2065. promise = this._responderRenegotiate(remoteDescription).then(() => {
  2066. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  2067. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  2068. });
  2069. }
  2070. return promise.then(() => {
  2071. // Set the source name of the new track.
  2072. if (oldTrack
  2073. && newTrack
  2074. && oldTrack.isVideoTrack()) {
  2075. newTrack.setSourceName(oldTrack.getSourceName());
  2076. }
  2077. });
  2078. })
  2079. .then(() => finishedCallback(), error => finishedCallback(error));
  2080. };
  2081. return new Promise((resolve, reject) => {
  2082. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  2083. this.modificationQueue.push(
  2084. workFunction,
  2085. error => {
  2086. if (error) {
  2087. logger.error(`${this} Replace track error:`, error);
  2088. reject(error);
  2089. } else {
  2090. logger.info(`${this} Replace track done!`);
  2091. resolve();
  2092. }
  2093. });
  2094. });
  2095. }
  2096. /**
  2097. * Parse the information from the xml sourceRemoveElem and translate it
  2098. * into sdp lines
  2099. * @param {jquery xml element} sourceRemoveElem the source-remove
  2100. * element from jingle
  2101. * @param {SDP object} currentRemoteSdp the current remote
  2102. * sdp (as of this new source-remove)
  2103. * @returns {list} a list of SDP line strings that should
  2104. * be removed from the remote SDP
  2105. */
  2106. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  2107. const removeSsrcInfo = [];
  2108. $(sourceRemoveElem).each((i1, content) => {
  2109. const name = $(content).attr('name');
  2110. let lines = '';
  2111. $(content)
  2112. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  2113. .each(function() {
  2114. /* eslint-disable no-invalid-this */
  2115. const semantics = this.getAttribute('semantics');
  2116. const ssrcs
  2117. = $(this)
  2118. .find('>source')
  2119. .map(function() {
  2120. return this.getAttribute('ssrc');
  2121. })
  2122. .get();
  2123. if (ssrcs.length) {
  2124. lines
  2125. += `a=ssrc-group:${semantics} ${
  2126. ssrcs.join(' ')}\r\n`;
  2127. }
  2128. /* eslint-enable no-invalid-this */
  2129. });
  2130. const ssrcs = [];
  2131. // handles both >source and >description>source versions
  2132. const tmp
  2133. = $(content).find(
  2134. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  2135. tmp.each(function() {
  2136. // eslint-disable-next-line no-invalid-this
  2137. const ssrc = $(this).attr('ssrc');
  2138. ssrcs.push(ssrc);
  2139. });
  2140. currentRemoteSdp.media.forEach((media, i2) => {
  2141. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  2142. return;
  2143. }
  2144. if (!removeSsrcInfo[i2]) {
  2145. removeSsrcInfo[i2] = '';
  2146. }
  2147. ssrcs.forEach(ssrc => {
  2148. const ssrcLines
  2149. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  2150. if (ssrcLines.length) {
  2151. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  2152. }
  2153. });
  2154. removeSsrcInfo[i2] += lines;
  2155. });
  2156. });
  2157. return removeSsrcInfo;
  2158. }
  2159. /**
  2160. * Will print an error if there is any difference, between the SSRCs given
  2161. * in the <tt>oldSDP</tt> and the ones currently described in
  2162. * the peerconnection's local description.
  2163. * @param {string} operationName the operation's name which will be printed
  2164. * in the error message.
  2165. * @param {SDP} oldSDP the old local SDP which will be compared with
  2166. * the current one.
  2167. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  2168. * otherwise.
  2169. * @private
  2170. */
  2171. _verifyNoSSRCChanged(operationName, oldSDP) {
  2172. const currentLocalSDP
  2173. = new SDP(this.peerconnection.localDescription.sdp);
  2174. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  2175. const addedMedia = sdpDiff.getNewMedia();
  2176. if (Object.keys(addedMedia).length) {
  2177. logger.error(`${this} - some SSRC were added on ${operationName}`, addedMedia);
  2178. return false;
  2179. }
  2180. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  2181. const removedMedia = sdpDiff.getNewMedia();
  2182. if (Object.keys(removedMedia).length) {
  2183. logger.error(`${this} - some SSRCs were removed on ${operationName}`, removedMedia);
  2184. return false;
  2185. }
  2186. return true;
  2187. }
  2188. /**
  2189. * Adds local track back to the peerconnection associated with this session.
  2190. * @param {JitsiLocalTrack} track
  2191. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  2192. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  2193. * details in case something goes wrong.
  2194. */
  2195. addTrackToPc(track) {
  2196. return this._addRemoveTrack(false /* add */, track)
  2197. .then(() => {
  2198. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  2199. // unmutes it the first time, all the parameters need to be configured.
  2200. if (track.isVideoTrack()) {
  2201. return this.peerconnection.configureSenderVideoEncodings(track);
  2202. }
  2203. });
  2204. }
  2205. /**
  2206. * Remove local track as part of the mute operation.
  2207. * @param {JitsiLocalTrack} track the local track to be removed
  2208. * @return {Promise} a promise which will be resolved once the local track
  2209. * is removed from this session and the renegotiation is performed.
  2210. * The promise will be rejected with a <tt>string</tt> that the describes
  2211. * the error if anything goes wrong.
  2212. */
  2213. removeTrackFromPc(track) {
  2214. return this._addRemoveTrack(true /* remove */, track);
  2215. }
  2216. /**
  2217. * See {@link addTrackToPc} and {@link removeTrackFromPc}.
  2218. * @param {boolean} isRemove <tt>true</tt> for "remove" operation or <tt>false</tt> for "add" operation.
  2219. * @param {JitsiLocalTrack} track the track that will be added/removed
  2220. * @private
  2221. */
  2222. _addRemoveTrack(isRemove, track) {
  2223. if (!track) {
  2224. return Promise.reject('invalid "track" argument value');
  2225. }
  2226. const operationName = isRemove ? 'removeTrack' : 'addTrack';
  2227. const workFunction = finishedCallback => {
  2228. const tpc = this.peerconnection;
  2229. if (!tpc) {
  2230. finishedCallback(`Error: tried ${operationName} track with no active peer connection`);
  2231. return;
  2232. }
  2233. const oldLocalSDP = tpc.localDescription.sdp;
  2234. const operationPromise
  2235. = isRemove
  2236. ? tpc.removeTrackFromPc(track)
  2237. : tpc.addTrackToPc(track);
  2238. operationPromise
  2239. .then(shouldRenegotiate => {
  2240. if (shouldRenegotiate && oldLocalSDP && tpc.remoteDescription.sdp) {
  2241. this._renegotiate()
  2242. .then(() => {
  2243. // The results are ignored, as this check failure is not enough to fail the whole
  2244. // operation. It will log an error inside for plan-b.
  2245. !this.usesUnifiedPlan && this._verifyNoSSRCChanged(operationName, new SDP(oldLocalSDP));
  2246. const newLocalSdp = tpc.localDescription.sdp;
  2247. // Signal the ssrc if an unmute operation results in a new ssrc being generated.
  2248. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(newLocalSdp));
  2249. finishedCallback();
  2250. });
  2251. } else {
  2252. finishedCallback();
  2253. }
  2254. },
  2255. finishedCallback /* will be called with an error */);
  2256. };
  2257. logger.debug(`${this} Queued ${operationName} task`);
  2258. return new Promise((resolve, reject) => {
  2259. this.modificationQueue.push(
  2260. workFunction,
  2261. error => {
  2262. if (error) {
  2263. logger.error(`${this} ${operationName} failed`);
  2264. reject(error);
  2265. } else {
  2266. logger.debug(`${this} ${operationName} done`);
  2267. resolve();
  2268. }
  2269. });
  2270. });
  2271. }
  2272. /**
  2273. * Resumes or suspends video media transfer over the p2p peer connection.
  2274. *
  2275. * @param {boolean} videoActive <tt>true</tt> to enable video media transfer or <tt>false</tt> to suspend video
  2276. * media transmission.
  2277. * @return {Promise} a <tt>Promise</tt> which will resolve once the operation is done. It will be rejected with
  2278. * an error description as a string in case anything goes wrong.
  2279. */
  2280. setP2pVideoTransferActive(videoActive) {
  2281. if (!this.peerconnection) {
  2282. return Promise.reject('Can not modify video transfer active state,'
  2283. + ' before "initialize" is called');
  2284. }
  2285. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  2286. logger.info(`${this} Queued make ${logVideoStr} task`);
  2287. const workFunction = finishedCallback => {
  2288. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  2289. if (this._localVideoActive !== videoActive) {
  2290. this._localVideoActive = videoActive;
  2291. if (this.isP2P && isSessionActive) {
  2292. this.sendContentModify();
  2293. }
  2294. }
  2295. this.peerconnection.setVideoTransferActive(this._localVideoActive && this._remoteVideoActive);
  2296. // Always initiate a renegotiation cycle for p2p connection when the media direction is changed.
  2297. this._renegotiate()
  2298. .then(() => finishedCallback())
  2299. .catch(error => finishedCallback(error));
  2300. };
  2301. return new Promise((resolve, reject) => {
  2302. this.modificationQueue.push(
  2303. workFunction,
  2304. error => {
  2305. if (error) {
  2306. logger.error(`${this} Make ${logVideoStr} task failed!`);
  2307. reject(error);
  2308. } else {
  2309. logger.debug(`${this} Make ${logVideoStr} task done!`);
  2310. resolve();
  2311. }
  2312. });
  2313. });
  2314. }
  2315. /**
  2316. * Will put and execute on the queue a session modify task. It checks if the sourceMaxFrameHeight (as requested by
  2317. * the p2p peer) or the senders attribute of the video content has changed and modifies the local video sources
  2318. * accordingly.
  2319. */
  2320. modifyContents(jingleContents) {
  2321. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  2322. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  2323. if (sourceMaxFrameHeights) {
  2324. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  2325. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  2326. }
  2327. if (newVideoSenders === null) {
  2328. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  2329. return;
  2330. }
  2331. const workFunction = finishedCallback => {
  2332. if (this._assertNotEnded() && this._modifyRemoteVideoActive(newVideoSenders)) {
  2333. // Will do the sRD/sLD cycle to update SDPs and adjust the media direction.
  2334. this._renegotiate()
  2335. .then(finishedCallback, finishedCallback /* (error) */);
  2336. } else {
  2337. finishedCallback();
  2338. }
  2339. };
  2340. logger.debug(`${this} queued "content-modify" task(video senders="${newVideoSenders}")`);
  2341. this.modificationQueue.push(
  2342. workFunction,
  2343. error => {
  2344. if (error) {
  2345. logger.error(`${this} "content-modify" failed`, error);
  2346. } else {
  2347. logger.debug(`${this} "content-modify" task(video senders="${newVideoSenders}") done`);
  2348. }
  2349. });
  2350. }
  2351. /**
  2352. * Processes new value of remote video "senders" Jingle attribute and tries to apply it for
  2353. * {@link _remoteVideoActive}.
  2354. * @param {string} remoteVideoSenders the value of "senders" attribute of Jingle video content element advertised
  2355. * by remote peer.
  2356. * @return {boolean} <tt>true</tt> if the change affected state of the underlying peerconnection and renegotiation
  2357. * is required for the changes to take effect.
  2358. * @private
  2359. */
  2360. _modifyRemoteVideoActive(remoteVideoSenders) {
  2361. const isRemoteVideoActive
  2362. = remoteVideoSenders === 'both'
  2363. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  2364. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  2365. if (isRemoteVideoActive !== this._remoteVideoActive) {
  2366. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  2367. this._remoteVideoActive = isRemoteVideoActive;
  2368. return this.peerconnection.setVideoTransferActive(this._localVideoActive && this._remoteVideoActive);
  2369. }
  2370. return false;
  2371. }
  2372. /**
  2373. * Figures out added/removed ssrcs and send update IQs.
  2374. * @param oldSDP SDP object for old description.
  2375. * @param newSDP SDP object for new description.
  2376. */
  2377. notifyMySSRCUpdate(oldSDP, newSDP) {
  2378. if (this.state !== JingleSessionState.ACTIVE) {
  2379. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  2380. return;
  2381. }
  2382. if (!this.connection.connected) {
  2383. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2384. if (!this._cachedOldLocalSdp) {
  2385. this._cachedOldLocalSdp = oldSDP;
  2386. }
  2387. this._cachedNewLocalSdp = newSDP;
  2388. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  2389. return;
  2390. }
  2391. this._cachedOldLocalSdp = undefined;
  2392. this._cachedNewLocalSdp = undefined;
  2393. const getSignaledSourceInfo = sdpDiffer => {
  2394. const newMedia = sdpDiffer.getNewMedia();
  2395. let ssrcs = [];
  2396. let mediaType = null;
  2397. // It is assumed that sources are signaled one at a time.
  2398. Object.keys(newMedia).forEach(mediaIndex => {
  2399. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  2400. mediaType = newMedia[mediaIndex].mid;
  2401. if (signaledSsrcs?.length) {
  2402. ssrcs = ssrcs.concat(signaledSsrcs);
  2403. }
  2404. });
  2405. return {
  2406. mediaType,
  2407. ssrcs
  2408. };
  2409. };
  2410. // send source-remove IQ.
  2411. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2412. const remove = $iq({ to: this.remoteJid,
  2413. type: 'set' })
  2414. .c('jingle', {
  2415. xmlns: 'urn:xmpp:jingle:1',
  2416. action: 'source-remove',
  2417. initiator: this.initiatorJid,
  2418. sid: this.sid
  2419. }
  2420. );
  2421. sdpDiffer.toJingle(remove);
  2422. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  2423. // need to
  2424. const ctx = {};
  2425. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2426. if (removedSsrcInfo.ssrcs.length) {
  2427. // Log only the SSRCs instead of the full IQ.
  2428. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  2429. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  2430. this.connection.sendIQ(
  2431. remove,
  2432. () => {
  2433. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  2434. },
  2435. this.newJingleErrorHandler(remove, error => {
  2436. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  2437. }),
  2438. IQ_TIMEOUT);
  2439. }
  2440. // send source-add IQ.
  2441. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2442. const add = $iq({ to: this.remoteJid,
  2443. type: 'set' })
  2444. .c('jingle', {
  2445. xmlns: 'urn:xmpp:jingle:1',
  2446. action: 'source-add',
  2447. initiator: this.initiatorJid,
  2448. sid: this.sid
  2449. }
  2450. );
  2451. sdpDiffer.toJingle(add);
  2452. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2453. if (addedSsrcInfo.ssrcs.length) {
  2454. // Log only the SSRCs instead of the full IQ.
  2455. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  2456. this.connection.sendIQ(
  2457. add,
  2458. () => {
  2459. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  2460. },
  2461. this.newJingleErrorHandler(add, error => {
  2462. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  2463. }),
  2464. IQ_TIMEOUT);
  2465. }
  2466. }
  2467. /**
  2468. * Method returns function(errorResponse) which is a callback to be passed
  2469. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2470. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2471. * structure is as follows:
  2472. * {
  2473. * code: {XMPP error response code}
  2474. * reason: {the name of XMPP error reason element or 'timeout' if the
  2475. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2476. * source: {request.tree() that provides original request}
  2477. * session: {this JingleSessionPC.toString()}
  2478. * }
  2479. * @param request Strophe IQ instance which is the request to be dumped into
  2480. * the error structure
  2481. * @param failureCb function(error) called when error response was returned
  2482. * or when a timeout has occurred.
  2483. * @returns {function(this:JingleSessionPC)}
  2484. */
  2485. newJingleErrorHandler(request, failureCb) {
  2486. return errResponse => {
  2487. const error = {};
  2488. // Get XMPP error code and condition(reason)
  2489. const errorElSel = $(errResponse).find('error');
  2490. if (errorElSel.length) {
  2491. error.code = errorElSel.attr('code');
  2492. const errorReasonSel = $(errResponse).find('error :first');
  2493. if (errorReasonSel.length) {
  2494. error.reason = errorReasonSel[0].tagName;
  2495. }
  2496. const errorMsgSel = errorElSel.find('>text');
  2497. if (errorMsgSel.length) {
  2498. error.msg = errorMsgSel.text();
  2499. }
  2500. }
  2501. if (!errResponse) {
  2502. error.reason = 'timeout';
  2503. }
  2504. error.session = this.toString();
  2505. if (failureCb) {
  2506. failureCb(error);
  2507. } else if (this.state === JingleSessionState.ENDED
  2508. && error.reason === 'item-not-found') {
  2509. // When remote peer decides to terminate the session, but it
  2510. // still have few messages on the queue for processing,
  2511. // it will first send us 'session-terminate' (we enter ENDED)
  2512. // and then follow with 'item-not-found' for the queued requests
  2513. // We don't want to have that logged on error level.
  2514. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  2515. } else {
  2516. GlobalOnErrorHandler.callErrorHandler(
  2517. new Error(
  2518. `Jingle error: ${JSON.stringify(error)}`));
  2519. }
  2520. };
  2521. }
  2522. /**
  2523. * Returns the ice connection state for the peer connection.
  2524. * @returns the ice connection state for the peer connection.
  2525. */
  2526. getIceConnectionState() {
  2527. return this.peerconnection.getConnectionState();
  2528. }
  2529. /**
  2530. * Closes the peerconnection.
  2531. */
  2532. close() {
  2533. this.state = JingleSessionState.ENDED;
  2534. this.establishmentDuration = undefined;
  2535. if (this.peerconnection) {
  2536. this.peerconnection.onicecandidate = null;
  2537. this.peerconnection.oniceconnectionstatechange = null;
  2538. this.peerconnection.onnegotiationneeded = null;
  2539. this.peerconnection.onsignalingstatechange = null;
  2540. }
  2541. logger.debug(`${this} Clearing modificationQueue`);
  2542. // Remove any pending tasks from the queue
  2543. this.modificationQueue.clear();
  2544. logger.debug(`${this} Queued PC close task`);
  2545. this.modificationQueue.push(finishCallback => {
  2546. // do not try to close if already closed.
  2547. this.peerconnection && this.peerconnection.close();
  2548. finishCallback();
  2549. logger.debug(`${this} PC close task done!`);
  2550. });
  2551. logger.debug(`${this} Shutdown modificationQueue!`);
  2552. // No more tasks can go in after the close task
  2553. this.modificationQueue.shutdown();
  2554. }
  2555. /**
  2556. * Converts to string with minor summary.
  2557. * @return {string}
  2558. */
  2559. toString() {
  2560. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2561. }
  2562. /**
  2563. * If the A/B test for suspend video is disabled according to the room's
  2564. * configuration, returns undefined. Otherwise returns a boolean which
  2565. * indicates whether the suspend video option should be enabled or disabled.
  2566. * @param {JingleSessionPCOptions} options - The config options.
  2567. */
  2568. _abtestSuspendVideoEnabled({ abTesting }) {
  2569. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2570. return;
  2571. }
  2572. // We want the two participants in a P2P call to agree on the value of
  2573. // the "suspend" option. We use the JID of the initiator, because it is
  2574. // both randomly selected and agreed upon by both participants.
  2575. return integerHash(this.initiatorJid) % 2 === 0;
  2576. }
  2577. }