Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 106KB

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