You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 101KB

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