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

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