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

JingleSessionPC.js 63KB

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