Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSessionPC.js 57KB

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