Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSessionPC.js 72KB

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