modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 115KB

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