Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 107KB

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