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

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