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

JingleSessionPC.js 87KB

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