您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 98KB

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