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

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