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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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. // Set local description OK, now localSDP up to date
  389. this.sendTransportAccept(this.localSDP, success, failure);
  390. },
  391. failure);
  392. },
  393. failure
  394. );
  395. };
  396. /**
  397. * Sends Jingle 'session-accept' message.
  398. * @param localSDP the 'SDP' object with local session description
  399. * @param {function()} success callback called when we recive 'RESULT' packet for
  400. * 'session-accept'
  401. * @param {function(error)} failure called when we receive an error response or
  402. * when the request has timed out.
  403. */
  404. JingleSessionPC.prototype.sendSessionAccept = function (success, failure) {
  405. // NOTE: since we're just reading from it, we don't need to be within
  406. // the modification queue to access the local description
  407. let localSDP = new SDP(this.peerconnection.localDescription.sdp);
  408. var accept = $iq({to: this.peerjid,
  409. type: 'set'})
  410. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  411. action: 'session-accept',
  412. initiator: this.initiator,
  413. responder: this.responder,
  414. sid: this.sid });
  415. if (this.webrtcIceTcpDisable) {
  416. localSDP.removeTcpCandidates = true;
  417. }
  418. if (this.webrtcIceUdpDisable) {
  419. localSDP.removeUdpCandidates = true;
  420. }
  421. if (this.failICE) {
  422. localSDP.failICE = true;
  423. }
  424. localSDP.toJingle(
  425. accept,
  426. this.initiator == this.me ? 'initiator' : 'responder',
  427. null);
  428. this.fixJingle(accept);
  429. // Calling tree() to print something useful
  430. accept = accept.tree();
  431. logger.info("Sending session-accept", accept);
  432. var self = this;
  433. this.connection.sendIQ(accept,
  434. success,
  435. this.newJingleErrorHandler(accept, function (error) {
  436. failure(error);
  437. // 'session-accept' is a critical timeout and we'll have to restart
  438. self.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_TIMEOUT);
  439. }),
  440. IQ_TIMEOUT);
  441. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  442. // fingerprint and setup) ASAP in order to start the connection
  443. // establishment.
  444. //
  445. // FIXME Flushing the connection at this point triggers an issue with BOSH
  446. // request handling in Prosody on slow connections.
  447. //
  448. // The problem is that this request will be quite large and it may take time
  449. // before it reaches Prosody. In the meantime Strophe may decide to send
  450. // the next one. And it was observed that a small request with
  451. // 'transport-info' usually follows this one. It does reach Prosody before
  452. // the previous one was completely received. 'rid' on the server is
  453. // increased and Prosody ignores the request with 'session-accept'. It will
  454. // never reach Jicofo and everything in the request table is lost. Removing
  455. // the flush does not guarantee it will never happen, but makes it much less
  456. // likely('transport-info' is bundled with 'session-accept' and any
  457. // immediate requests).
  458. //
  459. // this.connection.flush();
  460. };
  461. /**
  462. * Sends Jingle 'transport-accept' message which is a response to
  463. * 'transport-replace'.
  464. * @param localSDP the 'SDP' object with local session description
  465. * @param success callback called when we receive 'RESULT' packet for
  466. * 'transport-replace'
  467. * @param failure function(error) called when we receive an error response or
  468. * when the request has timed out.
  469. */
  470. JingleSessionPC.prototype.sendTransportAccept = function(localSDP, success,
  471. failure) {
  472. var self = this;
  473. var tAccept = $iq({to: this.peerjid, type: 'set'})
  474. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  475. action: 'transport-accept',
  476. initiator: this.initiator,
  477. sid: this.sid});
  478. localSDP.media.forEach(function(medialines, idx){
  479. var mline = SDPUtil.parse_mline(medialines.split('\r\n')[0]);
  480. tAccept.c('content',
  481. { creator: self.initiator == self.me ? 'initiator' : 'responder',
  482. name: mline.media
  483. }
  484. );
  485. localSDP.transportToJingle(idx, tAccept);
  486. tAccept.up();
  487. });
  488. // Calling tree() to print something useful to the logger
  489. tAccept = tAccept.tree();
  490. console.info("Sending transport-accept: ", tAccept);
  491. self.connection.sendIQ(tAccept,
  492. success,
  493. self.newJingleErrorHandler(tAccept, failure),
  494. IQ_TIMEOUT);
  495. };
  496. /**
  497. * Sends Jingle 'transport-reject' message which is a response to
  498. * 'transport-replace'.
  499. * @param success callback called when we receive 'RESULT' packet for
  500. * 'transport-replace'
  501. * @param failure function(error) called when we receive an error response or
  502. * when the request has timed out.
  503. */
  504. JingleSessionPC.prototype.sendTransportReject = function(success, failure) {
  505. // Send 'transport-reject', so that the focus will
  506. // know that we've failed
  507. var tReject = $iq({to: this.peerjid, type: 'set'})
  508. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  509. action: 'transport-reject',
  510. initiator: this.initiator,
  511. sid: this.sid});
  512. tReject = tReject.tree();
  513. logger.info("Sending 'transport-reject", tReject);
  514. this.connection.sendIQ(tReject,
  515. success,
  516. this.newJingleErrorHandler(tReject, failure),
  517. IQ_TIMEOUT);
  518. };
  519. /**
  520. * @inheritDoc
  521. */
  522. JingleSessionPC.prototype.terminate = function (reason, text,
  523. success, failure) {
  524. this.state = JingleSessionState.ENDED;
  525. var term = $iq({to: this.peerjid,
  526. type: 'set'})
  527. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  528. action: 'session-terminate',
  529. initiator: this.initiator,
  530. sid: this.sid})
  531. .c('reason')
  532. .c(reason || 'success');
  533. if (text) {
  534. term.up().c('text').t(text);
  535. }
  536. // Calling tree() to print something useful
  537. term = term.tree();
  538. logger.info("Sending session-terminate", term);
  539. this.connection.sendIQ(
  540. term, success, this.newJingleErrorHandler(term, failure), IQ_TIMEOUT);
  541. // this should result in 'onTerminated' being called by strope.jingle.js
  542. this.connection.jingle.terminate(this.sid);
  543. };
  544. JingleSessionPC.prototype.onTerminated = function (reasonCondition,
  545. reasonText) {
  546. this.state = 'ended';
  547. // Do something with reason and reasonCondition when we start to care
  548. //this.reasonCondition = reasonCondition;
  549. //this.reasonText = reasonText;
  550. logger.info("Session terminated", this, reasonCondition, reasonText);
  551. this.close();
  552. };
  553. /**
  554. * Parse the information from the xml sourceAddElem and translate it
  555. * into sdp lines
  556. * @param {jquery xml element} sourceAddElem the source-add
  557. * element from jingle
  558. * @param {SDP object} currentRemoteSdp the current remote
  559. * sdp (as of this new source-add)
  560. * @returns {list} a list of SDP line strings that should
  561. * be added to the remote SDP
  562. */
  563. JingleSessionPC.prototype._parseSsrcInfoFromSourceAdd = function (sourceAddElem, currentRemoteSdp) {
  564. let addSsrcInfo = [];
  565. $(sourceAddElem).each(function (idx, content) {
  566. var name = $(content).attr('name');
  567. var lines = '';
  568. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  569. var semantics = this.getAttribute('semantics');
  570. var ssrcs = $(this).find('>source').map(function () {
  571. return this.getAttribute('ssrc');
  572. }).get();
  573. if (ssrcs.length) {
  574. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  575. }
  576. });
  577. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  578. tmp.each(function () {
  579. var ssrc = $(this).attr('ssrc');
  580. if (currentRemoteSdp.containsSSRC(ssrc)) {
  581. logger.warn("Source-add request for existing SSRC: " + ssrc);
  582. return;
  583. }
  584. $(this).find('>parameter').each(function () {
  585. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  586. if ($(this).attr('value') && $(this).attr('value').length)
  587. lines += ':' + $(this).attr('value');
  588. lines += '\r\n';
  589. });
  590. });
  591. currentRemoteSdp.media.forEach(function(media, idx) {
  592. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  593. return;
  594. if (!addSsrcInfo[idx]) {
  595. addSsrcInfo[idx] = '';
  596. }
  597. addSsrcInfo[idx] += lines;
  598. });
  599. });
  600. return addSsrcInfo;
  601. };
  602. /**
  603. * Handles a Jingle source-add message for this Jingle session.
  604. * @param elem An array of Jingle "content" elements.
  605. */
  606. JingleSessionPC.prototype.addRemoteStream = function (elem) {
  607. // FIXME: dirty waiting
  608. if (!this.peerconnection.localDescription) {
  609. logger.warn("addSource - localDescription not ready yet");
  610. setTimeout(() => this.addRemoteStream(elem), 200);
  611. return;
  612. }
  613. logger.log('Processing add remote stream');
  614. logger.log('ICE connection state: ', this.peerconnection.iceConnectionState);
  615. this.readSsrcInfo(elem);
  616. let workFunction = (finishedCallback) => {
  617. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  618. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  619. let addSsrcInfo = this._parseSsrcInfoFromSourceAdd(elem, sdp);
  620. let newRemoteSdp = this._processRemoteAddSource(addSsrcInfo);
  621. this._renegotiate(newRemoteSdp)
  622. .then(() => {
  623. logger.info("Remote source-add processed");
  624. var newSdp = new SDP(this.peerconnection.localDescription.sdp);
  625. logger.log("SDPs", mySdp, newSdp);
  626. this.notifyMySSRCUpdate(mySdp, newSdp);
  627. finishedCallback();
  628. }, (error) => {
  629. logger.error("Error renegotiating after processing remote source-add: " + error);
  630. finishedCallback(error);
  631. });
  632. };
  633. this.modificationQueue.push(workFunction);
  634. };
  635. /**
  636. * Handles a Jingle source-remove message for this Jingle session.
  637. * @param elem An array of Jingle "content" elements.
  638. */
  639. JingleSessionPC.prototype.removeRemoteStream = function (elem) {
  640. // FIXME: dirty waiting
  641. if (!this.peerconnection.localDescription) {
  642. logger.warn("removeSource - localDescription not ready yet");
  643. setTimeout(() => this.removeRemoteStream(elem), 200);
  644. return;
  645. }
  646. logger.log('Remove remote stream');
  647. logger.log('ICE connection state: ', this.peerconnection.iceConnectionState);
  648. let workFunction = (finishedCallback) => {
  649. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  650. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  651. let removeSsrcInfo = this._parseSsrcInfoFromSourceRemove(elem, sdp);
  652. let newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  653. this._renegotiate(newRemoteSdp)
  654. .then(() => {
  655. logger.info("Remote source-remove processed");
  656. var newSdp = new SDP(this.peerconnection.localDescription.sdp);
  657. logger.log("SDPs", mySdp, newSdp);
  658. this.notifyMySSRCUpdate(mySdp, newSdp);
  659. finishedCallback();
  660. }, (error) => {
  661. logger.info("Error renegotiating after processing remote source-remove: " + error);
  662. finishedCallback(error);
  663. });
  664. };
  665. this.modificationQueue.push(workFunction);
  666. };
  667. /**
  668. * The 'task' function will be given a callback it MUST call with either:
  669. * 1) No arguments if it was successful or
  670. * 2) An error argument if there was an error
  671. * If the task wants to process the success or failure of the task, it should
  672. * pass a handler to the .push function, e.g.:
  673. * queue.push(task, (err) => {
  674. * if (err) {
  675. * // error handling
  676. * } else {
  677. * // success handling
  678. * }
  679. * });
  680. */
  681. JingleSessionPC.prototype._processQueueTasks = function (task, finishedCallback) {
  682. task(finishedCallback);
  683. };
  684. /**
  685. * Takes in a jingle offer iq, returns the new sdp offer
  686. * @param {jquery xml element} offerIq the incoming offer
  687. * @returns {SDP object} the jingle offer translated to SDP
  688. */
  689. JingleSessionPC.prototype._processNewJingleOfferIq = function(offerIq) {
  690. let remoteSdp = new SDP('');
  691. if (this.webrtcIceTcpDisable) {
  692. remoteSdp.removeTcpCandidates = true;
  693. }
  694. if (this.webrtcIceUdpDisable) {
  695. remoteSdp.removeUdpCandidates = true;
  696. }
  697. if (this.failICE) {
  698. remoteSdp.failICE = true;
  699. }
  700. remoteSdp.fromJingle(offerIq);
  701. this.readSsrcInfo($(offerIq).find(">content"));
  702. return remoteSdp;
  703. };
  704. /**
  705. * Remove the given ssrc lines from the current remote sdp
  706. * @param {list} removeSsrcInfo a list of SDP line strings that
  707. * should be removed from the remote SDP
  708. * @returns type {SDP Object} the new remote SDP (after removing the lines
  709. * in removeSsrcInfo
  710. */
  711. JingleSessionPC.prototype._processRemoteRemoveSource = function (removeSsrcInfo) {
  712. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  713. removeSsrcInfo.forEach(function(lines, idx) {
  714. lines = lines.split('\r\n');
  715. lines.pop(); // remove empty last element;
  716. lines.forEach(function(line) {
  717. remoteSdp.media[idx] = remoteSdp.media[idx].replace(line + '\r\n', '');
  718. });
  719. });
  720. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  721. return remoteSdp;
  722. };
  723. /**
  724. * Add the given ssrc lines to the current remote sdp
  725. * @param {list} addSsrcInfo a list of SDP line strings that
  726. * should be added to the remote SDP
  727. * @returns type {SDP Object} the new remote SDP (after removing the lines
  728. * in removeSsrcInfo
  729. */
  730. JingleSessionPC.prototype._processRemoteAddSource = function (addSsrcInfo) {
  731. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  732. addSsrcInfo.forEach(function(lines, idx) {
  733. remoteSdp.media[idx] += lines;
  734. });
  735. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  736. return remoteSdp;
  737. };
  738. /**
  739. * Do a new o/a flow using the existing remote description
  740. * @param {SDP object} optionalRemoteSdp optional remote sdp
  741. * to use. If not provided, the remote sdp from the
  742. * peerconnection will be used
  743. * @returns {Promise} promise which resolves when the
  744. * o/a flow is complete with no arguments or
  745. * rejects with an error {string}
  746. */
  747. JingleSessionPC.prototype._renegotiate = function(optionalRemoteSdp) {
  748. let media_constraints = this.media_constraints;
  749. let remoteSdp = optionalRemoteSdp || new SDP(this.peerconnection.remoteDescription.sdp);
  750. let remoteDescription = new RTCSessionDescription({
  751. type: "offer",
  752. sdp: remoteSdp.raw
  753. });
  754. //TODO(brian): in the code below there are 2 chunks of code that relate
  755. // to observing changes in local and remove ufrags. since they
  756. // just need to read and observe the SDPs, we should create the
  757. // notion of an SDP observer in TraceablePeerConnection that
  758. // gets notified of all SDP changes. Code like the ufrag
  759. // logic below could listen to that and be separated from
  760. // core flows like this.
  761. return new Promise((resolve, reject) => {
  762. let remoteUfrag = getUfrag(remoteDescription.sdp);
  763. if (remoteUfrag != this.remoteUfrag) {
  764. this.remoteUfrag = remoteUfrag;
  765. this.room.eventEmitter.emit(
  766. XMPPEvents.REMOTE_UFRAG_CHANGED, remoteUfrag);
  767. }
  768. logger.debug("Renegotiate: setting remote description");
  769. this.peerconnection.setRemoteDescription(
  770. remoteDescription,
  771. () => {
  772. if (this.signalingState === 'closed') {
  773. reject("Attemped to setRemoteDescription in state closed");
  774. }
  775. logger.debug("Renegotiate: creating answer");
  776. this.peerconnection.createAnswer(
  777. (answer) => {
  778. let localUfrag = getUfrag(answer.sdp);
  779. if (localUfrag != this.localUfrag) {
  780. this.localUfrag = localUfrag;
  781. this.room.eventEmitter.emit(
  782. XMPPEvents.LOCAL_UFRAG_CHANGED, localUfrag);
  783. }
  784. logger.debug("Renegotiate: setting local description");
  785. this.peerconnection.setLocalDescription(
  786. answer,
  787. () => { resolve(); },
  788. (error) => { reject("setLocalDescription failed: " + error); }
  789. );
  790. },
  791. (error) => { reject("createAnswer failed: " + error); },
  792. media_constraints
  793. );
  794. },
  795. (error) => {
  796. reject("setRemoteDescription failed: " + error);
  797. }
  798. );
  799. });
  800. };
  801. /**
  802. * Replaces oldStream with newStream and performs a single offer/answer
  803. * cycle after both operations are done. Either oldStream or newStream
  804. * can be null; replacing a valid 'oldStream' with a null 'newStream'
  805. * effectively just removes 'oldStream'
  806. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  807. * replaced
  808. * @param {JitsiLocalTrack|null} newTrack the new track to use
  809. * @returns {Promise} which resolves once the replacement is complete
  810. * with no arguments or rejects with an error {string}
  811. */
  812. JingleSessionPC.prototype.replaceTrack = function (oldTrack, newTrack) {
  813. return new Promise((resolve, reject) => {
  814. let workFunction = (finishedCallback) => {
  815. let oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  816. this.removeStreamFromPeerConnection(oldTrack);
  817. this.addStreamToPeerConnection(newTrack);
  818. this._renegotiate()
  819. .then(() => {
  820. var newSdp = new SDP(this.peerconnection.localDescription.sdp);
  821. this.notifyMySSRCUpdate(oldSdp, newSdp);
  822. finishedCallback();
  823. }, (error) => {
  824. logger.error("replaceTrack renegotiation failed: " + error);
  825. finishedCallback(error);
  826. });
  827. };
  828. this.modificationQueue.push(
  829. workFunction,
  830. (error) => {
  831. if (!error) {
  832. resolve();
  833. } else {
  834. reject(error);
  835. }
  836. }
  837. );
  838. });
  839. };
  840. /**
  841. * Just add the stream to the peerconnection
  842. * @param stream either the low-level webrtc MediaStream or
  843. * a Jitsi mediastream
  844. * NOTE: must be called within a work function being executed
  845. * by the modification queue.
  846. */
  847. JingleSessionPC.prototype.addStreamToPeerConnection = function (stream, ssrcInfo) {
  848. let actualStream = stream && stream.getOriginalStream ? stream.getOriginalStream() : stream;
  849. if (this.peerconnection) {
  850. this.peerconnection.addStream(actualStream, ssrcInfo);
  851. }
  852. };
  853. /**
  854. * Parse the information from the xml sourceRemoveElem and translate it
  855. * into sdp lines
  856. * @param {jquery xml element} sourceRemoveElem the source-remove
  857. * element from jingle
  858. * @param {SDP object} currentRemoteSdp the current remote
  859. * sdp (as of this new source-remove)
  860. * @returns {list} a list of SDP line strings that should
  861. * be removed from the remote SDP
  862. */
  863. JingleSessionPC.prototype._parseSsrcInfoFromSourceRemove = function (sourceRemoveElem, currentRemoteSdp) {
  864. let removeSsrcInfo = [];
  865. $(sourceRemoveElem).each(function (idx, content) {
  866. var name = $(content).attr('name');
  867. var lines = '';
  868. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  869. var semantics = this.getAttribute('semantics');
  870. var ssrcs = $(this).find('>source').map(function () {
  871. return this.getAttribute('ssrc');
  872. }).get();
  873. if (ssrcs.length) {
  874. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  875. }
  876. });
  877. var ssrcs = [];
  878. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  879. tmp.each(function () {
  880. var ssrc = $(this).attr('ssrc');
  881. ssrcs.push(ssrc);
  882. });
  883. currentRemoteSdp.media.forEach(function(media, idx) {
  884. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  885. return;
  886. if (!removeSsrcInfo[idx]) {
  887. removeSsrcInfo[idx] = '';
  888. }
  889. ssrcs.forEach(function(ssrc) {
  890. var ssrcLines = SDPUtil.find_lines(media, 'a=ssrc:' + ssrc);
  891. if (ssrcLines.length) {
  892. removeSsrcInfo[idx] += ssrcLines.join("\r\n")+"\r\n";
  893. }
  894. });
  895. removeSsrcInfo[idx] += lines;
  896. });
  897. });
  898. return removeSsrcInfo;
  899. };
  900. /**
  901. * Adds stream.
  902. * @param stream new stream that will be added.
  903. * @param callback callback executed after successful stream addition.
  904. * @param errorCallback callback executed if stream addition fail.
  905. * @param ssrcInfo object with information about the SSRCs associated with the
  906. * stream.
  907. * @param dontModifySources {boolean} if true _modifySources won't be called.
  908. * Used for streams added before the call start.
  909. * NOTE(brian): there is a decent amount of overlap here with replaceTrack that
  910. * could be re-used...however we can't leverage that currently because the
  911. * extra work we do here must be in the work function context and if we
  912. * then called replaceTrack we'd be adding another task on the queue
  913. * from within a task which would then deadlock. The 'replaceTrack' core
  914. * logic should be moved into a helper function that could be called within
  915. * the 'doReplaceStream' task or the 'doAddStream' task (for example)
  916. */
  917. JingleSessionPC.prototype.addStream = function (stream, callback, errorCallback,
  918. ssrcInfo, dontModifySources) {
  919. let workFunction = (finishedCallback) => {
  920. if (!this.peerconnection) {
  921. finishedCallback("Error: tried adding stream with no active peer connection");
  922. return;
  923. }
  924. this.addStreamToPeerConnection(stream, ssrcInfo);
  925. if (ssrcInfo) {
  926. // available only on video mute/unmute
  927. this.modifiedSSRCs[ssrcInfo.type] =
  928. this.modifiedSSRCs[ssrcInfo.type] || [];
  929. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  930. }
  931. if (dontModifySources) {
  932. finishedCallback();
  933. return;
  934. }
  935. let oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  936. this._renegotiate()
  937. .then(() => {
  938. let newSdp = new SDP(this.peerconnection.localDescription.sdp);
  939. logger.log("SDPs", oldSdp, newSdp);
  940. this.notifyMySSRCUpdate(oldSdp, newSdp);
  941. finishedCallback();
  942. }, (error) => {
  943. finishedCallback(error);
  944. });
  945. };
  946. this.modificationQueue.push(
  947. workFunction,
  948. (error) => {
  949. if (!error) {
  950. callback();
  951. } else {
  952. errorCallback(error);
  953. }
  954. }
  955. );
  956. };
  957. /**
  958. * Generate ssrc info object for a stream with the following properties:
  959. * - ssrcs - Array of the ssrcs associated with the stream.
  960. * - groups - Array of the groups associated with the stream.
  961. */
  962. JingleSessionPC.prototype.generateNewStreamSSRCInfo = function () {
  963. return this.peerconnection.generateNewStreamSSRCInfo();
  964. };
  965. /**
  966. * Remove stream handling for firefox
  967. * @param stream: webrtc media stream
  968. */
  969. JingleSessionPC.prototype._handleFirefoxRemoveStream = function (stream) {
  970. if (!stream) { //There is nothing to be changed
  971. return;
  972. }
  973. var sender = null;
  974. // On Firefox we don't replace MediaStreams as this messes up the
  975. // m-lines (which can't be removed in Plan Unified) and brings a lot
  976. // of complications. Instead, we use the RTPSender and remove just
  977. // the track.
  978. var track = null;
  979. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  980. track = stream.getAudioTracks()[0];
  981. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  982. track = stream.getVideoTracks()[0];
  983. }
  984. if (!track) {
  985. var msg = "Cannot remove tracks: no tracks.";
  986. logger.log(msg);
  987. return;
  988. }
  989. // Find the right sender (for audio or video)
  990. this.peerconnection.peerconnection.getSenders().some(function (s) {
  991. if (s.track === track) {
  992. sender = s;
  993. return true;
  994. }
  995. });
  996. if (sender) {
  997. this.peerconnection.peerconnection.removeTrack(sender);
  998. } else {
  999. logger.log("Cannot remove tracks: no RTPSender.");
  1000. }
  1001. };
  1002. /**
  1003. * Just remove the stream from the peerconnection
  1004. * @param {JitsiLocalTrack|MediaStream} stream the stream to remove
  1005. * NOTE: must be called within a work function being executed
  1006. * by the modification queue.
  1007. */
  1008. JingleSessionPC.prototype.removeStreamFromPeerConnection = function (stream) {
  1009. let actualStream
  1010. = stream && stream.getOriginalStream
  1011. ? stream.getOriginalStream() : stream;
  1012. if (!this.peerconnection) {
  1013. return;
  1014. }
  1015. if (RTCBrowserType.getBrowserType() ===
  1016. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1017. this._handleFirefoxRemoveStream(actualStream);
  1018. } else if (actualStream) {
  1019. this.peerconnection.removeStream(actualStream);
  1020. }
  1021. };
  1022. /**
  1023. * Remove streams.
  1024. * @param stream stream that will be removed.
  1025. * @param callback callback executed after successful stream addition.
  1026. * @param errorCallback callback executed if stream addition fail.
  1027. * @param ssrcInfo object with information about the SSRCs associated with the
  1028. * stream.
  1029. */
  1030. JingleSessionPC.prototype.removeStream = function (stream, callback, errorCallback,
  1031. ssrcInfo) {
  1032. let workFunction = (finishedCallback) => {
  1033. if (!this.peerconnection) {
  1034. finishedCallback();
  1035. return;
  1036. }
  1037. if (RTCBrowserType.getBrowserType() ===
  1038. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1039. this._handleFirefoxRemoveStream(stream);
  1040. } else if (stream) {
  1041. this.removeStreamFromPeerConnection(stream);
  1042. }
  1043. let oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1044. this._renegotiate()
  1045. .then(() => {
  1046. let newSdp = new SDP(this.peerconnection.localDescription.sdp);
  1047. if (ssrcInfo) {
  1048. this.modifiedSSRCs[ssrcInfo.type] =
  1049. this.modifiedSSRCs[ssrcInfo.type] || [];
  1050. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1051. }
  1052. logger.log("SDPs", oldSdp, newSdp);
  1053. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1054. finishedCallback();
  1055. }, (error) => {
  1056. finishedCallback(error);
  1057. });
  1058. };
  1059. this.modificationQueue.push(
  1060. workFunction,
  1061. (error) => {
  1062. if (!error) {
  1063. callback();
  1064. } else {
  1065. errorCallback(error);
  1066. }
  1067. }
  1068. );
  1069. };
  1070. /**
  1071. * Figures out added/removed ssrcs and send update IQs.
  1072. * @param old_sdp SDP object for old description.
  1073. * @param new_sdp SDP object for new description.
  1074. */
  1075. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  1076. if (this.state !== JingleSessionState.ACTIVE){
  1077. logger.warn(
  1078. "Skipping SSRC update in \'" + this.state + " \' state.");
  1079. return;
  1080. }
  1081. // send source-remove IQ.
  1082. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  1083. var remove = $iq({to: this.peerjid, type: 'set'})
  1084. .c('jingle', {
  1085. xmlns: 'urn:xmpp:jingle:1',
  1086. action: 'source-remove',
  1087. initiator: this.initiator,
  1088. sid: this.sid
  1089. }
  1090. );
  1091. sdpDiffer.toJingle(remove);
  1092. var removed = this.fixJingle(remove);
  1093. if (removed && remove) {
  1094. logger.info("Sending source-remove", remove.tree());
  1095. this.connection.sendIQ(
  1096. remove, null, this.newJingleErrorHandler(remove, function (error) {
  1097. GlobalOnErrorHandler.callErrorHandler(
  1098. new Error("Jingle error: " + JSON.stringify(error)));
  1099. }), IQ_TIMEOUT);
  1100. } else {
  1101. logger.log('removal not necessary');
  1102. }
  1103. // send source-add IQ.
  1104. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1105. var add = $iq({to: this.peerjid, type: 'set'})
  1106. .c('jingle', {
  1107. xmlns: 'urn:xmpp:jingle:1',
  1108. action: 'source-add',
  1109. initiator: this.initiator,
  1110. sid: this.sid
  1111. }
  1112. );
  1113. sdpDiffer.toJingle(add);
  1114. var added = this.fixJingle(add);
  1115. if (added && add) {
  1116. logger.info("Sending source-add", add.tree());
  1117. this.connection.sendIQ(
  1118. add, null, this.newJingleErrorHandler(add, function (error) {
  1119. GlobalOnErrorHandler.callErrorHandler(
  1120. new Error("Jingle error: " + JSON.stringify(error)));
  1121. }), IQ_TIMEOUT);
  1122. } else {
  1123. logger.log('addition not necessary');
  1124. }
  1125. };
  1126. /**
  1127. * Method returns function(errorResponse) which is a callback to be passed to
  1128. * Strophe connection.sendIQ method. An 'error' structure is created that is
  1129. * passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1130. * structure is as follows:
  1131. * {
  1132. * code: {XMPP error response code}
  1133. * reason: {the name of XMPP error reason element or 'timeout' if the request
  1134. * has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1135. * source: {request.tree() that provides original request}
  1136. * session: {JingleSessionPC instance on which the error occurred}
  1137. * }
  1138. * @param request Strophe IQ instance which is the request to be dumped into
  1139. * the error structure
  1140. * @param failureCb function(error) called when error response was returned or
  1141. * when a timeout has occurred.
  1142. * @returns {function(this:JingleSessionPC)}
  1143. */
  1144. JingleSessionPC.prototype.newJingleErrorHandler = function(request, failureCb) {
  1145. return function (errResponse) {
  1146. var error = { };
  1147. // Get XMPP error code and condition(reason)
  1148. var errorElSel = $(errResponse).find('error');
  1149. if (errorElSel.length) {
  1150. error.code = errorElSel.attr('code');
  1151. var errorReasonSel = $(errResponse).find('error :first');
  1152. if (errorReasonSel.length)
  1153. error.reason = errorReasonSel[0].tagName;
  1154. }
  1155. if (!errResponse) {
  1156. error.reason = 'timeout';
  1157. }
  1158. error.source = null;
  1159. if (request && "function" == typeof request.tree) {
  1160. error.source = request.tree();
  1161. }
  1162. // Commented to fix JSON.stringify(error) exception for circular
  1163. // dependancies when we print that error.
  1164. // FIXME: Maybe we can include part of the session object
  1165. // error.session = this;
  1166. logger.error("Jingle error", error);
  1167. if (failureCb) {
  1168. failureCb(error);
  1169. }
  1170. }.bind(this);
  1171. };
  1172. JingleSessionPC.onJingleFatalError = function (session, error)
  1173. {
  1174. if (this.room) {
  1175. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  1176. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1177. }
  1178. };
  1179. /**
  1180. * @inheritDoc
  1181. */
  1182. JingleSessionPC.prototype.getPeerMediaInfo = function (owner, mediaType) {
  1183. return this.room.getMediaPresenceInfo(owner, mediaType);
  1184. };
  1185. /**
  1186. * @inheritDoc
  1187. */
  1188. JingleSessionPC.prototype.getSSRCOwner = function(ssrc) {
  1189. return this.ssrcOwners[ssrc];
  1190. };
  1191. /**
  1192. * Returns the ice connection state for the peer connection.
  1193. * @returns the ice connection state for the peer connection.
  1194. */
  1195. JingleSessionPC.prototype.getIceConnectionState = function () {
  1196. return this.peerconnection.iceConnectionState;
  1197. };
  1198. /**
  1199. * Closes the peerconnection.
  1200. */
  1201. JingleSessionPC.prototype.close = function () {
  1202. this.closed = true;
  1203. // do not try to close if already closed.
  1204. this.peerconnection
  1205. && ((this.peerconnection.signalingState
  1206. && this.peerconnection.signalingState !== 'closed')
  1207. || (this.peerconnection.connectionState
  1208. && this.peerconnection.connectionState !== 'closed'))
  1209. && this.peerconnection.close();
  1210. };
  1211. /**
  1212. * Fixes the outgoing jingle packets by removing the nodes related to the
  1213. * muted/unmuted streams, handles removing of muted stream, etc.
  1214. * @param jingle the jingle packet that is going to be sent
  1215. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1216. */
  1217. JingleSessionPC.prototype.fixJingle = function(jingle) {
  1218. var action = $(jingle.nodeTree).find("jingle").attr("action");
  1219. switch (action) {
  1220. case "source-add":
  1221. case "session-accept":
  1222. this.fixSourceAddJingle(jingle);
  1223. break;
  1224. case "source-remove":
  1225. this.fixSourceRemoveJingle(jingle);
  1226. break;
  1227. default:
  1228. var errmsg = "Unknown jingle action!";
  1229. GlobalOnErrorHandler.callErrorHandler(errmsg);
  1230. logger.error(errmsg);
  1231. return false;
  1232. }
  1233. var sources = $(jingle.tree()).find(">jingle>content>description>source");
  1234. return sources && sources.length > 0;
  1235. };
  1236. /**
  1237. * Fixes the outgoing jingle packets with action source-add by removing the
  1238. * nodes related to the unmuted streams
  1239. * @param jingle the jingle packet that is going to be sent
  1240. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1241. */
  1242. JingleSessionPC.prototype.fixSourceAddJingle = function (jingle) {
  1243. var ssrcs = this.modifiedSSRCs["unmute"];
  1244. this.modifiedSSRCs["unmute"] = [];
  1245. if(ssrcs && ssrcs.length) {
  1246. ssrcs.forEach(function (ssrcObj) {
  1247. var desc = $(jingle.tree()).find(">jingle>content[name=\"" +
  1248. ssrcObj.mtype + "\"]>description");
  1249. if(!desc || !desc.length)
  1250. return;
  1251. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1252. var sourceNode = desc.find(">source[ssrc=\"" +
  1253. ssrc + "\"]");
  1254. sourceNode.remove();
  1255. });
  1256. ssrcObj.ssrc.groups.forEach(function (group) {
  1257. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1258. group.group.semantics + "\"]:has(source[ssrc=\"" +
  1259. group.primarySSRC +
  1260. "\"])");
  1261. groupNode.remove();
  1262. });
  1263. });
  1264. }
  1265. ssrcs = this.modifiedSSRCs["addMuted"];
  1266. this.modifiedSSRCs["addMuted"] = [];
  1267. if(ssrcs && ssrcs.length) {
  1268. ssrcs.forEach(function (ssrcObj) {
  1269. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1270. var cname = Math.random().toString(36).substring(2);
  1271. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1272. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1273. sourceNode.remove();
  1274. var sourceXML = "<source " +
  1275. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1276. ssrc + "\">" +
  1277. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1278. " value=\"" + ssrcObj.msid + "\" name=\"msid\"/>" +
  1279. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1280. " value=\"" + cname + "\" name=\"cname\" />" + "</source>";
  1281. desc.append(sourceXML);
  1282. });
  1283. ssrcObj.ssrc.groups.forEach(function (group) {
  1284. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1285. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1286. "\"])");
  1287. groupNode.remove();
  1288. desc.append("<ssrc-group semantics=\"" +
  1289. group.group.semantics +
  1290. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1291. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1292. "</ssrc-group>");
  1293. });
  1294. });
  1295. }
  1296. };
  1297. /**
  1298. * Fixes the outgoing jingle packets with action source-remove by removing the
  1299. * nodes related to the muted streams, handles removing of muted stream
  1300. * @param jingle the jingle packet that is going to be sent
  1301. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1302. */
  1303. JingleSessionPC.prototype.fixSourceRemoveJingle = function(jingle) {
  1304. var ssrcs = this.modifiedSSRCs["mute"];
  1305. this.modifiedSSRCs["mute"] = [];
  1306. if(ssrcs && ssrcs.length)
  1307. ssrcs.forEach(function (ssrcObj) {
  1308. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1309. var sourceNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1310. ssrcObj.mtype + "\"]>description>source[ssrc=\"" +
  1311. ssrc + "\"]");
  1312. sourceNode.remove();
  1313. });
  1314. ssrcObj.ssrc.groups.forEach(function (group) {
  1315. var groupNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1316. ssrcObj.mtype + "\"]>description>ssrc-group[semantics=\"" +
  1317. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1318. "\"])");
  1319. groupNode.remove();
  1320. });
  1321. });
  1322. ssrcs = this.modifiedSSRCs["remove"];
  1323. this.modifiedSSRCs["remove"] = [];
  1324. if(ssrcs && ssrcs.length)
  1325. ssrcs.forEach(function (ssrcObj) {
  1326. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1327. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1328. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1329. if(!sourceNode || !sourceNode.length) {
  1330. //Maybe we have to include cname, msid, etc here?
  1331. desc.append("<source " +
  1332. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1333. ssrc + "\"></source>");
  1334. }
  1335. });
  1336. ssrcObj.ssrc.groups.forEach(function (group) {
  1337. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1338. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1339. "\"])");
  1340. if(!groupNode || !groupNode.length) {
  1341. desc.append("<ssrc-group semantics=\"" +
  1342. group.group.semantics +
  1343. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1344. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1345. "</ssrc-group>");
  1346. }
  1347. });
  1348. });
  1349. };
  1350. /**
  1351. * Returns the description node related to the passed content type. If the node
  1352. * doesn't exists it will be created.
  1353. * @param jingle - the jingle packet
  1354. * @param mtype - the content type(audio, video, etc.)
  1355. */
  1356. function createDescriptionNode(jingle, mtype) {
  1357. var content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1358. mtype + "\"]");
  1359. if(!content || !content.length) {
  1360. $(jingle.tree()).find(">jingle").append(
  1361. "<content name=\"" + mtype + "\"></content>");
  1362. content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1363. mtype + "\"]");
  1364. }
  1365. var desc = content.find(">description");
  1366. if(!desc || !desc.length) {
  1367. content.append("<description " +
  1368. "xmlns=\"urn:xmpp:jingle:apps:rtp:1\" media=\"" +
  1369. mtype + "\"></description>");
  1370. desc = content.find(">description");
  1371. }
  1372. return desc;
  1373. }
  1374. /**
  1375. * Extracts the ice username fragment from an SDP string.
  1376. */
  1377. function getUfrag(sdp) {
  1378. var ufragLines = sdp.split('\n').filter(function(line) {
  1379. return line.startsWith("a=ice-ufrag:");});
  1380. if (ufragLines.length > 0) {
  1381. return ufragLines[0].substr("a=ice-ufrag:".length);
  1382. }
  1383. }
  1384. module.exports = JingleSessionPC;