Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

JingleSessionPC.js 47KB

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