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

JingleSessionPC.js 118KB

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