Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JingleSessionPC.js 120KB

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