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

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