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

JingleSessionPC.js 110KB

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