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

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