You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 56KB

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