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

JingleSessionPC.js 61KB

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