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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724
  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(() => finishedCallback(), error => finishedCallback(error));
  575. };
  576. this.modificationQueue.push(
  577. workFunction,
  578. error => {
  579. if (error) {
  580. logger.error(`${this} onnegotiationneeded error`, error);
  581. } else {
  582. logger.debug(`${this} onnegotiationneeded executed - OK`);
  583. }
  584. });
  585. }
  586. };
  587. }
  588. /**
  589. * Remote preference for receive video max frame height.
  590. *
  591. * @returns {Number|undefined}
  592. */
  593. getRemoteRecvMaxFrameHeight() {
  594. if (this.isP2P) {
  595. return this.remoteRecvMaxFrameHeight;
  596. }
  597. return undefined;
  598. }
  599. /**
  600. * Remote preference for receive video max frame heights when source-name signaling is enabled.
  601. *
  602. * @returns {Map<string, number>|undefined}
  603. */
  604. getRemoteSourcesRecvMaxFrameHeight() {
  605. if (this.isP2P) {
  606. return this.remoteSourceMaxFrameHeights;
  607. }
  608. return undefined;
  609. }
  610. /**
  611. * Sends given candidate in Jingle 'transport-info' message.
  612. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  613. * @private
  614. */
  615. sendIceCandidate(candidate) {
  616. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  617. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  618. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  619. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  620. if (!(ice && jcand)) {
  621. logger.error('failed to get ice && jcand');
  622. return;
  623. }
  624. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  625. if (this.usedrip) {
  626. if (this.dripContainer.length === 0) {
  627. setTimeout(() => {
  628. if (this.dripContainer.length === 0) {
  629. return;
  630. }
  631. this.sendIceCandidates(this.dripContainer);
  632. this.dripContainer = [];
  633. }, ICE_CAND_GATHERING_TIMEOUT);
  634. }
  635. this.dripContainer.push(candidate);
  636. } else {
  637. this.sendIceCandidates([ candidate ]);
  638. }
  639. } else {
  640. logger.log(`${this} sendIceCandidate: last candidate`);
  641. // FIXME: remember to re-think in ICE-restart
  642. this.lasticecandidate = true;
  643. }
  644. }
  645. /**
  646. * Sends given candidates in Jingle 'transport-info' message.
  647. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  648. * candidate instances
  649. * @private
  650. */
  651. sendIceCandidates(candidates) {
  652. if (!this._assertNotEnded('sendIceCandidates')) {
  653. return;
  654. }
  655. logger.log(`${this} sendIceCandidates ${JSON.stringify(candidates)}`);
  656. const cand = $iq({ to: this.remoteJid,
  657. type: 'set' })
  658. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  659. action: 'transport-info',
  660. initiator: this.initiatorJid,
  661. sid: this.sid });
  662. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  663. for (let mid = 0; mid < localSDP.media.length; mid++) {
  664. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  665. const mline
  666. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  667. if (cands.length > 0) {
  668. const ice
  669. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  670. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  671. cand.c('content', {
  672. creator: this.initiatorJid === this.localJid
  673. ? 'initiator' : 'responder',
  674. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  675. }).c('transport', ice);
  676. for (let i = 0; i < cands.length; i++) {
  677. const candidate
  678. = SDPUtil.candidateToJingle(cands[i].candidate);
  679. // Mangle ICE candidate if 'failICE' test option is enabled
  680. if (this.failICE) {
  681. candidate.ip = '1.1.1.1';
  682. }
  683. cand.c('candidate', candidate).up();
  684. }
  685. // add fingerprint
  686. const fingerprintLine
  687. = SDPUtil.findLine(
  688. localSDP.media[mid],
  689. 'a=fingerprint:', localSDP.session);
  690. if (fingerprintLine) {
  691. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  692. tmp.required = true;
  693. cand.c(
  694. 'fingerprint',
  695. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  696. .t(tmp.fingerprint);
  697. delete tmp.fingerprint;
  698. cand.attrs(tmp);
  699. cand.up();
  700. }
  701. cand.up(); // transport
  702. cand.up(); // content
  703. }
  704. }
  705. // might merge last-candidate notification into this, but it is called
  706. // a lot later. See webrtc issue #2340
  707. // logger.log('was this the last candidate', this.lasticecandidate);
  708. this.connection.sendIQ(
  709. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  710. }
  711. /**
  712. * Sends Jingle 'session-info' message which includes custom Jitsi Meet
  713. * 'ice-state' element with the text value 'failed' to let Jicofo know
  714. * that the ICE connection has entered the failed state. It can then
  715. * choose to re-create JVB channels and send 'transport-replace' to
  716. * retry the connection.
  717. */
  718. sendIceFailedNotification() {
  719. const sessionInfo
  720. = $iq({
  721. to: this.remoteJid,
  722. type: 'set' })
  723. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  724. action: 'session-info',
  725. initiator: this.initiatorJid,
  726. sid: this.sid })
  727. .c('ice-state', { xmlns: 'http://jitsi.org/protocol/focus' })
  728. .t('failed')
  729. .up();
  730. this._bridgeSessionId
  731. && sessionInfo.c(
  732. 'bridge-session', {
  733. xmlns: 'http://jitsi.org/protocol/focus',
  734. id: this._bridgeSessionId
  735. });
  736. this.connection.sendIQ2(
  737. sessionInfo, {
  738. /*
  739. * This message will be often sent when there are connectivity
  740. * issues, so make it slightly longer than Prosody's default BOSH
  741. * inactivity timeout of 60 seconds.
  742. */
  743. timeout: 65
  744. })
  745. .catch(this.newJingleErrorHandler(sessionInfo));
  746. }
  747. /**
  748. * {@inheritDoc}
  749. */
  750. addIceCandidates(elem) {
  751. if (this.peerconnection.signalingState === 'closed') {
  752. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  753. return;
  754. }
  755. const iceCandidates = [];
  756. elem.find('>content>transport>candidate')
  757. .each((idx, candidate) => {
  758. let line = SDPUtil.candidateFromJingle(candidate);
  759. line = line.replace('\r\n', '').replace('a=', '');
  760. // FIXME this code does not care to handle
  761. // non-bundle transport
  762. const rtcCandidate = new RTCIceCandidate({
  763. sdpMLineIndex: 0,
  764. // FF comes up with more complex names like audio-23423,
  765. // Given that it works on both Chrome and FF without
  766. // providing it, let's leave it like this for the time
  767. // being...
  768. // sdpMid: 'audio',
  769. sdpMid: '',
  770. candidate: line
  771. });
  772. iceCandidates.push(rtcCandidate);
  773. });
  774. if (!iceCandidates.length) {
  775. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  776. return;
  777. }
  778. // We want to have this task queued, so that we know it is executed,
  779. // after the initial sRD/sLD offer/answer cycle was done (based on
  780. // the assumption that candidates are spawned after the offer/answer
  781. // and XMPP preserves order).
  782. const workFunction = finishedCallback => {
  783. for (const iceCandidate of iceCandidates) {
  784. this.peerconnection.addIceCandidate(iceCandidate)
  785. .then(
  786. () => logger.debug(`${this} addIceCandidate ok!`),
  787. err => logger.error(`${this} addIceCandidate failed!`, err));
  788. }
  789. finishedCallback();
  790. logger.debug(`${this} ICE candidates task finished`);
  791. };
  792. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  793. this.modificationQueue.push(workFunction);
  794. }
  795. /**
  796. *
  797. * @param contents
  798. */
  799. readSsrcInfo(contents) {
  800. const ssrcs = $(contents).find('>description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  801. ssrcs.each((i, ssrcElement) => {
  802. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  803. let sourceName;
  804. if (ssrcElement.hasAttribute('name')) {
  805. sourceName = ssrcElement.getAttribute('name');
  806. }
  807. if (this.isP2P) {
  808. // In P2P all SSRCs are owner by the remote peer
  809. this._signalingLayer.setSSRCOwner(ssrc, Strophe.getResourceFromJid(this.remoteJid), sourceName);
  810. } else {
  811. $(ssrcElement)
  812. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  813. .each((i3, ssrcInfoElement) => {
  814. const owner = ssrcInfoElement.getAttribute('owner');
  815. if (owner?.length) {
  816. if (isNaN(ssrc) || ssrc < 0) {
  817. logger.warn(`${this} Invalid SSRC ${ssrc} value received for ${owner}`);
  818. } else {
  819. this._signalingLayer.setSSRCOwner(ssrc, getEndpointId(owner), sourceName);
  820. }
  821. }
  822. });
  823. }
  824. });
  825. }
  826. /**
  827. * Returns the video codec configured as the preferred codec on the peerconnection.
  828. */
  829. getConfiguredVideoCodec() {
  830. return this.peerconnection.getConfiguredVideoCodec();
  831. }
  832. /**
  833. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  834. *
  835. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  836. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  837. * 'session-accept' sent.
  838. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  839. * can be used to log some details about the error.
  840. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  841. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  842. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  843. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  844. * assumption that the initial offer/answer cycle has been executed already.
  845. */
  846. acceptOffer(jingleOffer, success, failure, localTracks = []) {
  847. this.setOfferAnswerCycle(
  848. jingleOffer,
  849. () => {
  850. // FIXME we may not care about RESULT packet for session-accept
  851. // then we should either call 'success' here immediately or
  852. // modify sendSessionAccept method to do that
  853. this.sendSessionAccept(() => {
  854. // Start processing tasks on the modification queue.
  855. logger.debug(`${this} Resuming the modification queue after session is established!`);
  856. this.modificationQueue.resume();
  857. success();
  858. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  859. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  860. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  861. // This will happen when someone shares a secondary source to a two people call, the other user
  862. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  863. // point, there are 2 video tracks which need to be signaled to the remote peer.
  864. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  865. videoTracks.length && videoTracks.splice(0, 1);
  866. videoTracks.length && this.addTracks(videoTracks);
  867. },
  868. error => {
  869. failure(error);
  870. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  871. });
  872. },
  873. failure,
  874. localTracks);
  875. }
  876. /**
  877. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  878. *
  879. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  880. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  881. */
  882. invite(localTracks = []) {
  883. if (!this.isInitiator) {
  884. throw new Error('Trying to invite from the responder session');
  885. }
  886. logger.debug(`${this} Executing invite task`);
  887. const addTracks = [];
  888. for (const track of localTracks) {
  889. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  890. }
  891. Promise.all(addTracks)
  892. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  893. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  894. .then(() => {
  895. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  896. this.sendSessionInitiate(this.peerconnection.localDescription.sdp);
  897. })
  898. .then(() => {
  899. logger.debug(`${this} invite executed - OK`);
  900. })
  901. .catch(error => {
  902. logger.error(`${this} invite error`, error);
  903. });
  904. }
  905. /**
  906. * Sends 'session-initiate' to the remote peer.
  907. *
  908. * NOTE this method is synchronous and we're not waiting for the RESULT
  909. * response which would delay the startup process.
  910. *
  911. * @param {string} offerSdp - The local session description which will be
  912. * used to generate an offer.
  913. * @private
  914. */
  915. sendSessionInitiate(offerSdp) {
  916. let init = $iq({
  917. to: this.remoteJid,
  918. type: 'set'
  919. }).c('jingle', {
  920. xmlns: 'urn:xmpp:jingle:1',
  921. action: 'session-initiate',
  922. initiator: this.initiatorJid,
  923. sid: this.sid
  924. });
  925. new SDP(offerSdp).toJingle(
  926. init,
  927. this.isInitiator ? 'initiator' : 'responder');
  928. init = init.tree();
  929. logger.debug(`${this} Session-initiate: `, init);
  930. this.connection.sendIQ(init,
  931. () => {
  932. logger.info(`${this} Got RESULT for "session-initiate"`);
  933. },
  934. error => {
  935. logger.error(`${this} "session-initiate" error`, error);
  936. },
  937. IQ_TIMEOUT);
  938. }
  939. /**
  940. * Sets the answer received from the remote peer as the remote description.
  941. *
  942. * @param jingleAnswer
  943. */
  944. setAnswer(jingleAnswer) {
  945. if (!this.isInitiator) {
  946. throw new Error('Trying to set an answer on the responder session');
  947. }
  948. logger.debug(`${this} Executing setAnswer task`);
  949. const newRemoteSdp = this._processNewJingleOfferIq(jingleAnswer);
  950. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  951. const remoteDescription = new RTCSessionDescription({
  952. type: 'answer',
  953. sdp: newRemoteSdp.raw
  954. });
  955. this.peerconnection.setRemoteDescription(remoteDescription)
  956. .then(() => {
  957. if (this.state === JingleSessionState.PENDING) {
  958. this.state = JingleSessionState.ACTIVE;
  959. // Start processing tasks on the modification queue.
  960. logger.debug(`${this} Resuming the modification queue after session is established!`);
  961. this.modificationQueue.resume();
  962. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  963. this.sendContentModify();
  964. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  965. }
  966. })
  967. .then(() => {
  968. logger.debug(`${this} setAnswer task done`);
  969. })
  970. .catch(error => {
  971. logger.error(`${this} setAnswer task failed: ${error}`);
  972. });
  973. }
  974. /**
  975. * This is a setRemoteDescription/setLocalDescription cycle which starts at converting Strophe Jingle IQ into
  976. * remote offer SDP. Once converted, setRemoteDescription, createAnswer and setLocalDescription calls follow.
  977. *
  978. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element of the offer (or answer) IQ
  979. * @param success callback called when sRD/sLD cycle finishes successfully.
  980. * @param failure callback called with an error object as an argument if we fail at any point during setRD,
  981. * createAnswer, setLD.
  982. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  983. * the offer/answer cycle executes (for the local track addition to be an atomic operation together with the
  984. * offer/answer).
  985. */
  986. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  987. logger.debug(`${this} Executing setOfferAnswerCycle task`);
  988. const addTracks = [];
  989. const audioTracks = localTracks.filter(track => track.getType() === MediaType.AUDIO);
  990. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  991. let tracks = localTracks;
  992. // Add only 1 video track at a time. Adding 2 or more video tracks to the peerconnection at the same time
  993. // makes the browser go into a renegotiation loop by firing 'negotiationneeded' event after every
  994. // renegotiation.
  995. if (videoTracks.length > 1) {
  996. tracks = [ ...audioTracks, videoTracks[0] ];
  997. }
  998. for (const track of tracks) {
  999. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1000. }
  1001. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  1002. const bridgeSession = $(jingleOfferAnswerIq).find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]');
  1003. const bridgeSessionId = bridgeSession.attr('id');
  1004. if (bridgeSessionId !== this._bridgeSessionId) {
  1005. this._bridgeSessionId = bridgeSessionId;
  1006. }
  1007. Promise.all(addTracks)
  1008. .then(() => this._renegotiate(newRemoteSdp.raw))
  1009. .then(() => {
  1010. this.peerconnection.processLocalSdpForTransceiverInfo(tracks);
  1011. if (this.state === JingleSessionState.PENDING) {
  1012. this.state = JingleSessionState.ACTIVE;
  1013. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1014. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1015. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1016. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1017. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1018. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1019. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1020. if (this.isP2P && (!this._localSendReceiveVideoActive || this._sourceReceiverConstraints)) {
  1021. this.sendContentModify();
  1022. }
  1023. }
  1024. })
  1025. .then(() => {
  1026. logger.debug(`${this} setOfferAnswerCycle task done`);
  1027. success();
  1028. })
  1029. .catch(error => {
  1030. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1031. failure(error);
  1032. });
  1033. }
  1034. /**
  1035. * Updates the codecs on the peerconnection and initiates a renegotiation for the
  1036. * new codec config to take effect.
  1037. *
  1038. * @param {CodecMimeType} preferred the preferred codec.
  1039. * @param {CodecMimeType} disabled the codec that needs to be disabled.
  1040. */
  1041. setVideoCodecs(codecList) {
  1042. if (this._assertNotEnded()) {
  1043. logger.info(`${this} setVideoCodecs: ${codecList}`);
  1044. this.peerconnection.setVideoCodecs(codecList);
  1045. // Initiate a renegotiate for the codec setting to take effect.
  1046. const workFunction = finishedCallback => {
  1047. this._renegotiate()
  1048. .then(() => this.peerconnection.configureSenderVideoEncodings())
  1049. .then(
  1050. () => {
  1051. logger.debug(`${this} setVideoCodecs task is done`);
  1052. return finishedCallback();
  1053. }, error => {
  1054. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  1055. return finishedCallback(error);
  1056. });
  1057. };
  1058. logger.debug(`${this} Queued setVideoCodecs task`);
  1059. // Queue and execute
  1060. this.modificationQueue.push(workFunction);
  1061. }
  1062. }
  1063. /* eslint-enable max-params */
  1064. /**
  1065. * Although it states "replace transport" it does accept full Jingle offer
  1066. * which should contain new ICE transport details.
  1067. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  1068. * transport info.
  1069. * @param success callback called when we succeed to accept new offer.
  1070. * @param failure function(error) called when we fail to accept new offer.
  1071. */
  1072. replaceTransport(jingleOfferElem, success, failure) {
  1073. if (this.options.enableForcedReload) {
  1074. const sdp = new SDP(this.peerconnection.localDescription.sdp);
  1075. this.sendTransportAccept(sdp, success, failure);
  1076. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTARTED, this);
  1077. return;
  1078. }
  1079. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  1080. // We need to first reject the 'data' section to have the SCTP stack
  1081. // cleaned up to signal the known data channel is now invalid. After
  1082. // that the original offer is set to have the SCTP connection
  1083. // established with the new bridge.
  1084. const originalOffer = jingleOfferElem.clone();
  1085. jingleOfferElem
  1086. .find('>content[name=\'data\']')
  1087. .attr('senders', 'rejected');
  1088. // Remove all remote sources in order to reset the client's state
  1089. // for the remote MediaStreams. When a conference is moved to
  1090. // another bridge it will start streaming with a sequence number
  1091. // that is not in sync with the most recently seen by the client.
  1092. // The symptoms include frozen or black video and lots of "failed to
  1093. // unprotect SRTP packets" in Chrome logs.
  1094. jingleOfferElem
  1095. .find('>content>description>source')
  1096. .remove();
  1097. jingleOfferElem
  1098. .find('>content>description>ssrc-group')
  1099. .remove();
  1100. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  1101. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  1102. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  1103. // fingerprint has changed by setting an all zeros key.
  1104. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  1105. newFingerprint.attr('hash', 'sha-1');
  1106. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  1107. const workFunction = finishedCallback => {
  1108. // First set an offer with a rejected 'data' section
  1109. this.setOfferAnswerCycle(
  1110. jingleOfferElem,
  1111. () => {
  1112. // Now set the original offer(with the 'data' section)
  1113. this.setOfferAnswerCycle(
  1114. originalOffer,
  1115. () => {
  1116. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1117. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1118. localSDP.initialLastN = this.options.channelLastN;
  1119. }
  1120. this.sendTransportAccept(localSDP, success, failure);
  1121. this.room.eventEmitter.emit(
  1122. XMPPEvents.ICE_RESTART_SUCCESS,
  1123. this,
  1124. originalOffer);
  1125. finishedCallback();
  1126. }, error => finishedCallback(error)
  1127. );
  1128. }, error => finishedCallback(error)
  1129. );
  1130. };
  1131. logger.debug(`${this} Queued ICE restart task`);
  1132. // Queue and execute
  1133. this.modificationQueue.push(
  1134. workFunction,
  1135. error => {
  1136. if (error) {
  1137. if (error instanceof ClearedQueueError) {
  1138. // The session might have been terminated before the task was executed, making it obsolete.
  1139. logger.debug(`${this} ICE restart task aborted: session terminated`);
  1140. success();
  1141. return;
  1142. }
  1143. logger.error(`${this} ICE restart task failed: ${error}`);
  1144. failure(error);
  1145. } else {
  1146. logger.debug(`${this} ICE restart task done`);
  1147. success();
  1148. }
  1149. });
  1150. }
  1151. /**
  1152. * Sends Jingle 'session-accept' message.
  1153. * @param {function()} success callback called when we receive 'RESULT'
  1154. * packet for the 'session-accept'
  1155. * @param {function(error)} failure called when we receive an error response
  1156. * or when the request has timed out.
  1157. * @private
  1158. */
  1159. sendSessionAccept(success, failure) {
  1160. // NOTE: since we're just reading from it, we don't need to be within
  1161. // the modification queue to access the local description
  1162. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1163. const accept = $iq({ to: this.remoteJid,
  1164. type: 'set' })
  1165. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1166. action: 'session-accept',
  1167. initiator: this.initiatorJid,
  1168. responder: this.responderJid,
  1169. sid: this.sid });
  1170. if (this.webrtcIceTcpDisable) {
  1171. localSDP.removeTcpCandidates = true;
  1172. }
  1173. if (this.webrtcIceUdpDisable) {
  1174. localSDP.removeUdpCandidates = true;
  1175. }
  1176. if (this.failICE) {
  1177. localSDP.failICE = true;
  1178. }
  1179. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1180. localSDP.initialLastN = this.options.channelLastN;
  1181. }
  1182. localSDP.toJingle(
  1183. accept,
  1184. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1185. logger.info(`${this} Sending session-accept`);
  1186. logger.debug(accept.tree());
  1187. this.connection.sendIQ(accept,
  1188. success,
  1189. this.newJingleErrorHandler(accept, error => {
  1190. failure(error);
  1191. // 'session-accept' is a critical timeout and we'll
  1192. // have to restart
  1193. this.room.eventEmitter.emit(
  1194. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1195. }),
  1196. IQ_TIMEOUT);
  1197. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1198. // fingerprint and setup) ASAP in order to start the connection
  1199. // establishment.
  1200. //
  1201. // FIXME Flushing the connection at this point triggers an issue with
  1202. // BOSH request handling in Prosody on slow connections.
  1203. //
  1204. // The problem is that this request will be quite large and it may take
  1205. // time before it reaches Prosody. In the meantime Strophe may decide
  1206. // to send the next one. And it was observed that a small request with
  1207. // 'transport-info' usually follows this one. It does reach Prosody
  1208. // before the previous one was completely received. 'rid' on the server
  1209. // is increased and Prosody ignores the request with 'session-accept'.
  1210. // It will never reach Jicofo and everything in the request table is
  1211. // lost. Removing the flush does not guarantee it will never happen, but
  1212. // makes it much less likely('transport-info' is bundled with
  1213. // 'session-accept' and any immediate requests).
  1214. //
  1215. // this.connection.flush();
  1216. }
  1217. /**
  1218. * Will send 'content-modify' IQ in order to ask the remote peer to
  1219. * either stop or resume sending video media or to adjust sender's video constraints.
  1220. * @private
  1221. */
  1222. sendContentModify() {
  1223. const senders = this._localSendReceiveVideoActive ? 'both' : 'none';
  1224. const sessionModify
  1225. = $iq({
  1226. to: this.remoteJid,
  1227. type: 'set'
  1228. })
  1229. .c('jingle', {
  1230. xmlns: 'urn:xmpp:jingle:1',
  1231. action: 'content-modify',
  1232. initiator: this.initiatorJid,
  1233. sid: this.sid
  1234. })
  1235. .c('content', {
  1236. name: MediaType.VIDEO,
  1237. senders
  1238. });
  1239. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  1240. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  1241. sessionModify
  1242. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1243. .attrs({
  1244. sourceName,
  1245. maxHeight
  1246. });
  1247. sessionModify.up();
  1248. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  1249. });
  1250. }
  1251. logger.debug(sessionModify.tree());
  1252. this.connection.sendIQ(
  1253. sessionModify,
  1254. null,
  1255. this.newJingleErrorHandler(sessionModify),
  1256. IQ_TIMEOUT);
  1257. }
  1258. /**
  1259. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1260. * the remote p2p peer.
  1261. *
  1262. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1263. */
  1264. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1265. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1266. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1267. if (this.isP2P) {
  1268. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1269. // be synced after offer/answer.
  1270. if (this.state === JingleSessionState.ACTIVE) {
  1271. this.sendContentModify();
  1272. }
  1273. }
  1274. }
  1275. /**
  1276. * Sends Jingle 'transport-accept' message which is a response to
  1277. * 'transport-replace'.
  1278. * @param localSDP the 'SDP' object with local session description
  1279. * @param success callback called when we receive 'RESULT' packet for
  1280. * 'transport-replace'
  1281. * @param failure function(error) called when we receive an error response
  1282. * or when the request has timed out.
  1283. * @private
  1284. */
  1285. sendTransportAccept(localSDP, success, failure) {
  1286. const transportAccept = $iq({ to: this.remoteJid,
  1287. type: 'set' })
  1288. .c('jingle', {
  1289. xmlns: 'urn:xmpp:jingle:1',
  1290. action: 'transport-accept',
  1291. initiator: this.initiatorJid,
  1292. sid: this.sid
  1293. });
  1294. localSDP.media.forEach((medialines, idx) => {
  1295. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1296. transportAccept.c('content',
  1297. {
  1298. creator:
  1299. this.initiatorJid === this.localJid
  1300. ? 'initiator'
  1301. : 'responder',
  1302. name: mline.media
  1303. }
  1304. );
  1305. localSDP.transportToJingle(idx, transportAccept);
  1306. transportAccept.up();
  1307. });
  1308. logger.info(`${this} Sending transport-accept`);
  1309. logger.debug(transportAccept.tree());
  1310. this.connection.sendIQ(transportAccept,
  1311. success,
  1312. this.newJingleErrorHandler(transportAccept, failure),
  1313. IQ_TIMEOUT);
  1314. }
  1315. /**
  1316. * Sends Jingle 'transport-reject' message which is a response to
  1317. * 'transport-replace'.
  1318. * @param success callback called when we receive 'RESULT' packet for
  1319. * 'transport-replace'
  1320. * @param failure function(error) called when we receive an error response
  1321. * or when the request has timed out.
  1322. *
  1323. * FIXME method should be marked as private, but there's some spaghetti that
  1324. * needs to be fixed prior doing that
  1325. */
  1326. sendTransportReject(success, failure) {
  1327. // Send 'transport-reject', so that the focus will
  1328. // know that we've failed
  1329. const transportReject = $iq({ to: this.remoteJid,
  1330. type: 'set' })
  1331. .c('jingle', {
  1332. xmlns: 'urn:xmpp:jingle:1',
  1333. action: 'transport-reject',
  1334. initiator: this.initiatorJid,
  1335. sid: this.sid
  1336. });
  1337. logger.info(`${this} Sending 'transport-reject'`);
  1338. logger.debug(transportReject.tree());
  1339. this.connection.sendIQ(transportReject,
  1340. success,
  1341. this.newJingleErrorHandler(transportReject, failure),
  1342. IQ_TIMEOUT);
  1343. }
  1344. /**
  1345. * Sets the resolution constraint on the local camera track.
  1346. * @param {number} maxFrameHeight - The user preferred max frame height.
  1347. * @param {string} sourceName - The source name of the track.
  1348. * @returns {Promise} promise that will be resolved when the operation is
  1349. * successful and rejected otherwise.
  1350. */
  1351. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1352. if (this._assertNotEnded()) {
  1353. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1354. const jitsiLocalTrack = sourceName
  1355. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1356. : this.rtc.getLocalVideoTrack();
  1357. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1358. }
  1359. return Promise.resolve();
  1360. }
  1361. /**
  1362. * @inheritDoc
  1363. */
  1364. terminate(success, failure, options) {
  1365. if (this.state === JingleSessionState.ENDED) {
  1366. return;
  1367. }
  1368. if (!options || Boolean(options.sendSessionTerminate)) {
  1369. const sessionTerminate
  1370. = $iq({
  1371. to: this.remoteJid,
  1372. type: 'set'
  1373. })
  1374. .c('jingle', {
  1375. xmlns: 'urn:xmpp:jingle:1',
  1376. action: 'session-terminate',
  1377. initiator: this.initiatorJid,
  1378. sid: this.sid
  1379. })
  1380. .c('reason')
  1381. .c((options && options.reason) || 'success')
  1382. .up();
  1383. if (options && options.reasonDescription) {
  1384. sessionTerminate
  1385. .c('text')
  1386. .t(options.reasonDescription)
  1387. .up()
  1388. .up();
  1389. } else {
  1390. sessionTerminate.up();
  1391. }
  1392. this._bridgeSessionId
  1393. && sessionTerminate.c(
  1394. 'bridge-session', {
  1395. xmlns: 'http://jitsi.org/protocol/focus',
  1396. id: this._bridgeSessionId,
  1397. restart: options && options.requestRestart === true
  1398. }).up();
  1399. logger.info(`${this} Sending session-terminate`);
  1400. logger.debug(sessionTerminate.tree());
  1401. this.connection.sendIQ(
  1402. sessionTerminate,
  1403. success,
  1404. this.newJingleErrorHandler(sessionTerminate, failure),
  1405. IQ_TIMEOUT);
  1406. } else {
  1407. logger.info(`${this} Skipped sending session-terminate`);
  1408. }
  1409. // this should result in 'onTerminated' being called by strope.jingle.js
  1410. this.connection.jingle.terminate(this.sid);
  1411. }
  1412. /**
  1413. *
  1414. * @param reasonCondition
  1415. * @param reasonText
  1416. */
  1417. onTerminated(reasonCondition, reasonText) {
  1418. // Do something with reason and reasonCondition when we start to care
  1419. // this.reasonCondition = reasonCondition;
  1420. // this.reasonText = reasonText;
  1421. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1422. this._xmppListeners.forEach(removeListener => removeListener());
  1423. this._xmppListeners = [];
  1424. if (this._removeSenderVideoConstraintsChangeListener) {
  1425. this._removeSenderVideoConstraintsChangeListener();
  1426. }
  1427. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1428. this.peerconnection.getRemoteTracks().forEach(track => {
  1429. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1430. });
  1431. }
  1432. this.close();
  1433. }
  1434. /**
  1435. * Handles XMPP connection state changes.
  1436. *
  1437. * @param {XmppConnection.Status} status - The new status.
  1438. */
  1439. onXmppStatusChanged(status) {
  1440. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1441. logger.info(`${this} Sending SSRC update on reconnect`);
  1442. this.notifyMySSRCUpdate(
  1443. this._cachedOldLocalSdp,
  1444. this._cachedNewLocalSdp);
  1445. }
  1446. }
  1447. /**
  1448. * Parse the information from the xml sourceAddElem and translate it
  1449. * into sdp lines
  1450. * @param {jquery xml element} sourceAddElem the source-add
  1451. * element from jingle
  1452. * @param {SDP object} currentRemoteSdp the current remote
  1453. * sdp (as of this new source-add)
  1454. * @returns {list} a list of SDP line strings that should
  1455. * be added to the remote SDP
  1456. */
  1457. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1458. const addSsrcInfo = [];
  1459. const self = this;
  1460. $(sourceAddElem).each((i1, content) => {
  1461. const name = $(content).attr('name');
  1462. let lines = '';
  1463. $(content)
  1464. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1465. .each(function() {
  1466. // eslint-disable-next-line no-invalid-this
  1467. const semantics = this.getAttribute('semantics');
  1468. const ssrcs
  1469. = $(this) // eslint-disable-line no-invalid-this
  1470. .find('>source')
  1471. .map(function() {
  1472. // eslint-disable-next-line no-invalid-this
  1473. return this.getAttribute('ssrc');
  1474. })
  1475. .get();
  1476. if (ssrcs.length) {
  1477. lines += `a=ssrc-group:${semantics} ${ssrcs.join(' ')}\r\n`;
  1478. }
  1479. });
  1480. // handles both >source and >description>source
  1481. const tmp
  1482. = $(content).find(
  1483. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1484. /* eslint-disable no-invalid-this */
  1485. tmp.each(function() {
  1486. const ssrc = $(this).attr('ssrc');
  1487. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1488. // Do not print the warning for unified plan p2p case since ssrcs are never removed from the SDP.
  1489. !self.isP2P && logger.warn(`${self} Source-add request for existing SSRC: ${ssrc}`);
  1490. return;
  1491. }
  1492. // eslint-disable-next-line newline-per-chained-call
  1493. $(this).find('>parameter').each(function() {
  1494. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1495. if ($(this).attr('value') && $(this).attr('value').length) {
  1496. lines += `:${$(this).attr('value')}`;
  1497. }
  1498. lines += '\r\n';
  1499. });
  1500. });
  1501. let midFound = false;
  1502. /* eslint-enable no-invalid-this */
  1503. currentRemoteSdp.media.forEach((media, i2) => {
  1504. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1505. return;
  1506. }
  1507. if (!addSsrcInfo[i2]) {
  1508. addSsrcInfo[i2] = '';
  1509. }
  1510. addSsrcInfo[i2] += lines;
  1511. midFound = true;
  1512. });
  1513. // In p2p unified mode with multi-stream enabled, the new sources will have content name that doesn't exist
  1514. // in the current remote description. Add a new m-line for this newly signaled source.
  1515. if (!midFound && this.isP2P) {
  1516. addSsrcInfo[name] = lines;
  1517. }
  1518. });
  1519. return addSsrcInfo;
  1520. }
  1521. /**
  1522. * Handles a Jingle source-add message for this Jingle session.
  1523. * @param elem An array of Jingle "content" elements.
  1524. */
  1525. addRemoteStream(elem) {
  1526. this._addOrRemoveRemoteStream(true /* add */, elem);
  1527. }
  1528. /**
  1529. * Handles a Jingle source-remove message for this Jingle session.
  1530. * @param elem An array of Jingle "content" elements.
  1531. */
  1532. removeRemoteStream(elem) {
  1533. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1534. }
  1535. /**
  1536. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1537. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1538. *
  1539. * @param {Object} message - The source map message.
  1540. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1541. * @returns {void}
  1542. */
  1543. processSourceMap(message, mediaType) {
  1544. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1545. return;
  1546. }
  1547. const newSsrcs = [];
  1548. for (const src of message.mappedSources) {
  1549. const { owner, source, ssrc } = src;
  1550. const isNewSsrc = this.peerconnection.addRemoteSsrc(ssrc, source);
  1551. if (isNewSsrc) {
  1552. newSsrcs.push(src);
  1553. logger.debug(`New SSRC signaled ${ssrc}: owner=${owner}, source-name=${source}`);
  1554. // Check if there is an old mapping for the given source and clear the owner on the associated track.
  1555. const oldSsrc = this.peerconnection.remoteSources.get(source);
  1556. if (oldSsrc) {
  1557. this._signalingLayer.removeSSRCOwners([ oldSsrc ]);
  1558. const track = this.peerconnection.getTrackBySSRC(oldSsrc);
  1559. if (track) {
  1560. track.setSourceName(undefined);
  1561. track.setOwner(undefined);
  1562. track._setVideoType(undefined);
  1563. }
  1564. }
  1565. } else {
  1566. logger.debug(`Existing SSRC re-mapped ${ssrc}: new owner=${owner}, source-name=${source}`);
  1567. const track = this.peerconnection.getTrackBySSRC(ssrc);
  1568. this._signalingLayer.setSSRCOwner(ssrc, owner, source);
  1569. track.setSourceName(source);
  1570. track.setOwner(owner);
  1571. // Update the muted state and the video type on the track since the presence for this track could have
  1572. // been received before the updated source map is received on the bridge channel.
  1573. const peerMediaInfo = this._signalingLayer.getPeerMediaInfo(owner, mediaType, source);
  1574. if (peerMediaInfo) {
  1575. track._setVideoType(peerMediaInfo.videoType);
  1576. this.peerconnection._sourceMutedChanged(source, peerMediaInfo.muted);
  1577. }
  1578. }
  1579. }
  1580. // Add the new SSRCs to the remote description by generating a source message.
  1581. if (newSsrcs.length) {
  1582. let node = $build('content', {
  1583. xmlns: 'urn:xmpp:jingle:1',
  1584. name: mediaType
  1585. }).c('description', {
  1586. xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  1587. media: mediaType
  1588. });
  1589. for (const src of newSsrcs) {
  1590. const { rtx, ssrc, source } = src;
  1591. let msid;
  1592. if (mediaType === MediaType.VIDEO) {
  1593. const idx = ++this.numRemoteVideoSources;
  1594. msid = `remote-video-${idx} remote-video-${idx}`;
  1595. if (rtx !== '-1') {
  1596. _addSourceElement(node, src, rtx, msid);
  1597. node.c('ssrc-group', {
  1598. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1599. semantics: 'FID'
  1600. })
  1601. .c('source', {
  1602. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1603. ssrc
  1604. })
  1605. .up()
  1606. .c('source', {
  1607. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1608. ssrc: rtx
  1609. })
  1610. .up()
  1611. .up();
  1612. }
  1613. } else {
  1614. const idx = ++this.numRemoteAudioSources;
  1615. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1616. }
  1617. _addSourceElement(node, src, ssrc, msid);
  1618. this.peerconnection.remoteSources.set(source, ssrc);
  1619. }
  1620. node = node.up();
  1621. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1622. }
  1623. }
  1624. /**
  1625. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1626. *
  1627. * @param {string} id Endpoint id of the participant that has left the call.
  1628. * @returns {void}
  1629. */
  1630. removeRemoteStreamsOnLeave(id) {
  1631. const workFunction = finishCallback => {
  1632. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1633. if (removeSsrcInfo.length) {
  1634. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1635. this._renegotiate(newRemoteSdp.raw)
  1636. .then(() => finishCallback(), error => finishCallback(error));
  1637. } else {
  1638. finishCallback();
  1639. }
  1640. };
  1641. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1642. this.modificationQueue.push(
  1643. workFunction,
  1644. error => {
  1645. if (error) {
  1646. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1647. } else {
  1648. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1649. }
  1650. });
  1651. }
  1652. /**
  1653. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1654. * Jingle session.
  1655. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1656. * otherwise.
  1657. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1658. * @private
  1659. */
  1660. _addOrRemoveRemoteStream(isAdd, elem) {
  1661. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1662. if (isAdd) {
  1663. this.readSsrcInfo(elem);
  1664. }
  1665. const workFunction = finishedCallback => {
  1666. if (!this.peerconnection.localDescription
  1667. || !this.peerconnection.localDescription.sdp) {
  1668. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1669. logger.error(errMsg);
  1670. finishedCallback(errMsg);
  1671. return;
  1672. }
  1673. logger.log(`${this} Processing ${logPrefix}`);
  1674. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1675. const addOrRemoveSsrcInfo
  1676. = isAdd
  1677. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1678. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1679. const newRemoteSdp
  1680. = isAdd
  1681. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1682. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1683. this._renegotiate(newRemoteSdp.raw).then(() => {
  1684. logger.log(`${this} ${logPrefix} - OK`);
  1685. finishedCallback();
  1686. }, error => {
  1687. logger.error(`${this} ${logPrefix} failed:`, error);
  1688. finishedCallback(error);
  1689. });
  1690. };
  1691. logger.debug(`${this} Queued ${logPrefix} task`);
  1692. // Queue and execute
  1693. this.modificationQueue.push(workFunction);
  1694. }
  1695. /**
  1696. * Takes in a jingle offer iq, returns the new sdp offer
  1697. * @param {jquery xml element} offerIq the incoming offer
  1698. * @returns {SDP object} the jingle offer translated to SDP
  1699. */
  1700. _processNewJingleOfferIq(offerIq) {
  1701. const remoteSdp = new SDP('');
  1702. if (this.webrtcIceTcpDisable) {
  1703. remoteSdp.removeTcpCandidates = true;
  1704. }
  1705. if (this.webrtcIceUdpDisable) {
  1706. remoteSdp.removeUdpCandidates = true;
  1707. }
  1708. if (this.failICE) {
  1709. remoteSdp.failICE = true;
  1710. }
  1711. remoteSdp.fromJingle(offerIq);
  1712. this.readSsrcInfo($(offerIq).find('>content'));
  1713. return remoteSdp;
  1714. }
  1715. /**
  1716. * Remove the given ssrc lines from the current remote sdp
  1717. * @param {list} removeSsrcInfo a list of SDP line strings that
  1718. * should be removed from the remote SDP
  1719. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1720. * in removeSsrcInfo
  1721. */
  1722. _processRemoteRemoveSource(removeSsrcInfo) {
  1723. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1724. let ssrcs;
  1725. removeSsrcInfo.forEach(lines => {
  1726. // eslint-disable-next-line no-param-reassign
  1727. lines = lines.split('\r\n');
  1728. lines.pop(); // remove empty last element;
  1729. ssrcs = lines.map(line => Number(line.split('a=ssrc:')[1]?.split(' ')[0]));
  1730. let mid;
  1731. lines.forEach(line => {
  1732. mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1733. if (mid > -1) {
  1734. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1735. if (this.isP2P) {
  1736. const mediaType = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0])?.media;
  1737. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, false);
  1738. [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ].forEach(direction => {
  1739. remoteSdp.media[mid] = remoteSdp.media[mid]
  1740. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1741. });
  1742. } else {
  1743. // Jvb connections will have direction set to 'sendonly' for the remote sources.
  1744. remoteSdp.media[mid] = remoteSdp.media[mid]
  1745. .replace(`a=${MediaDirection.SENDONLY}`, `a=${MediaDirection.INACTIVE}`);
  1746. // Reject the m-line so that the browser removes the associated transceiver from the list
  1747. // of available transceivers. This will prevent the client from trying to re-use these
  1748. // inactive transceivers when additional video sources are added to the peerconnection.
  1749. const { media, port } = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0]);
  1750. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`m=${media} ${port}`, `m=${media} 0`);
  1751. }
  1752. }
  1753. });
  1754. });
  1755. // Update the ssrc owners list.
  1756. ssrcs?.length && this._signalingLayer.removeSSRCOwners(ssrcs);
  1757. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1758. return remoteSdp;
  1759. }
  1760. /**
  1761. * Add the given ssrc lines to the current remote sdp
  1762. * @param {list} addSsrcInfo a list of SDP line strings that
  1763. * should be added to the remote SDP
  1764. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1765. * in removeSsrcInfo
  1766. */
  1767. _processRemoteAddSource(addSsrcInfo) {
  1768. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1769. // Add a new m-line in the remote description if the source info for a secondary video source is recceived from
  1770. // the remote p2p peer when multi-stream support is enabled.
  1771. if (addSsrcInfo.length > remoteSdp.media.length && this.isP2P) {
  1772. remoteSdp.addMlineForNewLocalSource(MediaType.VIDEO);
  1773. remoteSdp = new SDP(remoteSdp.raw);
  1774. }
  1775. addSsrcInfo.forEach((lines, idx) => {
  1776. remoteSdp.media[idx] += lines;
  1777. // Make sure to change the direction to 'sendrecv/sendonly' only for p2p connections. For jvb connections,
  1778. // a new m-line is added for the new remote sources.
  1779. if (this.isP2P) {
  1780. const mediaType = SDPUtil.parseMLine(remoteSdp.media[idx].split('\r\n')[0])?.media;
  1781. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, true);
  1782. [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ].forEach(direction => {
  1783. remoteSdp.media[idx] = remoteSdp.media[idx]
  1784. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1785. });
  1786. }
  1787. });
  1788. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1789. return remoteSdp;
  1790. }
  1791. /**
  1792. * Does a new offer/answer flow using the existing remote description (if not provided) and signals any new sources
  1793. * to Jicofo or the remote peer.
  1794. *
  1795. * @param {string} [optionalRemoteSdp] optional, raw remote sdp to use. If not provided, the remote sdp from the
  1796. * peerconnection will be used.
  1797. * @returns {Promise} promise which resolves when the o/a flow is complete with no arguments or rejects with an
  1798. * error {string}
  1799. */
  1800. _renegotiate(optionalRemoteSdp) {
  1801. if (this.peerconnection.signalingState === 'closed') {
  1802. const error = new Error('Attempted to renegotiate in state closed');
  1803. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1804. return Promise.reject(error);
  1805. }
  1806. const remoteSdp = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1807. if (!remoteSdp) {
  1808. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1809. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1810. return Promise.reject(error);
  1811. }
  1812. const remoteDescription = new RTCSessionDescription({
  1813. type: 'offer',
  1814. sdp: remoteSdp
  1815. });
  1816. const oldLocalSDP = this.peerconnection.localDescription.sdp;
  1817. logger.debug(`${this} Renegotiate: setting remote description`);
  1818. return this.peerconnection.setRemoteDescription(remoteDescription)
  1819. .then(() => {
  1820. logger.debug(`${this} Renegotiate: creating answer`);
  1821. return this.peerconnection.createAnswer(this.mediaConstraints);
  1822. })
  1823. .then(answer => {
  1824. logger.debug(`${this} Renegotiate: setting local description`);
  1825. return this.peerconnection.setLocalDescription(answer);
  1826. })
  1827. .then(() => {
  1828. if (oldLocalSDP) {
  1829. // Send the source updates after every renegotiation cycle.
  1830. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(this.peerconnection.localDescription.sdp));
  1831. }
  1832. });
  1833. }
  1834. /**
  1835. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  1836. * being added to the peerconnection for the first time.
  1837. *
  1838. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  1839. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  1840. * otherwise.
  1841. */
  1842. addTracks(localTracks = null) {
  1843. if (!localTracks?.length) {
  1844. Promise.reject(new Error('No tracks passed'));
  1845. }
  1846. if (localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  1847. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  1848. }
  1849. const replaceTracks = [];
  1850. const workFunction = finishedCallback => {
  1851. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1852. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  1853. .find(t => t.receiver.track.kind === MediaType.VIDEO
  1854. && t.direction === MediaDirection.RECVONLY
  1855. && t.currentDirection === MediaDirection.RECVONLY);
  1856. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  1857. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  1858. // existing one in that case.
  1859. for (const track of localTracks) {
  1860. if (!this.isP2P || !recvOnlyTransceiver) {
  1861. remoteSdp.addMlineForNewLocalSource(track.getType());
  1862. }
  1863. }
  1864. this._renegotiate(remoteSdp.raw)
  1865. .then(() => {
  1866. // Replace the tracks on the newly generated transceivers.
  1867. for (const track of localTracks) {
  1868. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  1869. }
  1870. return Promise.all(replaceTracks);
  1871. })
  1872. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  1873. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  1874. .then(() => this._renegotiate())
  1875. .then(() => finishedCallback(), error => finishedCallback(error));
  1876. };
  1877. return new Promise((resolve, reject) => {
  1878. logger.debug(`${this} Queued renegotiation after addTrack`);
  1879. this.modificationQueue.push(
  1880. workFunction,
  1881. error => {
  1882. if (error) {
  1883. if (error instanceof ClearedQueueError) {
  1884. // The session might have been terminated before the task was executed, making it obsolete.
  1885. logger.debug(`${this} renegotiation after addTrack aborted: session terminated`);
  1886. resolve();
  1887. return;
  1888. }
  1889. logger.error(`${this} renegotiation after addTrack error`, error);
  1890. reject(error);
  1891. } else {
  1892. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1893. resolve();
  1894. }
  1895. });
  1896. });
  1897. }
  1898. /**
  1899. * Resumes or suspends media transfer over the underlying peer connection.
  1900. *
  1901. * @param {boolean} active - <tt>true</tt> to enable media transfer or <tt>false</tt> to suspend media transmission
  1902. * @returns {Promise}
  1903. */
  1904. setMediaTransferActive(active) {
  1905. return this.peerconnection.tpcUtils.setMediaTransferActive(active)
  1906. .then(() => {
  1907. this.peerconnection.audioTransferActive = active;
  1908. this.peerconnection.videoTransferActive = active;
  1909. // Reconfigure the video tracks so that only the correct encodings are active.
  1910. const promises = [];
  1911. for (const track of this.rtc.getLocalVideoTracks()) {
  1912. promises.push(this.peerconnection.configureSenderVideoEncodings(track));
  1913. }
  1914. return Promise.allSettled(promises);
  1915. });
  1916. }
  1917. /**
  1918. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1919. * offer/answer cycle after both operations are done. Either
  1920. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1921. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1922. * <tt>oldTrack</tt>
  1923. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1924. * replaced
  1925. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1926. * @returns {Promise} which resolves once the replacement is complete
  1927. * with no arguments or rejects with an error {string}
  1928. */
  1929. replaceTrack(oldTrack, newTrack) {
  1930. const workFunction = finishedCallback => {
  1931. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  1932. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1933. .then(shouldRenegotiate => {
  1934. let promise = Promise.resolve();
  1935. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  1936. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  1937. if (shouldRenegotiate && (oldTrack || newTrack) && this.state === JingleSessionState.ACTIVE) {
  1938. promise = this._renegotiate();
  1939. }
  1940. return promise.then(() => {
  1941. // Set the source name of the new track.
  1942. if (oldTrack && newTrack && oldTrack.isVideoTrack()) {
  1943. newTrack.setSourceName(oldTrack.getSourceName());
  1944. }
  1945. });
  1946. })
  1947. .then(() => finishedCallback(), error => finishedCallback(error));
  1948. };
  1949. return new Promise((resolve, reject) => {
  1950. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  1951. this.modificationQueue.push(
  1952. workFunction,
  1953. error => {
  1954. if (error) {
  1955. if (error instanceof ClearedQueueError) {
  1956. // The session might have been terminated before the task was executed, making it obsolete.
  1957. logger.debug('Replace track aborted: session terminated');
  1958. resolve();
  1959. return;
  1960. }
  1961. logger.error(`${this} Replace track error:`, error);
  1962. reject(error);
  1963. } else {
  1964. logger.info(`${this} Replace track done!`);
  1965. resolve();
  1966. }
  1967. });
  1968. });
  1969. }
  1970. /**
  1971. * Parse the information from the xml sourceRemoveElem and translate it
  1972. * into sdp lines
  1973. * @param {jquery xml element} sourceRemoveElem the source-remove
  1974. * element from jingle
  1975. * @param {SDP object} currentRemoteSdp the current remote
  1976. * sdp (as of this new source-remove)
  1977. * @returns {list} a list of SDP line strings that should
  1978. * be removed from the remote SDP
  1979. */
  1980. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1981. const removeSsrcInfo = [];
  1982. $(sourceRemoveElem).each((i1, content) => {
  1983. const name = $(content).attr('name');
  1984. let lines = '';
  1985. $(content)
  1986. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1987. .each(function() {
  1988. /* eslint-disable no-invalid-this */
  1989. const semantics = this.getAttribute('semantics');
  1990. const ssrcs
  1991. = $(this)
  1992. .find('>source')
  1993. .map(function() {
  1994. return this.getAttribute('ssrc');
  1995. })
  1996. .get();
  1997. if (ssrcs.length) {
  1998. lines
  1999. += `a=ssrc-group:${semantics} ${
  2000. ssrcs.join(' ')}\r\n`;
  2001. }
  2002. /* eslint-enable no-invalid-this */
  2003. });
  2004. const ssrcs = [];
  2005. // handles both >source and >description>source versions
  2006. const tmp
  2007. = $(content).find(
  2008. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  2009. tmp.each(function() {
  2010. // eslint-disable-next-line no-invalid-this
  2011. const ssrc = $(this).attr('ssrc');
  2012. ssrcs.push(ssrc);
  2013. });
  2014. currentRemoteSdp.media.forEach((media, i2) => {
  2015. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  2016. return;
  2017. }
  2018. if (!removeSsrcInfo[i2]) {
  2019. removeSsrcInfo[i2] = '';
  2020. }
  2021. ssrcs.forEach(ssrc => {
  2022. const ssrcLines
  2023. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  2024. if (ssrcLines.length) {
  2025. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  2026. }
  2027. });
  2028. removeSsrcInfo[i2] += lines;
  2029. });
  2030. });
  2031. return removeSsrcInfo;
  2032. }
  2033. /**
  2034. * Adds local track back to the peerconnection associated with this session.
  2035. * @param {JitsiLocalTrack} track
  2036. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  2037. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  2038. * details in case something goes wrong.
  2039. */
  2040. addTrackToPc(track) {
  2041. return this._addRemoveTrack(false /* add */, track)
  2042. .then(() => {
  2043. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  2044. // unmutes it the first time, all the parameters need to be configured.
  2045. if (track.isVideoTrack()) {
  2046. return this.peerconnection.configureSenderVideoEncodings(track);
  2047. }
  2048. });
  2049. }
  2050. /**
  2051. * Remove local track as part of the mute operation.
  2052. * @param {JitsiLocalTrack} track the local track to be removed
  2053. * @return {Promise} a promise which will be resolved once the local track
  2054. * is removed from this session and the renegotiation is performed.
  2055. * The promise will be rejected with a <tt>string</tt> that the describes
  2056. * the error if anything goes wrong.
  2057. */
  2058. removeTrackFromPc(track) {
  2059. return this._addRemoveTrack(true /* remove */, track);
  2060. }
  2061. /**
  2062. * See {@link addTrackToPc} and {@link removeTrackFromPc}.
  2063. * @param {boolean} isRemove <tt>true</tt> for "remove" operation or <tt>false</tt> for "add" operation.
  2064. * @param {JitsiLocalTrack} track the track that will be added/removed
  2065. * @private
  2066. */
  2067. _addRemoveTrack(isRemove, track) {
  2068. if (!track) {
  2069. return Promise.reject('invalid "track" argument value');
  2070. }
  2071. const operationName = isRemove ? 'removeTrack' : 'addTrack';
  2072. const workFunction = finishedCallback => {
  2073. const tpc = this.peerconnection;
  2074. if (!tpc) {
  2075. finishedCallback(`Error: tried ${operationName} track with no active peer connection`);
  2076. return;
  2077. }
  2078. const operationPromise
  2079. = isRemove
  2080. ? tpc.removeTrackFromPc(track)
  2081. : tpc.addTrackToPc(track);
  2082. operationPromise
  2083. .then(shouldRenegotiate => {
  2084. if (shouldRenegotiate) {
  2085. this._renegotiate().then(finishedCallback);
  2086. } else {
  2087. finishedCallback();
  2088. }
  2089. },
  2090. finishedCallback /* will be called with an error */);
  2091. };
  2092. logger.debug(`${this} Queued ${operationName} task`);
  2093. return new Promise((resolve, reject) => {
  2094. this.modificationQueue.push(
  2095. workFunction,
  2096. error => {
  2097. if (error) {
  2098. if (error instanceof ClearedQueueError) {
  2099. // The session might have been terminated before the task was executed, making it obsolete.
  2100. logger.debug(`${this} ${operationName} aborted: session terminated`);
  2101. resolve();
  2102. return;
  2103. }
  2104. logger.error(`${this} ${operationName} failed`);
  2105. reject(error);
  2106. } else {
  2107. logger.debug(`${this} ${operationName} done`);
  2108. resolve();
  2109. }
  2110. });
  2111. });
  2112. }
  2113. /**
  2114. * Resumes or suspends video media transfer over the p2p peer connection.
  2115. *
  2116. * @param {boolean} videoActive <tt>true</tt> to enable video media transfer or <tt>false</tt> to suspend video
  2117. * media transmission.
  2118. * @return {Promise} a <tt>Promise</tt> which will resolve once the operation is done. It will be rejected with
  2119. * an error description as a string in case anything goes wrong.
  2120. */
  2121. setP2pVideoTransferActive(videoActive) {
  2122. if (!this.peerconnection) {
  2123. return Promise.reject('Can not modify video transfer active state,'
  2124. + ' before "initialize" is called');
  2125. }
  2126. if (this._localSendReceiveVideoActive !== videoActive) {
  2127. this._localSendReceiveVideoActive = videoActive;
  2128. if (this.isP2P && this.state === JingleSessionState.ACTIVE) {
  2129. this.sendContentModify();
  2130. }
  2131. return this.peerconnection
  2132. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  2133. }
  2134. return Promise.resolve();
  2135. }
  2136. /**
  2137. * Enables/disables local video based on 'senders' attribute of the video conent in 'content-modify' IQ sent by the
  2138. * remote peer. Also, checks if the sourceMaxFrameHeight (as requested by the p2p peer) or the senders attribute of
  2139. * the video content has changed and modifies the local video resolution accordingly.
  2140. */
  2141. modifyContents(jingleContents) {
  2142. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  2143. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  2144. if (sourceMaxFrameHeights) {
  2145. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  2146. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  2147. }
  2148. if (newVideoSenders === null) {
  2149. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  2150. return;
  2151. }
  2152. if (!this._assertNotEnded()) {
  2153. return;
  2154. }
  2155. const isRemoteVideoActive
  2156. = newVideoSenders === 'both'
  2157. || (newVideoSenders === 'initiator' && this.isInitiator)
  2158. || (newVideoSenders === 'responder' && !this.isInitiator);
  2159. if (isRemoteVideoActive !== this._remoteSendReceiveVideoActive) {
  2160. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  2161. this._remoteSendReceiveVideoActive = isRemoteVideoActive;
  2162. this.peerconnection
  2163. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  2164. }
  2165. }
  2166. /**
  2167. * Figures out added/removed ssrcs and send update IQs.
  2168. * @param oldSDP SDP object for old description.
  2169. * @param newSDP SDP object for new description.
  2170. */
  2171. notifyMySSRCUpdate(oldSDP, newSDP) {
  2172. if (this.state !== JingleSessionState.ACTIVE) {
  2173. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  2174. return;
  2175. }
  2176. if (!this.connection.connected) {
  2177. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2178. if (!this._cachedOldLocalSdp) {
  2179. this._cachedOldLocalSdp = oldSDP;
  2180. }
  2181. this._cachedNewLocalSdp = newSDP;
  2182. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  2183. return;
  2184. }
  2185. this._cachedOldLocalSdp = undefined;
  2186. this._cachedNewLocalSdp = undefined;
  2187. const getSignaledSourceInfo = sdpDiffer => {
  2188. const newMedia = sdpDiffer.getNewMedia();
  2189. let ssrcs = [];
  2190. let mediaType = null;
  2191. // It is assumed that sources are signaled one at a time.
  2192. Object.keys(newMedia).forEach(mediaIndex => {
  2193. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  2194. mediaType = newMedia[mediaIndex].mid;
  2195. if (signaledSsrcs?.length) {
  2196. ssrcs = ssrcs.concat(signaledSsrcs);
  2197. }
  2198. });
  2199. return {
  2200. mediaType,
  2201. ssrcs
  2202. };
  2203. };
  2204. // send source-remove IQ.
  2205. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2206. const remove = $iq({ to: this.remoteJid,
  2207. type: 'set' })
  2208. .c('jingle', {
  2209. xmlns: 'urn:xmpp:jingle:1',
  2210. action: 'source-remove',
  2211. initiator: this.initiatorJid,
  2212. sid: this.sid
  2213. }
  2214. );
  2215. sdpDiffer.toJingle(remove);
  2216. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  2217. // need to
  2218. const ctx = {};
  2219. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2220. if (removedSsrcInfo.ssrcs.length) {
  2221. // Log only the SSRCs instead of the full IQ.
  2222. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  2223. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  2224. this.connection.sendIQ(
  2225. remove,
  2226. () => {
  2227. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  2228. },
  2229. this.newJingleErrorHandler(remove, error => {
  2230. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  2231. }),
  2232. IQ_TIMEOUT);
  2233. }
  2234. // send source-add IQ.
  2235. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2236. const add = $iq({ to: this.remoteJid,
  2237. type: 'set' })
  2238. .c('jingle', {
  2239. xmlns: 'urn:xmpp:jingle:1',
  2240. action: 'source-add',
  2241. initiator: this.initiatorJid,
  2242. sid: this.sid
  2243. }
  2244. );
  2245. sdpDiffer.toJingle(add);
  2246. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2247. if (addedSsrcInfo.ssrcs.length) {
  2248. // Log only the SSRCs instead of the full IQ.
  2249. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  2250. this.connection.sendIQ(
  2251. add,
  2252. () => {
  2253. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  2254. },
  2255. this.newJingleErrorHandler(add, error => {
  2256. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  2257. }),
  2258. IQ_TIMEOUT);
  2259. }
  2260. }
  2261. /**
  2262. * Method returns function(errorResponse) which is a callback to be passed
  2263. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2264. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2265. * structure is as follows:
  2266. * {
  2267. * code: {XMPP error response code}
  2268. * reason: {the name of XMPP error reason element or 'timeout' if the
  2269. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2270. * source: {request.tree() that provides original request}
  2271. * session: {this JingleSessionPC.toString()}
  2272. * }
  2273. * @param request Strophe IQ instance which is the request to be dumped into
  2274. * the error structure
  2275. * @param failureCb function(error) called when error response was returned
  2276. * or when a timeout has occurred.
  2277. * @returns {function(this:JingleSessionPC)}
  2278. */
  2279. newJingleErrorHandler(request, failureCb) {
  2280. return errResponse => {
  2281. const error = {};
  2282. // Get XMPP error code and condition(reason)
  2283. const errorElSel = $(errResponse).find('error');
  2284. if (errorElSel.length) {
  2285. error.code = errorElSel.attr('code');
  2286. const errorReasonSel = $(errResponse).find('error :first');
  2287. if (errorReasonSel.length) {
  2288. error.reason = errorReasonSel[0].tagName;
  2289. }
  2290. const errorMsgSel = errorElSel.find('>text');
  2291. if (errorMsgSel.length) {
  2292. error.msg = errorMsgSel.text();
  2293. }
  2294. }
  2295. if (!errResponse) {
  2296. error.reason = 'timeout';
  2297. }
  2298. error.session = this.toString();
  2299. if (failureCb) {
  2300. failureCb(error);
  2301. } else if (this.state === JingleSessionState.ENDED
  2302. && error.reason === 'item-not-found') {
  2303. // When remote peer decides to terminate the session, but it
  2304. // still have few messages on the queue for processing,
  2305. // it will first send us 'session-terminate' (we enter ENDED)
  2306. // and then follow with 'item-not-found' for the queued requests
  2307. // We don't want to have that logged on error level.
  2308. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  2309. } else {
  2310. logger.error(`Jingle error: ${JSON.stringify(error)}`);
  2311. }
  2312. };
  2313. }
  2314. /**
  2315. * Returns the ice connection state for the peer connection.
  2316. * @returns the ice connection state for the peer connection.
  2317. */
  2318. getIceConnectionState() {
  2319. return this.peerconnection.getConnectionState();
  2320. }
  2321. /**
  2322. * Closes the peerconnection.
  2323. */
  2324. close() {
  2325. this.state = JingleSessionState.ENDED;
  2326. this.establishmentDuration = undefined;
  2327. if (this.peerconnection) {
  2328. this.peerconnection.onicecandidate = null;
  2329. this.peerconnection.oniceconnectionstatechange = null;
  2330. this.peerconnection.onnegotiationneeded = null;
  2331. this.peerconnection.onsignalingstatechange = null;
  2332. }
  2333. logger.debug(`${this} Clearing modificationQueue`);
  2334. // Remove any pending tasks from the queue
  2335. this.modificationQueue.clear();
  2336. logger.debug(`${this} Queued PC close task`);
  2337. this.modificationQueue.push(finishCallback => {
  2338. // do not try to close if already closed.
  2339. this.peerconnection && this.peerconnection.close();
  2340. finishCallback();
  2341. logger.debug(`${this} PC close task done!`);
  2342. });
  2343. logger.debug(`${this} Shutdown modificationQueue!`);
  2344. // No more tasks can go in after the close task
  2345. this.modificationQueue.shutdown();
  2346. }
  2347. /**
  2348. * Converts to string with minor summary.
  2349. * @return {string}
  2350. */
  2351. toString() {
  2352. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2353. }
  2354. }