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

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