You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 107KB

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