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

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