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

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