Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 63KB

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