You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 62KB

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