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 119KB

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