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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  1. /* global $, $iq, Strophe */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. const logger = getLogger(__filename);
  4. import JingleSession from './JingleSession';
  5. const SDPDiffer = require('./SDPDiffer');
  6. const SDPUtil = require('./SDPUtil');
  7. const SDP = require('./SDP');
  8. const async = require('async');
  9. const XMPPEvents = require('../../service/xmpp/XMPPEvents');
  10. const RTCBrowserType = require('../RTC/RTCBrowserType');
  11. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  12. const Statistics = require('../statistics/statistics');
  13. import * as JingleSessionState from './JingleSessionState';
  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 {object} options a set of config options
  38. * @param {boolean} options.webrtcIceUdpDisable <tt>true</tt> to block UDP
  39. * candidates.
  40. * @param {boolean} options.webrtcIceTcpDisable <tt>true</tt> to block TCP
  41. * candidates.
  42. * @param {boolean} options.failICE it's an option used in the tests. Set to
  43. * <tt>true</tt> to block any real candidates and make the ICE fail.
  44. *
  45. * @constructor
  46. *
  47. * @implements {SignalingLayer}
  48. */
  49. constructor(
  50. sid,
  51. me,
  52. peerjid,
  53. connection,
  54. mediaConstraints,
  55. iceConfig,
  56. options) {
  57. super(sid, me, peerjid, connection, mediaConstraints, iceConfig);
  58. this.lasticecandidate = false;
  59. this.closed = false;
  60. this.modifyingLocalStreams = false;
  61. /**
  62. * Used to keep state about muted/unmuted video streams
  63. * so we can prevent errant source-add/source-removes
  64. * from happening
  65. */
  66. this.modifiedSSRCs = {};
  67. /**
  68. * The local ICE username fragment for this session.
  69. */
  70. this.localUfrag = null;
  71. /**
  72. * The remote ICE username fragment for this session.
  73. */
  74. this.remoteUfrag = null;
  75. /**
  76. * A map that stores SSRCs of remote streams. And is used only locally
  77. * We store the mapping when jingle is received, and later is used
  78. * onaddstream webrtc event where we have only the ssrc
  79. * FIXME: This map got filled and never cleaned and can grow during
  80. * long conference
  81. * @type {{}} maps SSRC number to jid
  82. */
  83. this.ssrcOwners = {};
  84. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  85. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  86. /**
  87. * Flag used to enforce ICE failure through the URL parameter for
  88. * the automatic testing purpose.
  89. * @type {boolean}
  90. */
  91. this.failICE = Boolean(options.failICE);
  92. this.modificationQueue
  93. = async.queue(this._processQueueTasks.bind(this), 1);
  94. }
  95. /* eslint-enable max-params */
  96. /**
  97. *
  98. */
  99. doInitialize() {
  100. this.lasticecandidate = false;
  101. // True if reconnect is in progress
  102. this.isreconnect = false;
  103. // Set to true if the connection was ever stable
  104. this.wasstable = false;
  105. // Create new peer connection instance
  106. this.peerconnection
  107. = this.rtc.createPeerConnection(
  108. this,
  109. this.connection.jingle.iceConfig,
  110. /* Options */
  111. {
  112. disableSimulcast: this.room.options.disableSimulcast,
  113. disableRtx: this.room.options.disableRtx,
  114. preferH264: this.room.options.preferH264
  115. });
  116. this.peerconnection.onicecandidate = ev => {
  117. if (!ev) {
  118. // There was an incomplete check for ev before which left
  119. // the last line of the function unprotected from a potential
  120. // throw of an exception. Consequently, it may be argued that
  121. // the check is unnecessary. Anyway, I'm leaving it and making
  122. // the check complete.
  123. return;
  124. }
  125. // XXX this is broken, candidate is not parsed.
  126. const candidate = ev.candidate;
  127. if (candidate) {
  128. // Discard candidates of disabled protocols.
  129. let protocol = candidate.protocol;
  130. if (typeof protocol === 'string') {
  131. protocol = protocol.toLowerCase();
  132. if (protocol === 'tcp' || protocol === 'ssltcp') {
  133. if (this.webrtcIceTcpDisable) {
  134. return;
  135. }
  136. } else if (protocol === 'udp') {
  137. if (this.webrtcIceUdpDisable) {
  138. return;
  139. }
  140. }
  141. }
  142. }
  143. this.sendIceCandidate(candidate);
  144. };
  145. // Note there is a change in the spec about closed:
  146. // This value moved into the RTCPeerConnectionState enum in
  147. // the May 13, 2016 draft of the specification, as it reflects the state
  148. // of the RTCPeerConnection, not the signaling connection. You now
  149. // detect a closed connection by checking for connectionState to be
  150. // "closed" instead.
  151. // I suppose at some point this will be moved to onconnectionstatechange
  152. this.peerconnection.onsignalingstatechange = () => {
  153. if (!this.peerconnection) {
  154. return;
  155. }
  156. if (this.peerconnection.signalingState === 'stable') {
  157. this.wasstable = true;
  158. } else if (
  159. (this.peerconnection.signalingState === 'closed'
  160. || this.peerconnection.connectionState === 'closed')
  161. && !this.closed) {
  162. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED);
  163. }
  164. };
  165. /**
  166. * The oniceconnectionstatechange event handler contains the code to
  167. * execute when the iceconnectionstatechange event, of type Event,
  168. * is received by this RTCPeerConnection. Such an event is sent when
  169. * the value of RTCPeerConnection.iceConnectionState changes.
  170. */
  171. this.peerconnection.oniceconnectionstatechange = () => {
  172. if (!this.peerconnection) {
  173. return;
  174. }
  175. const now = window.performance.now();
  176. this.room.connectionTimes[
  177. `ice.state.${this.peerconnection.iceConnectionState}`]
  178. = now;
  179. logger.log(
  180. `(TIME) ICE ${this.peerconnection.iceConnectionState}:\t`,
  181. now);
  182. Statistics.analytics.sendEvent(
  183. `ice.${this.peerconnection.iceConnectionState}`,
  184. { value: now });
  185. this.room.eventEmitter.emit(
  186. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  187. this.peerconnection.iceConnectionState);
  188. switch (this.peerconnection.iceConnectionState) {
  189. case 'connected':
  190. // Informs interested parties that the connection has been
  191. // restored.
  192. if (this.peerconnection.signalingState === 'stable'
  193. && this.isreconnect) {
  194. this.room.eventEmitter.emit(
  195. XMPPEvents.CONNECTION_RESTORED);
  196. }
  197. this.isreconnect = false;
  198. break;
  199. case 'disconnected':
  200. if (this.closed) {
  201. break;
  202. }
  203. this.isreconnect = true;
  204. // Informs interested parties that the connection has been
  205. // interrupted.
  206. if (this.wasstable) {
  207. this.room.eventEmitter.emit(
  208. XMPPEvents.CONNECTION_INTERRUPTED);
  209. }
  210. break;
  211. case 'failed':
  212. this.room.eventEmitter.emit(
  213. XMPPEvents.CONNECTION_ICE_FAILED, this.peerconnection);
  214. break;
  215. }
  216. };
  217. this.peerconnection.onnegotiationneeded = () => {
  218. this.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, this);
  219. };
  220. }
  221. /**
  222. *
  223. * @param candidate
  224. */
  225. sendIceCandidate(candidate) {
  226. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  227. if (candidate && !this.lasticecandidate) {
  228. const ice
  229. = SDPUtil.iceparams(
  230. localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  231. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  232. if (!(ice && jcand)) {
  233. const errorMesssage = 'failed to get ice && jcand';
  234. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  235. logger.error(errorMesssage);
  236. return;
  237. }
  238. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  239. if (this.usedrip) {
  240. if (this.dripContainer.length === 0) {
  241. // start 20ms callout
  242. setTimeout(() => {
  243. if (this.dripContainer.length === 0) {
  244. return;
  245. }
  246. this.sendIceCandidates(this.dripContainer);
  247. this.dripContainer = [];
  248. }, 20);
  249. }
  250. this.dripContainer.push(candidate);
  251. } else {
  252. this.sendIceCandidates([ candidate ]);
  253. }
  254. } else {
  255. logger.log('sendIceCandidate: last candidate.');
  256. // FIXME: remember to re-think in ICE-restart
  257. this.lasticecandidate = true;
  258. }
  259. }
  260. /**
  261. *
  262. * @param candidates
  263. */
  264. sendIceCandidates(candidates) {
  265. logger.log('sendIceCandidates', candidates);
  266. const cand = $iq({ to: this.peerjid,
  267. type: 'set' })
  268. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  269. action: 'transport-info',
  270. initiator: this.initiator,
  271. sid: this.sid });
  272. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  273. for (let mid = 0; mid < localSDP.media.length; mid++) {
  274. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  275. const mline
  276. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  277. if (cands.length > 0) {
  278. const ice
  279. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  280. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  281. cand.c('content', {
  282. creator: this.initiator === this.localJid
  283. ? 'initiator' : 'responder',
  284. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  285. }).c('transport', ice);
  286. for (let i = 0; i < cands.length; i++) {
  287. const candidate
  288. = SDPUtil.candidateToJingle(cands[i].candidate);
  289. // Mangle ICE candidate if 'failICE' test option is enabled
  290. if (this.failICE) {
  291. candidate.ip = '1.1.1.1';
  292. }
  293. cand.c('candidate', candidate).up();
  294. }
  295. // add fingerprint
  296. const fingerprintLine
  297. = SDPUtil.findLine(
  298. localSDP.media[mid],
  299. 'a=fingerprint:', localSDP.session);
  300. if (fingerprintLine) {
  301. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  302. tmp.required = true;
  303. cand.c(
  304. 'fingerprint',
  305. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  306. .t(tmp.fingerprint);
  307. delete tmp.fingerprint;
  308. cand.attrs(tmp);
  309. cand.up();
  310. }
  311. cand.up(); // transport
  312. cand.up(); // content
  313. }
  314. }
  315. // might merge last-candidate notification into this, but it is called
  316. // a lot later. See webrtc issue #2340
  317. // logger.log('was this the last candidate', this.lasticecandidate);
  318. this.connection.sendIQ(
  319. cand, null, this.newJingleErrorHandler(cand, error => {
  320. GlobalOnErrorHandler.callErrorHandler(
  321. new Error(`Jingle error: ${JSON.stringify(error)}`));
  322. }), IQ_TIMEOUT);
  323. }
  324. /**
  325. *
  326. * @param contents
  327. */
  328. readSsrcInfo(contents) {
  329. $(contents).each((i1, content) => {
  330. const ssrcs
  331. = $(content).find(
  332. 'description>'
  333. + 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  334. ssrcs.each((i2, ssrcElement) => {
  335. const ssrc = ssrcElement.getAttribute('ssrc');
  336. $(ssrcElement)
  337. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  338. .each((i3, ssrcInfoElement) => {
  339. const owner = ssrcInfoElement.getAttribute('owner');
  340. if (owner && owner.length) {
  341. this.ssrcOwners[ssrc]
  342. = Strophe.getResourceFromJid(owner);
  343. }
  344. }
  345. );
  346. });
  347. });
  348. }
  349. /**
  350. * Makes the underlying TraceablePeerConnection generate new SSRC for
  351. * the recvonly video stream.
  352. * @deprecated
  353. */
  354. generateRecvonlySsrc() {
  355. if (this.peerconnection) {
  356. this.peerconnection.generateRecvonlySsrc();
  357. } else {
  358. logger.error(
  359. 'Unable to generate recvonly SSRC - no peerconnection');
  360. }
  361. }
  362. /**
  363. * Accepts incoming Jingle 'session-initiate' and should send
  364. * 'session-accept' in result.
  365. * @param jingleOffer jQuery selector pointing to the jingle element of
  366. * the offer IQ
  367. * @param success callback called when we accept incoming session
  368. * successfully and receive RESULT packet to 'session-accept' sent.
  369. * @param failure function(error) called if for any reason we fail to accept
  370. * the incoming offer. 'error' argument can be used to log some
  371. * details about the error.
  372. */
  373. acceptOffer(jingleOffer, success, failure) {
  374. this.state = JingleSessionState.ACTIVE;
  375. this.setOfferCycle(
  376. jingleOffer,
  377. () => {
  378. // FIXME we may not care about RESULT packet for session-accept
  379. // then we should either call 'success' here immediately or
  380. // modify sendSessionAccept method to do that
  381. this.sendSessionAccept(success, failure);
  382. },
  383. failure);
  384. }
  385. /**
  386. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  387. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  388. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  389. * @param jingleOfferIq jQuery selector pointing to the jingle element of
  390. * the offer IQ
  391. * @param success callback called when sRD/sLD cycle finishes successfully.
  392. * @param failure callback called with an error object as an argument if we
  393. * fail at any point during setRD, createAnswer, setLD.
  394. */
  395. setOfferCycle(jingleOfferIq, success, failure) {
  396. const workFunction = finishedCallback => {
  397. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferIq);
  398. this._renegotiate(newRemoteSdp)
  399. .then(() => {
  400. finishedCallback();
  401. }, error => {
  402. logger.error(
  403. `Error renegotiating after setting new remote offer: ${
  404. error}`);
  405. JingleSessionPC.onJingleFatalError(this, error);
  406. finishedCallback(error);
  407. });
  408. };
  409. this.modificationQueue.push(
  410. workFunction,
  411. error => {
  412. error ? failure(error) : success();
  413. });
  414. }
  415. /**
  416. * Although it states "replace transport" it does accept full Jingle offer
  417. * which should contain new ICE transport details.
  418. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  419. * transport info.
  420. * @param success callback called when we succeed to accept new offer.
  421. * @param failure function(error) called when we fail to accept new offer.
  422. */
  423. replaceTransport(jingleOfferElem, success, failure) {
  424. // We need to first set an offer without the 'data' section to have the
  425. // SCTP stack cleaned up. After that the original offer is set to have
  426. // the SCTP connection established with the new bridge.
  427. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING);
  428. const originalOffer = jingleOfferElem.clone();
  429. jingleOfferElem.find('>content[name=\'data\']').remove();
  430. // First set an offer without the 'data' section
  431. this.setOfferCycle(
  432. jingleOfferElem,
  433. () => {
  434. // Now set the original offer(with the 'data' section)
  435. this.setOfferCycle(
  436. originalOffer,
  437. () => {
  438. const localSDP
  439. = new SDP(this.peerconnection.localDescription.sdp);
  440. this.sendTransportAccept(localSDP, success, failure);
  441. },
  442. failure);
  443. },
  444. failure
  445. );
  446. }
  447. /**
  448. * Sends Jingle 'session-accept' message.
  449. * @param {function()} success callback called when we receive 'RESULT'
  450. * packet for the 'session-accept'
  451. * @param {function(error)} failure called when we receive an error response
  452. * or when the request has timed out.
  453. */
  454. sendSessionAccept(success, failure) {
  455. // NOTE: since we're just reading from it, we don't need to be within
  456. // the modification queue to access the local description
  457. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  458. let accept = $iq({ to: this.peerjid,
  459. type: 'set' })
  460. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  461. action: 'session-accept',
  462. initiator: this.initiator,
  463. responder: this.responder,
  464. sid: this.sid });
  465. if (this.webrtcIceTcpDisable) {
  466. localSDP.removeTcpCandidates = true;
  467. }
  468. if (this.webrtcIceUdpDisable) {
  469. localSDP.removeUdpCandidates = true;
  470. }
  471. if (this.failICE) {
  472. localSDP.failICE = true;
  473. }
  474. localSDP.toJingle(
  475. accept,
  476. this.initiator === this.localJid ? 'initiator' : 'responder',
  477. null);
  478. this.fixJingle(accept);
  479. // Calling tree() to print something useful
  480. accept = accept.tree();
  481. logger.info('Sending session-accept', accept);
  482. this.connection.sendIQ(accept,
  483. success,
  484. this.newJingleErrorHandler(accept, error => {
  485. failure(error);
  486. // 'session-accept' is a critical timeout and we'll
  487. // have to restart
  488. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_TIMEOUT);
  489. }),
  490. IQ_TIMEOUT);
  491. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  492. // fingerprint and setup) ASAP in order to start the connection
  493. // establishment.
  494. //
  495. // FIXME Flushing the connection at this point triggers an issue with
  496. // BOSH request handling in Prosody on slow connections.
  497. //
  498. // The problem is that this request will be quite large and it may take
  499. // time before it reaches Prosody. In the meantime Strophe may decide
  500. // to send the next one. And it was observed that a small request with
  501. // 'transport-info' usually follows this one. It does reach Prosody
  502. // before the previous one was completely received. 'rid' on the server
  503. // is increased and Prosody ignores the request with 'session-accept'.
  504. // It will never reach Jicofo and everything in the request table is
  505. // lost. Removing the flush does not guarantee it will never happen, but
  506. // makes it much less likely('transport-info' is bundled with
  507. // 'session-accept' and any immediate requests).
  508. //
  509. // this.connection.flush();
  510. }
  511. /**
  512. * Sends Jingle 'transport-accept' message which is a response to
  513. * 'transport-replace'.
  514. * @param localSDP the 'SDP' object with local session description
  515. * @param success callback called when we receive 'RESULT' packet for
  516. * 'transport-replace'
  517. * @param failure function(error) called when we receive an error response
  518. * or when the request has timed out.
  519. */
  520. sendTransportAccept(localSDP, success, failure) {
  521. let transportAccept = $iq({ to: this.peerjid,
  522. type: 'set' })
  523. .c('jingle', {
  524. xmlns: 'urn:xmpp:jingle:1',
  525. action: 'transport-accept',
  526. initiator: this.initiator,
  527. sid: this.sid
  528. });
  529. localSDP.media.forEach((medialines, idx) => {
  530. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  531. transportAccept.c('content',
  532. {
  533. creator:
  534. this.initiator === this.localJid
  535. ? 'initiator'
  536. : 'responder',
  537. name: mline.media
  538. }
  539. );
  540. localSDP.transportToJingle(idx, transportAccept);
  541. transportAccept.up();
  542. });
  543. // Calling tree() to print something useful to the logger
  544. transportAccept = transportAccept.tree();
  545. logger.info('Sending transport-accept: ', transportAccept);
  546. this.connection.sendIQ(transportAccept,
  547. success,
  548. this.newJingleErrorHandler(transportAccept, failure),
  549. IQ_TIMEOUT);
  550. }
  551. /**
  552. * Sends Jingle 'transport-reject' message which is a response to
  553. * 'transport-replace'.
  554. * @param success callback called when we receive 'RESULT' packet for
  555. * 'transport-replace'
  556. * @param failure function(error) called when we receive an error response
  557. * or when the request has timed out.
  558. */
  559. sendTransportReject(success, failure) {
  560. // Send 'transport-reject', so that the focus will
  561. // know that we've failed
  562. let transportReject = $iq({ to: this.peerjid,
  563. type: 'set' })
  564. .c('jingle', {
  565. xmlns: 'urn:xmpp:jingle:1',
  566. action: 'transport-reject',
  567. initiator: this.initiator,
  568. sid: this.sid
  569. });
  570. transportReject = transportReject.tree();
  571. logger.info('Sending \'transport-reject', transportReject);
  572. this.connection.sendIQ(transportReject,
  573. success,
  574. this.newJingleErrorHandler(transportReject, failure),
  575. IQ_TIMEOUT);
  576. }
  577. /* eslint-disable max-params */
  578. /**
  579. * @inheritDoc
  580. */
  581. terminate(reason, text, success, failure) {
  582. this.state = JingleSessionState.ENDED;
  583. let sessionTerminate = $iq({ to: this.peerjid,
  584. type: 'set' })
  585. .c('jingle', {
  586. xmlns: 'urn:xmpp:jingle:1',
  587. action: 'session-terminate',
  588. initiator: this.initiator,
  589. sid: this.sid
  590. })
  591. .c('reason')
  592. .c(reason || 'success');
  593. if (text) {
  594. // eslint-disable-next-line newline-per-chained-call
  595. sessionTerminate.up().c('text').t(text);
  596. }
  597. // Calling tree() to print something useful
  598. sessionTerminate = sessionTerminate.tree();
  599. logger.info('Sending session-terminate', sessionTerminate);
  600. this.connection.sendIQ(
  601. sessionTerminate,
  602. success,
  603. this.newJingleErrorHandler(sessionTerminate, failure), IQ_TIMEOUT);
  604. // this should result in 'onTerminated' being called by strope.jingle.js
  605. this.connection.jingle.terminate(this.sid);
  606. }
  607. /* eslint-enable max-params */
  608. /**
  609. *
  610. * @param reasonCondition
  611. * @param reasonText
  612. */
  613. onTerminated(reasonCondition, reasonText) {
  614. this.state = 'ended';
  615. // Do something with reason and reasonCondition when we start to care
  616. // this.reasonCondition = reasonCondition;
  617. // this.reasonText = reasonText;
  618. logger.info('Session terminated', this, reasonCondition, reasonText);
  619. this.close();
  620. }
  621. /**
  622. * Parse the information from the xml sourceAddElem and translate it
  623. * into sdp lines
  624. * @param {jquery xml element} sourceAddElem the source-add
  625. * element from jingle
  626. * @param {SDP object} currentRemoteSdp the current remote
  627. * sdp (as of this new source-add)
  628. * @returns {list} a list of SDP line strings that should
  629. * be added to the remote SDP
  630. */
  631. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  632. const addSsrcInfo = [];
  633. $(sourceAddElem).each((i1, content) => {
  634. const name = $(content).attr('name');
  635. let lines = '';
  636. $(content)
  637. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  638. .each(function() {
  639. // eslint-disable-next-line no-invalid-this
  640. const semantics = this.getAttribute('semantics');
  641. const ssrcs
  642. = $(this) // eslint-disable-line no-invalid-this
  643. .find('>source')
  644. .map(function() {
  645. // eslint-disable-next-line no-invalid-this
  646. return this.getAttribute('ssrc');
  647. })
  648. .get();
  649. if (ssrcs.length) {
  650. lines
  651. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  652. }\r\n`;
  653. }
  654. });
  655. // handles both >source and >description>source
  656. const tmp
  657. = $(content).find(
  658. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  659. /* eslint-disable no-invalid-this */
  660. tmp.each(function() {
  661. const ssrc = $(this).attr('ssrc');
  662. if (currentRemoteSdp.containsSSRC(ssrc)) {
  663. logger.warn(
  664. `Source-add request for existing SSRC: ${ssrc}`);
  665. return;
  666. }
  667. // eslint-disable-next-line newline-per-chained-call
  668. $(this).find('>parameter').each(function() {
  669. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  670. if ($(this).attr('value') && $(this).attr('value').length) {
  671. lines += `:${$(this).attr('value')}`;
  672. }
  673. lines += '\r\n';
  674. });
  675. });
  676. /* eslint-enable no-invalid-this */
  677. currentRemoteSdp.media.forEach((media, i2) => {
  678. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  679. return;
  680. }
  681. if (!addSsrcInfo[i2]) {
  682. addSsrcInfo[i2] = '';
  683. }
  684. addSsrcInfo[i2] += lines;
  685. });
  686. });
  687. return addSsrcInfo;
  688. }
  689. /**
  690. * Handles a Jingle source-add message for this Jingle session.
  691. * @param elem An array of Jingle "content" elements.
  692. */
  693. addRemoteStream(elem) {
  694. // FIXME there is not stop condition for this wait !!!
  695. if (!this.peerconnection.localDescription) {
  696. logger.warn('addSource - localDescription not ready yet');
  697. setTimeout(() => this.addRemoteStream(elem), 200);
  698. return;
  699. }
  700. logger.log('Processing add remote stream');
  701. logger.log(
  702. 'ICE connection state: ', this.peerconnection.iceConnectionState);
  703. this.readSsrcInfo(elem);
  704. const workFunction = finishedCallback => {
  705. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  706. const mySdp = new SDP(this.peerconnection.localDescription.sdp);
  707. const addSsrcInfo = this._parseSsrcInfoFromSourceAdd(elem, sdp);
  708. const newRemoteSdp = this._processRemoteAddSource(addSsrcInfo);
  709. this._renegotiate(newRemoteSdp)
  710. .then(() => {
  711. logger.info('Remote source-add processed');
  712. const newSdp
  713. = new SDP(this.peerconnection.localDescription.sdp);
  714. logger.log('SDPs', mySdp, newSdp);
  715. this.notifyMySSRCUpdate(mySdp, newSdp);
  716. finishedCallback();
  717. }, error => {
  718. logger.error(
  719. 'Error renegotiating after processing remote'
  720. + ` source-add: ${error}`);
  721. finishedCallback(error);
  722. });
  723. };
  724. this.modificationQueue.push(workFunction);
  725. }
  726. /**
  727. * Handles a Jingle source-remove message for this Jingle session.
  728. * @param elem An array of Jingle "content" elements.
  729. */
  730. removeRemoteStream(elem) {
  731. // FIXME there is no stop condition for this wait !
  732. if (!this.peerconnection.localDescription) {
  733. logger.warn('removeSource - localDescription not ready yet');
  734. setTimeout(() => this.removeRemoteStream(elem), 200);
  735. return;
  736. }
  737. logger.log('Remove remote stream');
  738. logger.log(
  739. 'ICE connection state: ', this.peerconnection.iceConnectionState);
  740. const workFunction = finishedCallback => {
  741. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  742. const mySdp = new SDP(this.peerconnection.localDescription.sdp);
  743. const removeSsrcInfo
  744. = this._parseSsrcInfoFromSourceRemove(elem, sdp);
  745. const newRemoteSdp
  746. = this._processRemoteRemoveSource(removeSsrcInfo);
  747. this._renegotiate(newRemoteSdp)
  748. .then(() => {
  749. logger.info('Remote source-remove processed');
  750. const newSdp
  751. = new SDP(this.peerconnection.localDescription.sdp);
  752. logger.log('SDPs', mySdp, newSdp);
  753. this.notifyMySSRCUpdate(mySdp, newSdp);
  754. finishedCallback();
  755. }, error => {
  756. logger.error(
  757. 'Error renegotiating after processing remote'
  758. + ` source-remove: ${error}`);
  759. finishedCallback(error);
  760. });
  761. };
  762. this.modificationQueue.push(workFunction);
  763. }
  764. /**
  765. * The 'task' function will be given a callback it MUST call with either:
  766. * 1) No arguments if it was successful or
  767. * 2) An error argument if there was an error
  768. * If the task wants to process the success or failure of the task, it
  769. * should pass a handler to the .push function, e.g.:
  770. * queue.push(task, (err) => {
  771. * if (err) {
  772. * // error handling
  773. * } else {
  774. * // success handling
  775. * }
  776. * });
  777. */
  778. _processQueueTasks(task, finishedCallback) {
  779. task(finishedCallback);
  780. }
  781. /**
  782. * Takes in a jingle offer iq, returns the new sdp offer
  783. * @param {jquery xml element} offerIq the incoming offer
  784. * @returns {SDP object} the jingle offer translated to SDP
  785. */
  786. _processNewJingleOfferIq(offerIq) {
  787. const remoteSdp = new SDP('');
  788. if (this.webrtcIceTcpDisable) {
  789. remoteSdp.removeTcpCandidates = true;
  790. }
  791. if (this.webrtcIceUdpDisable) {
  792. remoteSdp.removeUdpCandidates = true;
  793. }
  794. if (this.failICE) {
  795. remoteSdp.failICE = true;
  796. }
  797. remoteSdp.fromJingle(offerIq);
  798. this.readSsrcInfo($(offerIq).find('>content'));
  799. return remoteSdp;
  800. }
  801. /**
  802. * Remove the given ssrc lines from the current remote sdp
  803. * @param {list} removeSsrcInfo a list of SDP line strings that
  804. * should be removed from the remote SDP
  805. * @returns type {SDP Object} the new remote SDP (after removing the lines
  806. * in removeSsrcInfo
  807. */
  808. _processRemoteRemoveSource(removeSsrcInfo) {
  809. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  810. removeSsrcInfo.forEach((lines, idx) => {
  811. // eslint-disable-next-line no-param-reassign
  812. lines = lines.split('\r\n');
  813. lines.pop(); // remove empty last element;
  814. lines.forEach(line => {
  815. remoteSdp.media[idx]
  816. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  817. });
  818. });
  819. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  820. return remoteSdp;
  821. }
  822. /**
  823. * Add the given ssrc lines to the current remote sdp
  824. * @param {list} addSsrcInfo a list of SDP line strings that
  825. * should be added to the remote SDP
  826. * @returns type {SDP Object} the new remote SDP (after removing the lines
  827. * in removeSsrcInfo
  828. */
  829. _processRemoteAddSource(addSsrcInfo) {
  830. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  831. addSsrcInfo.forEach((lines, idx) => {
  832. remoteSdp.media[idx] += lines;
  833. });
  834. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  835. return remoteSdp;
  836. }
  837. /**
  838. * Do a new o/a flow using the existing remote description
  839. * @param {SDP object} optionalRemoteSdp optional remote sdp
  840. * to use. If not provided, the remote sdp from the
  841. * peerconnection will be used
  842. * @returns {Promise} promise which resolves when the
  843. * o/a flow is complete with no arguments or
  844. * rejects with an error {string}
  845. */
  846. _renegotiate(optionalRemoteSdp) {
  847. const mediaConstraints = this.mediaConstraints;
  848. const remoteSdp
  849. = optionalRemoteSdp
  850. || new SDP(this.peerconnection.remoteDescription.sdp);
  851. const remoteDescription = new RTCSessionDescription({
  852. type: 'offer',
  853. sdp: remoteSdp.raw
  854. });
  855. // TODO(brian): in the code below there are 2 chunks of code that relate
  856. // to observing changes in local and remove ufrags. since they
  857. // just need to read and observe the SDPs, we should create the
  858. // notion of an SDP observer in TraceablePeerConnection that
  859. // gets notified of all SDP changes. Code like the ufrag
  860. // logic below could listen to that and be separated from
  861. // core flows like this.
  862. return new Promise((resolve, reject) => {
  863. const remoteUfrag = JingleSessionPC.getUfrag(remoteDescription.sdp);
  864. if (remoteUfrag !== this.remoteUfrag) {
  865. this.remoteUfrag = remoteUfrag;
  866. this.room.eventEmitter.emit(
  867. XMPPEvents.REMOTE_UFRAG_CHANGED, remoteUfrag);
  868. }
  869. logger.debug('Renegotiate: setting remote description');
  870. this.peerconnection.setRemoteDescription(
  871. remoteDescription,
  872. () => {
  873. if (this.signalingState === 'closed') {
  874. reject(
  875. 'Attempted to setRemoteDescription in state'
  876. + ' closed');
  877. return;
  878. }
  879. logger.debug('Renegotiate: creating answer');
  880. this.peerconnection.createAnswer(
  881. answer => {
  882. const localUfrag
  883. = JingleSessionPC.getUfrag(answer.sdp);
  884. if (localUfrag !== this.localUfrag) {
  885. this.localUfrag = localUfrag;
  886. this.room.eventEmitter.emit(
  887. XMPPEvents.LOCAL_UFRAG_CHANGED,
  888. localUfrag);
  889. }
  890. logger.debug(
  891. 'Renegotiate: setting local description');
  892. this.peerconnection.setLocalDescription(
  893. answer,
  894. () => {
  895. resolve();
  896. },
  897. error => {
  898. reject(
  899. `setLocalDescription failed: ${error}`);
  900. }
  901. );
  902. },
  903. error => reject(`createAnswer failed: ${error}`),
  904. mediaConstraints
  905. );
  906. },
  907. error => {
  908. reject(`setRemoteDescription failed: ${error}`);
  909. }
  910. );
  911. });
  912. }
  913. /**
  914. * Replaces oldStream with newStream and performs a single offer/answer
  915. * cycle after both operations are done. Either oldStream or newStream
  916. * can be null; replacing a valid 'oldStream' with a null 'newStream'
  917. * effectively just removes 'oldStream'
  918. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  919. * replaced
  920. * @param {JitsiLocalTrack|null} newTrack the new track to use
  921. * @returns {Promise} which resolves once the replacement is complete
  922. * with no arguments or rejects with an error {string}
  923. */
  924. replaceTrack(oldTrack, newTrack) {
  925. return new Promise((resolve, reject) => {
  926. const workFunction = finishedCallback => {
  927. const oldSdp
  928. = new SDP(this.peerconnection.localDescription.sdp);
  929. // NOTE the code below assumes that no more than 1 video track
  930. // can be added to the peer connection.
  931. // Transition from no video to video (possibly screen sharing)
  932. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  933. // Clearing current primary SSRC will make
  934. // the SdpConsistency generate a new one which will result
  935. // with:
  936. // 1. source-remove for the recvonly
  937. // 2. source-add for the new video stream
  938. this.peerconnection.clearRecvonlySsrc();
  939. // Transition from video to no video
  940. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  941. // Clearing current primary SSRC and generating the recvonly
  942. // will result in:
  943. // 1. source-remove for the old video stream
  944. // 2. source-add for the recvonly stream
  945. this.peerconnection.clearRecvonlySsrc();
  946. this.peerconnection.generateRecvonlySsrc();
  947. }
  948. this.removeStreamFromPeerConnection(oldTrack);
  949. this.addStreamToPeerConnection(newTrack);
  950. this._renegotiate()
  951. .then(() => {
  952. const newSdp
  953. = new SDP(this.peerconnection.localDescription.sdp);
  954. this.notifyMySSRCUpdate(oldSdp, newSdp);
  955. finishedCallback();
  956. }, error => {
  957. logger.error(
  958. `replaceTrack renegotiation failed: ${error}`);
  959. finishedCallback(error);
  960. });
  961. };
  962. this.modificationQueue.push(
  963. workFunction,
  964. error => {
  965. error ? reject(error) : resolve();
  966. });
  967. });
  968. }
  969. /**
  970. * Just add the stream to the peerconnection
  971. * @param stream either the low-level webrtc MediaStream or
  972. * a Jitsi mediastream
  973. * NOTE: must be called within a work function being executed
  974. * by the modification queue.
  975. */
  976. addStreamToPeerConnection(stream, ssrcInfo) {
  977. const actualStream
  978. = stream && stream.getOriginalStream
  979. ? stream.getOriginalStream() : stream;
  980. if (this.peerconnection) {
  981. this.peerconnection.addStream(actualStream, ssrcInfo);
  982. }
  983. }
  984. /**
  985. * Parse the information from the xml sourceRemoveElem and translate it
  986. * into sdp lines
  987. * @param {jquery xml element} sourceRemoveElem the source-remove
  988. * element from jingle
  989. * @param {SDP object} currentRemoteSdp the current remote
  990. * sdp (as of this new source-remove)
  991. * @returns {list} a list of SDP line strings that should
  992. * be removed from the remote SDP
  993. */
  994. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  995. const removeSsrcInfo = [];
  996. $(sourceRemoveElem).each((i1, content) => {
  997. const name = $(content).attr('name');
  998. let lines = '';
  999. $(content)
  1000. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1001. .each(function() {
  1002. /* eslint-disable no-invalid-this */
  1003. const semantics = this.getAttribute('semantics');
  1004. const ssrcs
  1005. = $(this)
  1006. .find('>source')
  1007. .map(function() {
  1008. return this.getAttribute('ssrc');
  1009. })
  1010. .get();
  1011. if (ssrcs.length) {
  1012. lines
  1013. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  1014. }\r\n`;
  1015. }
  1016. /* eslint-enable no-invalid-this */
  1017. });
  1018. const ssrcs = [];
  1019. // handles both >source and >description>source versions
  1020. const tmp
  1021. = $(content).find(
  1022. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1023. tmp.each(function() {
  1024. // eslint-disable-next-line no-invalid-this
  1025. const ssrc = $(this).attr('ssrc');
  1026. ssrcs.push(ssrc);
  1027. });
  1028. currentRemoteSdp.media.forEach((media, i2) => {
  1029. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1030. return;
  1031. }
  1032. if (!removeSsrcInfo[i2]) {
  1033. removeSsrcInfo[i2] = '';
  1034. }
  1035. ssrcs.forEach(ssrc => {
  1036. const ssrcLines
  1037. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1038. if (ssrcLines.length) {
  1039. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1040. }
  1041. });
  1042. removeSsrcInfo[i2] += lines;
  1043. });
  1044. });
  1045. return removeSsrcInfo;
  1046. }
  1047. /* eslint-disable max-params */
  1048. /**
  1049. * Adds stream.
  1050. * @param stream new stream that will be added.
  1051. * @param callback callback executed after successful stream addition.
  1052. * @param errorCallback callback executed if stream addition fail.
  1053. * @param ssrcInfo object with information about the SSRCs associated with
  1054. * the stream.
  1055. * @param dontModifySources {boolean} if true _modifySources won't be
  1056. * called.
  1057. * Used for streams added before the call start.
  1058. * NOTE(brian): there is a decent amount of overlap here with replaceTrack
  1059. * that could be re-used...however we can't leverage that currently because
  1060. * the extra work we do here must be in the work function context and if we
  1061. * then called replaceTrack we'd be adding another task on the queue
  1062. * from within a task which would then deadlock. The 'replaceTrack' core
  1063. * logic should be moved into a helper function that could be called within
  1064. * the 'doReplaceStream' task or the 'doAddStream' task (for example)
  1065. */
  1066. addStream(stream, callback, errorCallback, ssrcInfo, dontModifySources) {
  1067. const workFunction = finishedCallback => {
  1068. if (!this.peerconnection) {
  1069. finishedCallback(
  1070. 'Error: tried adding stream with no active peer'
  1071. + ' connection');
  1072. return;
  1073. }
  1074. this.addStreamToPeerConnection(stream, ssrcInfo);
  1075. if (ssrcInfo) {
  1076. // available only on video mute/unmute
  1077. this.modifiedSSRCs[ssrcInfo.type]
  1078. = this.modifiedSSRCs[ssrcInfo.type] || [];
  1079. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1080. }
  1081. if (dontModifySources) {
  1082. finishedCallback();
  1083. return;
  1084. }
  1085. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1086. this._renegotiate()
  1087. .then(() => {
  1088. const newSdp
  1089. = new SDP(this.peerconnection.localDescription.sdp);
  1090. // FIXME objects should not be logged
  1091. logger.log('SDPs', oldSdp, newSdp);
  1092. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1093. finishedCallback();
  1094. }, error => {
  1095. finishedCallback(error);
  1096. });
  1097. };
  1098. this.modificationQueue.push(
  1099. workFunction,
  1100. error => {
  1101. error ? errorCallback(error) : callback();
  1102. });
  1103. }
  1104. /* eslint-enable max-params */
  1105. /**
  1106. * Generate ssrc info object for a stream with the following properties:
  1107. * - ssrcs - Array of the ssrcs associated with the stream.
  1108. * - groups - Array of the groups associated with the stream.
  1109. */
  1110. generateNewStreamSSRCInfo() {
  1111. return this.peerconnection.generateNewStreamSSRCInfo();
  1112. }
  1113. /**
  1114. * Remove stream handling for firefox
  1115. * @param stream: webrtc media stream
  1116. */
  1117. _handleFirefoxRemoveStream(stream) {
  1118. if (!stream) { // There is nothing to be changed
  1119. return;
  1120. }
  1121. let sender = null;
  1122. // On Firefox we don't replace MediaStreams as this messes up the
  1123. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1124. // of complications. Instead, we use the RTPSender and remove just
  1125. // the track.
  1126. let track = null;
  1127. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1128. track = stream.getAudioTracks()[0];
  1129. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1130. track = stream.getVideoTracks()[0];
  1131. }
  1132. if (!track) {
  1133. const msg = 'Cannot remove tracks: no tracks.';
  1134. logger.log(msg);
  1135. return;
  1136. }
  1137. // Find the right sender (for audio or video)
  1138. this.peerconnection.peerconnection.getSenders().some(s => {
  1139. if (s.track === track) {
  1140. sender = s;
  1141. return true;
  1142. }
  1143. return false;
  1144. });
  1145. if (sender) {
  1146. this.peerconnection.peerconnection.removeTrack(sender);
  1147. } else {
  1148. logger.log('Cannot remove tracks: no RTPSender.');
  1149. }
  1150. }
  1151. /**
  1152. * Just remove the stream from the peerconnection
  1153. * @param {JitsiLocalTrack|MediaStream} stream the stream to remove
  1154. * NOTE: must be called within a work function being executed
  1155. * by the modification queue.
  1156. */
  1157. removeStreamFromPeerConnection(stream) {
  1158. const actualStream
  1159. = stream && stream.getOriginalStream
  1160. ? stream.getOriginalStream() : stream;
  1161. if (!this.peerconnection) {
  1162. return;
  1163. }
  1164. if (RTCBrowserType.getBrowserType()
  1165. === RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1166. this._handleFirefoxRemoveStream(actualStream);
  1167. } else if (actualStream) {
  1168. this.peerconnection.removeStream(actualStream);
  1169. }
  1170. }
  1171. /* eslint-disable max-params */
  1172. /**
  1173. * Remove streams.
  1174. * @param stream stream that will be removed.
  1175. * @param callback callback executed after successful stream addition.
  1176. * @param errorCallback callback executed if stream addition fail.
  1177. * @param ssrcInfo object with information about the SSRCs associated with
  1178. * the stream.
  1179. */
  1180. removeStream(stream, callback, errorCallback, ssrcInfo) {
  1181. const workFunction = finishedCallback => {
  1182. if (!this.peerconnection) {
  1183. finishedCallback();
  1184. return;
  1185. }
  1186. if (RTCBrowserType.getBrowserType()
  1187. === RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1188. this._handleFirefoxRemoveStream(stream);
  1189. } else if (stream) {
  1190. this.removeStreamFromPeerConnection(stream);
  1191. }
  1192. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1193. this._renegotiate()
  1194. .then(() => {
  1195. const newSdp
  1196. = new SDP(this.peerconnection.localDescription.sdp);
  1197. if (ssrcInfo) {
  1198. this.modifiedSSRCs[ssrcInfo.type]
  1199. = this.modifiedSSRCs[ssrcInfo.type] || [];
  1200. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1201. }
  1202. logger.log('SDPs', oldSdp, newSdp);
  1203. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1204. finishedCallback();
  1205. }, error => {
  1206. finishedCallback(error);
  1207. });
  1208. };
  1209. this.modificationQueue.push(
  1210. workFunction,
  1211. error => {
  1212. error ? errorCallback(error) : callback();
  1213. });
  1214. }
  1215. /* eslint-enable max-params */
  1216. /**
  1217. * Figures out added/removed ssrcs and send update IQs.
  1218. * @param oldSDP SDP object for old description.
  1219. * @param newSDP SDP object for new description.
  1220. */
  1221. notifyMySSRCUpdate(oldSDP, newSDP) {
  1222. if (this.state !== JingleSessionState.ACTIVE) {
  1223. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  1224. return;
  1225. }
  1226. // send source-remove IQ.
  1227. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  1228. const remove = $iq({ to: this.peerjid,
  1229. type: 'set' })
  1230. .c('jingle', {
  1231. xmlns: 'urn:xmpp:jingle:1',
  1232. action: 'source-remove',
  1233. initiator: this.initiator,
  1234. sid: this.sid
  1235. }
  1236. );
  1237. sdpDiffer.toJingle(remove);
  1238. const removed = this.fixJingle(remove);
  1239. if (removed && remove) {
  1240. logger.info('Sending source-remove', remove.tree());
  1241. this.connection.sendIQ(
  1242. remove, null,
  1243. this.newJingleErrorHandler(remove, error => {
  1244. GlobalOnErrorHandler.callErrorHandler(
  1245. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1246. }), IQ_TIMEOUT);
  1247. } else {
  1248. logger.log('removal not necessary');
  1249. }
  1250. // send source-add IQ.
  1251. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  1252. const add = $iq({ to: this.peerjid,
  1253. type: 'set' })
  1254. .c('jingle', {
  1255. xmlns: 'urn:xmpp:jingle:1',
  1256. action: 'source-add',
  1257. initiator: this.initiator,
  1258. sid: this.sid
  1259. }
  1260. );
  1261. sdpDiffer.toJingle(add);
  1262. const added = this.fixJingle(add);
  1263. if (added && add) {
  1264. logger.info('Sending source-add', add.tree());
  1265. this.connection.sendIQ(
  1266. add, null, this.newJingleErrorHandler(add, error => {
  1267. GlobalOnErrorHandler.callErrorHandler(
  1268. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1269. }), IQ_TIMEOUT);
  1270. } else {
  1271. logger.log('addition not necessary');
  1272. }
  1273. }
  1274. /**
  1275. * Method returns function(errorResponse) which is a callback to be passed
  1276. * to Strophe connection.sendIQ method. An 'error' structure is created that
  1277. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1278. * structure is as follows:
  1279. * {
  1280. * code: {XMPP error response code}
  1281. * reason: {the name of XMPP error reason element or 'timeout' if the
  1282. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1283. * source: {request.tree() that provides original request}
  1284. * session: {JingleSessionPC instance on which the error occurred}
  1285. * }
  1286. * @param request Strophe IQ instance which is the request to be dumped into
  1287. * the error structure
  1288. * @param failureCb function(error) called when error response was returned
  1289. * or when a timeout has occurred.
  1290. * @returns {function(this:JingleSessionPC)}
  1291. */
  1292. newJingleErrorHandler(request, failureCb) {
  1293. return function(errResponse) {
  1294. const error = {};
  1295. // Get XMPP error code and condition(reason)
  1296. const errorElSel = $(errResponse).find('error');
  1297. if (errorElSel.length) {
  1298. error.code = errorElSel.attr('code');
  1299. const errorReasonSel = $(errResponse).find('error :first');
  1300. if (errorReasonSel.length) {
  1301. error.reason = errorReasonSel[0].tagName;
  1302. }
  1303. }
  1304. if (!errResponse) {
  1305. error.reason = 'timeout';
  1306. }
  1307. error.source = null;
  1308. if (request && typeof request.tree === 'function') {
  1309. error.source = request.tree();
  1310. }
  1311. // Commented to fix JSON.stringify(error) exception for circular
  1312. // dependancies when we print that error.
  1313. // FIXME: Maybe we can include part of the session object
  1314. // error.session = this;
  1315. logger.error('Jingle error', error);
  1316. if (failureCb) {
  1317. failureCb(error);
  1318. }
  1319. };
  1320. }
  1321. /**
  1322. *
  1323. * @param session
  1324. * @param error
  1325. */
  1326. static onJingleFatalError(session, error) {
  1327. if (this.room) {
  1328. this.room.eventEmitter.emit(
  1329. XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  1330. this.room.eventEmitter.emit(
  1331. XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1332. }
  1333. }
  1334. /**
  1335. * @inheritDoc
  1336. */
  1337. getPeerMediaInfo(owner, mediaType) {
  1338. return this.room.getMediaPresenceInfo(owner, mediaType);
  1339. }
  1340. /**
  1341. * @inheritDoc
  1342. */
  1343. getSSRCOwner(ssrc) {
  1344. return this.ssrcOwners[ssrc];
  1345. }
  1346. /**
  1347. * Returns the ice connection state for the peer connection.
  1348. * @returns the ice connection state for the peer connection.
  1349. */
  1350. getIceConnectionState() {
  1351. return this.peerconnection.iceConnectionState;
  1352. }
  1353. /**
  1354. * Closes the peerconnection.
  1355. */
  1356. close() {
  1357. this.closed = true;
  1358. // do not try to close if already closed.
  1359. this.peerconnection
  1360. && ((this.peerconnection.signalingState
  1361. && this.peerconnection.signalingState !== 'closed')
  1362. || (this.peerconnection.connectionState
  1363. && this.peerconnection.connectionState !== 'closed'))
  1364. && this.peerconnection.close();
  1365. }
  1366. /**
  1367. * Fixes the outgoing jingle packets by removing the nodes related to the
  1368. * muted/unmuted streams, handles removing of muted stream, etc.
  1369. * @param jingle the jingle packet that is going to be sent
  1370. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1371. */
  1372. fixJingle(jingle) {
  1373. // eslint-disable-next-line newline-per-chained-call
  1374. const action = $(jingle.nodeTree).find('jingle').attr('action');
  1375. switch (action) {
  1376. case 'source-add':
  1377. case 'session-accept':
  1378. this.fixSourceAddJingle(jingle);
  1379. break;
  1380. case 'source-remove':
  1381. this.fixSourceRemoveJingle(jingle);
  1382. break;
  1383. default: {
  1384. const errmsg = 'Unknown jingle action!';
  1385. GlobalOnErrorHandler.callErrorHandler(errmsg);
  1386. logger.error(errmsg);
  1387. return false;
  1388. }
  1389. }
  1390. const sources
  1391. = $(jingle.tree()).find('>jingle>content>description>source');
  1392. return sources && sources.length > 0;
  1393. }
  1394. /**
  1395. * Fixes the outgoing jingle packets with action source-add by removing the
  1396. * nodes related to the unmuted streams
  1397. * @param jingle the jingle packet that is going to be sent
  1398. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1399. */
  1400. fixSourceAddJingle(jingle) {
  1401. let ssrcs = this.modifiedSSRCs.unmute;
  1402. this.modifiedSSRCs.unmute = [];
  1403. if (ssrcs && ssrcs.length) {
  1404. ssrcs.forEach(ssrcObj => {
  1405. const desc
  1406. = $(jingle.tree()).find(
  1407. `>jingle>content[name="${ssrcObj.mtype}"]>description`);
  1408. if (!desc || !desc.length) {
  1409. return;
  1410. }
  1411. ssrcObj.ssrcs.forEach(ssrc => {
  1412. const sourceNode = desc.find(`>source[ssrc="${ssrc}"]`);
  1413. sourceNode.remove();
  1414. });
  1415. ssrcObj.groups.forEach(group => {
  1416. const groupNode = desc.find(`>ssrc-group[semantics="${
  1417. group.semantics}"]:has(source[ssrc="${
  1418. group.ssrcs[0]}"])`);
  1419. groupNode.remove();
  1420. });
  1421. });
  1422. }
  1423. ssrcs = this.modifiedSSRCs.addMuted;
  1424. this.modifiedSSRCs.addMuted = [];
  1425. if (ssrcs && ssrcs.length) {
  1426. ssrcs.forEach(ssrcObj => {
  1427. const desc
  1428. = JingleSessionPC.createDescriptionNode(
  1429. jingle, ssrcObj.mtype);
  1430. // eslint-disable-next-line newline-per-chained-call
  1431. const cname = Math.random().toString(36).substring(2);
  1432. ssrcObj.ssrcs.forEach(ssrc => {
  1433. const sourceNode
  1434. = desc.find(`>source[ssrc="${ssrc}"]`);
  1435. sourceNode.remove();
  1436. const sourceXML
  1437. = '<source xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1438. + ` ssrc="${ssrc}">`
  1439. + '<parameter xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1440. + ` value="${ssrcObj.msid}" name="msid"/>`
  1441. + '<parameter xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1442. + ` value="${cname}" name="cname" />`
  1443. + '</source>';
  1444. desc.append(sourceXML);
  1445. });
  1446. ssrcObj.groups.forEach(group => {
  1447. const groupNode
  1448. = desc.find(
  1449. `>ssrc-group[semantics="${group.semantics
  1450. }"]:has(source[ssrc="${group.ssrcs[0]}"])`);
  1451. groupNode.remove();
  1452. desc.append(
  1453. `<ssrc-group semantics="${group.semantics
  1454. }" xmlns="urn:xmpp:jingle:apps:rtp:ssma:0">`
  1455. + `<source ssrc="${group.ssrcs.join('"/><source ssrc="')
  1456. }"/></ssrc-group>`);
  1457. });
  1458. });
  1459. }
  1460. }
  1461. /**
  1462. * Fixes the outgoing jingle packets with action source-remove by removing
  1463. * the nodes related to the muted streams, handles removing of muted stream
  1464. * @param jingle the jingle packet that is going to be sent
  1465. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1466. */
  1467. fixSourceRemoveJingle(jingle) {
  1468. let ssrcs = this.modifiedSSRCs.mute;
  1469. this.modifiedSSRCs.mute = [];
  1470. if (ssrcs && ssrcs.length) {
  1471. ssrcs.forEach(ssrcObj => {
  1472. ssrcObj.ssrcs.forEach(ssrc => {
  1473. const sourceNode
  1474. = $(jingle.tree()).find(
  1475. `>jingle>content[name="${ssrcObj.mtype
  1476. }"]>description>source[ssrc="${ssrc}"]`);
  1477. sourceNode.remove();
  1478. });
  1479. ssrcObj.groups.forEach(group => {
  1480. const groupNode
  1481. = $(jingle.tree()).find(
  1482. `>jingle>content[name="${ssrcObj.mtype
  1483. }"]>description>ssrc-group[semantics="${
  1484. group.semantics}"]:has(source[ssrc="${
  1485. group.ssrcs[0]}"])`);
  1486. groupNode.remove();
  1487. });
  1488. });
  1489. }
  1490. ssrcs = this.modifiedSSRCs.remove;
  1491. this.modifiedSSRCs.remove = [];
  1492. if (ssrcs && ssrcs.length) {
  1493. ssrcs.forEach(ssrcObj => {
  1494. const desc
  1495. = JingleSessionPC.createDescriptionNode(
  1496. jingle, ssrcObj.mtype);
  1497. ssrcObj.ssrcs.forEach(ssrc => {
  1498. const sourceNode
  1499. = desc.find(`>source[ssrc="${ssrc}"]`);
  1500. if (!sourceNode || !sourceNode.length) {
  1501. // Maybe we have to include cname, msid, etc here?
  1502. desc.append(
  1503. '<source xmlns="urn:xmpp:jingle:apps:rtp:ssma:0" '
  1504. + `ssrc="${ssrc}"></source>`);
  1505. }
  1506. });
  1507. ssrcObj.groups.forEach(group => {
  1508. const groupNode
  1509. = desc.find(`>ssrc-group[semantics="${
  1510. group.semantics}"]:has(source[ssrc="${
  1511. group.ssrcs[0]}"])`);
  1512. if (!groupNode || !groupNode.length) {
  1513. desc.append(
  1514. `<ssrc-group semantics="${group.semantics
  1515. }" xmlns="urn:xmpp:jingle:apps:rtp:ssma:0">`
  1516. + `<source ssrc="${
  1517. group.ssrcs.join('"/><source ssrc="')}"/>`
  1518. + '</ssrc-group>');
  1519. }
  1520. });
  1521. });
  1522. }
  1523. }
  1524. /**
  1525. * Returns the description node related to the passed content type. If the
  1526. * node doesn't exists it will be created.
  1527. * @param jingle - the jingle packet
  1528. * @param mtype - the content type(audio, video, etc.)
  1529. */
  1530. static createDescriptionNode(jingle, mtype) {
  1531. let content = $(jingle.tree()).find(`>jingle>content[name="${mtype}"]`);
  1532. if (!content || !content.length) {
  1533. $(jingle.tree())
  1534. .find('>jingle')
  1535. .append(`<content name="${mtype}"></content>`);
  1536. content = $(jingle.tree()).find(`>jingle>content[name="${mtype}"]`);
  1537. }
  1538. let desc = content.find('>description');
  1539. if (!desc || !desc.length) {
  1540. content.append(
  1541. `<description xmlns="urn:xmpp:jingle:apps:rtp:1" media="${
  1542. mtype}"></description>`);
  1543. desc = content.find('>description');
  1544. }
  1545. return desc;
  1546. }
  1547. /**
  1548. * Extracts the ice username fragment from an SDP string.
  1549. */
  1550. static getUfrag(sdp) {
  1551. const ufragLines
  1552. = sdp.split('\n').filter(line => line.startsWith('a=ice-ufrag:'));
  1553. if (ufragLines.length > 0) {
  1554. return ufragLines[0].substr('a=ice-ufrag:'.length);
  1555. }
  1556. }
  1557. }