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

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