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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  1. /* global $, $iq, Strophe */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. const logger = getLogger(__filename);
  4. import JingleSession from './JingleSession';
  5. const SDPDiffer = require('./SDPDiffer');
  6. const SDPUtil = require('./SDPUtil');
  7. const SDP = require('./SDP');
  8. const async = require('async');
  9. const XMPPEvents = require('../../service/xmpp/XMPPEvents');
  10. const RTCBrowserType = require('../RTC/RTCBrowserType');
  11. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  12. const Statistics = require('../statistics/statistics');
  13. import * as JingleSessionState from './JingleSessionState';
  14. /**
  15. * Constant tells how long we're going to wait for IQ response, before timeout
  16. * error is triggered.
  17. * @type {number}
  18. */
  19. const IQ_TIMEOUT = 10000;
  20. export default class JingleSessionPC extends JingleSession {
  21. /**
  22. * Creates new <tt>JingleSessionPC</tt>
  23. * @param {string} sid the Jingle Session ID - random string which
  24. * identifies the session
  25. * @param {string} me our JID
  26. * @param {string} peerjid remote peer JID
  27. * @param {Strophe.Connection} connection Strophe XMPP connection instance
  28. * used to send packets.
  29. * @param media_constraints the media constraints object passed to
  30. * createOffer/Answer, as defined by the WebRTC standard
  31. * @param ice_config the ICE servers config object as defined by the WebRTC
  32. * standard.
  33. * @param {object} options a set of config options
  34. * @param {boolean} options.webrtcIceUdpDisable <tt>true</tt> to block UDP
  35. * candidates.
  36. * @param {boolean} options.webrtcIceTcpDisable <tt>true</tt> to block TCP
  37. * candidates.
  38. * @param {boolean} options.failICE it's an option used in the tests. Set to
  39. * <tt>true</tt> to block any real candidates and make the ICE fail.
  40. *
  41. * @constructor
  42. *
  43. * @implements {SignalingLayer}
  44. */
  45. constructor(sid, me, peerjid, connection,
  46. media_constraints, ice_config, options) {
  47. super(sid, me, peerjid, connection, media_constraints, ice_config);
  48. this.lasticecandidate = false;
  49. this.closed = false;
  50. this.modifyingLocalStreams = false;
  51. /**
  52. * Used to keep state about muted/unmuted video streams
  53. * so we can prevent errant source-add/source-removes
  54. * from happening
  55. */
  56. this.modifiedSSRCs = {};
  57. /**
  58. * The local ICE username fragment for this session.
  59. */
  60. this.localUfrag = null;
  61. /**
  62. * The remote ICE username fragment for this session.
  63. */
  64. this.remoteUfrag = null;
  65. /**
  66. * A map that stores SSRCs of remote streams. And is used only locally
  67. * We store the mapping when jingle is received, and later is used
  68. * onaddstream webrtc event where we have only the ssrc
  69. * FIXME: This map got filled and never cleaned and can grow during
  70. * long conference
  71. * @type {{}} maps SSRC number to jid
  72. */
  73. this.ssrcOwners = {};
  74. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  75. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  76. /**
  77. * Flag used to enforce ICE failure through the URL parameter for
  78. * the automatic testing purpose.
  79. * @type {boolean}
  80. */
  81. this.failICE = Boolean(options.failICE);
  82. this.modificationQueue
  83. = async.queue(this._processQueueTasks.bind(this), 1);
  84. }
  85. doInitialize() {
  86. this.lasticecandidate = false;
  87. // True if reconnect is in progress
  88. this.isreconnect = false;
  89. // Set to true if the connection was ever stable
  90. this.wasstable = false;
  91. // Create new peer connection instance
  92. this.peerconnection
  93. = this.rtc.createPeerConnection(
  94. this,
  95. this.connection.jingle.ice_config,
  96. /* Options */
  97. {
  98. disableSimulcast: this.room.options.disableSimulcast,
  99. disableRtx: this.room.options.disableRtx,
  100. preferH264: this.room.options.preferH264
  101. });
  102. this.peerconnection.onicecandidate = ev => {
  103. if (!ev) {
  104. // There was an incomplete check for ev before which left
  105. // the last line of the function unprotected from a potential
  106. // throw of an exception. Consequently, it may be argued that
  107. // the check is unnecessary. Anyway, I'm leaving it and making
  108. // the check complete.
  109. return;
  110. }
  111. // XXX this is broken, candidate is not parsed.
  112. const candidate = ev.candidate;
  113. if (candidate) {
  114. // Discard candidates of disabled protocols.
  115. let protocol = candidate.protocol;
  116. if (typeof protocol === 'string') {
  117. protocol = protocol.toLowerCase();
  118. if (protocol === 'tcp' || protocol === 'ssltcp') {
  119. if (this.webrtcIceTcpDisable) {
  120. return;
  121. }
  122. } else if (protocol == 'udp') {
  123. if (this.webrtcIceUdpDisable) {
  124. return;
  125. }
  126. }
  127. }
  128. }
  129. this.sendIceCandidate(candidate);
  130. };
  131. // Note there is a change in the spec about closed:
  132. // This value moved into the RTCPeerConnectionState enum in
  133. // the May 13, 2016 draft of the specification, as it reflects the state
  134. // of the RTCPeerConnection, not the signaling connection. You now
  135. // detect a closed connection by checking for connectionState to be
  136. // "closed" instead.
  137. // I suppose at some point this will be moved to onconnectionstatechange
  138. this.peerconnection.onsignalingstatechange = () => {
  139. if (!this.peerconnection) {
  140. return;
  141. }
  142. if (this.peerconnection.signalingState === 'stable') {
  143. this.wasstable = true;
  144. } else if (
  145. (this.peerconnection.signalingState === 'closed'
  146. || this.peerconnection.connectionState === 'closed')
  147. && !this.closed) {
  148. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED);
  149. }
  150. };
  151. /**
  152. * The oniceconnectionstatechange event handler contains the code to
  153. * execute when the iceconnectionstatechange event, of type Event,
  154. * is received by this RTCPeerConnection. Such an event is sent when
  155. * the value of RTCPeerConnection.iceConnectionState changes.
  156. */
  157. this.peerconnection.oniceconnectionstatechange = () => {
  158. if (!this.peerconnection) {
  159. return;
  160. }
  161. const now = window.performance.now();
  162. this.room.connectionTimes[
  163. `ice.state.${this.peerconnection.iceConnectionState}`]
  164. = now;
  165. logger.log(
  166. `(TIME) ICE ${this.peerconnection.iceConnectionState}:\t`,
  167. now);
  168. Statistics.analytics.sendEvent(
  169. `ice.${this.peerconnection.iceConnectionState}`,
  170. { value: now });
  171. this.room.eventEmitter.emit(
  172. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  173. this.peerconnection.iceConnectionState);
  174. switch (this.peerconnection.iceConnectionState) {
  175. case 'connected':
  176. // Informs interested parties that the connection has been
  177. // restored.
  178. if (this.peerconnection.signalingState === 'stable'
  179. && this.isreconnect) {
  180. this.room.eventEmitter.emit(
  181. XMPPEvents.CONNECTION_RESTORED);
  182. }
  183. this.isreconnect = false;
  184. break;
  185. case 'disconnected':
  186. if (this.closed) {
  187. break;
  188. }
  189. this.isreconnect = true;
  190. // Informs interested parties that the connection has been
  191. // interrupted.
  192. if (this.wasstable) {
  193. this.room.eventEmitter.emit(
  194. XMPPEvents.CONNECTION_INTERRUPTED);
  195. }
  196. break;
  197. case 'failed':
  198. this.room.eventEmitter.emit(
  199. XMPPEvents.CONNECTION_ICE_FAILED, this.peerconnection);
  200. break;
  201. }
  202. };
  203. this.peerconnection.onnegotiationneeded = () => {
  204. this.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, this);
  205. };
  206. }
  207. sendIceCandidate(candidate) {
  208. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  209. if (candidate && !this.lasticecandidate) {
  210. const ice
  211. = SDPUtil.iceparams(
  212. localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  213. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  214. if (!(ice && jcand)) {
  215. const errorMesssage = 'failed to get ice && jcand';
  216. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  217. logger.error(errorMesssage);
  218. return;
  219. }
  220. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  221. if (this.usedrip) {
  222. if (this.drip_container.length === 0) {
  223. // start 20ms callout
  224. setTimeout(() => {
  225. if (this.drip_container.length === 0) {
  226. return;
  227. }
  228. this.sendIceCandidates(this.drip_container);
  229. this.drip_container = [];
  230. }, 20);
  231. }
  232. this.drip_container.push(candidate);
  233. } else {
  234. this.sendIceCandidates([ candidate ]);
  235. }
  236. } else {
  237. logger.log('sendIceCandidate: last candidate.');
  238. // FIXME: remember to re-think in ICE-restart
  239. this.lasticecandidate = true;
  240. }
  241. }
  242. sendIceCandidates(candidates) {
  243. logger.log('sendIceCandidates', candidates);
  244. const cand = $iq({ to: this.peerjid,
  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.parse_mline(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 fingerprint_line
  275. = SDPUtil.find_line(
  276. localSDP.media[mid],
  277. 'a=fingerprint:', localSDP.session);
  278. if (fingerprint_line) {
  279. const tmp = SDPUtil.parse_fingerprint(fingerprint_line);
  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((idx, content) => {
  304. const ssrcs
  305. = $(content).find(
  306. 'description>'
  307. + 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  308. ssrcs.each((idx, ssrcElement) => {
  309. const ssrc = ssrcElement.getAttribute('ssrc');
  310. $(ssrcElement)
  311. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  312. .each((idx, 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.parse_mline(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((idx, 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, idx) => {
  641. if (!SDPUtil.find_line(media, `a=mid:${name}`)) {
  642. return;
  643. }
  644. if (!addSsrcInfo[idx]) {
  645. addSsrcInfo[idx] = '';
  646. }
  647. addSsrcInfo[idx] += 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. lines = lines.split('\r\n');
  775. lines.pop(); // remove empty last element;
  776. lines.forEach(line => {
  777. remoteSdp.media[idx]
  778. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  779. });
  780. });
  781. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  782. return remoteSdp;
  783. }
  784. /**
  785. * Add the given ssrc lines to the current remote sdp
  786. * @param {list} addSsrcInfo a list of SDP line strings that
  787. * should be added to the remote SDP
  788. * @returns type {SDP Object} the new remote SDP (after removing the lines
  789. * in removeSsrcInfo
  790. */
  791. _processRemoteAddSource(addSsrcInfo) {
  792. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  793. addSsrcInfo.forEach((lines, idx) => {
  794. remoteSdp.media[idx] += lines;
  795. });
  796. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  797. return remoteSdp;
  798. }
  799. /**
  800. * Do a new o/a flow using the existing remote description
  801. * @param {SDP object} optionalRemoteSdp optional remote sdp
  802. * to use. If not provided, the remote sdp from the
  803. * peerconnection will be used
  804. * @returns {Promise} promise which resolves when the
  805. * o/a flow is complete with no arguments or
  806. * rejects with an error {string}
  807. */
  808. _renegotiate(optionalRemoteSdp) {
  809. const media_constraints = this.media_constraints;
  810. const remoteSdp
  811. = optionalRemoteSdp
  812. || new SDP(this.peerconnection.remoteDescription.sdp);
  813. const remoteDescription = new RTCSessionDescription({
  814. type: 'offer',
  815. sdp: remoteSdp.raw
  816. });
  817. // TODO(brian): in the code below there are 2 chunks of code that relate
  818. // to observing changes in local and remove ufrags. since they
  819. // just need to read and observe the SDPs, we should create the
  820. // notion of an SDP observer in TraceablePeerConnection that
  821. // gets notified of all SDP changes. Code like the ufrag
  822. // logic below could listen to that and be separated from
  823. // core flows like this.
  824. return new Promise((resolve, reject) => {
  825. const remoteUfrag = JingleSessionPC.getUfrag(remoteDescription.sdp);
  826. if (remoteUfrag != this.remoteUfrag) {
  827. this.remoteUfrag = remoteUfrag;
  828. this.room.eventEmitter.emit(
  829. XMPPEvents.REMOTE_UFRAG_CHANGED, remoteUfrag);
  830. }
  831. logger.debug('Renegotiate: setting remote description');
  832. this.peerconnection.setRemoteDescription(
  833. remoteDescription,
  834. () => {
  835. if (this.signalingState === 'closed') {
  836. reject(
  837. 'Attempted to setRemoteDescription in state'
  838. + ' closed');
  839. return;
  840. }
  841. logger.debug('Renegotiate: creating answer');
  842. this.peerconnection.createAnswer(
  843. answer => {
  844. const localUfrag
  845. = JingleSessionPC.getUfrag(answer.sdp);
  846. if (localUfrag != this.localUfrag) {
  847. this.localUfrag = localUfrag;
  848. this.room.eventEmitter.emit(
  849. XMPPEvents.LOCAL_UFRAG_CHANGED,
  850. localUfrag);
  851. }
  852. logger.debug(
  853. 'Renegotiate: setting local description');
  854. this.peerconnection.setLocalDescription(
  855. answer,
  856. () => {
  857. resolve();
  858. },
  859. error => {
  860. reject(
  861. `setLocalDescription failed: ${error}`);
  862. }
  863. );
  864. },
  865. error => reject(`createAnswer failed: ${error}`),
  866. media_constraints
  867. );
  868. },
  869. error => {
  870. reject(`setRemoteDescription failed: ${error}`);
  871. }
  872. );
  873. });
  874. }
  875. /**
  876. * Replaces oldStream with newStream and performs a single offer/answer
  877. * cycle after both operations are done. Either oldStream or newStream
  878. * can be null; replacing a valid 'oldStream' with a null 'newStream'
  879. * effectively just removes 'oldStream'
  880. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  881. * replaced
  882. * @param {JitsiLocalTrack|null} newTrack the new track to use
  883. * @returns {Promise} which resolves once the replacement is complete
  884. * with no arguments or rejects with an error {string}
  885. */
  886. replaceTrack(oldTrack, newTrack) {
  887. return new Promise((resolve, reject) => {
  888. const workFunction = finishedCallback => {
  889. const oldSdp
  890. = new SDP(this.peerconnection.localDescription.sdp);
  891. // NOTE the code below assumes that no more than 1 video track
  892. // can be added to the peer connection.
  893. // Transition from no video to video (possibly screen sharing)
  894. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  895. // Clearing current primary SSRC will make
  896. // the SdpConsistency generate a new one which will result
  897. // with:
  898. // 1. source-remove for the recvonly
  899. // 2. source-add for the new video stream
  900. this.peerconnection.clearRecvonlySsrc();
  901. // Transition from video to no video
  902. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  903. // Clearing current primary SSRC and generating the recvonly
  904. // will result in:
  905. // 1. source-remove for the old video stream
  906. // 2. source-add for the recvonly stream
  907. this.peerconnection.clearRecvonlySsrc();
  908. this.peerconnection.generateRecvonlySsrc();
  909. }
  910. this.removeStreamFromPeerConnection(oldTrack);
  911. this.addStreamToPeerConnection(newTrack);
  912. this._renegotiate()
  913. .then(() => {
  914. const newSdp
  915. = new SDP(this.peerconnection.localDescription.sdp);
  916. this.notifyMySSRCUpdate(oldSdp, newSdp);
  917. finishedCallback();
  918. }, error => {
  919. logger.error(
  920. `replaceTrack renegotiation failed: ${error}`);
  921. finishedCallback(error);
  922. });
  923. };
  924. this.modificationQueue.push(
  925. workFunction,
  926. error => {
  927. error ? reject(error) : resolve();
  928. });
  929. });
  930. }
  931. /**
  932. * Just add the stream to the peerconnection
  933. * @param stream either the low-level webrtc MediaStream or
  934. * a Jitsi mediastream
  935. * NOTE: must be called within a work function being executed
  936. * by the modification queue.
  937. */
  938. addStreamToPeerConnection(stream, ssrcInfo) {
  939. const actualStream
  940. = stream && stream.getOriginalStream
  941. ? stream.getOriginalStream() : stream;
  942. if (this.peerconnection) {
  943. this.peerconnection.addStream(actualStream, ssrcInfo);
  944. }
  945. }
  946. /**
  947. * Parse the information from the xml sourceRemoveElem and translate it
  948. * into sdp lines
  949. * @param {jquery xml element} sourceRemoveElem the source-remove
  950. * element from jingle
  951. * @param {SDP object} currentRemoteSdp the current remote
  952. * sdp (as of this new source-remove)
  953. * @returns {list} a list of SDP line strings that should
  954. * be removed from the remote SDP
  955. */
  956. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  957. const removeSsrcInfo = [];
  958. $(sourceRemoveElem).each((idx, content) => {
  959. const name = $(content).attr('name');
  960. let lines = '';
  961. $(content)
  962. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  963. .each(function() {
  964. const semantics = this.getAttribute('semantics');
  965. const ssrcs
  966. = $(this)
  967. .find('>source')
  968. .map(function() {
  969. return this.getAttribute('ssrc');
  970. })
  971. .get();
  972. if (ssrcs.length) {
  973. lines
  974. += `a=ssrc-group:${semantics} ${ssrcs.join(' ')
  975. }\r\n`;
  976. }
  977. });
  978. const ssrcs = [];
  979. // handles both >source and >description>source versions
  980. const tmp
  981. = $(content).find(
  982. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  983. tmp.each(function() {
  984. const ssrc = $(this).attr('ssrc');
  985. ssrcs.push(ssrc);
  986. });
  987. currentRemoteSdp.media.forEach((media, idx) => {
  988. if (!SDPUtil.find_line(media, `a=mid:${name}`)) {
  989. return;
  990. }
  991. if (!removeSsrcInfo[idx]) {
  992. removeSsrcInfo[idx] = '';
  993. }
  994. ssrcs.forEach(ssrc => {
  995. const ssrcLines
  996. = SDPUtil.find_lines(media, `a=ssrc:${ssrc}`);
  997. if (ssrcLines.length) {
  998. removeSsrcInfo[idx] += `${ssrcLines.join('\r\n')}\r\n`;
  999. }
  1000. });
  1001. removeSsrcInfo[idx] += lines;
  1002. });
  1003. });
  1004. return removeSsrcInfo;
  1005. }
  1006. /**
  1007. * Adds stream.
  1008. * @param stream new stream that will be added.
  1009. * @param callback callback executed after successful stream addition.
  1010. * @param errorCallback callback executed if stream addition fail.
  1011. * @param ssrcInfo object with information about the SSRCs associated with
  1012. * the stream.
  1013. * @param dontModifySources {boolean} if true _modifySources won't be
  1014. * called.
  1015. * Used for streams added before the call start.
  1016. * NOTE(brian): there is a decent amount of overlap here with replaceTrack
  1017. * that could be re-used...however we can't leverage that currently because
  1018. * the extra work we do here must be in the work function context and if we
  1019. * then called replaceTrack we'd be adding another task on the queue
  1020. * from within a task which would then deadlock. The 'replaceTrack' core
  1021. * logic should be moved into a helper function that could be called within
  1022. * the 'doReplaceStream' task or the 'doAddStream' task (for example)
  1023. */
  1024. addStream(stream, callback, errorCallback, ssrcInfo, dontModifySources) {
  1025. const workFunction = finishedCallback => {
  1026. if (!this.peerconnection) {
  1027. finishedCallback(
  1028. 'Error: tried adding stream with no active peer'
  1029. + ' connection');
  1030. return;
  1031. }
  1032. this.addStreamToPeerConnection(stream, ssrcInfo);
  1033. if (ssrcInfo) {
  1034. // available only on video mute/unmute
  1035. this.modifiedSSRCs[ssrcInfo.type]
  1036. = this.modifiedSSRCs[ssrcInfo.type] || [];
  1037. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1038. }
  1039. if (dontModifySources) {
  1040. finishedCallback();
  1041. return;
  1042. }
  1043. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1044. this._renegotiate()
  1045. .then(() => {
  1046. const newSdp
  1047. = new SDP(this.peerconnection.localDescription.sdp);
  1048. // FIXME objects should not be logged
  1049. logger.log('SDPs', oldSdp, newSdp);
  1050. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1051. finishedCallback();
  1052. }, error => {
  1053. finishedCallback(error);
  1054. });
  1055. };
  1056. this.modificationQueue.push(
  1057. workFunction,
  1058. error => {
  1059. error ? errorCallback(error) : callback();
  1060. });
  1061. }
  1062. /**
  1063. * Generate ssrc info object for a stream with the following properties:
  1064. * - ssrcs - Array of the ssrcs associated with the stream.
  1065. * - groups - Array of the groups associated with the stream.
  1066. */
  1067. generateNewStreamSSRCInfo() {
  1068. return this.peerconnection.generateNewStreamSSRCInfo();
  1069. }
  1070. /**
  1071. * Remove stream handling for firefox
  1072. * @param stream: webrtc media stream
  1073. */
  1074. _handleFirefoxRemoveStream(stream) {
  1075. if (!stream) { // There is nothing to be changed
  1076. return;
  1077. }
  1078. let sender = null;
  1079. // On Firefox we don't replace MediaStreams as this messes up the
  1080. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1081. // of complications. Instead, we use the RTPSender and remove just
  1082. // the track.
  1083. let track = null;
  1084. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1085. track = stream.getAudioTracks()[0];
  1086. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1087. track = stream.getVideoTracks()[0];
  1088. }
  1089. if (!track) {
  1090. const msg = 'Cannot remove tracks: no tracks.';
  1091. logger.log(msg);
  1092. return;
  1093. }
  1094. // Find the right sender (for audio or video)
  1095. this.peerconnection.peerconnection.getSenders().some(s => {
  1096. if (s.track === track) {
  1097. sender = s;
  1098. return true;
  1099. }
  1100. return false;
  1101. });
  1102. if (sender) {
  1103. this.peerconnection.peerconnection.removeTrack(sender);
  1104. } else {
  1105. logger.log('Cannot remove tracks: no RTPSender.');
  1106. }
  1107. }
  1108. /**
  1109. * Just remove the stream from the peerconnection
  1110. * @param {JitsiLocalTrack|MediaStream} stream the stream to remove
  1111. * NOTE: must be called within a work function being executed
  1112. * by the modification queue.
  1113. */
  1114. removeStreamFromPeerConnection(stream) {
  1115. const actualStream
  1116. = stream && stream.getOriginalStream
  1117. ? stream.getOriginalStream() : stream;
  1118. if (!this.peerconnection) {
  1119. return;
  1120. }
  1121. if (RTCBrowserType.getBrowserType()
  1122. === RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1123. this._handleFirefoxRemoveStream(actualStream);
  1124. } else if (actualStream) {
  1125. this.peerconnection.removeStream(actualStream);
  1126. }
  1127. }
  1128. /**
  1129. * Remove streams.
  1130. * @param stream stream that will be removed.
  1131. * @param callback callback executed after successful stream addition.
  1132. * @param errorCallback callback executed if stream addition fail.
  1133. * @param ssrcInfo object with information about the SSRCs associated with
  1134. * the stream.
  1135. */
  1136. removeStream(stream, callback, errorCallback, ssrcInfo) {
  1137. const workFunction = finishedCallback => {
  1138. if (!this.peerconnection) {
  1139. finishedCallback();
  1140. return;
  1141. }
  1142. if (RTCBrowserType.getBrowserType()
  1143. === RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1144. this._handleFirefoxRemoveStream(stream);
  1145. } else if (stream) {
  1146. this.removeStreamFromPeerConnection(stream);
  1147. }
  1148. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1149. this._renegotiate()
  1150. .then(() => {
  1151. const newSdp
  1152. = new SDP(this.peerconnection.localDescription.sdp);
  1153. if (ssrcInfo) {
  1154. this.modifiedSSRCs[ssrcInfo.type]
  1155. = this.modifiedSSRCs[ssrcInfo.type] || [];
  1156. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1157. }
  1158. logger.log('SDPs', oldSdp, newSdp);
  1159. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1160. finishedCallback();
  1161. }, error => {
  1162. finishedCallback(error);
  1163. });
  1164. };
  1165. this.modificationQueue.push(
  1166. workFunction,
  1167. error => {
  1168. error ? errorCallback(error) : callback();
  1169. });
  1170. }
  1171. /**
  1172. * Figures out added/removed ssrcs and send update IQs.
  1173. * @param old_sdp SDP object for old description.
  1174. * @param new_sdp SDP object for new description.
  1175. */
  1176. notifyMySSRCUpdate(old_sdp, new_sdp) {
  1177. if (this.state !== JingleSessionState.ACTIVE) {
  1178. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  1179. return;
  1180. }
  1181. // send source-remove IQ.
  1182. let sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  1183. const remove = $iq({ to: this.peerjid,
  1184. type: 'set' })
  1185. .c('jingle', {
  1186. xmlns: 'urn:xmpp:jingle:1',
  1187. action: 'source-remove',
  1188. initiator: this.initiator,
  1189. sid: this.sid
  1190. }
  1191. );
  1192. sdpDiffer.toJingle(remove);
  1193. const removed = this.fixJingle(remove);
  1194. if (removed && remove) {
  1195. logger.info('Sending source-remove', remove.tree());
  1196. this.connection.sendIQ(
  1197. remove, null,
  1198. this.newJingleErrorHandler(remove, error => {
  1199. GlobalOnErrorHandler.callErrorHandler(
  1200. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1201. }), IQ_TIMEOUT);
  1202. } else {
  1203. logger.log('removal not necessary');
  1204. }
  1205. // send source-add IQ.
  1206. sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1207. const add = $iq({ to: this.peerjid,
  1208. type: 'set' })
  1209. .c('jingle', {
  1210. xmlns: 'urn:xmpp:jingle:1',
  1211. action: 'source-add',
  1212. initiator: this.initiator,
  1213. sid: this.sid
  1214. }
  1215. );
  1216. sdpDiffer.toJingle(add);
  1217. const added = this.fixJingle(add);
  1218. if (added && add) {
  1219. logger.info('Sending source-add', add.tree());
  1220. this.connection.sendIQ(
  1221. add, null, this.newJingleErrorHandler(add, error => {
  1222. GlobalOnErrorHandler.callErrorHandler(
  1223. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1224. }), IQ_TIMEOUT);
  1225. } else {
  1226. logger.log('addition not necessary');
  1227. }
  1228. }
  1229. /**
  1230. * Method returns function(errorResponse) which is a callback to be passed
  1231. * to Strophe connection.sendIQ method. An 'error' structure is created that
  1232. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1233. * structure is as follows:
  1234. * {
  1235. * code: {XMPP error response code}
  1236. * reason: {the name of XMPP error reason element or 'timeout' if the
  1237. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1238. * source: {request.tree() that provides original request}
  1239. * session: {JingleSessionPC instance on which the error occurred}
  1240. * }
  1241. * @param request Strophe IQ instance which is the request to be dumped into
  1242. * the error structure
  1243. * @param failureCb function(error) called when error response was returned
  1244. * or when a timeout has occurred.
  1245. * @returns {function(this:JingleSessionPC)}
  1246. */
  1247. newJingleErrorHandler(request, failureCb) {
  1248. return function(errResponse) {
  1249. const error = {};
  1250. // Get XMPP error code and condition(reason)
  1251. const errorElSel = $(errResponse).find('error');
  1252. if (errorElSel.length) {
  1253. error.code = errorElSel.attr('code');
  1254. const errorReasonSel = $(errResponse).find('error :first');
  1255. if (errorReasonSel.length) {
  1256. error.reason = errorReasonSel[0].tagName;
  1257. }
  1258. }
  1259. if (!errResponse) {
  1260. error.reason = 'timeout';
  1261. }
  1262. error.source = null;
  1263. if (request && typeof request.tree === 'function') {
  1264. error.source = request.tree();
  1265. }
  1266. // Commented to fix JSON.stringify(error) exception for circular
  1267. // dependancies when we print that error.
  1268. // FIXME: Maybe we can include part of the session object
  1269. // error.session = this;
  1270. logger.error('Jingle error', error);
  1271. if (failureCb) {
  1272. failureCb(error);
  1273. }
  1274. };
  1275. }
  1276. static onJingleFatalError(session, error) {
  1277. if (this.room) {
  1278. this.room.eventEmitter.emit(
  1279. XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  1280. this.room.eventEmitter.emit(
  1281. XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1282. }
  1283. }
  1284. /**
  1285. * @inheritDoc
  1286. */
  1287. getPeerMediaInfo(owner, mediaType) {
  1288. return this.room.getMediaPresenceInfo(owner, mediaType);
  1289. }
  1290. /**
  1291. * @inheritDoc
  1292. */
  1293. getSSRCOwner(ssrc) {
  1294. return this.ssrcOwners[ssrc];
  1295. }
  1296. /**
  1297. * Returns the ice connection state for the peer connection.
  1298. * @returns the ice connection state for the peer connection.
  1299. */
  1300. getIceConnectionState() {
  1301. return this.peerconnection.iceConnectionState;
  1302. }
  1303. /**
  1304. * Closes the peerconnection.
  1305. */
  1306. close() {
  1307. this.closed = true;
  1308. // do not try to close if already closed.
  1309. this.peerconnection
  1310. && ((this.peerconnection.signalingState
  1311. && this.peerconnection.signalingState !== 'closed')
  1312. || (this.peerconnection.connectionState
  1313. && this.peerconnection.connectionState !== 'closed'))
  1314. && this.peerconnection.close();
  1315. }
  1316. /**
  1317. * Fixes the outgoing jingle packets by removing the nodes related to the
  1318. * muted/unmuted streams, handles removing of muted stream, etc.
  1319. * @param jingle the jingle packet that is going to be sent
  1320. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1321. */
  1322. fixJingle(jingle) {
  1323. // eslint-disable-next-line newline-per-chained-call
  1324. const action = $(jingle.nodeTree).find('jingle').attr('action');
  1325. switch (action) {
  1326. case 'source-add':
  1327. case 'session-accept':
  1328. this.fixSourceAddJingle(jingle);
  1329. break;
  1330. case 'source-remove':
  1331. this.fixSourceRemoveJingle(jingle);
  1332. break;
  1333. default: {
  1334. const errmsg = 'Unknown jingle action!';
  1335. GlobalOnErrorHandler.callErrorHandler(errmsg);
  1336. logger.error(errmsg);
  1337. return false;
  1338. }
  1339. }
  1340. const sources
  1341. = $(jingle.tree()).find('>jingle>content>description>source');
  1342. return sources && sources.length > 0;
  1343. }
  1344. /**
  1345. * Fixes the outgoing jingle packets with action source-add by removing the
  1346. * nodes related to the unmuted streams
  1347. * @param jingle the jingle packet that is going to be sent
  1348. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1349. */
  1350. fixSourceAddJingle(jingle) {
  1351. let ssrcs = this.modifiedSSRCs.unmute;
  1352. this.modifiedSSRCs.unmute = [];
  1353. if (ssrcs && ssrcs.length) {
  1354. ssrcs.forEach(ssrcObj => {
  1355. const desc
  1356. = $(jingle.tree()).find(
  1357. `>jingle>content[name="${ssrcObj.mtype}"]>description`);
  1358. if (!desc || !desc.length) {
  1359. return;
  1360. }
  1361. ssrcObj.ssrcs.forEach(ssrc => {
  1362. const sourceNode = desc.find(`>source[ssrc="${ssrc}"]`);
  1363. sourceNode.remove();
  1364. });
  1365. ssrcObj.groups.forEach(group => {
  1366. const groupNode = desc.find(`>ssrc-group[semantics="${
  1367. group.semantics}"]:has(source[ssrc="${
  1368. group.ssrcs[0]}"])`);
  1369. groupNode.remove();
  1370. });
  1371. });
  1372. }
  1373. ssrcs = this.modifiedSSRCs.addMuted;
  1374. this.modifiedSSRCs.addMuted = [];
  1375. if (ssrcs && ssrcs.length) {
  1376. ssrcs.forEach(ssrcObj => {
  1377. const desc
  1378. = JingleSessionPC.createDescriptionNode(
  1379. jingle, ssrcObj.mtype);
  1380. // eslint-disable-next-line newline-per-chained-call
  1381. const cname = Math.random().toString(36).substring(2);
  1382. ssrcObj.ssrcs.forEach(ssrc => {
  1383. const sourceNode
  1384. = desc.find(`>source[ssrc="${ssrc}"]`);
  1385. sourceNode.remove();
  1386. const sourceXML
  1387. = '<source xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1388. + ` ssrc="${ssrc}">`
  1389. + '<parameter xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1390. + ` value="${ssrcObj.msid}" name="msid"/>`
  1391. + '<parameter xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"'
  1392. + ` value="${cname}" name="cname" />`
  1393. + '</source>';
  1394. desc.append(sourceXML);
  1395. });
  1396. ssrcObj.groups.forEach(group => {
  1397. const groupNode
  1398. = desc.find(
  1399. `>ssrc-group[semantics="${group.semantics
  1400. }"]:has(source[ssrc="${group.ssrcs[0]}"])`);
  1401. groupNode.remove();
  1402. desc.append(
  1403. `<ssrc-group semantics="${group.semantics
  1404. }" xmlns="urn:xmpp:jingle:apps:rtp:ssma:0">`
  1405. + `<source ssrc="${group.ssrcs.join('"/><source ssrc="')
  1406. }"/></ssrc-group>`);
  1407. });
  1408. });
  1409. }
  1410. }
  1411. /**
  1412. * Fixes the outgoing jingle packets with action source-remove by removing
  1413. * the nodes related to the muted streams, handles removing of muted stream
  1414. * @param jingle the jingle packet that is going to be sent
  1415. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1416. */
  1417. fixSourceRemoveJingle(jingle) {
  1418. let ssrcs = this.modifiedSSRCs.mute;
  1419. this.modifiedSSRCs.mute = [];
  1420. if (ssrcs && ssrcs.length) {
  1421. ssrcs.forEach(ssrcObj => {
  1422. ssrcObj.ssrcs.forEach(ssrc => {
  1423. const sourceNode
  1424. = $(jingle.tree()).find(
  1425. `>jingle>content[name="${ssrcObj.mtype
  1426. }"]>description>source[ssrc="${ssrc}"]`);
  1427. sourceNode.remove();
  1428. });
  1429. ssrcObj.groups.forEach(group => {
  1430. const groupNode
  1431. = $(jingle.tree()).find(
  1432. `>jingle>content[name="${ssrcObj.mtype
  1433. }"]>description>ssrc-group[semantics="${
  1434. group.semantics}"]:has(source[ssrc="${
  1435. group.ssrcs[0]}"])`);
  1436. groupNode.remove();
  1437. });
  1438. });
  1439. }
  1440. ssrcs = this.modifiedSSRCs.remove;
  1441. this.modifiedSSRCs.remove = [];
  1442. if (ssrcs && ssrcs.length) {
  1443. ssrcs.forEach(ssrcObj => {
  1444. const desc
  1445. = JingleSessionPC.createDescriptionNode(
  1446. jingle, ssrcObj.mtype);
  1447. ssrcObj.ssrcs.forEach(ssrc => {
  1448. const sourceNode
  1449. = desc.find(`>source[ssrc="${ssrc}"]`);
  1450. if (!sourceNode || !sourceNode.length) {
  1451. // Maybe we have to include cname, msid, etc here?
  1452. desc.append(
  1453. '<source xmlns="urn:xmpp:jingle:apps:rtp:ssma:0" '
  1454. + `ssrc="${ssrc}"></source>`);
  1455. }
  1456. });
  1457. ssrcObj.groups.forEach(group => {
  1458. const groupNode
  1459. = desc.find(`>ssrc-group[semantics="${
  1460. group.semantics}"]:has(source[ssrc="${
  1461. group.ssrcs[0]}"])`);
  1462. if (!groupNode || !groupNode.length) {
  1463. desc.append(
  1464. `<ssrc-group semantics="${group.semantics
  1465. }" xmlns="urn:xmpp:jingle:apps:rtp:ssma:0">`
  1466. + `<source ssrc="${
  1467. group.ssrcs.join('"/><source ssrc="')}"/>`
  1468. + '</ssrc-group>');
  1469. }
  1470. });
  1471. });
  1472. }
  1473. }
  1474. /**
  1475. * Returns the description node related to the passed content type. If the
  1476. * node doesn't exists it will be created.
  1477. * @param jingle - the jingle packet
  1478. * @param mtype - the content type(audio, video, etc.)
  1479. */
  1480. static createDescriptionNode(jingle, mtype) {
  1481. let content = $(jingle.tree()).find(`>jingle>content[name="${mtype}"]`);
  1482. if (!content || !content.length) {
  1483. $(jingle.tree())
  1484. .find('>jingle')
  1485. .append(`<content name="${mtype}"></content>`);
  1486. content = $(jingle.tree()).find(`>jingle>content[name="${mtype}"]`);
  1487. }
  1488. let desc = content.find('>description');
  1489. if (!desc || !desc.length) {
  1490. content.append(
  1491. `<description xmlns="urn:xmpp:jingle:apps:rtp:1" media="${
  1492. mtype}"></description>`);
  1493. desc = content.find('>description');
  1494. }
  1495. return desc;
  1496. }
  1497. /**
  1498. * Extracts the ice username fragment from an SDP string.
  1499. */
  1500. static getUfrag(sdp) {
  1501. const ufragLines
  1502. = sdp.split('\n').filter(line => line.startsWith('a=ice-ufrag:'));
  1503. if (ufragLines.length > 0) {
  1504. return ufragLines[0].substr('a=ice-ufrag:'.length);
  1505. }
  1506. }
  1507. }