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

JingleSessionPC.js 106KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729
  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. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  829. *
  830. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  831. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  832. * 'session-accept' sent.
  833. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  834. * can be used to log some details about the error.
  835. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  836. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  837. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  838. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  839. * assumption that the initial offer/answer cycle has been executed already.
  840. */
  841. acceptOffer(jingleOffer, success, failure, localTracks = []) {
  842. this.setOfferAnswerCycle(
  843. jingleOffer,
  844. () => {
  845. // FIXME we may not care about RESULT packet for session-accept
  846. // then we should either call 'success' here immediately or
  847. // modify sendSessionAccept method to do that
  848. this.sendSessionAccept(() => {
  849. // Start processing tasks on the modification queue.
  850. logger.debug(`${this} Resuming the modification queue after session is established!`);
  851. this.modificationQueue.resume();
  852. success();
  853. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  854. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  855. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  856. // This will happen when someone shares a secondary source to a two people call, the other user
  857. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  858. // point, there are 2 video tracks which need to be signaled to the remote peer.
  859. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  860. videoTracks.length && videoTracks.splice(0, 1);
  861. videoTracks.length && this.addTracks(videoTracks);
  862. },
  863. error => {
  864. failure(error);
  865. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  866. });
  867. },
  868. failure,
  869. localTracks);
  870. }
  871. /**
  872. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  873. *
  874. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  875. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  876. */
  877. invite(localTracks = []) {
  878. if (!this.isInitiator) {
  879. throw new Error('Trying to invite from the responder session');
  880. }
  881. logger.debug(`${this} Executing invite task`);
  882. const addTracks = [];
  883. for (const track of localTracks) {
  884. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  885. }
  886. Promise.all(addTracks)
  887. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  888. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  889. .then(() => {
  890. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  891. this.sendSessionInitiate(this.peerconnection.localDescription.sdp);
  892. })
  893. .then(() => {
  894. logger.debug(`${this} invite executed - OK`);
  895. })
  896. .catch(error => {
  897. logger.error(`${this} invite error`, error);
  898. });
  899. }
  900. /**
  901. * Sends 'session-initiate' to the remote peer.
  902. *
  903. * NOTE this method is synchronous and we're not waiting for the RESULT
  904. * response which would delay the startup process.
  905. *
  906. * @param {string} offerSdp - The local session description which will be
  907. * used to generate an offer.
  908. * @private
  909. */
  910. sendSessionInitiate(offerSdp) {
  911. let init = $iq({
  912. to: this.remoteJid,
  913. type: 'set'
  914. }).c('jingle', {
  915. xmlns: 'urn:xmpp:jingle:1',
  916. action: 'session-initiate',
  917. initiator: this.initiatorJid,
  918. sid: this.sid
  919. });
  920. new SDP(offerSdp).toJingle(
  921. init,
  922. this.isInitiator ? 'initiator' : 'responder');
  923. init = init.tree();
  924. logger.debug(`${this} Session-initiate: `, init);
  925. this.connection.sendIQ(init,
  926. () => {
  927. logger.info(`${this} Got RESULT for "session-initiate"`);
  928. },
  929. error => {
  930. logger.error(`${this} "session-initiate" error`, error);
  931. },
  932. IQ_TIMEOUT);
  933. }
  934. /**
  935. * Sets the answer received from the remote peer as the remote description.
  936. *
  937. * @param jingleAnswer
  938. */
  939. setAnswer(jingleAnswer) {
  940. if (!this.isInitiator) {
  941. throw new Error('Trying to set an answer on the responder session');
  942. }
  943. logger.debug(`${this} Executing setAnswer task`);
  944. const newRemoteSdp = this._processNewJingleOfferIq(jingleAnswer);
  945. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  946. const remoteDescription = new RTCSessionDescription({
  947. type: 'answer',
  948. sdp: newRemoteSdp.raw
  949. });
  950. this.peerconnection.setRemoteDescription(remoteDescription)
  951. .then(() => {
  952. if (this.state === JingleSessionState.PENDING) {
  953. this.state = JingleSessionState.ACTIVE;
  954. // Start processing tasks on the modification queue.
  955. logger.debug(`${this} Resuming the modification queue after session is established!`);
  956. this.modificationQueue.resume();
  957. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  958. this.sendContentModify();
  959. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  960. }
  961. })
  962. .then(() => {
  963. logger.debug(`${this} setAnswer task done`);
  964. })
  965. .catch(error => {
  966. logger.error(`${this} setAnswer task failed: ${error}`);
  967. });
  968. }
  969. /**
  970. * This is a setRemoteDescription/setLocalDescription cycle which starts at converting Strophe Jingle IQ into
  971. * remote offer SDP. Once converted, setRemoteDescription, createAnswer and setLocalDescription calls follow.
  972. *
  973. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element of the offer (or answer) IQ
  974. * @param success callback called when sRD/sLD cycle finishes successfully.
  975. * @param failure callback called with an error object as an argument if we fail at any point during setRD,
  976. * createAnswer, setLD.
  977. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  978. * the offer/answer cycle executes (for the local track addition to be an atomic operation together with the
  979. * offer/answer).
  980. */
  981. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  982. logger.debug(`${this} Executing setOfferAnswerCycle task`);
  983. const addTracks = [];
  984. const audioTracks = localTracks.filter(track => track.getType() === MediaType.AUDIO);
  985. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  986. let tracks = localTracks;
  987. // Add only 1 video track at a time. Adding 2 or more video tracks to the peerconnection at the same time
  988. // makes the browser go into a renegotiation loop by firing 'negotiationneeded' event after every
  989. // renegotiation.
  990. if (videoTracks.length > 1) {
  991. tracks = [ ...audioTracks, videoTracks[0] ];
  992. }
  993. for (const track of tracks) {
  994. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  995. }
  996. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  997. const bridgeSession = $(jingleOfferAnswerIq).find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]');
  998. const bridgeSessionId = bridgeSession.attr('id');
  999. if (bridgeSessionId !== this._bridgeSessionId) {
  1000. this._bridgeSessionId = bridgeSessionId;
  1001. }
  1002. Promise.all(addTracks)
  1003. .then(() => this._renegotiate(newRemoteSdp.raw))
  1004. .then(() => {
  1005. this.peerconnection.processLocalSdpForTransceiverInfo(tracks);
  1006. if (this.state === JingleSessionState.PENDING) {
  1007. this.state = JingleSessionState.ACTIVE;
  1008. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1009. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1010. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1011. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1012. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1013. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1014. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1015. if (this.isP2P && (!this._localSendReceiveVideoActive || this._sourceReceiverConstraints)) {
  1016. this.sendContentModify();
  1017. }
  1018. }
  1019. })
  1020. .then(() => {
  1021. logger.debug(`${this} setOfferAnswerCycle task done`);
  1022. success();
  1023. })
  1024. .catch(error => {
  1025. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1026. failure(error);
  1027. });
  1028. }
  1029. /**
  1030. * Updates the codecs on the peerconnection and initiates a renegotiation for the
  1031. * new codec config to take effect.
  1032. *
  1033. * @param {CodecMimeType} preferred the preferred codec.
  1034. * @param {CodecMimeType} disabled the codec that needs to be disabled.
  1035. */
  1036. setVideoCodecs(codecList) {
  1037. if (this._assertNotEnded()) {
  1038. logger.info(`${this} setVideoCodecs: ${codecList}`);
  1039. this.peerconnection.setVideoCodecs(codecList);
  1040. // Initiate a renegotiate for the codec setting to take effect.
  1041. const workFunction = finishedCallback => {
  1042. this._renegotiate()
  1043. .then(() => this.peerconnection.configureVideoSenderEncodings())
  1044. .then(
  1045. () => {
  1046. logger.debug(`${this} setVideoCodecs task is done`);
  1047. return finishedCallback();
  1048. }, error => {
  1049. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  1050. return finishedCallback(error);
  1051. });
  1052. };
  1053. logger.debug(`${this} Queued setVideoCodecs task`);
  1054. // Queue and execute
  1055. this.modificationQueue.push(workFunction);
  1056. }
  1057. }
  1058. /* eslint-enable max-params */
  1059. /**
  1060. * Although it states "replace transport" it does accept full Jingle offer
  1061. * which should contain new ICE transport details.
  1062. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  1063. * transport info.
  1064. * @param success callback called when we succeed to accept new offer.
  1065. * @param failure function(error) called when we fail to accept new offer.
  1066. */
  1067. replaceTransport(jingleOfferElem, success, failure) {
  1068. if (this.options.enableForcedReload) {
  1069. const sdp = new SDP(this.peerconnection.localDescription.sdp);
  1070. this.sendTransportAccept(sdp, success, failure);
  1071. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTARTED, this);
  1072. return;
  1073. }
  1074. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  1075. // We need to first reject the 'data' section to have the SCTP stack
  1076. // cleaned up to signal the known data channel is now invalid. After
  1077. // that the original offer is set to have the SCTP connection
  1078. // established with the new bridge.
  1079. const originalOffer = jingleOfferElem.clone();
  1080. jingleOfferElem
  1081. .find('>content[name=\'data\']')
  1082. .attr('senders', 'rejected');
  1083. // Remove all remote sources in order to reset the client's state
  1084. // for the remote MediaStreams. When a conference is moved to
  1085. // another bridge it will start streaming with a sequence number
  1086. // that is not in sync with the most recently seen by the client.
  1087. // The symptoms include frozen or black video and lots of "failed to
  1088. // unprotect SRTP packets" in Chrome logs.
  1089. jingleOfferElem
  1090. .find('>content>description>source')
  1091. .remove();
  1092. jingleOfferElem
  1093. .find('>content>description>ssrc-group')
  1094. .remove();
  1095. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  1096. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  1097. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  1098. // fingerprint has changed by setting an all zeros key.
  1099. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  1100. newFingerprint.attr('hash', 'sha-1');
  1101. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  1102. const workFunction = finishedCallback => {
  1103. // First set an offer with a rejected 'data' section
  1104. this.setOfferAnswerCycle(
  1105. jingleOfferElem,
  1106. () => {
  1107. // Now set the original offer(with the 'data' section)
  1108. this.setOfferAnswerCycle(
  1109. originalOffer,
  1110. () => {
  1111. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1112. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1113. localSDP.initialLastN = this.options.channelLastN;
  1114. }
  1115. this.sendTransportAccept(localSDP, success, failure);
  1116. this.room.eventEmitter.emit(
  1117. XMPPEvents.ICE_RESTART_SUCCESS,
  1118. this,
  1119. originalOffer);
  1120. finishedCallback();
  1121. }, error => finishedCallback(error)
  1122. );
  1123. }, error => finishedCallback(error)
  1124. );
  1125. };
  1126. logger.debug(`${this} Queued ICE restart task`);
  1127. // Queue and execute
  1128. this.modificationQueue.push(
  1129. workFunction,
  1130. error => {
  1131. if (error) {
  1132. if (error instanceof ClearedQueueError) {
  1133. // The session might have been terminated before the task was executed, making it obsolete.
  1134. logger.debug(`${this} ICE restart task aborted: session terminated`);
  1135. success();
  1136. return;
  1137. }
  1138. logger.error(`${this} ICE restart task failed: ${error}`);
  1139. failure(error);
  1140. } else {
  1141. logger.debug(`${this} ICE restart task done`);
  1142. success();
  1143. }
  1144. });
  1145. }
  1146. /**
  1147. * Sends Jingle 'session-accept' message.
  1148. * @param {function()} success callback called when we receive 'RESULT'
  1149. * packet for the 'session-accept'
  1150. * @param {function(error)} failure called when we receive an error response
  1151. * or when the request has timed out.
  1152. * @private
  1153. */
  1154. sendSessionAccept(success, failure) {
  1155. // NOTE: since we're just reading from it, we don't need to be within
  1156. // the modification queue to access the local description
  1157. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1158. const accept = $iq({ to: this.remoteJid,
  1159. type: 'set' })
  1160. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1161. action: 'session-accept',
  1162. initiator: this.initiatorJid,
  1163. responder: this.responderJid,
  1164. sid: this.sid });
  1165. if (this.webrtcIceTcpDisable) {
  1166. localSDP.removeTcpCandidates = true;
  1167. }
  1168. if (this.webrtcIceUdpDisable) {
  1169. localSDP.removeUdpCandidates = true;
  1170. }
  1171. if (this.failICE) {
  1172. localSDP.failICE = true;
  1173. }
  1174. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1175. localSDP.initialLastN = this.options.channelLastN;
  1176. }
  1177. localSDP.toJingle(
  1178. accept,
  1179. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1180. logger.info(`${this} Sending session-accept`);
  1181. logger.debug(accept.tree());
  1182. this.connection.sendIQ(accept,
  1183. success,
  1184. this.newJingleErrorHandler(accept, error => {
  1185. failure(error);
  1186. // 'session-accept' is a critical timeout and we'll
  1187. // have to restart
  1188. this.room.eventEmitter.emit(
  1189. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1190. }),
  1191. IQ_TIMEOUT);
  1192. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1193. // fingerprint and setup) ASAP in order to start the connection
  1194. // establishment.
  1195. //
  1196. // FIXME Flushing the connection at this point triggers an issue with
  1197. // BOSH request handling in Prosody on slow connections.
  1198. //
  1199. // The problem is that this request will be quite large and it may take
  1200. // time before it reaches Prosody. In the meantime Strophe may decide
  1201. // to send the next one. And it was observed that a small request with
  1202. // 'transport-info' usually follows this one. It does reach Prosody
  1203. // before the previous one was completely received. 'rid' on the server
  1204. // is increased and Prosody ignores the request with 'session-accept'.
  1205. // It will never reach Jicofo and everything in the request table is
  1206. // lost. Removing the flush does not guarantee it will never happen, but
  1207. // makes it much less likely('transport-info' is bundled with
  1208. // 'session-accept' and any immediate requests).
  1209. //
  1210. // this.connection.flush();
  1211. }
  1212. /**
  1213. * Will send 'content-modify' IQ in order to ask the remote peer to
  1214. * either stop or resume sending video media or to adjust sender's video constraints.
  1215. * @private
  1216. */
  1217. sendContentModify() {
  1218. const senders = this._localSendReceiveVideoActive ? 'both' : 'none';
  1219. const sessionModify
  1220. = $iq({
  1221. to: this.remoteJid,
  1222. type: 'set'
  1223. })
  1224. .c('jingle', {
  1225. xmlns: 'urn:xmpp:jingle:1',
  1226. action: 'content-modify',
  1227. initiator: this.initiatorJid,
  1228. sid: this.sid
  1229. })
  1230. .c('content', {
  1231. name: MediaType.VIDEO,
  1232. senders
  1233. });
  1234. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  1235. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  1236. sessionModify
  1237. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1238. .attrs({
  1239. sourceName,
  1240. maxHeight
  1241. });
  1242. sessionModify.up();
  1243. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  1244. });
  1245. }
  1246. logger.debug(sessionModify.tree());
  1247. this.connection.sendIQ(
  1248. sessionModify,
  1249. null,
  1250. this.newJingleErrorHandler(sessionModify),
  1251. IQ_TIMEOUT);
  1252. }
  1253. /**
  1254. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1255. * the remote p2p peer.
  1256. *
  1257. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1258. */
  1259. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1260. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1261. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1262. if (this.isP2P) {
  1263. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1264. // be synced after offer/answer.
  1265. if (this.state === JingleSessionState.ACTIVE) {
  1266. this.sendContentModify();
  1267. }
  1268. }
  1269. }
  1270. /**
  1271. * Sends Jingle 'transport-accept' message which is a response to
  1272. * 'transport-replace'.
  1273. * @param localSDP the 'SDP' object with local session description
  1274. * @param success callback called when we receive 'RESULT' packet for
  1275. * 'transport-replace'
  1276. * @param failure function(error) called when we receive an error response
  1277. * or when the request has timed out.
  1278. * @private
  1279. */
  1280. sendTransportAccept(localSDP, success, failure) {
  1281. const transportAccept = $iq({ to: this.remoteJid,
  1282. type: 'set' })
  1283. .c('jingle', {
  1284. xmlns: 'urn:xmpp:jingle:1',
  1285. action: 'transport-accept',
  1286. initiator: this.initiatorJid,
  1287. sid: this.sid
  1288. });
  1289. localSDP.media.forEach((medialines, idx) => {
  1290. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1291. transportAccept.c('content',
  1292. {
  1293. creator:
  1294. this.initiatorJid === this.localJid
  1295. ? 'initiator'
  1296. : 'responder',
  1297. name: mline.media
  1298. }
  1299. );
  1300. localSDP.transportToJingle(idx, transportAccept);
  1301. transportAccept.up();
  1302. });
  1303. logger.info(`${this} Sending transport-accept`);
  1304. logger.debug(transportAccept.tree());
  1305. this.connection.sendIQ(transportAccept,
  1306. success,
  1307. this.newJingleErrorHandler(transportAccept, failure),
  1308. IQ_TIMEOUT);
  1309. }
  1310. /**
  1311. * Sends Jingle 'transport-reject' message which is a response to
  1312. * 'transport-replace'.
  1313. * @param success callback called when we receive 'RESULT' packet for
  1314. * 'transport-replace'
  1315. * @param failure function(error) called when we receive an error response
  1316. * or when the request has timed out.
  1317. *
  1318. * FIXME method should be marked as private, but there's some spaghetti that
  1319. * needs to be fixed prior doing that
  1320. */
  1321. sendTransportReject(success, failure) {
  1322. // Send 'transport-reject', so that the focus will
  1323. // know that we've failed
  1324. const transportReject = $iq({ to: this.remoteJid,
  1325. type: 'set' })
  1326. .c('jingle', {
  1327. xmlns: 'urn:xmpp:jingle:1',
  1328. action: 'transport-reject',
  1329. initiator: this.initiatorJid,
  1330. sid: this.sid
  1331. });
  1332. logger.info(`${this} Sending 'transport-reject'`);
  1333. logger.debug(transportReject.tree());
  1334. this.connection.sendIQ(transportReject,
  1335. success,
  1336. this.newJingleErrorHandler(transportReject, failure),
  1337. IQ_TIMEOUT);
  1338. }
  1339. /**
  1340. * Sets the resolution constraint on the local camera track.
  1341. * @param {number} maxFrameHeight - The user preferred max frame height.
  1342. * @param {string} sourceName - The source name of the track.
  1343. * @returns {Promise} promise that will be resolved when the operation is
  1344. * successful and rejected otherwise.
  1345. */
  1346. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1347. if (this._assertNotEnded()) {
  1348. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1349. const jitsiLocalTrack = sourceName
  1350. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1351. : this.rtc.getLocalVideoTrack();
  1352. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1353. }
  1354. return Promise.resolve();
  1355. }
  1356. /**
  1357. * @inheritDoc
  1358. */
  1359. terminate(success, failure, options) {
  1360. if (this.state === JingleSessionState.ENDED) {
  1361. return;
  1362. }
  1363. if (!options || Boolean(options.sendSessionTerminate)) {
  1364. const sessionTerminate
  1365. = $iq({
  1366. to: this.remoteJid,
  1367. type: 'set'
  1368. })
  1369. .c('jingle', {
  1370. xmlns: 'urn:xmpp:jingle:1',
  1371. action: 'session-terminate',
  1372. initiator: this.initiatorJid,
  1373. sid: this.sid
  1374. })
  1375. .c('reason')
  1376. .c((options && options.reason) || 'success')
  1377. .up();
  1378. if (options && options.reasonDescription) {
  1379. sessionTerminate
  1380. .c('text')
  1381. .t(options.reasonDescription)
  1382. .up()
  1383. .up();
  1384. } else {
  1385. sessionTerminate.up();
  1386. }
  1387. this._bridgeSessionId
  1388. && sessionTerminate.c(
  1389. 'bridge-session', {
  1390. xmlns: 'http://jitsi.org/protocol/focus',
  1391. id: this._bridgeSessionId,
  1392. restart: options && options.requestRestart === true
  1393. }).up();
  1394. logger.info(`${this} Sending session-terminate`);
  1395. logger.debug(sessionTerminate.tree());
  1396. this.connection.sendIQ(
  1397. sessionTerminate,
  1398. success,
  1399. this.newJingleErrorHandler(sessionTerminate, failure),
  1400. IQ_TIMEOUT);
  1401. } else {
  1402. logger.info(`${this} Skipped sending session-terminate`);
  1403. }
  1404. // this should result in 'onTerminated' being called by strope.jingle.js
  1405. this.connection.jingle.terminate(this.sid);
  1406. }
  1407. /**
  1408. *
  1409. * @param reasonCondition
  1410. * @param reasonText
  1411. */
  1412. onTerminated(reasonCondition, reasonText) {
  1413. // Do something with reason and reasonCondition when we start to care
  1414. // this.reasonCondition = reasonCondition;
  1415. // this.reasonText = reasonText;
  1416. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1417. this._xmppListeners.forEach(removeListener => removeListener());
  1418. this._xmppListeners = [];
  1419. if (this._removeSenderVideoConstraintsChangeListener) {
  1420. this._removeSenderVideoConstraintsChangeListener();
  1421. }
  1422. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1423. this.peerconnection.getRemoteTracks().forEach(track => {
  1424. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1425. });
  1426. }
  1427. this.close();
  1428. }
  1429. /**
  1430. * Handles XMPP connection state changes.
  1431. *
  1432. * @param {XmppConnection.Status} status - The new status.
  1433. */
  1434. onXmppStatusChanged(status) {
  1435. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1436. logger.info(`${this} Sending SSRC update on reconnect`);
  1437. this.notifyMySSRCUpdate(
  1438. this._cachedOldLocalSdp,
  1439. this._cachedNewLocalSdp);
  1440. }
  1441. }
  1442. /**
  1443. * Parse the information from the xml sourceAddElem and translate it
  1444. * into sdp lines
  1445. * @param {jquery xml element} sourceAddElem the source-add
  1446. * element from jingle
  1447. * @param {SDP object} currentRemoteSdp the current remote
  1448. * sdp (as of this new source-add)
  1449. * @returns {list} a list of SDP line strings that should
  1450. * be added to the remote SDP
  1451. */
  1452. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1453. const addSsrcInfo = [];
  1454. const self = this;
  1455. $(sourceAddElem).each((i1, content) => {
  1456. const name = $(content).attr('name');
  1457. let lines = '';
  1458. $(content)
  1459. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1460. .each(function() {
  1461. // eslint-disable-next-line no-invalid-this
  1462. const semantics = this.getAttribute('semantics');
  1463. const ssrcs
  1464. = $(this) // eslint-disable-line no-invalid-this
  1465. .find('>source')
  1466. .map(function() {
  1467. // eslint-disable-next-line no-invalid-this
  1468. return this.getAttribute('ssrc');
  1469. })
  1470. .get();
  1471. if (ssrcs.length) {
  1472. lines += `a=ssrc-group:${semantics} ${ssrcs.join(' ')}\r\n`;
  1473. }
  1474. });
  1475. // handles both >source and >description>source
  1476. const tmp
  1477. = $(content).find(
  1478. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1479. /* eslint-disable no-invalid-this */
  1480. tmp.each(function() {
  1481. const ssrc = $(this).attr('ssrc');
  1482. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1483. // Do not print the warning for unified plan p2p case since ssrcs are never removed from the SDP.
  1484. !self.isP2P && logger.warn(`${self} Source-add request for existing SSRC: ${ssrc}`);
  1485. return;
  1486. }
  1487. // eslint-disable-next-line newline-per-chained-call
  1488. $(this).find('>parameter').each(function() {
  1489. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1490. if ($(this).attr('value') && $(this).attr('value').length) {
  1491. lines += `:${$(this).attr('value')}`;
  1492. }
  1493. lines += '\r\n';
  1494. });
  1495. });
  1496. let midFound = false;
  1497. /* eslint-enable no-invalid-this */
  1498. currentRemoteSdp.media.forEach((media, i2) => {
  1499. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1500. return;
  1501. }
  1502. if (!addSsrcInfo[i2]) {
  1503. addSsrcInfo[i2] = '';
  1504. }
  1505. addSsrcInfo[i2] += lines;
  1506. midFound = true;
  1507. });
  1508. // In p2p unified mode with multi-stream enabled, the new sources will have content name that doesn't exist
  1509. // in the current remote description. Add a new m-line for this newly signaled source.
  1510. if (!midFound && this.isP2P) {
  1511. addSsrcInfo[name] = lines;
  1512. }
  1513. });
  1514. return addSsrcInfo;
  1515. }
  1516. /**
  1517. * Handles a Jingle source-add message for this Jingle session.
  1518. * @param elem An array of Jingle "content" elements.
  1519. */
  1520. addRemoteStream(elem) {
  1521. this._addOrRemoveRemoteStream(true /* add */, elem);
  1522. }
  1523. /**
  1524. * Handles a Jingle source-remove message for this Jingle session.
  1525. * @param elem An array of Jingle "content" elements.
  1526. */
  1527. removeRemoteStream(elem) {
  1528. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1529. }
  1530. /**
  1531. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1532. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1533. *
  1534. * @param {Object} message - The source map message.
  1535. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1536. * @returns {void}
  1537. */
  1538. processSourceMap(message, mediaType) {
  1539. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1540. return;
  1541. }
  1542. const newSsrcs = [];
  1543. for (const src of message.mappedSources) {
  1544. const { owner, source, ssrc } = src;
  1545. const isNewSsrc = this.peerconnection.addRemoteSsrc(ssrc, source);
  1546. if (isNewSsrc) {
  1547. newSsrcs.push(src);
  1548. logger.debug(`New SSRC signaled ${ssrc}: owner=${owner}, source-name=${source}`);
  1549. // Check if there is an old mapping for the given source and clear the owner on the associated track.
  1550. const oldSsrc = this.peerconnection.remoteSources.get(source);
  1551. if (oldSsrc) {
  1552. this._signalingLayer.removeSSRCOwners([ oldSsrc ]);
  1553. const track = this.peerconnection.getTrackBySSRC(oldSsrc);
  1554. if (track) {
  1555. track.setSourceName(null);
  1556. track.setOwner(null);
  1557. track._setVideoType(null);
  1558. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_REMOVED, track);
  1559. }
  1560. }
  1561. } else {
  1562. logger.debug(`Existing SSRC re-mapped ${ssrc}: new owner=${owner}, source-name=${source}`);
  1563. const track = this.peerconnection.getTrackBySSRC(ssrc);
  1564. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_REMOVED, track);
  1565. this._signalingLayer.setSSRCOwner(ssrc, owner, source);
  1566. track.setSourceName(source);
  1567. track.setOwner(owner);
  1568. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_OWNER_ADDED, track);
  1569. // Update the muted state and the video type on the track since the presence for this track could have
  1570. // been received before the updated source map is received on the bridge channel.
  1571. const peerMediaInfo = this._signalingLayer.getPeerMediaInfo(owner, mediaType, source);
  1572. if (peerMediaInfo) {
  1573. track._setVideoType(peerMediaInfo.videoType);
  1574. this.peerconnection._sourceMutedChanged(source, peerMediaInfo.muted);
  1575. }
  1576. }
  1577. }
  1578. // Add the new SSRCs to the remote description by generating a source message.
  1579. if (newSsrcs.length) {
  1580. let node = $build('content', {
  1581. xmlns: 'urn:xmpp:jingle:1',
  1582. name: mediaType
  1583. }).c('description', {
  1584. xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  1585. media: mediaType
  1586. });
  1587. for (const src of newSsrcs) {
  1588. const { rtx, ssrc, source } = src;
  1589. let msid;
  1590. if (mediaType === MediaType.VIDEO) {
  1591. const idx = ++this.numRemoteVideoSources;
  1592. msid = `remote-video-${idx} remote-video-${idx}`;
  1593. if (rtx !== '-1') {
  1594. _addSourceElement(node, src, rtx, msid);
  1595. node.c('ssrc-group', {
  1596. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1597. semantics: 'FID'
  1598. })
  1599. .c('source', {
  1600. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1601. ssrc
  1602. })
  1603. .up()
  1604. .c('source', {
  1605. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1606. ssrc: rtx
  1607. })
  1608. .up()
  1609. .up();
  1610. }
  1611. } else {
  1612. const idx = ++this.numRemoteAudioSources;
  1613. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1614. }
  1615. _addSourceElement(node, src, ssrc, msid);
  1616. this.peerconnection.remoteSources.set(source, ssrc);
  1617. }
  1618. node = node.up();
  1619. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1620. }
  1621. }
  1622. /**
  1623. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1624. *
  1625. * @param {string} id Endpoint id of the participant that has left the call.
  1626. * @returns {void}
  1627. */
  1628. removeRemoteStreamsOnLeave(id) {
  1629. const workFunction = finishCallback => {
  1630. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1631. if (removeSsrcInfo.length) {
  1632. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1633. this._renegotiate(newRemoteSdp.raw)
  1634. .then(() => finishCallback(), error => finishCallback(error));
  1635. } else {
  1636. finishCallback();
  1637. }
  1638. };
  1639. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1640. this.modificationQueue.push(
  1641. workFunction,
  1642. error => {
  1643. if (error) {
  1644. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1645. } else {
  1646. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1647. }
  1648. });
  1649. }
  1650. /**
  1651. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1652. * Jingle session.
  1653. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1654. * otherwise.
  1655. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1656. * @private
  1657. */
  1658. _addOrRemoveRemoteStream(isAdd, elem) {
  1659. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1660. if (isAdd) {
  1661. this.readSsrcInfo(elem);
  1662. }
  1663. const workFunction = finishedCallback => {
  1664. if (!this.peerconnection.localDescription
  1665. || !this.peerconnection.localDescription.sdp) {
  1666. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1667. logger.error(errMsg);
  1668. finishedCallback(errMsg);
  1669. return;
  1670. }
  1671. logger.log(`${this} Processing ${logPrefix}`);
  1672. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1673. const addOrRemoveSsrcInfo
  1674. = isAdd
  1675. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1676. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1677. const newRemoteSdp
  1678. = isAdd
  1679. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1680. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1681. this._renegotiate(newRemoteSdp.raw).then(() => {
  1682. logger.log(`${this} ${logPrefix} - OK`);
  1683. finishedCallback();
  1684. }, error => {
  1685. logger.error(`${this} ${logPrefix} failed:`, error);
  1686. finishedCallback(error);
  1687. });
  1688. };
  1689. logger.debug(`${this} Queued ${logPrefix} task`);
  1690. // Queue and execute
  1691. this.modificationQueue.push(workFunction);
  1692. }
  1693. /**
  1694. * Takes in a jingle offer iq, returns the new sdp offer
  1695. * @param {jquery xml element} offerIq the incoming offer
  1696. * @returns {SDP object} the jingle offer translated to SDP
  1697. */
  1698. _processNewJingleOfferIq(offerIq) {
  1699. const remoteSdp = new SDP('');
  1700. if (this.webrtcIceTcpDisable) {
  1701. remoteSdp.removeTcpCandidates = true;
  1702. }
  1703. if (this.webrtcIceUdpDisable) {
  1704. remoteSdp.removeUdpCandidates = true;
  1705. }
  1706. if (this.failICE) {
  1707. remoteSdp.failICE = true;
  1708. }
  1709. remoteSdp.fromJingle(offerIq);
  1710. this.readSsrcInfo($(offerIq).find('>content'));
  1711. return remoteSdp;
  1712. }
  1713. /**
  1714. * Remove the given ssrc lines from the current remote sdp
  1715. * @param {list} removeSsrcInfo a list of SDP line strings that
  1716. * should be removed from the remote SDP
  1717. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1718. * in removeSsrcInfo
  1719. */
  1720. _processRemoteRemoveSource(removeSsrcInfo) {
  1721. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1722. let ssrcs;
  1723. removeSsrcInfo.forEach(lines => {
  1724. // eslint-disable-next-line no-param-reassign
  1725. lines = lines.split('\r\n');
  1726. lines.pop(); // remove empty last element;
  1727. ssrcs = lines.map(line => Number(line.split('a=ssrc:')[1]?.split(' ')[0]));
  1728. let mid;
  1729. lines.forEach(line => {
  1730. mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1731. if (mid > -1) {
  1732. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1733. if (this.isP2P) {
  1734. const mediaType = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0])?.media;
  1735. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, false);
  1736. [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ].forEach(direction => {
  1737. remoteSdp.media[mid] = remoteSdp.media[mid]
  1738. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1739. });
  1740. } else {
  1741. // Jvb connections will have direction set to 'sendonly' for the remote sources.
  1742. remoteSdp.media[mid] = remoteSdp.media[mid]
  1743. .replace(`a=${MediaDirection.SENDONLY}`, `a=${MediaDirection.INACTIVE}`);
  1744. // Reject the m-line so that the browser removes the associated transceiver from the list
  1745. // of available transceivers. This will prevent the client from trying to re-use these
  1746. // inactive transceivers when additional video sources are added to the peerconnection.
  1747. const { media, port } = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0]);
  1748. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`m=${media} ${port}`, `m=${media} 0`);
  1749. }
  1750. }
  1751. });
  1752. });
  1753. // Update the ssrc owners list.
  1754. ssrcs?.length && this._signalingLayer.removeSSRCOwners(ssrcs);
  1755. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1756. return remoteSdp;
  1757. }
  1758. /**
  1759. * Add the given ssrc lines to the current remote sdp
  1760. * @param {list} addSsrcInfo a list of SDP line strings that
  1761. * should be added to the remote SDP
  1762. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1763. * in removeSsrcInfo
  1764. */
  1765. _processRemoteAddSource(addSsrcInfo) {
  1766. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1767. // Add a new m-line in the remote description if the source info for a secondary video source is recceived from
  1768. // the remote p2p peer when multi-stream support is enabled.
  1769. if (addSsrcInfo.length > remoteSdp.media.length && this.isP2P) {
  1770. remoteSdp.addMlineForNewLocalSource(MediaType.VIDEO);
  1771. remoteSdp = new SDP(remoteSdp.raw);
  1772. }
  1773. addSsrcInfo.forEach((lines, idx) => {
  1774. remoteSdp.media[idx] += lines;
  1775. // Make sure to change the direction to 'sendrecv/sendonly' only for p2p connections. For jvb connections,
  1776. // a new m-line is added for the new remote sources.
  1777. if (this.isP2P) {
  1778. const mediaType = SDPUtil.parseMLine(remoteSdp.media[idx].split('\r\n')[0])?.media;
  1779. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, true);
  1780. [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ].forEach(direction => {
  1781. remoteSdp.media[idx] = remoteSdp.media[idx]
  1782. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1783. });
  1784. }
  1785. });
  1786. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1787. return remoteSdp;
  1788. }
  1789. /**
  1790. * Does a new offer/answer flow using the existing remote description (if not provided) and signals any new sources
  1791. * to Jicofo or the remote peer.
  1792. *
  1793. * @param {string} [optionalRemoteSdp] optional, raw remote sdp to use. If not provided, the remote sdp from the
  1794. * peerconnection will be used.
  1795. * @returns {Promise} promise which resolves when the o/a flow is complete with no arguments or rejects with an
  1796. * error {string}
  1797. */
  1798. _renegotiate(optionalRemoteSdp) {
  1799. if (this.peerconnection.signalingState === 'closed') {
  1800. const error = new Error('Attempted to renegotiate in state closed');
  1801. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1802. return Promise.reject(error);
  1803. }
  1804. const remoteSdp = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1805. if (!remoteSdp) {
  1806. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1807. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1808. return Promise.reject(error);
  1809. }
  1810. const remoteDescription = new RTCSessionDescription({
  1811. type: 'offer',
  1812. sdp: remoteSdp
  1813. });
  1814. const oldLocalSDP = this.peerconnection.localDescription.sdp;
  1815. logger.debug(`${this} Renegotiate: setting remote description`);
  1816. return this.peerconnection.setRemoteDescription(remoteDescription)
  1817. .then(() => {
  1818. logger.debug(`${this} Renegotiate: creating answer`);
  1819. return this.peerconnection.createAnswer(this.mediaConstraints);
  1820. })
  1821. .then(answer => {
  1822. logger.debug(`${this} Renegotiate: setting local description`);
  1823. return this.peerconnection.setLocalDescription(answer);
  1824. })
  1825. .then(() => {
  1826. if (oldLocalSDP) {
  1827. // Send the source updates after every renegotiation cycle.
  1828. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(this.peerconnection.localDescription.sdp));
  1829. }
  1830. });
  1831. }
  1832. /**
  1833. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  1834. * being added to the peerconnection for the first time.
  1835. *
  1836. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  1837. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  1838. * otherwise.
  1839. */
  1840. addTracks(localTracks = null) {
  1841. if (!localTracks?.length) {
  1842. Promise.reject(new Error('No tracks passed'));
  1843. }
  1844. if (localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  1845. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  1846. }
  1847. const replaceTracks = [];
  1848. const workFunction = finishedCallback => {
  1849. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1850. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  1851. .find(t => t.receiver.track.kind === MediaType.VIDEO
  1852. && t.direction === MediaDirection.RECVONLY
  1853. && t.currentDirection === MediaDirection.RECVONLY);
  1854. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  1855. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  1856. // existing one in that case.
  1857. for (const track of localTracks) {
  1858. if (!this.isP2P || !recvOnlyTransceiver) {
  1859. remoteSdp.addMlineForNewLocalSource(track.getType());
  1860. }
  1861. }
  1862. this._renegotiate(remoteSdp.raw)
  1863. .then(() => {
  1864. // Replace the tracks on the newly generated transceivers.
  1865. for (const track of localTracks) {
  1866. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  1867. }
  1868. return Promise.all(replaceTracks);
  1869. })
  1870. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  1871. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  1872. .then(() => this._renegotiate())
  1873. .then(() => finishedCallback(), error => finishedCallback(error));
  1874. };
  1875. return new Promise((resolve, reject) => {
  1876. logger.debug(`${this} Queued renegotiation after addTrack`);
  1877. this.modificationQueue.push(
  1878. workFunction,
  1879. error => {
  1880. if (error) {
  1881. if (error instanceof ClearedQueueError) {
  1882. // The session might have been terminated before the task was executed, making it obsolete.
  1883. logger.debug(`${this} renegotiation after addTrack aborted: session terminated`);
  1884. resolve();
  1885. return;
  1886. }
  1887. logger.error(`${this} renegotiation after addTrack error`, error);
  1888. reject(error);
  1889. } else {
  1890. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1891. resolve();
  1892. }
  1893. });
  1894. });
  1895. }
  1896. /**
  1897. * Resumes or suspends media transfer over the underlying peer connection.
  1898. *
  1899. * @param {boolean} active - <tt>true</tt> to enable media transfer or <tt>false</tt> to suspend media transmission
  1900. * @returns {Promise}
  1901. */
  1902. setMediaTransferActive(active) {
  1903. const changed = this.peerconnection.audioTransferActive !== active
  1904. || this.peerconnection.videoTransferActive !== active;
  1905. if (!changed) {
  1906. return Promise.resolve();
  1907. }
  1908. return this.peerconnection.tpcUtils.setMediaTransferActive(active)
  1909. .then(() => {
  1910. this.peerconnection.audioTransferActive = active;
  1911. this.peerconnection.videoTransferActive = active;
  1912. // Reconfigure the audio and video tracks so that only the correct encodings are active.
  1913. const promises = [];
  1914. promises.push(this.peerconnection.configureVideoSenderEncodings());
  1915. promises.push(this.peerconnection.configureAudioSenderEncodings());
  1916. return Promise.allSettled(promises);
  1917. });
  1918. }
  1919. /**
  1920. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1921. * offer/answer cycle after both operations are done. Either
  1922. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1923. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1924. * <tt>oldTrack</tt>
  1925. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1926. * replaced
  1927. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1928. * @returns {Promise} which resolves once the replacement is complete
  1929. * with no arguments or rejects with an error {string}
  1930. */
  1931. replaceTrack(oldTrack, newTrack) {
  1932. const workFunction = finishedCallback => {
  1933. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  1934. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1935. .then(shouldRenegotiate => {
  1936. let promise = Promise.resolve();
  1937. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  1938. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  1939. if (shouldRenegotiate && (oldTrack || newTrack) && this.state === JingleSessionState.ACTIVE) {
  1940. promise = this._renegotiate();
  1941. }
  1942. return promise.then(() => {
  1943. // Set the source name of the new track.
  1944. if (oldTrack && newTrack && oldTrack.isVideoTrack()) {
  1945. newTrack.setSourceName(oldTrack.getSourceName());
  1946. }
  1947. });
  1948. })
  1949. .then(() => finishedCallback(), error => finishedCallback(error));
  1950. };
  1951. return new Promise((resolve, reject) => {
  1952. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  1953. this.modificationQueue.push(
  1954. workFunction,
  1955. error => {
  1956. if (error) {
  1957. if (error instanceof ClearedQueueError) {
  1958. // The session might have been terminated before the task was executed, making it obsolete.
  1959. logger.debug('Replace track aborted: session terminated');
  1960. resolve();
  1961. return;
  1962. }
  1963. logger.error(`${this} Replace track error:`, error);
  1964. reject(error);
  1965. } else {
  1966. logger.info(`${this} Replace track done!`);
  1967. resolve();
  1968. }
  1969. });
  1970. });
  1971. }
  1972. /**
  1973. * Parse the information from the xml sourceRemoveElem and translate it
  1974. * into sdp lines
  1975. * @param {jquery xml element} sourceRemoveElem the source-remove
  1976. * element from jingle
  1977. * @param {SDP object} currentRemoteSdp the current remote
  1978. * sdp (as of this new source-remove)
  1979. * @returns {list} a list of SDP line strings that should
  1980. * be removed from the remote SDP
  1981. */
  1982. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1983. const removeSsrcInfo = [];
  1984. $(sourceRemoveElem).each((i1, content) => {
  1985. const name = $(content).attr('name');
  1986. let lines = '';
  1987. $(content)
  1988. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1989. .each(function() {
  1990. /* eslint-disable no-invalid-this */
  1991. const semantics = this.getAttribute('semantics');
  1992. const ssrcs
  1993. = $(this)
  1994. .find('>source')
  1995. .map(function() {
  1996. return this.getAttribute('ssrc');
  1997. })
  1998. .get();
  1999. if (ssrcs.length) {
  2000. lines
  2001. += `a=ssrc-group:${semantics} ${
  2002. ssrcs.join(' ')}\r\n`;
  2003. }
  2004. /* eslint-enable no-invalid-this */
  2005. });
  2006. const ssrcs = [];
  2007. // handles both >source and >description>source versions
  2008. const tmp
  2009. = $(content).find(
  2010. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  2011. tmp.each(function() {
  2012. // eslint-disable-next-line no-invalid-this
  2013. const ssrc = $(this).attr('ssrc');
  2014. ssrcs.push(ssrc);
  2015. });
  2016. currentRemoteSdp.media.forEach((media, i2) => {
  2017. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  2018. return;
  2019. }
  2020. if (!removeSsrcInfo[i2]) {
  2021. removeSsrcInfo[i2] = '';
  2022. }
  2023. ssrcs.forEach(ssrc => {
  2024. const ssrcLines
  2025. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  2026. if (ssrcLines.length) {
  2027. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  2028. }
  2029. });
  2030. removeSsrcInfo[i2] += lines;
  2031. });
  2032. });
  2033. return removeSsrcInfo;
  2034. }
  2035. /**
  2036. * Adds local track back to the peerconnection associated with this session.
  2037. * @param {JitsiLocalTrack} track
  2038. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  2039. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  2040. * details in case something goes wrong.
  2041. */
  2042. addTrackToPc(track) {
  2043. return this._addRemoveTrack(false /* add */, track)
  2044. .then(() => {
  2045. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  2046. // unmutes it the first time, all the parameters need to be configured.
  2047. if (track.isVideoTrack()) {
  2048. return this.peerconnection.configureVideoSenderEncodings(track);
  2049. }
  2050. });
  2051. }
  2052. /**
  2053. * Remove local track as part of the mute operation.
  2054. * @param {JitsiLocalTrack} track the local track to be removed
  2055. * @return {Promise} a promise which will be resolved once the local track
  2056. * is removed from this session and the renegotiation is performed.
  2057. * The promise will be rejected with a <tt>string</tt> that the describes
  2058. * the error if anything goes wrong.
  2059. */
  2060. removeTrackFromPc(track) {
  2061. return this._addRemoveTrack(true /* remove */, track);
  2062. }
  2063. /**
  2064. * See {@link addTrackToPc} and {@link removeTrackFromPc}.
  2065. * @param {boolean} isRemove <tt>true</tt> for "remove" operation or <tt>false</tt> for "add" operation.
  2066. * @param {JitsiLocalTrack} track the track that will be added/removed
  2067. * @private
  2068. */
  2069. _addRemoveTrack(isRemove, track) {
  2070. if (!track) {
  2071. return Promise.reject('invalid "track" argument value');
  2072. }
  2073. const operationName = isRemove ? 'removeTrack' : 'addTrack';
  2074. const workFunction = finishedCallback => {
  2075. const tpc = this.peerconnection;
  2076. if (!tpc) {
  2077. finishedCallback(`Error: tried ${operationName} track with no active peer connection`);
  2078. return;
  2079. }
  2080. const operationPromise
  2081. = isRemove
  2082. ? tpc.removeTrackFromPc(track)
  2083. : tpc.addTrackToPc(track);
  2084. operationPromise
  2085. .then(shouldRenegotiate => {
  2086. if (shouldRenegotiate) {
  2087. this._renegotiate().then(finishedCallback);
  2088. } else {
  2089. finishedCallback();
  2090. }
  2091. },
  2092. finishedCallback /* will be called with an error */);
  2093. };
  2094. logger.debug(`${this} Queued ${operationName} task`);
  2095. return new Promise((resolve, reject) => {
  2096. this.modificationQueue.push(
  2097. workFunction,
  2098. error => {
  2099. if (error) {
  2100. if (error instanceof ClearedQueueError) {
  2101. // The session might have been terminated before the task was executed, making it obsolete.
  2102. logger.debug(`${this} ${operationName} aborted: session terminated`);
  2103. resolve();
  2104. return;
  2105. }
  2106. logger.error(`${this} ${operationName} failed`);
  2107. reject(error);
  2108. } else {
  2109. logger.debug(`${this} ${operationName} done`);
  2110. resolve();
  2111. }
  2112. });
  2113. });
  2114. }
  2115. /**
  2116. * Resumes or suspends video media transfer over the p2p peer connection.
  2117. *
  2118. * @param {boolean} videoActive <tt>true</tt> to enable video media transfer or <tt>false</tt> to suspend video
  2119. * media transmission.
  2120. * @return {Promise} a <tt>Promise</tt> which will resolve once the operation is done. It will be rejected with
  2121. * an error description as a string in case anything goes wrong.
  2122. */
  2123. setP2pVideoTransferActive(videoActive) {
  2124. if (!this.peerconnection) {
  2125. return Promise.reject('Can not modify video transfer active state,'
  2126. + ' before "initialize" is called');
  2127. }
  2128. if (this._localSendReceiveVideoActive !== videoActive) {
  2129. this._localSendReceiveVideoActive = videoActive;
  2130. if (this.isP2P && this.state === JingleSessionState.ACTIVE) {
  2131. this.sendContentModify();
  2132. }
  2133. return this.peerconnection
  2134. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  2135. }
  2136. return Promise.resolve();
  2137. }
  2138. /**
  2139. * Enables/disables local video based on 'senders' attribute of the video conent in 'content-modify' IQ sent by the
  2140. * remote peer. Also, checks if the sourceMaxFrameHeight (as requested by the p2p peer) or the senders attribute of
  2141. * the video content has changed and modifies the local video resolution accordingly.
  2142. */
  2143. modifyContents(jingleContents) {
  2144. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  2145. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  2146. if (sourceMaxFrameHeights) {
  2147. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  2148. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  2149. }
  2150. if (newVideoSenders === null) {
  2151. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  2152. return;
  2153. }
  2154. if (!this._assertNotEnded()) {
  2155. return;
  2156. }
  2157. const isRemoteVideoActive
  2158. = newVideoSenders === 'both'
  2159. || (newVideoSenders === 'initiator' && this.isInitiator)
  2160. || (newVideoSenders === 'responder' && !this.isInitiator);
  2161. if (isRemoteVideoActive !== this._remoteSendReceiveVideoActive) {
  2162. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  2163. this._remoteSendReceiveVideoActive = isRemoteVideoActive;
  2164. this.peerconnection
  2165. .setVideoTransferActive(this._localSendReceiveVideoActive && this._remoteSendReceiveVideoActive);
  2166. }
  2167. }
  2168. /**
  2169. * Figures out added/removed ssrcs and send update IQs.
  2170. * @param oldSDP SDP object for old description.
  2171. * @param newSDP SDP object for new description.
  2172. */
  2173. notifyMySSRCUpdate(oldSDP, newSDP) {
  2174. if (this.state !== JingleSessionState.ACTIVE) {
  2175. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  2176. return;
  2177. }
  2178. if (!this.connection.connected) {
  2179. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2180. if (!this._cachedOldLocalSdp) {
  2181. this._cachedOldLocalSdp = oldSDP;
  2182. }
  2183. this._cachedNewLocalSdp = newSDP;
  2184. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  2185. return;
  2186. }
  2187. this._cachedOldLocalSdp = undefined;
  2188. this._cachedNewLocalSdp = undefined;
  2189. const getSignaledSourceInfo = sdpDiffer => {
  2190. const newMedia = sdpDiffer.getNewMedia();
  2191. let ssrcs = [];
  2192. let mediaType = null;
  2193. // It is assumed that sources are signaled one at a time.
  2194. Object.keys(newMedia).forEach(mediaIndex => {
  2195. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  2196. mediaType = newMedia[mediaIndex].mid;
  2197. if (signaledSsrcs?.length) {
  2198. ssrcs = ssrcs.concat(signaledSsrcs);
  2199. }
  2200. });
  2201. return {
  2202. mediaType,
  2203. ssrcs
  2204. };
  2205. };
  2206. // send source-remove IQ.
  2207. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2208. const remove = $iq({ to: this.remoteJid,
  2209. type: 'set' })
  2210. .c('jingle', {
  2211. xmlns: 'urn:xmpp:jingle:1',
  2212. action: 'source-remove',
  2213. initiator: this.initiatorJid,
  2214. sid: this.sid
  2215. }
  2216. );
  2217. sdpDiffer.toJingle(remove);
  2218. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  2219. // need to
  2220. const ctx = {};
  2221. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2222. if (removedSsrcInfo.ssrcs.length) {
  2223. // Log only the SSRCs instead of the full IQ.
  2224. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  2225. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  2226. this.connection.sendIQ(
  2227. remove,
  2228. () => {
  2229. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  2230. },
  2231. this.newJingleErrorHandler(remove, error => {
  2232. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  2233. }),
  2234. IQ_TIMEOUT);
  2235. }
  2236. // send source-add IQ.
  2237. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2238. const add = $iq({ to: this.remoteJid,
  2239. type: 'set' })
  2240. .c('jingle', {
  2241. xmlns: 'urn:xmpp:jingle:1',
  2242. action: 'source-add',
  2243. initiator: this.initiatorJid,
  2244. sid: this.sid
  2245. }
  2246. );
  2247. sdpDiffer.toJingle(add);
  2248. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2249. if (addedSsrcInfo.ssrcs.length) {
  2250. // Log only the SSRCs instead of the full IQ.
  2251. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  2252. this.connection.sendIQ(
  2253. add,
  2254. () => {
  2255. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  2256. },
  2257. this.newJingleErrorHandler(add, error => {
  2258. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  2259. }),
  2260. IQ_TIMEOUT);
  2261. }
  2262. }
  2263. /**
  2264. * Method returns function(errorResponse) which is a callback to be passed
  2265. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2266. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2267. * structure is as follows:
  2268. * {
  2269. * code: {XMPP error response code}
  2270. * reason: {the name of XMPP error reason element or 'timeout' if the
  2271. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2272. * source: {request.tree() that provides original request}
  2273. * session: {this JingleSessionPC.toString()}
  2274. * }
  2275. * @param request Strophe IQ instance which is the request to be dumped into
  2276. * the error structure
  2277. * @param failureCb function(error) called when error response was returned
  2278. * or when a timeout has occurred.
  2279. * @returns {function(this:JingleSessionPC)}
  2280. */
  2281. newJingleErrorHandler(request, failureCb) {
  2282. return errResponse => {
  2283. const error = {};
  2284. // Get XMPP error code and condition(reason)
  2285. const errorElSel = $(errResponse).find('error');
  2286. if (errorElSel.length) {
  2287. error.code = errorElSel.attr('code');
  2288. const errorReasonSel = $(errResponse).find('error :first');
  2289. if (errorReasonSel.length) {
  2290. error.reason = errorReasonSel[0].tagName;
  2291. }
  2292. const errorMsgSel = errorElSel.find('>text');
  2293. if (errorMsgSel.length) {
  2294. error.msg = errorMsgSel.text();
  2295. }
  2296. }
  2297. if (!errResponse) {
  2298. error.reason = 'timeout';
  2299. }
  2300. error.session = this.toString();
  2301. if (failureCb) {
  2302. failureCb(error);
  2303. } else if (this.state === JingleSessionState.ENDED
  2304. && error.reason === 'item-not-found') {
  2305. // When remote peer decides to terminate the session, but it
  2306. // still have few messages on the queue for processing,
  2307. // it will first send us 'session-terminate' (we enter ENDED)
  2308. // and then follow with 'item-not-found' for the queued requests
  2309. // We don't want to have that logged on error level.
  2310. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  2311. } else {
  2312. logger.error(`Jingle error: ${JSON.stringify(error)}`);
  2313. }
  2314. };
  2315. }
  2316. /**
  2317. * Returns the ice connection state for the peer connection.
  2318. * @returns the ice connection state for the peer connection.
  2319. */
  2320. getIceConnectionState() {
  2321. return this.peerconnection.getConnectionState();
  2322. }
  2323. /**
  2324. * Closes the peerconnection.
  2325. */
  2326. close() {
  2327. this.state = JingleSessionState.ENDED;
  2328. this.establishmentDuration = undefined;
  2329. if (this.peerconnection) {
  2330. this.peerconnection.onicecandidate = null;
  2331. this.peerconnection.oniceconnectionstatechange = null;
  2332. this.peerconnection.onnegotiationneeded = null;
  2333. this.peerconnection.onsignalingstatechange = null;
  2334. }
  2335. logger.debug(`${this} Clearing modificationQueue`);
  2336. // Remove any pending tasks from the queue
  2337. this.modificationQueue.clear();
  2338. logger.debug(`${this} Queued PC close task`);
  2339. this.modificationQueue.push(finishCallback => {
  2340. // do not try to close if already closed.
  2341. this.peerconnection && this.peerconnection.close();
  2342. finishCallback();
  2343. logger.debug(`${this} PC close task done!`);
  2344. });
  2345. logger.debug(`${this} Shutdown modificationQueue!`);
  2346. // No more tasks can go in after the close task
  2347. this.modificationQueue.shutdown();
  2348. }
  2349. /**
  2350. * Converts to string with minor summary.
  2351. * @return {string}
  2352. */
  2353. toString() {
  2354. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2355. }
  2356. }