Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JingleSessionPC.js 61KB

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