modified lib-jitsi-meet dev repo
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JingleSessionPC.js 105KB

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