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

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