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

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