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. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  707. *
  708. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  709. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  710. * 'session-accept' sent.
  711. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  712. * can be used to log some details about the error.
  713. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  714. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  715. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  716. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  717. * assumption that the initial offer/answer cycle has been executed already.
  718. */
  719. acceptOffer(jingleOffer, success, failure, localTracks = []) {
  720. this.setOfferAnswerCycle(
  721. jingleOffer,
  722. () => {
  723. // FIXME we may not care about RESULT packet for session-accept
  724. // then we should either call 'success' here immediately or
  725. // modify sendSessionAccept method to do that
  726. this.sendSessionAccept(() => {
  727. // Start processing tasks on the modification queue.
  728. logger.debug(`${this} Resuming the modification queue after session is established!`);
  729. this.modificationQueue.resume();
  730. success();
  731. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  732. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  733. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  734. // This will happen when someone shares a secondary source to a two people call, the other user
  735. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  736. // point, there are 2 video tracks which need to be signaled to the remote peer.
  737. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  738. videoTracks.length && videoTracks.splice(0, 1);
  739. videoTracks.length && this.addTracks(videoTracks);
  740. },
  741. error => {
  742. failure(error);
  743. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  744. });
  745. },
  746. failure,
  747. localTracks);
  748. }
  749. /**
  750. * {@inheritDoc}
  751. */
  752. addIceCandidates(elem) {
  753. if (this.peerconnection.signalingState === 'closed') {
  754. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  755. return;
  756. }
  757. const iceCandidates = [];
  758. elem.find('>content>transport>candidate')
  759. .each((idx, candidate) => {
  760. let line = SDPUtil.candidateFromJingle(candidate);
  761. line = line.replace('\r\n', '').replace('a=', '');
  762. // FIXME this code does not care to handle
  763. // non-bundle transport
  764. const rtcCandidate = new RTCIceCandidate({
  765. sdpMLineIndex: 0,
  766. // FF comes up with more complex names like audio-23423,
  767. // Given that it works on both Chrome and FF without
  768. // providing it, let's leave it like this for the time
  769. // being...
  770. // sdpMid: 'audio',
  771. sdpMid: '',
  772. candidate: line
  773. });
  774. iceCandidates.push(rtcCandidate);
  775. });
  776. if (!iceCandidates.length) {
  777. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  778. return;
  779. }
  780. // We want to have this task queued, so that we know it is executed,
  781. // after the initial sRD/sLD offer/answer cycle was done (based on
  782. // the assumption that candidates are spawned after the offer/answer
  783. // and XMPP preserves order).
  784. const workFunction = finishedCallback => {
  785. for (const iceCandidate of iceCandidates) {
  786. this.peerconnection.addIceCandidate(iceCandidate)
  787. .then(
  788. () => logger.debug(`${this} addIceCandidate ok!`),
  789. err => logger.error(`${this} addIceCandidate failed!`, err));
  790. }
  791. finishedCallback();
  792. logger.debug(`${this} ICE candidates task finished`);
  793. };
  794. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  795. this.modificationQueue.push(workFunction);
  796. }
  797. /**
  798. * Handles a Jingle source-add message for this Jingle session.
  799. *
  800. * @param {Array<Element>} elem an array of Jingle "content" elements.
  801. * @returns {Promise} resolved when the operation is done or rejected with an error.
  802. */
  803. addRemoteStream(elem) {
  804. this._addOrRemoveRemoteStream(true /* add */, elem);
  805. }
  806. /**
  807. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  808. * being added to the peerconnection for the first time.
  809. *
  810. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  811. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  812. * otherwise.
  813. */
  814. addTracks(localTracks = null) {
  815. if (!localTracks?.length) {
  816. Promise.reject(new Error('No tracks passed'));
  817. }
  818. if (localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  819. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  820. }
  821. const replaceTracks = [];
  822. const workFunction = finishedCallback => {
  823. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  824. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  825. .find(t => t.receiver.track.kind === MediaType.VIDEO
  826. && t.direction === MediaDirection.RECVONLY
  827. && t.currentDirection === MediaDirection.RECVONLY);
  828. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  829. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  830. // existing one in that case.
  831. for (const track of localTracks) {
  832. if (!this.isP2P || !recvOnlyTransceiver) {
  833. remoteSdp.addMlineForNewLocalSource(track.getType());
  834. }
  835. }
  836. this._renegotiate(remoteSdp.raw)
  837. .then(() => {
  838. // Replace the tracks on the newly generated transceivers.
  839. for (const track of localTracks) {
  840. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  841. }
  842. return Promise.all(replaceTracks);
  843. })
  844. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  845. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  846. .then(() => this._renegotiate())
  847. .then(() => finishedCallback(), error => finishedCallback(error));
  848. };
  849. return new Promise((resolve, reject) => {
  850. logger.debug(`${this} Queued renegotiation after addTrack`);
  851. this.modificationQueue.push(
  852. workFunction,
  853. error => {
  854. if (error) {
  855. if (error instanceof ClearedQueueError) {
  856. // The session might have been terminated before the task was executed, making it obsolete.
  857. logger.debug(`${this} renegotiation after addTrack aborted: session terminated`);
  858. resolve();
  859. return;
  860. }
  861. logger.error(`${this} renegotiation after addTrack error`, error);
  862. reject(error);
  863. } else {
  864. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  865. resolve();
  866. }
  867. });
  868. });
  869. }
  870. /**
  871. * Adds local track back to the peerconnection associated with this session.
  872. *
  873. * @param {JitsiLocalTrack} track - the local track to be added back to the peerconnection.
  874. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  875. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  876. * details in case something goes wrong.
  877. * @returns {Promise<void>}
  878. */
  879. addTrackToPc(track) {
  880. return this._addRemoveTrack(false /* add */, track)
  881. .then(() => {
  882. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  883. // unmutes it the first time, all the parameters need to be configured.
  884. if (track.isVideoTrack()) {
  885. return this.peerconnection.configureVideoSenderEncodings(track);
  886. }
  887. });
  888. }
  889. /**
  890. * Closes the underlying peerconnection and shuts down the modification queue.
  891. *
  892. * @returns {void}
  893. */
  894. close() {
  895. this.state = JingleSessionState.ENDED;
  896. this.establishmentDuration = undefined;
  897. if (this.peerconnection) {
  898. this.peerconnection.onicecandidate = null;
  899. this.peerconnection.oniceconnectionstatechange = null;
  900. this.peerconnection.onnegotiationneeded = null;
  901. this.peerconnection.onsignalingstatechange = null;
  902. }
  903. logger.debug(`${this} Clearing modificationQueue`);
  904. // Remove any pending tasks from the queue
  905. this.modificationQueue.clear();
  906. logger.debug(`${this} Queued PC close task`);
  907. this.modificationQueue.push(finishCallback => {
  908. // do not try to close if already closed.
  909. this.peerconnection && this.peerconnection.close();
  910. finishCallback();
  911. logger.debug(`${this} PC close task done!`);
  912. });
  913. logger.debug(`${this} Shutdown modificationQueue!`);
  914. // No more tasks can go in after the close task
  915. this.modificationQueue.shutdown();
  916. }
  917. /**
  918. * @inheritDoc
  919. * @param {JingleSessionPCOptions} options - a set of config options.
  920. * @returns {void}
  921. */
  922. doInitialize(options) {
  923. this.failICE = Boolean(options.failICE);
  924. this.lasticecandidate = false;
  925. this.options = options;
  926. /**
  927. * {@code true} if reconnect is in progress.
  928. * @type {boolean}
  929. */
  930. this.isReconnect = false;
  931. /**
  932. * Set to {@code true} if the connection was ever stable
  933. * @type {boolean}
  934. */
  935. this.wasstable = false;
  936. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  937. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  938. const pcOptions = { disableRtx: options.disableRtx };
  939. if (options.gatherStats) {
  940. pcOptions.maxstats = DEFAULT_MAX_STATS;
  941. }
  942. pcOptions.capScreenshareBitrate = false;
  943. pcOptions.codecSettings = options.codecSettings;
  944. pcOptions.enableInsertableStreams = options.enableInsertableStreams;
  945. pcOptions.usesCodecSelectionAPI = this.usesCodecSelectionAPI
  946. = browser.supportsCodecSelectionAPI() && options.testing?.enableCodecSelectionAPI && !this.isP2P;
  947. if (options.videoQuality) {
  948. const settings = Object.entries(options.videoQuality)
  949. .map(entry => {
  950. entry[0] = entry[0].toLowerCase();
  951. return entry;
  952. });
  953. pcOptions.videoQuality = Object.fromEntries(settings);
  954. }
  955. pcOptions.forceTurnRelay = options.forceTurnRelay;
  956. pcOptions.audioQuality = options.audioQuality;
  957. pcOptions.disableSimulcast = this.isP2P ? true : options.disableSimulcast;
  958. if (!this.isP2P) {
  959. // Do not send lower spatial layers for low fps screenshare and enable them only for high fps screenshare.
  960. pcOptions.capScreenshareBitrate = !(options.desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE);
  961. }
  962. if (options.startSilent) {
  963. pcOptions.startSilent = true;
  964. }
  965. this.peerconnection
  966. = this.rtc.createPeerConnection(
  967. this._signalingLayer,
  968. this.pcConfig,
  969. this.isP2P,
  970. pcOptions);
  971. this.peerconnection.onicecandidate = ev => {
  972. if (!ev) {
  973. // There was an incomplete check for ev before which left
  974. // the last line of the function unprotected from a potential
  975. // throw of an exception. Consequently, it may be argued that
  976. // the check is unnecessary. Anyway, I'm leaving it and making
  977. // the check complete.
  978. return;
  979. }
  980. // XXX this is broken, candidate is not parsed.
  981. const candidate = ev.candidate;
  982. const now = window.performance.now();
  983. if (candidate) {
  984. if (this._gatheringStartedTimestamp === null) {
  985. this._gatheringStartedTimestamp = now;
  986. }
  987. // Discard candidates of disabled protocols.
  988. let protocol = candidate.protocol;
  989. if (typeof protocol === 'string') {
  990. protocol = protocol.toLowerCase();
  991. if (protocol === 'tcp' || protocol === 'ssltcp') {
  992. if (this.webrtcIceTcpDisable) {
  993. return;
  994. }
  995. } else if (protocol === 'udp') {
  996. if (this.webrtcIceUdpDisable) {
  997. return;
  998. }
  999. }
  1000. }
  1001. } else if (!this._gatheringReported) {
  1002. // End of gathering
  1003. Statistics.sendAnalytics(
  1004. ICE_DURATION,
  1005. {
  1006. phase: 'gathering',
  1007. value: now - this._gatheringStartedTimestamp,
  1008. p2p: this.isP2P,
  1009. initiator: this.isInitiator
  1010. });
  1011. this._gatheringReported = true;
  1012. }
  1013. if (this.isP2P) {
  1014. this.sendIceCandidate(candidate);
  1015. }
  1016. };
  1017. // Note there is a change in the spec about closed:
  1018. // This value moved into the RTCPeerConnectionState enum in
  1019. // the May 13, 2016 draft of the specification, as it reflects the state
  1020. // of the RTCPeerConnection, not the signaling connection. You now
  1021. // detect a closed connection by checking for connectionState to be
  1022. // "closed" instead.
  1023. // I suppose at some point this will be moved to onconnectionstatechange
  1024. this.peerconnection.onsignalingstatechange = () => {
  1025. if (this.peerconnection.signalingState === 'stable') {
  1026. this.wasstable = true;
  1027. } else if (this.peerconnection.signalingState === 'closed'
  1028. || this.peerconnection.connectionState === 'closed') {
  1029. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  1030. }
  1031. };
  1032. /**
  1033. * The oniceconnectionstatechange event handler contains the code to
  1034. * execute when the iceconnectionstatechange event, of type Event,
  1035. * is received by this RTCPeerConnection. Such an event is sent when
  1036. * the value of RTCPeerConnection.iceConnectionState changes.
  1037. */
  1038. this.peerconnection.oniceconnectionstatechange = () => {
  1039. const now = window.performance.now();
  1040. let isStable = false;
  1041. if (!this.isP2P) {
  1042. this.room.connectionTimes[
  1043. `ice.state.${this.peerconnection.iceConnectionState}`]
  1044. = now;
  1045. }
  1046. logger.log(`(TIME) ICE ${this.peerconnection.iceConnectionState} ${this.isP2P ? 'P2P' : 'JVB'}:\t`, now);
  1047. Statistics.sendAnalytics(
  1048. ICE_STATE_CHANGED,
  1049. {
  1050. p2p: this.isP2P,
  1051. state: this.peerconnection.iceConnectionState,
  1052. 'signaling_state': this.peerconnection.signalingState,
  1053. reconnect: this.isReconnect,
  1054. value: now
  1055. });
  1056. this.room.eventEmitter.emit(
  1057. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  1058. this,
  1059. this.peerconnection.iceConnectionState);
  1060. switch (this.peerconnection.iceConnectionState) {
  1061. case 'checking':
  1062. this._iceCheckingStartedTimestamp = now;
  1063. break;
  1064. case 'connected':
  1065. case 'completed':
  1066. // Informs interested parties that the connection has been restored. This includes the case when
  1067. // media connection to the bridge has been restored after an ICE failure by using session-terminate.
  1068. if (this.peerconnection.signalingState === 'stable') {
  1069. isStable = true;
  1070. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED, this);
  1071. }
  1072. // Add a workaround for an issue on chrome in Unified plan when the local endpoint is the offerer.
  1073. // The 'signalingstatechange' event for 'stable' is handled after the 'iceconnectionstatechange' event
  1074. // for 'completed' is handled by the client. This prevents the client from firing a
  1075. // CONNECTION_ESTABLISHED event for the p2p session. As a result, the offerer continues to stay on the
  1076. // jvb connection while the remote peer switches to the p2p connection breaking the media flow between
  1077. // the endpoints.
  1078. // TODO - file a chromium bug and add the information here.
  1079. if (!this.wasConnected
  1080. && (this.wasstable
  1081. || isStable
  1082. || (this.isInitiator && (browser.isChromiumBased() || browser.isReactNative())))) {
  1083. Statistics.sendAnalytics(
  1084. ICE_DURATION,
  1085. {
  1086. phase: 'checking',
  1087. value: now - this._iceCheckingStartedTimestamp,
  1088. p2p: this.isP2P,
  1089. initiator: this.isInitiator
  1090. });
  1091. // Switch between ICE gathering and ICE checking whichever
  1092. // started first (scenarios are different for initiator
  1093. // vs responder)
  1094. const iceStarted
  1095. = Math.min(
  1096. this._iceCheckingStartedTimestamp,
  1097. this._gatheringStartedTimestamp);
  1098. this.establishmentDuration = now - iceStarted;
  1099. Statistics.sendAnalytics(
  1100. ICE_DURATION,
  1101. {
  1102. phase: 'establishment',
  1103. value: this.establishmentDuration,
  1104. p2p: this.isP2P,
  1105. initiator: this.isInitiator
  1106. });
  1107. this.wasConnected = true;
  1108. this.room.eventEmitter.emit(
  1109. XMPPEvents.CONNECTION_ESTABLISHED, this);
  1110. }
  1111. this.isReconnect = false;
  1112. break;
  1113. case 'disconnected':
  1114. this.isReconnect = true;
  1115. // Informs interested parties that the connection has been
  1116. // interrupted.
  1117. if (this.wasstable) {
  1118. this.room.eventEmitter.emit(
  1119. XMPPEvents.CONNECTION_INTERRUPTED, this);
  1120. }
  1121. break;
  1122. case 'failed':
  1123. this.room.eventEmitter.emit(
  1124. XMPPEvents.CONNECTION_ICE_FAILED, this);
  1125. break;
  1126. }
  1127. };
  1128. /**
  1129. * The connection state event is fired whenever the aggregate of underlying
  1130. * transports change their state.
  1131. */
  1132. this.peerconnection.onconnectionstatechange = () => {
  1133. const icestate = this.peerconnection.iceConnectionState;
  1134. switch (this.peerconnection.connectionState) {
  1135. case 'failed':
  1136. // Since version 76 Chrome no longer switches ICE connection
  1137. // state to failed (see
  1138. // https://bugs.chromium.org/p/chromium/issues/detail?id=982793
  1139. // for details) we use this workaround to recover from lost connections
  1140. if (icestate === 'disconnected') {
  1141. this.room.eventEmitter.emit(
  1142. XMPPEvents.CONNECTION_ICE_FAILED, this);
  1143. }
  1144. break;
  1145. }
  1146. };
  1147. /**
  1148. * The negotiationneeded event is fired whenever we shake the media on the
  1149. * RTCPeerConnection object.
  1150. */
  1151. this.peerconnection.onnegotiationneeded = () => {
  1152. const state = this.peerconnection.signalingState;
  1153. const remoteDescription = this.peerconnection.remoteDescription;
  1154. if (!this.isP2P
  1155. && state === 'stable'
  1156. && remoteDescription
  1157. && typeof remoteDescription.sdp === 'string') {
  1158. logger.info(`${this} onnegotiationneeded fired on ${this.peerconnection}`);
  1159. const workFunction = finishedCallback => {
  1160. this._renegotiate()
  1161. .then(() => this.peerconnection.configureAudioSenderEncodings())
  1162. .then(() => finishedCallback(), error => finishedCallback(error));
  1163. };
  1164. this.modificationQueue.push(
  1165. workFunction,
  1166. error => {
  1167. if (error) {
  1168. logger.error(`${this} onnegotiationneeded error`, error);
  1169. } else {
  1170. logger.debug(`${this} onnegotiationneeded executed - OK`);
  1171. }
  1172. });
  1173. }
  1174. };
  1175. }
  1176. /**
  1177. * Returns the ice connection state for the peer connection.
  1178. *
  1179. * @returns the ice connection state for the peer connection.
  1180. */
  1181. getIceConnectionState() {
  1182. return this.peerconnection.getConnectionState();
  1183. }
  1184. /**
  1185. * Returns the preference for max frame height for the remote video sources.
  1186. *
  1187. * @returns {Map<string, number>|undefined}
  1188. */
  1189. getRemoteSourcesRecvMaxFrameHeight() {
  1190. if (this.isP2P) {
  1191. return this.remoteSourceMaxFrameHeights;
  1192. }
  1193. return undefined;
  1194. }
  1195. /**
  1196. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  1197. *
  1198. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  1199. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  1200. * @returns {void}
  1201. */
  1202. invite(localTracks = []) {
  1203. if (!this.isInitiator) {
  1204. throw new Error('Trying to invite from the responder session');
  1205. }
  1206. logger.debug(`${this} Executing invite task`);
  1207. const addTracks = [];
  1208. for (const track of localTracks) {
  1209. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1210. }
  1211. Promise.all(addTracks)
  1212. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  1213. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  1214. .then(() => {
  1215. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  1216. this.sendSessionInitiate(this.peerconnection.localDescription.sdp);
  1217. })
  1218. .then(() => {
  1219. logger.debug(`${this} invite executed - OK`);
  1220. })
  1221. .catch(error => {
  1222. logger.error(`${this} invite error`, error);
  1223. });
  1224. }
  1225. /**
  1226. * Enables/disables local video based on 'senders' attribute of the video conent in 'content-modify' IQ sent by the
  1227. * remote peer. Also, checks if the sourceMaxFrameHeight (as requested by the p2p peer) or the senders attribute of
  1228. * the video content has changed and modifies the local video resolution accordingly.
  1229. *
  1230. * @param {Element} jingleContents - The content of the 'content-modify' IQ sent by the remote peer.
  1231. * @returns {void}
  1232. */
  1233. modifyContents(jingleContents) {
  1234. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  1235. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  1236. if (sourceMaxFrameHeights) {
  1237. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  1238. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  1239. }
  1240. if (newVideoSenders === null) {
  1241. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  1242. return;
  1243. }
  1244. if (!this._assertNotEnded()) {
  1245. return;
  1246. }
  1247. const isRemoteVideoActive
  1248. = newVideoSenders === 'both'
  1249. || (newVideoSenders === 'initiator' && this.isInitiator)
  1250. || (newVideoSenders === 'responder' && !this.isInitiator);
  1251. if (isRemoteVideoActive !== this._remoteSendReceiveVideoActive) {
  1252. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  1253. this._remoteSendReceiveVideoActive = isRemoteVideoActive;
  1254. this.peerconnection
  1255. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  1256. }
  1257. }
  1258. /**
  1259. * Method returns function(errorResponse) which is a callback to be passed to Strophe connection.sendIQ method. An
  1260. * 'error' structure is created that is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1261. * structure is as follows:
  1262. * {
  1263. * code: {XMPP error response code}
  1264. * reason: {the name of XMPP error reason element or 'timeout' if the
  1265. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1266. * source: {request.tree() that provides original request}
  1267. * session: {this JingleSessionPC.toString()}
  1268. * }
  1269. * @param request Strophe IQ instance which is the request to be dumped into the error structure.
  1270. * @param failureCb function(error) called when error response was returned or when a timeout has occurred.
  1271. * @returns {function(this:JingleSessionPC)}
  1272. */
  1273. newJingleErrorHandler(request, failureCb) {
  1274. return errResponse => {
  1275. const error = {};
  1276. // Get XMPP error code and condition(reason)
  1277. const errorElSel = $(errResponse).find('error');
  1278. if (errorElSel.length) {
  1279. error.code = errorElSel.attr('code');
  1280. const errorReasonSel = $(errResponse).find('error :first');
  1281. if (errorReasonSel.length) {
  1282. error.reason = errorReasonSel[0].tagName;
  1283. }
  1284. const errorMsgSel = errorElSel.find('>text');
  1285. if (errorMsgSel.length) {
  1286. error.msg = errorMsgSel.text();
  1287. }
  1288. }
  1289. if (!errResponse) {
  1290. error.reason = 'timeout';
  1291. }
  1292. error.session = this.toString();
  1293. if (failureCb) {
  1294. failureCb(error);
  1295. } else if (this.state === JingleSessionState.ENDED
  1296. && error.reason === 'item-not-found') {
  1297. // When remote peer decides to terminate the session, but it
  1298. // still have few messages on the queue for processing,
  1299. // it will first send us 'session-terminate' (we enter ENDED)
  1300. // and then follow with 'item-not-found' for the queued requests
  1301. // We don't want to have that logged on error level.
  1302. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  1303. } else {
  1304. logger.error(`Jingle error: ${JSON.stringify(error)}`);
  1305. }
  1306. };
  1307. }
  1308. /**
  1309. * Figures out added/removed ssrcs and sends updated IQs to the remote peer or Jicofo.
  1310. *
  1311. * @param oldSDP SDP object for old description.
  1312. * @param newSDP SDP object for new description.
  1313. * @returns {void}
  1314. */
  1315. notifyMySSRCUpdate(oldSDP, newSDP) {
  1316. if (this.state !== JingleSessionState.ACTIVE) {
  1317. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  1318. return;
  1319. }
  1320. if (!this.connection.connected) {
  1321. // The goal is to compare the oldest SDP with the latest one upon reconnect
  1322. if (!this._cachedOldLocalSdp) {
  1323. this._cachedOldLocalSdp = oldSDP;
  1324. }
  1325. this._cachedNewLocalSdp = newSDP;
  1326. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  1327. return;
  1328. }
  1329. this._cachedOldLocalSdp = undefined;
  1330. this._cachedNewLocalSdp = undefined;
  1331. const getSignaledSourceInfo = sdpDiffer => {
  1332. const newMedia = sdpDiffer.getNewMedia();
  1333. let ssrcs = [];
  1334. let mediaType = null;
  1335. // It is assumed that sources are signaled one at a time.
  1336. Object.keys(newMedia).forEach(mediaIndex => {
  1337. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  1338. mediaType = newMedia[mediaIndex].mediaType;
  1339. if (signaledSsrcs?.length) {
  1340. ssrcs = ssrcs.concat(signaledSsrcs);
  1341. }
  1342. });
  1343. return {
  1344. mediaType,
  1345. ssrcs
  1346. };
  1347. };
  1348. // send source-remove IQ.
  1349. let sdpDiffer = new SDPDiffer(newSDP, oldSDP, this.isP2P);
  1350. const remove = $iq({ to: this.remoteJid,
  1351. type: 'set' })
  1352. .c('jingle', {
  1353. xmlns: 'urn:xmpp:jingle:1',
  1354. action: 'source-remove',
  1355. initiator: this.initiatorJid,
  1356. sid: this.sid
  1357. }
  1358. );
  1359. sdpDiffer.toJingle(remove);
  1360. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  1361. // need to
  1362. const ctx = {};
  1363. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  1364. if (removedSsrcInfo.ssrcs.length) {
  1365. // Log only the SSRCs instead of the full IQ.
  1366. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  1367. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  1368. this.connection.sendIQ(
  1369. remove,
  1370. () => {
  1371. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  1372. },
  1373. this.newJingleErrorHandler(remove, error => {
  1374. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  1375. }),
  1376. IQ_TIMEOUT);
  1377. }
  1378. // send source-add IQ.
  1379. sdpDiffer = new SDPDiffer(oldSDP, newSDP, this.isP2P);
  1380. const add = $iq({ to: this.remoteJid,
  1381. type: 'set' })
  1382. .c('jingle', {
  1383. xmlns: 'urn:xmpp:jingle:1',
  1384. action: 'source-add',
  1385. initiator: this.initiatorJid,
  1386. sid: this.sid
  1387. }
  1388. );
  1389. sdpDiffer.toJingle(add);
  1390. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  1391. if (addedSsrcInfo.ssrcs.length) {
  1392. // Log only the SSRCs instead of the full IQ.
  1393. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  1394. this.connection.sendIQ(
  1395. add,
  1396. () => {
  1397. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  1398. },
  1399. this.newJingleErrorHandler(add, error => {
  1400. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  1401. }),
  1402. IQ_TIMEOUT);
  1403. }
  1404. }
  1405. /**
  1406. * Handles the termination of the session.
  1407. *
  1408. * @param {string} reasonCondition - The XMPP Jingle reason condition.
  1409. * @param {string} reasonText - The XMPP Jingle reason text.
  1410. * @returns {void}
  1411. */
  1412. onTerminated(reasonCondition, reasonText) {
  1413. // Do something with reason and reasonCondition when we start to care
  1414. // this.reasonCondition = reasonCondition;
  1415. // this.reasonText = reasonText;
  1416. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1417. this._xmppListeners.forEach(removeListener => removeListener());
  1418. this._xmppListeners = [];
  1419. if (this._removeSenderVideoConstraintsChangeListener) {
  1420. this._removeSenderVideoConstraintsChangeListener();
  1421. }
  1422. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1423. this.peerconnection.getRemoteTracks().forEach(track => {
  1424. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1425. });
  1426. }
  1427. this.close();
  1428. }
  1429. /**
  1430. * Handles XMPP connection state changes. Resends any session updates that were cached while the XMPP connection
  1431. * was down.
  1432. *
  1433. * @param {XmppConnection.Status} status - The new status.
  1434. * @returns {void}
  1435. */
  1436. onXmppStatusChanged(status) {
  1437. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1438. logger.info(`${this} Sending SSRC update on reconnect`);
  1439. this.notifyMySSRCUpdate(
  1440. this._cachedOldLocalSdp,
  1441. this._cachedNewLocalSdp);
  1442. }
  1443. }
  1444. /**
  1445. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1446. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1447. *
  1448. * @param {Object} message - The source map message.
  1449. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1450. * @returns {void}
  1451. */
  1452. processSourceMap(message, mediaType) {
  1453. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1454. return;
  1455. }
  1456. const newSsrcs = [];
  1457. for (const src of message.mappedSources) {
  1458. const { owner, source, ssrc } = src;
  1459. const isNewSsrc = this.peerconnection.addRemoteSsrc(ssrc, source);
  1460. if (isNewSsrc) {
  1461. newSsrcs.push(src);
  1462. logger.debug(`New SSRC signaled ${ssrc}: owner=${owner}, source-name=${source}`);
  1463. // Check if there is an old mapping for the given source and clear the owner on the associated track.
  1464. const oldSsrc = this.peerconnection.remoteSources.get(source);
  1465. if (oldSsrc) {
  1466. this._signalingLayer.removeSSRCOwners([ oldSsrc ]);
  1467. const track = this.peerconnection.getTrackBySSRC(oldSsrc);
  1468. if (track) {
  1469. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_SET, track);
  1470. }
  1471. }
  1472. } else {
  1473. const track = this.peerconnection.getTrackBySSRC(ssrc);
  1474. if (!track || (track.getParticipantId() === owner && track.getSourceName() === source)) {
  1475. !track && logger.warn(`Remote track for SSRC=${ssrc} hasn't been created yet,`
  1476. + 'not processing the source map');
  1477. continue; // eslint-disable-line no-continue
  1478. }
  1479. logger.debug(`Existing SSRC re-mapped ${ssrc}: new owner=${owner}, source-name=${source}`);
  1480. this._signalingLayer.setSSRCOwner(ssrc, owner, source);
  1481. // Update the muted state and the video type on the track since the presence for this track could have
  1482. // been received before the updated source map is received on the bridge channel.
  1483. const { muted, videoType } = this._signalingLayer.getPeerMediaInfo(owner, mediaType, source);
  1484. muted && this.peerconnection._sourceMutedChanged(source, muted);
  1485. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_SET, track, owner, source, videoType);
  1486. }
  1487. }
  1488. // Add the new SSRCs to the remote description by generating a source message.
  1489. if (newSsrcs.length) {
  1490. let node = $build('content', {
  1491. xmlns: 'urn:xmpp:jingle:1',
  1492. name: mediaType
  1493. }).c('description', {
  1494. xmlns: XEP.RTP_MEDIA,
  1495. media: mediaType
  1496. });
  1497. for (const src of newSsrcs) {
  1498. const { rtx, ssrc, source } = src;
  1499. let msid;
  1500. if (mediaType === MediaType.VIDEO) {
  1501. const idx = ++this.numRemoteVideoSources;
  1502. msid = `remote-video-${idx} remote-video-${idx}`;
  1503. if (rtx !== '-1') {
  1504. _addSourceElement(node, src, rtx, msid);
  1505. node.c('ssrc-group', {
  1506. xmlns: XEP.SOURCE_ATTRIBUTES,
  1507. semantics: 'FID'
  1508. })
  1509. .c('source', {
  1510. xmlns: XEP.SOURCE_ATTRIBUTES,
  1511. ssrc
  1512. })
  1513. .up()
  1514. .c('source', {
  1515. xmlns: XEP.SOURCE_ATTRIBUTES,
  1516. ssrc: rtx
  1517. })
  1518. .up()
  1519. .up();
  1520. }
  1521. } else {
  1522. const idx = ++this.numRemoteAudioSources;
  1523. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1524. }
  1525. _addSourceElement(node, src, ssrc, msid);
  1526. this.peerconnection.remoteSources.set(source, ssrc);
  1527. }
  1528. node = node.up();
  1529. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1530. }
  1531. }
  1532. /**
  1533. * Processes the Jingle message received from the peer and updates the SSRC owners for all the sources signaled
  1534. * in the Jingle message.
  1535. *
  1536. * @param {Element} contents - The content element of the jingle message.
  1537. * @returns {void}
  1538. */
  1539. readSsrcInfo(contents) {
  1540. const ssrcs = $(contents).find('>description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1541. ssrcs.each((i, ssrcElement) => {
  1542. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  1543. let sourceName;
  1544. if (ssrcElement.hasAttribute('name')) {
  1545. sourceName = ssrcElement.getAttribute('name');
  1546. }
  1547. if (this.isP2P) {
  1548. // In P2P all SSRCs are owner by the remote peer
  1549. this._signalingLayer.setSSRCOwner(ssrc, Strophe.getResourceFromJid(this.remoteJid), sourceName);
  1550. } else {
  1551. $(ssrcElement)
  1552. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  1553. .each((i3, ssrcInfoElement) => {
  1554. const owner = ssrcInfoElement.getAttribute('owner');
  1555. if (owner?.length) {
  1556. if (isNaN(ssrc) || ssrc < 0) {
  1557. logger.warn(`${this} Invalid SSRC ${ssrc} value received for ${owner}`);
  1558. } else {
  1559. this._signalingLayer.setSSRCOwner(ssrc, getEndpointId(owner), sourceName);
  1560. }
  1561. }
  1562. });
  1563. }
  1564. });
  1565. }
  1566. /**
  1567. * Handles a Jingle source-remove message for this Jingle session.
  1568. *
  1569. * @param {Array<Element>} contents - An array of content elements from the source-remove message.
  1570. * @returns {void}
  1571. */
  1572. removeRemoteStream(elem) {
  1573. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1574. }
  1575. /**
  1576. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1577. *
  1578. * @param {string} id Endpoint id of the participant that has left the call.
  1579. * @returns {void}
  1580. */
  1581. removeRemoteStreamsOnLeave(id) {
  1582. const workFunction = finishCallback => {
  1583. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1584. if (removeSsrcInfo.length) {
  1585. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1586. this._renegotiate(newRemoteSdp.raw)
  1587. .then(() => finishCallback(), error => finishCallback(error));
  1588. } else {
  1589. finishCallback();
  1590. }
  1591. };
  1592. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1593. this.modificationQueue.push(
  1594. workFunction,
  1595. error => {
  1596. if (error) {
  1597. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1598. } else {
  1599. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1600. }
  1601. });
  1602. }
  1603. /**
  1604. * Removes local track from the peerconnection as part of the mute operation.
  1605. *
  1606. * @param {JitsiLocalTrack} track the local track to be removed.
  1607. * @return {Promise} a promise which will be resolved once the local track is removed from this session or rejected
  1608. * with a <tt>string</tt> that the describes the error if anything goes wrong.
  1609. */
  1610. removeTrackFromPc(track) {
  1611. return this._addRemoveTrack(true /* remove */, track);
  1612. }
  1613. /**
  1614. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single offer/answer cycle (if needed) after
  1615. * both operations are done.
  1616. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid <tt>oldTrack</tt> with a null
  1617. * <tt>newTrack</tt> effectively just removes <tt>oldTrack</tt>.
  1618. *
  1619. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be replaced.
  1620. * @param {JitsiLocalTrack|null} newTrack the new track to use.
  1621. * @returns {Promise} which resolves once the replacement is complete with no arguments or rejects with an error.
  1622. */
  1623. replaceTrack(oldTrack, newTrack) {
  1624. const workFunction = finishedCallback => {
  1625. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  1626. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1627. .then(shouldRenegotiate => {
  1628. let promise = Promise.resolve();
  1629. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  1630. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  1631. if (shouldRenegotiate && (oldTrack || newTrack) && this.state === JingleSessionState.ACTIVE) {
  1632. promise = this._renegotiate();
  1633. }
  1634. return promise.then(() => {
  1635. // Set the source name of the new track.
  1636. if (oldTrack && newTrack && oldTrack.isVideoTrack()) {
  1637. newTrack.setSourceName(oldTrack.getSourceName());
  1638. }
  1639. });
  1640. })
  1641. .then(() => finishedCallback(), error => finishedCallback(error));
  1642. };
  1643. return new Promise((resolve, reject) => {
  1644. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  1645. this.modificationQueue.push(
  1646. workFunction,
  1647. error => {
  1648. if (error) {
  1649. if (error instanceof ClearedQueueError) {
  1650. // The session might have been terminated before the task was executed, making it obsolete.
  1651. logger.debug('Replace track aborted: session terminated');
  1652. resolve();
  1653. return;
  1654. }
  1655. logger.error(`${this} Replace track error:`, error);
  1656. reject(error);
  1657. } else {
  1658. logger.info(`${this} Replace track done!`);
  1659. resolve();
  1660. }
  1661. });
  1662. });
  1663. }
  1664. /**
  1665. * Sends 'content-modify' IQ in order to ask the remote peer to either stop or resume sending video media or to
  1666. * adjust sender's video constraints.
  1667. *
  1668. * @returns {void}
  1669. * @private
  1670. */
  1671. sendContentModify() {
  1672. const senders = this._localSendReceiveVideoActive ? 'both' : 'none';
  1673. const sessionModify
  1674. = $iq({
  1675. to: this.remoteJid,
  1676. type: 'set'
  1677. })
  1678. .c('jingle', {
  1679. xmlns: 'urn:xmpp:jingle:1',
  1680. action: 'content-modify',
  1681. initiator: this.initiatorJid,
  1682. sid: this.sid
  1683. })
  1684. .c('content', {
  1685. name: MediaType.VIDEO,
  1686. senders
  1687. });
  1688. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  1689. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  1690. sessionModify
  1691. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1692. .attrs({
  1693. sourceName,
  1694. maxHeight
  1695. });
  1696. sessionModify.up();
  1697. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  1698. });
  1699. }
  1700. logger.debug(sessionModify.tree());
  1701. this.connection.sendIQ(
  1702. sessionModify,
  1703. null,
  1704. this.newJingleErrorHandler(sessionModify),
  1705. IQ_TIMEOUT);
  1706. }
  1707. /**
  1708. * Sends given candidate in Jingle 'transport-info' message.
  1709. *
  1710. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  1711. * @private
  1712. * @returns {void}
  1713. */
  1714. sendIceCandidate(candidate) {
  1715. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1716. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  1717. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  1718. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  1719. if (!(ice && jcand)) {
  1720. logger.error('failed to get ice && jcand');
  1721. return;
  1722. }
  1723. ice.xmlns = XEP.ICE_UDP_TRANSPORT;
  1724. if (this.usedrip) {
  1725. if (this.dripContainer.length === 0) {
  1726. setTimeout(() => {
  1727. if (this.dripContainer.length === 0) {
  1728. return;
  1729. }
  1730. this.sendIceCandidates(this.dripContainer);
  1731. this.dripContainer = [];
  1732. }, ICE_CAND_GATHERING_TIMEOUT);
  1733. }
  1734. this.dripContainer.push(candidate);
  1735. } else {
  1736. this.sendIceCandidates([ candidate ]);
  1737. }
  1738. } else {
  1739. logger.log(`${this} sendIceCandidate: last candidate`);
  1740. // FIXME: remember to re-think in ICE-restart
  1741. this.lasticecandidate = true;
  1742. }
  1743. }
  1744. /**
  1745. * Sends given candidates in Jingle 'transport-info' message.
  1746. *
  1747. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE candidate instances.
  1748. * @returns {void}
  1749. * @private
  1750. */
  1751. sendIceCandidates(candidates) {
  1752. if (!this._assertNotEnded('sendIceCandidates')) {
  1753. return;
  1754. }
  1755. logger.log(`${this} sendIceCandidates ${JSON.stringify(candidates)}`);
  1756. const cand = $iq({ to: this.remoteJid,
  1757. type: 'set' })
  1758. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1759. action: 'transport-info',
  1760. initiator: this.initiatorJid,
  1761. sid: this.sid });
  1762. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1763. for (let mid = 0; mid < localSDP.media.length; mid++) {
  1764. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  1765. const mline
  1766. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  1767. if (cands.length > 0) {
  1768. const ice
  1769. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  1770. ice.xmlns = XEP.ICE_UDP_TRANSPORT;
  1771. cand.c('content', {
  1772. creator: this.initiatorJid === this.localJid
  1773. ? 'initiator' : 'responder',
  1774. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  1775. }).c('transport', ice);
  1776. for (let i = 0; i < cands.length; i++) {
  1777. const candidate
  1778. = SDPUtil.candidateToJingle(cands[i].candidate);
  1779. // Mangle ICE candidate if 'failICE' test option is enabled
  1780. if (this.failICE) {
  1781. candidate.ip = '1.1.1.1';
  1782. }
  1783. cand.c('candidate', candidate).up();
  1784. }
  1785. // add fingerprint
  1786. const fingerprintLine
  1787. = SDPUtil.findLine(
  1788. localSDP.media[mid],
  1789. 'a=fingerprint:', localSDP.session);
  1790. if (fingerprintLine) {
  1791. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  1792. tmp.required = true;
  1793. cand.c(
  1794. 'fingerprint',
  1795. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  1796. .t(tmp.fingerprint);
  1797. delete tmp.fingerprint;
  1798. cand.attrs(tmp);
  1799. cand.up();
  1800. }
  1801. cand.up(); // transport
  1802. cand.up(); // content
  1803. }
  1804. }
  1805. // might merge last-candidate notification into this, but it is called
  1806. // a lot later. See webrtc issue #2340
  1807. // logger.log('was this the last candidate', this.lasticecandidate);
  1808. this.connection.sendIQ(
  1809. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  1810. }
  1811. /**
  1812. * Sends Jingle 'session-accept' message.
  1813. *
  1814. * @param {function()} success callback called when we receive 'RESULT' packet for the 'session-accept'.
  1815. * @param {function(error)} failure called when we receive an error response or when the request has timed out.
  1816. * @returns {void}
  1817. * @private
  1818. */
  1819. sendSessionAccept(success, failure) {
  1820. // NOTE: since we're just reading from it, we don't need to be within
  1821. // the modification queue to access the local description
  1822. const localSDP = new SDP(this.peerconnection.localDescription.sdp, this.isP2P);
  1823. const accept = $iq({ to: this.remoteJid,
  1824. type: 'set' })
  1825. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1826. action: 'session-accept',
  1827. initiator: this.initiatorJid,
  1828. responder: this.responderJid,
  1829. sid: this.sid });
  1830. if (this.webrtcIceTcpDisable) {
  1831. localSDP.removeTcpCandidates = true;
  1832. }
  1833. if (this.webrtcIceUdpDisable) {
  1834. localSDP.removeUdpCandidates = true;
  1835. }
  1836. if (this.failICE) {
  1837. localSDP.failICE = true;
  1838. }
  1839. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1840. localSDP.initialLastN = this.options.channelLastN;
  1841. }
  1842. localSDP.toJingle(
  1843. accept,
  1844. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1845. logger.info(`${this} Sending session-accept`);
  1846. logger.debug(accept.tree());
  1847. this.connection.sendIQ(accept,
  1848. success,
  1849. this.newJingleErrorHandler(accept, error => {
  1850. failure(error);
  1851. // 'session-accept' is a critical timeout and we'll
  1852. // have to restart
  1853. this.room.eventEmitter.emit(
  1854. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1855. }),
  1856. IQ_TIMEOUT);
  1857. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1858. // fingerprint and setup) ASAP in order to start the connection
  1859. // establishment.
  1860. //
  1861. // FIXME Flushing the connection at this point triggers an issue with
  1862. // BOSH request handling in Prosody on slow connections.
  1863. //
  1864. // The problem is that this request will be quite large and it may take
  1865. // time before it reaches Prosody. In the meantime Strophe may decide
  1866. // to send the next one. And it was observed that a small request with
  1867. // 'transport-info' usually follows this one. It does reach Prosody
  1868. // before the previous one was completely received. 'rid' on the server
  1869. // is increased and Prosody ignores the request with 'session-accept'.
  1870. // It will never reach Jicofo and everything in the request table is
  1871. // lost. Removing the flush does not guarantee it will never happen, but
  1872. // makes it much less likely('transport-info' is bundled with
  1873. // 'session-accept' and any immediate requests).
  1874. //
  1875. // this.connection.flush();
  1876. }
  1877. /**
  1878. * Sends 'session-initiate' to the remote peer.
  1879. *
  1880. * NOTE this method is synchronous and we're not waiting for the RESULT
  1881. * response which would delay the startup process.
  1882. *
  1883. * @param {string} offerSdp - The local session description which will be used to generate an offer.
  1884. * @returns {void}
  1885. * @private
  1886. */
  1887. sendSessionInitiate(offerSdp) {
  1888. let init = $iq({
  1889. to: this.remoteJid,
  1890. type: 'set'
  1891. }).c('jingle', {
  1892. xmlns: 'urn:xmpp:jingle:1',
  1893. action: 'session-initiate',
  1894. initiator: this.initiatorJid,
  1895. sid: this.sid
  1896. });
  1897. new SDP(offerSdp, this.isP2P).toJingle(
  1898. init,
  1899. this.isInitiator ? 'initiator' : 'responder');
  1900. init = init.tree();
  1901. logger.debug(`${this} Session-initiate: `, init);
  1902. this.connection.sendIQ(init,
  1903. () => {
  1904. logger.info(`${this} Got RESULT for "session-initiate"`);
  1905. },
  1906. error => {
  1907. logger.error(`${this} "session-initiate" error`, error);
  1908. },
  1909. IQ_TIMEOUT);
  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. }