您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 64KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  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. const semantics = this.getAttribute('semantics');
  617. const ssrcs
  618. = $(this)
  619. .find('>source')
  620. .map(function() {
  621. return this.getAttribute('ssrc');
  622. })
  623. .get();
  624. if (ssrcs.length) {
  625. lines
  626. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  627. }\r\n`;
  628. }
  629. });
  630. // handles both >source and >description>source
  631. const tmp
  632. = $(content).find(
  633. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  634. tmp.each(function() {
  635. const ssrc = $(this).attr('ssrc');
  636. if (currentRemoteSdp.containsSSRC(ssrc)) {
  637. logger.warn(
  638. `Source-add request for existing SSRC: ${ssrc}`);
  639. return;
  640. }
  641. // eslint-disable-next-line newline-per-chained-call
  642. $(this).find('>parameter').each(function() {
  643. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  644. if ($(this).attr('value') && $(this).attr('value').length) {
  645. lines += `:${$(this).attr('value')}`;
  646. }
  647. lines += '\r\n';
  648. });
  649. });
  650. currentRemoteSdp.media.forEach((media, i2) => {
  651. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  652. return;
  653. }
  654. if (!addSsrcInfo[i2]) {
  655. addSsrcInfo[i2] = '';
  656. }
  657. addSsrcInfo[i2] += lines;
  658. });
  659. });
  660. return addSsrcInfo;
  661. }
  662. /**
  663. * Handles a Jingle source-add message for this Jingle session.
  664. * @param elem An array of Jingle "content" elements.
  665. */
  666. addRemoteStream(elem) {
  667. // FIXME there is not stop condition for this wait !!!
  668. if (!this.peerconnection.localDescription) {
  669. logger.warn('addSource - localDescription not ready yet');
  670. setTimeout(() => this.addRemoteStream(elem), 200);
  671. return;
  672. }
  673. logger.log('Processing add remote stream');
  674. logger.log(
  675. 'ICE connection state: ', this.peerconnection.iceConnectionState);
  676. this.readSsrcInfo(elem);
  677. const workFunction = finishedCallback => {
  678. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  679. const mySdp = new SDP(this.peerconnection.localDescription.sdp);
  680. const addSsrcInfo = this._parseSsrcInfoFromSourceAdd(elem, sdp);
  681. const newRemoteSdp = this._processRemoteAddSource(addSsrcInfo);
  682. this._renegotiate(newRemoteSdp)
  683. .then(() => {
  684. logger.info('Remote source-add processed');
  685. const newSdp
  686. = new SDP(this.peerconnection.localDescription.sdp);
  687. logger.log('SDPs', mySdp, newSdp);
  688. this.notifyMySSRCUpdate(mySdp, newSdp);
  689. finishedCallback();
  690. }, error => {
  691. logger.error(
  692. 'Error renegotiating after processing remote'
  693. + ` source-add: ${error}`);
  694. finishedCallback(error);
  695. });
  696. };
  697. this.modificationQueue.push(workFunction);
  698. }
  699. /**
  700. * Handles a Jingle source-remove message for this Jingle session.
  701. * @param elem An array of Jingle "content" elements.
  702. */
  703. removeRemoteStream(elem) {
  704. // FIXME there is no stop condition for this wait !
  705. if (!this.peerconnection.localDescription) {
  706. logger.warn('removeSource - localDescription not ready yet');
  707. setTimeout(() => this.removeRemoteStream(elem), 200);
  708. return;
  709. }
  710. logger.log('Remove remote stream');
  711. logger.log(
  712. 'ICE connection state: ', this.peerconnection.iceConnectionState);
  713. const workFunction = finishedCallback => {
  714. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  715. const mySdp = new SDP(this.peerconnection.localDescription.sdp);
  716. const removeSsrcInfo
  717. = this._parseSsrcInfoFromSourceRemove(elem, sdp);
  718. const newRemoteSdp
  719. = this._processRemoteRemoveSource(removeSsrcInfo);
  720. this._renegotiate(newRemoteSdp)
  721. .then(() => {
  722. logger.info('Remote source-remove processed');
  723. const newSdp
  724. = new SDP(this.peerconnection.localDescription.sdp);
  725. logger.log('SDPs', mySdp, newSdp);
  726. this.notifyMySSRCUpdate(mySdp, newSdp);
  727. finishedCallback();
  728. }, error => {
  729. logger.error(
  730. 'Error renegotiating after processing remote'
  731. + ` source-remove: ${error}`);
  732. finishedCallback(error);
  733. });
  734. };
  735. this.modificationQueue.push(workFunction);
  736. }
  737. /**
  738. * The 'task' function will be given a callback it MUST call with either:
  739. * 1) No arguments if it was successful or
  740. * 2) An error argument if there was an error
  741. * If the task wants to process the success or failure of the task, it
  742. * should pass a handler to the .push function, e.g.:
  743. * queue.push(task, (err) => {
  744. * if (err) {
  745. * // error handling
  746. * } else {
  747. * // success handling
  748. * }
  749. * });
  750. */
  751. _processQueueTasks(task, finishedCallback) {
  752. task(finishedCallback);
  753. }
  754. /**
  755. * Takes in a jingle offer iq, returns the new sdp offer
  756. * @param {jquery xml element} offerIq the incoming offer
  757. * @returns {SDP object} the jingle offer translated to SDP
  758. */
  759. _processNewJingleOfferIq(offerIq) {
  760. const remoteSdp = new SDP('');
  761. if (this.webrtcIceTcpDisable) {
  762. remoteSdp.removeTcpCandidates = true;
  763. }
  764. if (this.webrtcIceUdpDisable) {
  765. remoteSdp.removeUdpCandidates = true;
  766. }
  767. if (this.failICE) {
  768. remoteSdp.failICE = true;
  769. }
  770. remoteSdp.fromJingle(offerIq);
  771. this.readSsrcInfo($(offerIq).find('>content'));
  772. return remoteSdp;
  773. }
  774. /**
  775. * Remove the given ssrc lines from the current remote sdp
  776. * @param {list} removeSsrcInfo a list of SDP line strings that
  777. * should be removed from the remote SDP
  778. * @returns type {SDP Object} the new remote SDP (after removing the lines
  779. * in removeSsrcInfo
  780. */
  781. _processRemoteRemoveSource(removeSsrcInfo) {
  782. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  783. removeSsrcInfo.forEach((lines, idx) => {
  784. // eslint-disable-next-line no-param-reassign
  785. lines = lines.split('\r\n');
  786. lines.pop(); // remove empty last element;
  787. lines.forEach(line => {
  788. remoteSdp.media[idx]
  789. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  790. });
  791. });
  792. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  793. return remoteSdp;
  794. }
  795. /**
  796. * Add the given ssrc lines to the current remote sdp
  797. * @param {list} addSsrcInfo a list of SDP line strings that
  798. * should be added to the remote SDP
  799. * @returns type {SDP Object} the new remote SDP (after removing the lines
  800. * in removeSsrcInfo
  801. */
  802. _processRemoteAddSource(addSsrcInfo) {
  803. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  804. addSsrcInfo.forEach((lines, idx) => {
  805. remoteSdp.media[idx] += lines;
  806. });
  807. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  808. return remoteSdp;
  809. }
  810. /**
  811. * Do a new o/a flow using the existing remote description
  812. * @param {SDP object} optionalRemoteSdp optional remote sdp
  813. * to use. If not provided, the remote sdp from the
  814. * peerconnection will be used
  815. * @returns {Promise} promise which resolves when the
  816. * o/a flow is complete with no arguments or
  817. * rejects with an error {string}
  818. */
  819. _renegotiate(optionalRemoteSdp) {
  820. const mediaConstraints = this.mediaConstraints;
  821. const remoteSdp
  822. = optionalRemoteSdp
  823. || new SDP(this.peerconnection.remoteDescription.sdp);
  824. const remoteDescription = new RTCSessionDescription({
  825. type: 'offer',
  826. sdp: remoteSdp.raw
  827. });
  828. // TODO(brian): in the code below there are 2 chunks of code that relate
  829. // to observing changes in local and remove ufrags. since they
  830. // just need to read and observe the SDPs, we should create the
  831. // notion of an SDP observer in TraceablePeerConnection that
  832. // gets notified of all SDP changes. Code like the ufrag
  833. // logic below could listen to that and be separated from
  834. // core flows like this.
  835. return new Promise((resolve, reject) => {
  836. const remoteUfrag = JingleSessionPC.getUfrag(remoteDescription.sdp);
  837. if (remoteUfrag !== this.remoteUfrag) {
  838. this.remoteUfrag = remoteUfrag;
  839. this.room.eventEmitter.emit(
  840. XMPPEvents.REMOTE_UFRAG_CHANGED, remoteUfrag);
  841. }
  842. logger.debug('Renegotiate: setting remote description');
  843. this.peerconnection.setRemoteDescription(
  844. remoteDescription,
  845. () => {
  846. if (this.signalingState === 'closed') {
  847. reject(
  848. 'Attempted to setRemoteDescription in state'
  849. + ' closed');
  850. return;
  851. }
  852. logger.debug('Renegotiate: creating answer');
  853. this.peerconnection.createAnswer(
  854. answer => {
  855. const localUfrag
  856. = JingleSessionPC.getUfrag(answer.sdp);
  857. if (localUfrag !== this.localUfrag) {
  858. this.localUfrag = localUfrag;
  859. this.room.eventEmitter.emit(
  860. XMPPEvents.LOCAL_UFRAG_CHANGED,
  861. localUfrag);
  862. }
  863. logger.debug(
  864. 'Renegotiate: setting local description');
  865. this.peerconnection.setLocalDescription(
  866. answer,
  867. () => {
  868. resolve();
  869. },
  870. error => {
  871. reject(
  872. `setLocalDescription failed: ${error}`);
  873. }
  874. );
  875. },
  876. error => reject(`createAnswer failed: ${error}`),
  877. mediaConstraints
  878. );
  879. },
  880. error => {
  881. reject(`setRemoteDescription failed: ${error}`);
  882. }
  883. );
  884. });
  885. }
  886. /**
  887. * Replaces oldStream with newStream and performs a single offer/answer
  888. * cycle after both operations are done. Either oldStream or newStream
  889. * can be null; replacing a valid 'oldStream' with a null 'newStream'
  890. * effectively just removes 'oldStream'
  891. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  892. * replaced
  893. * @param {JitsiLocalTrack|null} newTrack the new track to use
  894. * @returns {Promise} which resolves once the replacement is complete
  895. * with no arguments or rejects with an error {string}
  896. */
  897. replaceTrack(oldTrack, newTrack) {
  898. return new Promise((resolve, reject) => {
  899. const workFunction = finishedCallback => {
  900. const oldSdp
  901. = new SDP(this.peerconnection.localDescription.sdp);
  902. // NOTE the code below assumes that no more than 1 video track
  903. // can be added to the peer connection.
  904. // Transition from no video to video (possibly screen sharing)
  905. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  906. // Clearing current primary SSRC will make
  907. // the SdpConsistency generate a new one which will result
  908. // with:
  909. // 1. source-remove for the recvonly
  910. // 2. source-add for the new video stream
  911. this.peerconnection.clearRecvonlySsrc();
  912. // Transition from video to no video
  913. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  914. // Clearing current primary SSRC and generating the recvonly
  915. // will result in:
  916. // 1. source-remove for the old video stream
  917. // 2. source-add for the recvonly stream
  918. this.peerconnection.clearRecvonlySsrc();
  919. this.peerconnection.generateRecvonlySsrc();
  920. }
  921. this.removeStreamFromPeerConnection(oldTrack);
  922. this.addStreamToPeerConnection(newTrack);
  923. this._renegotiate()
  924. .then(() => {
  925. const newSdp
  926. = new SDP(this.peerconnection.localDescription.sdp);
  927. this.notifyMySSRCUpdate(oldSdp, newSdp);
  928. finishedCallback();
  929. }, error => {
  930. logger.error(
  931. `replaceTrack renegotiation failed: ${error}`);
  932. finishedCallback(error);
  933. });
  934. };
  935. this.modificationQueue.push(
  936. workFunction,
  937. error => {
  938. error ? reject(error) : resolve();
  939. });
  940. });
  941. }
  942. /**
  943. * Just add the stream to the peerconnection
  944. * @param stream either the low-level webrtc MediaStream or
  945. * a Jitsi mediastream
  946. * NOTE: must be called within a work function being executed
  947. * by the modification queue.
  948. */
  949. addStreamToPeerConnection(stream, ssrcInfo) {
  950. const actualStream
  951. = stream && stream.getOriginalStream
  952. ? stream.getOriginalStream() : stream;
  953. if (this.peerconnection) {
  954. this.peerconnection.addStream(actualStream, ssrcInfo);
  955. }
  956. }
  957. /**
  958. * Parse the information from the xml sourceRemoveElem and translate it
  959. * into sdp lines
  960. * @param {jquery xml element} sourceRemoveElem the source-remove
  961. * element from jingle
  962. * @param {SDP object} currentRemoteSdp the current remote
  963. * sdp (as of this new source-remove)
  964. * @returns {list} a list of SDP line strings that should
  965. * be removed from the remote SDP
  966. */
  967. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  968. const removeSsrcInfo = [];
  969. $(sourceRemoveElem).each((i1, content) => {
  970. const name = $(content).attr('name');
  971. let lines = '';
  972. $(content)
  973. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  974. .each(function() {
  975. const semantics = this.getAttribute('semantics');
  976. const ssrcs
  977. = $(this)
  978. .find('>source')
  979. .map(function() {
  980. return this.getAttribute('ssrc');
  981. })
  982. .get();
  983. if (ssrcs.length) {
  984. lines
  985. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  986. }\r\n`;
  987. }
  988. });
  989. const ssrcs = [];
  990. // handles both >source and >description>source versions
  991. const tmp
  992. = $(content).find(
  993. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  994. tmp.each(function() {
  995. const ssrc = $(this).attr('ssrc');
  996. ssrcs.push(ssrc);
  997. });
  998. currentRemoteSdp.media.forEach((media, i2) => {
  999. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1000. return;
  1001. }
  1002. if (!removeSsrcInfo[i2]) {
  1003. removeSsrcInfo[i2] = '';
  1004. }
  1005. ssrcs.forEach(ssrc => {
  1006. const ssrcLines
  1007. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1008. if (ssrcLines.length) {
  1009. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1010. }
  1011. });
  1012. removeSsrcInfo[i2] += lines;
  1013. });
  1014. });
  1015. return removeSsrcInfo;
  1016. }
  1017. /* eslint-disable max-params */
  1018. /**
  1019. * Adds stream.
  1020. * @param stream new stream that will be added.
  1021. * @param callback callback executed after successful stream addition.
  1022. * @param errorCallback callback executed if stream addition fail.
  1023. * @param ssrcInfo object with information about the SSRCs associated with
  1024. * the stream.
  1025. * @param dontModifySources {boolean} if true _modifySources won't be
  1026. * called.
  1027. * Used for streams added before the call start.
  1028. * NOTE(brian): there is a decent amount of overlap here with replaceTrack
  1029. * that could be re-used...however we can't leverage that currently because
  1030. * the extra work we do here must be in the work function context and if we
  1031. * then called replaceTrack we'd be adding another task on the queue
  1032. * from within a task which would then deadlock. The 'replaceTrack' core
  1033. * logic should be moved into a helper function that could be called within
  1034. * the 'doReplaceStream' task or the 'doAddStream' task (for example)
  1035. */
  1036. addStream(stream, callback, errorCallback, ssrcInfo, dontModifySources) {
  1037. const workFunction = finishedCallback => {
  1038. if (!this.peerconnection) {
  1039. finishedCallback(
  1040. 'Error: tried adding stream with no active peer'
  1041. + ' connection');
  1042. return;
  1043. }
  1044. this.addStreamToPeerConnection(stream, ssrcInfo);
  1045. if (ssrcInfo) {
  1046. // available only on video mute/unmute
  1047. this.modifiedSSRCs[ssrcInfo.type]
  1048. = this.modifiedSSRCs[ssrcInfo.type] || [];
  1049. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1050. }
  1051. if (dontModifySources) {
  1052. finishedCallback();
  1053. return;
  1054. }
  1055. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1056. this._renegotiate()
  1057. .then(() => {
  1058. const newSdp
  1059. = new SDP(this.peerconnection.localDescription.sdp);
  1060. // FIXME objects should not be logged
  1061. logger.log('SDPs', oldSdp, newSdp);
  1062. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1063. finishedCallback();
  1064. }, error => {
  1065. finishedCallback(error);
  1066. });
  1067. };
  1068. this.modificationQueue.push(
  1069. workFunction,
  1070. error => {
  1071. error ? errorCallback(error) : callback();
  1072. });
  1073. }
  1074. /* eslint-enable max-params */
  1075. /**
  1076. * Generate ssrc info object for a stream with the following properties:
  1077. * - ssrcs - Array of the ssrcs associated with the stream.
  1078. * - groups - Array of the groups associated with the stream.
  1079. */
  1080. generateNewStreamSSRCInfo() {
  1081. return this.peerconnection.generateNewStreamSSRCInfo();
  1082. }
  1083. /**
  1084. * Remove stream handling for firefox
  1085. * @param stream: webrtc media stream
  1086. */
  1087. _handleFirefoxRemoveStream(stream) {
  1088. if (!stream) { // There is nothing to be changed
  1089. return;
  1090. }
  1091. let sender = null;
  1092. // On Firefox we don't replace MediaStreams as this messes up the
  1093. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1094. // of complications. Instead, we use the RTPSender and remove just
  1095. // the track.
  1096. let track = null;
  1097. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1098. track = stream.getAudioTracks()[0];
  1099. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1100. track = stream.getVideoTracks()[0];
  1101. }
  1102. if (!track) {
  1103. const msg = 'Cannot remove tracks: no tracks.';
  1104. logger.log(msg);
  1105. return;
  1106. }
  1107. // Find the right sender (for audio or video)
  1108. this.peerconnection.peerconnection.getSenders().some(s => {
  1109. if (s.track === track) {
  1110. sender = s;
  1111. return true;
  1112. }
  1113. return false;
  1114. });
  1115. if (sender) {
  1116. this.peerconnection.peerconnection.removeTrack(sender);
  1117. } else {
  1118. logger.log('Cannot remove tracks: no RTPSender.');
  1119. }
  1120. }
  1121. /**
  1122. * Just remove the stream from the peerconnection
  1123. * @param {JitsiLocalTrack|MediaStream} stream the stream to remove
  1124. * NOTE: must be called within a work function being executed
  1125. * by the modification queue.
  1126. */
  1127. removeStreamFromPeerConnection(stream) {
  1128. const actualStream
  1129. = stream && stream.getOriginalStream
  1130. ? stream.getOriginalStream() : stream;
  1131. if (!this.peerconnection) {
  1132. return;
  1133. }
  1134. if (RTCBrowserType.getBrowserType()
  1135. === RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1136. this._handleFirefoxRemoveStream(actualStream);
  1137. } else if (actualStream) {
  1138. this.peerconnection.removeStream(actualStream);
  1139. }
  1140. }
  1141. /* eslint-disable max-params */
  1142. /**
  1143. * Remove streams.
  1144. * @param stream stream that will be removed.
  1145. * @param callback callback executed after successful stream addition.
  1146. * @param errorCallback callback executed if stream addition fail.
  1147. * @param ssrcInfo object with information about the SSRCs associated with
  1148. * the stream.
  1149. */
  1150. removeStream(stream, callback, errorCallback, ssrcInfo) {
  1151. const workFunction = finishedCallback => {
  1152. if (!this.peerconnection) {
  1153. finishedCallback();
  1154. return;
  1155. }
  1156. if (RTCBrowserType.getBrowserType()
  1157. === RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1158. this._handleFirefoxRemoveStream(stream);
  1159. } else if (stream) {
  1160. this.removeStreamFromPeerConnection(stream);
  1161. }
  1162. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1163. this._renegotiate()
  1164. .then(() => {
  1165. const newSdp
  1166. = new SDP(this.peerconnection.localDescription.sdp);
  1167. if (ssrcInfo) {
  1168. this.modifiedSSRCs[ssrcInfo.type]
  1169. = this.modifiedSSRCs[ssrcInfo.type] || [];
  1170. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1171. }
  1172. logger.log('SDPs', oldSdp, newSdp);
  1173. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1174. finishedCallback();
  1175. }, error => {
  1176. finishedCallback(error);
  1177. });
  1178. };
  1179. this.modificationQueue.push(
  1180. workFunction,
  1181. error => {
  1182. error ? errorCallback(error) : callback();
  1183. });
  1184. }
  1185. /* eslint-enable max-params */
  1186. /**
  1187. * Figures out added/removed ssrcs and send update IQs.
  1188. * @param oldSDP SDP object for old description.
  1189. * @param newSDP SDP object for new description.
  1190. */
  1191. notifyMySSRCUpdate(oldSDP, newSDP) {
  1192. if (this.state !== JingleSessionState.ACTIVE) {
  1193. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  1194. return;
  1195. }
  1196. // send source-remove IQ.
  1197. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  1198. const remove = $iq({ to: this.peerjid,
  1199. type: 'set' })
  1200. .c('jingle', {
  1201. xmlns: 'urn:xmpp:jingle:1',
  1202. action: 'source-remove',
  1203. initiator: this.initiator,
  1204. sid: this.sid
  1205. }
  1206. );
  1207. sdpDiffer.toJingle(remove);
  1208. const removed = this.fixJingle(remove);
  1209. if (removed && remove) {
  1210. logger.info('Sending source-remove', remove.tree());
  1211. this.connection.sendIQ(
  1212. remove, null,
  1213. this.newJingleErrorHandler(remove, error => {
  1214. GlobalOnErrorHandler.callErrorHandler(
  1215. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1216. }), IQ_TIMEOUT);
  1217. } else {
  1218. logger.log('removal not necessary');
  1219. }
  1220. // send source-add IQ.
  1221. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  1222. const add = $iq({ to: this.peerjid,
  1223. type: 'set' })
  1224. .c('jingle', {
  1225. xmlns: 'urn:xmpp:jingle:1',
  1226. action: 'source-add',
  1227. initiator: this.initiator,
  1228. sid: this.sid
  1229. }
  1230. );
  1231. sdpDiffer.toJingle(add);
  1232. const added = this.fixJingle(add);
  1233. if (added && add) {
  1234. logger.info('Sending source-add', add.tree());
  1235. this.connection.sendIQ(
  1236. add, null, this.newJingleErrorHandler(add, error => {
  1237. GlobalOnErrorHandler.callErrorHandler(
  1238. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1239. }), IQ_TIMEOUT);
  1240. } else {
  1241. logger.log('addition not necessary');
  1242. }
  1243. }
  1244. /**
  1245. * Method returns function(errorResponse) which is a callback to be passed
  1246. * to Strophe connection.sendIQ method. An 'error' structure is created that
  1247. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1248. * structure is as follows:
  1249. * {
  1250. * code: {XMPP error response code}
  1251. * reason: {the name of XMPP error reason element or 'timeout' if the
  1252. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1253. * source: {request.tree() that provides original request}
  1254. * session: {JingleSessionPC instance on which the error occurred}
  1255. * }
  1256. * @param request Strophe IQ instance which is the request to be dumped into
  1257. * the error structure
  1258. * @param failureCb function(error) called when error response was returned
  1259. * or when a timeout has occurred.
  1260. * @returns {function(this:JingleSessionPC)}
  1261. */
  1262. newJingleErrorHandler(request, failureCb) {
  1263. return function(errResponse) {
  1264. const error = {};
  1265. // Get XMPP error code and condition(reason)
  1266. const errorElSel = $(errResponse).find('error');
  1267. if (errorElSel.length) {
  1268. error.code = errorElSel.attr('code');
  1269. const errorReasonSel = $(errResponse).find('error :first');
  1270. if (errorReasonSel.length) {
  1271. error.reason = errorReasonSel[0].tagName;
  1272. }
  1273. }
  1274. if (!errResponse) {
  1275. error.reason = 'timeout';
  1276. }
  1277. error.source = null;
  1278. if (request && typeof request.tree === 'function') {
  1279. error.source = request.tree();
  1280. }
  1281. // Commented to fix JSON.stringify(error) exception for circular
  1282. // dependancies when we print that error.
  1283. // FIXME: Maybe we can include part of the session object
  1284. // error.session = this;
  1285. logger.error('Jingle error', error);
  1286. if (failureCb) {
  1287. failureCb(error);
  1288. }
  1289. };
  1290. }
  1291. static onJingleFatalError(session, error) {
  1292. if (this.room) {
  1293. this.room.eventEmitter.emit(
  1294. XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  1295. this.room.eventEmitter.emit(
  1296. XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1297. }
  1298. }
  1299. /**
  1300. * @inheritDoc
  1301. */
  1302. getPeerMediaInfo(owner, mediaType) {
  1303. return this.room.getMediaPresenceInfo(owner, mediaType);
  1304. }
  1305. /**
  1306. * @inheritDoc
  1307. */
  1308. getSSRCOwner(ssrc) {
  1309. return this.ssrcOwners[ssrc];
  1310. }
  1311. /**
  1312. * Returns the ice connection state for the peer connection.
  1313. * @returns the ice connection state for the peer connection.
  1314. */
  1315. getIceConnectionState() {
  1316. return this.peerconnection.iceConnectionState;
  1317. }
  1318. /**
  1319. * Closes the peerconnection.
  1320. */
  1321. close() {
  1322. this.closed = true;
  1323. // do not try to close if already closed.
  1324. this.peerconnection
  1325. && ((this.peerconnection.signalingState
  1326. && this.peerconnection.signalingState !== 'closed')
  1327. || (this.peerconnection.connectionState
  1328. && this.peerconnection.connectionState !== 'closed'))
  1329. && this.peerconnection.close();
  1330. }
  1331. /**
  1332. * Fixes the outgoing jingle packets by removing the nodes related to the
  1333. * muted/unmuted streams, handles removing of muted stream, etc.
  1334. * @param jingle the jingle packet that is going to be sent
  1335. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1336. */
  1337. fixJingle(jingle) {
  1338. // eslint-disable-next-line newline-per-chained-call
  1339. const action = $(jingle.nodeTree).find('jingle').attr('action');
  1340. switch (action) {
  1341. case 'source-add':
  1342. case 'session-accept':
  1343. this.fixSourceAddJingle(jingle);
  1344. break;
  1345. case 'source-remove':
  1346. this.fixSourceRemoveJingle(jingle);
  1347. break;
  1348. default: {
  1349. const errmsg = 'Unknown jingle action!';
  1350. GlobalOnErrorHandler.callErrorHandler(errmsg);
  1351. logger.error(errmsg);
  1352. return false;
  1353. }
  1354. }
  1355. const sources
  1356. = $(jingle.tree()).find('>jingle>content>description>source');
  1357. return sources && sources.length > 0;
  1358. }
  1359. /**
  1360. * Fixes the outgoing jingle packets with action source-add by removing the
  1361. * nodes related to the unmuted streams
  1362. * @param jingle the jingle packet that is going to be sent
  1363. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1364. */
  1365. fixSourceAddJingle(jingle) {
  1366. let ssrcs = this.modifiedSSRCs.unmute;
  1367. this.modifiedSSRCs.unmute = [];
  1368. if (ssrcs && ssrcs.length) {
  1369. ssrcs.forEach(ssrcObj => {
  1370. const desc
  1371. = $(jingle.tree()).find(
  1372. `>jingle>content[name="${ssrcObj.mtype}"]>description`);
  1373. if (!desc || !desc.length) {
  1374. return;
  1375. }
  1376. ssrcObj.ssrcs.forEach(ssrc => {
  1377. const sourceNode = desc.find(`>source[ssrc="${ssrc}"]`);
  1378. sourceNode.remove();
  1379. });
  1380. ssrcObj.groups.forEach(group => {
  1381. const groupNode = desc.find(`>ssrc-group[semantics="${
  1382. group.semantics}"]:has(source[ssrc="${
  1383. group.ssrcs[0]}"])`);
  1384. groupNode.remove();
  1385. });
  1386. });
  1387. }
  1388. ssrcs = this.modifiedSSRCs.addMuted;
  1389. this.modifiedSSRCs.addMuted = [];
  1390. if (ssrcs && ssrcs.length) {
  1391. ssrcs.forEach(ssrcObj => {
  1392. const desc
  1393. = JingleSessionPC.createDescriptionNode(
  1394. jingle, ssrcObj.mtype);
  1395. // eslint-disable-next-line newline-per-chained-call
  1396. const cname = Math.random().toString(36).substring(2);
  1397. ssrcObj.ssrcs.forEach(ssrc => {
  1398. const sourceNode
  1399. = desc.find(`>source[ssrc="${ssrc}"]`);
  1400. sourceNode.remove();
  1401. const sourceXML
  1402. = '<source xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1403. + ` ssrc="${ssrc}">`
  1404. + '<parameter xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1405. + ` value="${ssrcObj.msid}" name="msid"/>`
  1406. + '<parameter xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1407. + ` value="${cname}" name="cname" />`
  1408. + '</source>';
  1409. desc.append(sourceXML);
  1410. });
  1411. ssrcObj.groups.forEach(group => {
  1412. const groupNode
  1413. = desc.find(
  1414. `>ssrc-group[semantics="${group.semantics
  1415. }"]:has(source[ssrc="${group.ssrcs[0]}"])`);
  1416. groupNode.remove();
  1417. desc.append(
  1418. `<ssrc-group semantics="${group.semantics
  1419. }" xmlns="urn:xmpp:jingle:apps:rtp:ssma:0">`
  1420. + `<source ssrc="${group.ssrcs.join('"/><source ssrc="')
  1421. }"/></ssrc-group>`);
  1422. });
  1423. });
  1424. }
  1425. }
  1426. /**
  1427. * Fixes the outgoing jingle packets with action source-remove by removing
  1428. * the nodes related to the muted streams, handles removing of muted stream
  1429. * @param jingle the jingle packet that is going to be sent
  1430. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1431. */
  1432. fixSourceRemoveJingle(jingle) {
  1433. let ssrcs = this.modifiedSSRCs.mute;
  1434. this.modifiedSSRCs.mute = [];
  1435. if (ssrcs && ssrcs.length) {
  1436. ssrcs.forEach(ssrcObj => {
  1437. ssrcObj.ssrcs.forEach(ssrc => {
  1438. const sourceNode
  1439. = $(jingle.tree()).find(
  1440. `>jingle>content[name="${ssrcObj.mtype
  1441. }"]>description>source[ssrc="${ssrc}"]`);
  1442. sourceNode.remove();
  1443. });
  1444. ssrcObj.groups.forEach(group => {
  1445. const groupNode
  1446. = $(jingle.tree()).find(
  1447. `>jingle>content[name="${ssrcObj.mtype
  1448. }"]>description>ssrc-group[semantics="${
  1449. group.semantics}"]:has(source[ssrc="${
  1450. group.ssrcs[0]}"])`);
  1451. groupNode.remove();
  1452. });
  1453. });
  1454. }
  1455. ssrcs = this.modifiedSSRCs.remove;
  1456. this.modifiedSSRCs.remove = [];
  1457. if (ssrcs && ssrcs.length) {
  1458. ssrcs.forEach(ssrcObj => {
  1459. const desc
  1460. = JingleSessionPC.createDescriptionNode(
  1461. jingle, ssrcObj.mtype);
  1462. ssrcObj.ssrcs.forEach(ssrc => {
  1463. const sourceNode
  1464. = desc.find(`>source[ssrc="${ssrc}"]`);
  1465. if (!sourceNode || !sourceNode.length) {
  1466. // Maybe we have to include cname, msid, etc here?
  1467. desc.append(
  1468. '<source xmlns="urn:xmpp:jingle:apps:rtp:ssma:0" '
  1469. + `ssrc="${ssrc}"></source>`);
  1470. }
  1471. });
  1472. ssrcObj.groups.forEach(group => {
  1473. const groupNode
  1474. = desc.find(`>ssrc-group[semantics="${
  1475. group.semantics}"]:has(source[ssrc="${
  1476. group.ssrcs[0]}"])`);
  1477. if (!groupNode || !groupNode.length) {
  1478. desc.append(
  1479. `<ssrc-group semantics="${group.semantics
  1480. }" xmlns="urn:xmpp:jingle:apps:rtp:ssma:0">`
  1481. + `<source ssrc="${
  1482. group.ssrcs.join('"/><source ssrc="')}"/>`
  1483. + '</ssrc-group>');
  1484. }
  1485. });
  1486. });
  1487. }
  1488. }
  1489. /**
  1490. * Returns the description node related to the passed content type. If the
  1491. * node doesn't exists it will be created.
  1492. * @param jingle - the jingle packet
  1493. * @param mtype - the content type(audio, video, etc.)
  1494. */
  1495. static createDescriptionNode(jingle, mtype) {
  1496. let content = $(jingle.tree()).find(`>jingle>content[name="${mtype}"]`);
  1497. if (!content || !content.length) {
  1498. $(jingle.tree())
  1499. .find('>jingle')
  1500. .append(`<content name="${mtype}"></content>`);
  1501. content = $(jingle.tree()).find(`>jingle>content[name="${mtype}"]`);
  1502. }
  1503. let desc = content.find('>description');
  1504. if (!desc || !desc.length) {
  1505. content.append(
  1506. `<description xmlns="urn:xmpp:jingle:apps:rtp:1" media="${
  1507. mtype}"></description>`);
  1508. desc = content.find('>description');
  1509. }
  1510. return desc;
  1511. }
  1512. /**
  1513. * Extracts the ice username fragment from an SDP string.
  1514. */
  1515. static getUfrag(sdp) {
  1516. const ufragLines
  1517. = sdp.split('\n').filter(line => line.startsWith('a=ice-ufrag:'));
  1518. if (ufragLines.length > 0) {
  1519. return ufragLines[0].substr('a=ice-ufrag:'.length);
  1520. }
  1521. }
  1522. }