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

JingleSessionPC.js 63KB

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