Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 63KB

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