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

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