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 57KB

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