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

JingleSessionPC.js 110KB

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