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