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 84KB

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