選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JingleSessionPC.js 109KB

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